Product case study · November 23, 2026
Ask Claude Code to fix a half-saved SQLite operation
Make a two-write SQLite operation fail halfway, ask Claude Code for a bounded repair, and verify saved state through a fresh database connection.

A useful rollback test checks what stayed in the database after failure, not just whether Python raised an exception.
An importer says “failed,” but its new label is already in the database. Run it again and you get a duplicate-label error instead. The first attempt did more than its error message admitted.
This is a good bug to give a coding agent because the requirement is easy to state and easy to test: save the label and its audit entry together, or save neither. The interesting part is where you look for proof. An exception tells you execution stopped. A fresh database connection tells you what survived.
You need Python 3.12 or newer with SQLite support, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. The fixture and reference repair were tested locally with Python 3.14.4; the Claude prompt is an authored exercise, not a recorded agent run. Sources were checked November 23, 2026.
Build a failure that leaves a trace
Use a disposable folder with synthetic data:
transaction_lab=$(mktemp -d /tmp/claude-sqlite-transaction.XXXXXX)
cd "$transaction_lab"
cat > labels.py <<'PY'
import sqlite3
def add_label(path, name, event_id):
con = sqlite3.connect(path, autocommit=False)
try:
con.execute("INSERT INTO labels(name) VALUES (?)", (name,))
con.commit()
con.execute("INSERT INTO audit(event_id) VALUES (?)", (event_id,))
con.commit()
finally:
con.close()
PY
The early commit() is deliberate. We will make the second insert fail by reusing an audit ID. The first insert has already been saved by then; closing the connection cannot undo that earlier commit.
Python’s SQLite transaction documentation recommends autocommit=False for DB-API transaction control. Setting it explicitly also makes the exercise independent of the connection’s default mode. The argument was added in Python 3.12, so an older interpreter is not suitable for this exact snippet.
Save this as test_labels.py:
import sqlite3
import tempfile
import unittest
from pathlib import Path
from labels import add_label
class LabelTests(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.path = Path(self.folder.name) / "practice.db"
con = sqlite3.connect(self.path, autocommit=False)
try:
con.execute("CREATE TABLE labels(name TEXT PRIMARY KEY)")
con.execute("CREATE TABLE audit(event_id TEXT PRIMARY KEY)")
con.execute("INSERT INTO labels VALUES ('existing')")
con.execute("INSERT INTO audit VALUES ('used-event')")
con.commit()
finally:
con.close()
def saved_rows(self):
con = sqlite3.connect(self.path, autocommit=False)
try:
labels = con.execute(
"SELECT name FROM labels ORDER BY name"
).fetchall()
audit = con.execute(
"SELECT event_id FROM audit ORDER BY event_id"
).fetchall()
return labels, audit
finally:
con.close()
def test_success_saves_both(self):
add_label(self.path, "new", "new-event")
self.assertEqual(
self.saved_rows(),
([("existing",), ("new",)],
[("new-event",), ("used-event",)]),
)
def test_second_write_failure_saves_neither(self):
before = self.saved_rows()
with self.assertRaises(sqlite3.IntegrityError):
add_label(self.path, "new", "used-event")
self.assertEqual(self.saved_rows(), before)
def test_first_write_failure_saves_neither(self):
before = self.saved_rows()
with self.assertRaises(sqlite3.IntegrityError):
add_label(self.path, "existing", "new-event")
self.assertEqual(self.saved_rows(), before)
Run:
python3 -m unittest -v test_labels
The baseline runs three tests: two pass and test_second_write_failure_saves_neither fails. The assertion finds the unwanted new label. Notice that assertRaises already succeeded: the expected exception happened, yet the operation was still wrong.
Each test creates its own database. Each state check opens a new connection after add_label returns or raises. That keeps the check focused on saved rows rather than changes visible only inside the writer’s transaction.
Give the agent a precise definition of failure
Start claude from the practice folder. If you need help establishing the workspace and permissions, use the first project session lesson.
Paste this task:
Read labels.py and test_labels.py. Run the tests and report the baseline.
Repair add_label so that the label and audit row are saved together.
If either insert fails, leave both tables unchanged and propagate the error.
The function owns its connection and must close it on every path.
Keep explicit autocommit=False and bound SQL parameters.
Change only labels.py. Do not edit tests or loosen database constraints.
Do not catch and suppress errors, use INSERT OR IGNORE, or delete rows
as compensation. Use the standard library; do not install packages,
access other databases, commit files or delegate.
Run the unchanged tests after the repair and explain the transaction boundary.
This follows Anthropic’s debugging workflow: provide the observed problem, investigate it, then verify the fix. A prompt’s file restriction is an instruction; inspect the active tool permissions before approving commands.
I would reject a patch that merely hides the duplicate-event exception. The audit failure is useful information. The repair should change what gets saved, not make the error disappear.
Keep the two writes inside one transaction
Compare the proposed patch with this reference:
import sqlite3
def add_label(path, name, event_id):
con = sqlite3.connect(path, autocommit=False)
try:
with con:
con.execute("INSERT INTO labels(name) VALUES (?)", (name,))
con.execute("INSERT INTO audit(event_id) VALUES (?)", (event_id,))
finally:
con.close()
The connection context manager commits on a successful exit and rolls back when an exception escapes its block. It does not close the connection; the finally block still matters. These semantics are documented in Python’s connection context manager guide.
Do not leave the first commit() inside the block. A later rollback cannot undo a transaction that was already committed. SQLite’s transaction reference describes the COMMIT and ROLLBACK boundaries; being inside one Python function does not combine separate committed transactions.
The chosen connection mode matters too. With autocommit=True, the connection context manager has no effect. Copying only with con: into an application that uses that mode would not reproduce this repair.
Verify the rows, then review the limits
Exit Claude and rerun the same command yourself:
python3 -m unittest -v test_labels
All three tests passed locally with the reference implementation. They establish that successful calls save both rows, while a constraint failure on either insert preserves the previously saved rows and reaches the caller as an exception.
If the second-write test still fails, inspect the patch for an early commit or a changed connection mode. If the success test fails, check whether the connection is being closed before the transaction commits. If no exception reaches the test, look for a broad except or INSERT OR IGNORE that has altered the requirement.
This is a small operation with an owned connection. An existing application may manage a larger transaction outside the function; do not add an inner commit that saves the caller’s other work. SQLite does not nest BEGIN transactions; its documentation points to savepoints for nested transaction scopes.
The exercise does not test concurrent writers, crash recovery or retry policy. It also cannot undo an email or HTTP request made between the inserts. Keep external side effects out of this practice operation. The useful habit to take back to your project is simple: trigger a failure after the first write, then ask a new connection what actually remained.
Sources
Official documentation checked November 23, 2026:
- Python: sqlite3 — explicit transaction mode, connection context manager and connection cleanup.
- SQLite: Transaction — commit/rollback boundaries and savepoints for nested scopes.
- Anthropic: Common workflows — debugging prompts and verification with Claude Code.
Put this to work
How transaction boundaries determine what survives a failed database operation.
Try
Repair a synthetic label-and-audit operation in a disposable Python folder.
Prove it worked
Run three tests that inspect persisted rows after success and two different failures.
Keep in view
- Reproduce an operation that raises an error but still saves its first write.
- Give Claude Code a transaction repair with fixed acceptance tests.
- Check both success and failure using a newly opened connection.