An import normalizes labels in batches of two. It reads IDs 3 and 7, updates its progress to 7, and stops before saving either result. On restart, the log says the import picked up where it left off. The database tells a different story. Both labels are missing.
The saved cursor should mean the results through this ID have committed. If the results and cursor are in SQLite, put both writes in one transaction.
Read from the last committed ID
This example has a fixed input with IDs 3, 7, and 12. Each batch selects the next IDs in ascending order, starting strictly after the saved ID. Gaps in the sequence are harmless. The cursor moves to the last ID actually read.
BEGIN IMMEDIATE acquires the write transaction before reading the cursor. A second connection using the same routine can proceed after the first commits, at which point it reads the new cursor. It can also receive a busy error if it cannot acquire the write transaction in time. Keep that transaction short. SQLite transaction documentation
| Where the run stops | What the next connection sees |
|---|---|
| After the first result insert, before commit | The old cursor and the old committed results |
| When the cursor update fails and the batch rolls back | The old cursor and the old committed results |
| After commit, before the runner records success | The new cursor and the new committed results |
Try it with Python and SQLite
Save this as checkpoint.py and run python checkpoint.py. The tests use temporary SQLite files and reopen the connection when they check durable state.
import sqlite3
import tempfile
from contextlib import closing
from pathlib import Path
import unittest
def open_db(path):
# SQL controls the transaction boundaries explicitly.
return sqlite3.connect(path, isolation_level=None)
def setup(db):
db.executescript('''
CREATE TABLE source (id INTEGER PRIMARY KEY, label TEXT NOT NULL);
CREATE TABLE results (source_id INTEGER PRIMARY KEY, label TEXT NOT NULL);
CREATE TABLE progress (
name TEXT PRIMARY KEY, last_id INTEGER NOT NULL
);
INSERT INTO progress VALUES ('labels', 0);
INSERT INTO source VALUES (3, ' amber '), (7, ' blue '), (12, ' clay ');
''')
def process_batch(db, size):
if size < 1:
raise ValueError('size must be positive')
db.execute('BEGIN IMMEDIATE')
try:
(last_id,) = db.execute(
"SELECT last_id FROM progress WHERE name = 'labels'"
).fetchone()
batch = db.execute(
'SELECT id, label FROM source WHERE id > ? ORDER BY id LIMIT ?',
(last_id, size),
).fetchall()
if batch:
db.executemany(
'INSERT INTO results VALUES (?, ?)',
[(item_id, label.strip()) for item_id, label in batch],
)
db.execute(
"UPDATE progress SET last_id = ? WHERE name = 'labels'",
(batch[-1][0],),
)
db.execute('COMMIT')
except BaseException:
if db.in_transaction:
db.execute('ROLLBACK')
raise
return len(batch)
class CheckpointTests(unittest.TestCase):
def setUp(self):
work = tempfile.TemporaryDirectory()
self.addCleanup(work.cleanup)
self.path = Path(work.name) / 'checkpoint.sqlite'
with closing(open_db(self.path)) as db:
setup(db)
def state(self):
with closing(open_db(self.path)) as db:
last_id = db.execute('SELECT last_id FROM progress').fetchone()[0]
rows = db.execute('SELECT * FROM results ORDER BY source_id').fetchall()
return last_id, rows
def batch(self, size):
with closing(open_db(self.path)) as db:
return process_batch(db, size)
def test_resume_uses_persisted_cursor_and_handles_id_gaps(self):
self.assertEqual(self.batch(2), 2)
self.assertEqual(self.state(), (7, [(3, 'amber'), (7, 'blue')]))
self.assertEqual(self.batch(2), 1)
self.assertEqual(self.state(), (12, [(3, 'amber'), (7, 'blue'), (12, 'clay')]))
self.assertEqual(self.batch(2), 0)
def test_failed_checkpoint_rolls_back_results(self):
with closing(open_db(self.path)) as db:
db.execute('''
CREATE TEMP TRIGGER fail_checkpoint BEFORE UPDATE ON progress
BEGIN SELECT RAISE(ABORT, 'checkpoint write failed'); END
''')
with self.assertRaisesRegex(sqlite3.IntegrityError, 'checkpoint write failed'):
process_batch(db, 2)
self.assertEqual(self.state(), (0, []))
self.assertEqual(self.batch(2), 2)
def test_failed_second_result_does_not_skip_first_or_second(self):
with closing(open_db(self.path)) as db:
db.execute('''
CREATE TEMP TRIGGER fail_second_result BEFORE INSERT ON results
WHEN NEW.source_id = 7
BEGIN SELECT RAISE(ABORT, 'second result failed'); END
''')
with self.assertRaisesRegex(sqlite3.IntegrityError, 'second result failed'):
process_batch(db, 2)
self.assertEqual(self.state(), (0, []))
self.assertEqual(self.batch(2), 2)
def test_progress_alone_can_skip_work(self):
# Deliberately broken control: checkpoint committed on its own.
with closing(open_db(self.path)) as db:
db.execute("UPDATE progress SET last_id = 7 WHERE name = 'labels'")
self.assertEqual(self.batch(2), 1)
self.assertEqual(self.state(), (12, [(12, 'clay')]))
if __name__ == '__main__':
unittest.main(verbosity=2)
The deliberately broken test commits the cursor by itself and demonstrates the lost rows. The other failure tests cause a result insert or the cursor update to fail and check both tables after reopening. The temporary triggers let the retry run without the fault. These tests cover transaction rollback and restart from committed state. A process kill during a commit and a power cut are separate tests.
Define what belongs to this run
This example assumes fixed input IDs, starting above zero. If a producer can insert an item behind the cursor, id > last_id will miss it. Use a fixed input snapshot or a queue that records completion per item when the source has out-of-order arrivals. If the batch sends webhooks or writes to another service, that effect needs its own recovery contract because it sits outside the SQLite transaction.
Which table would you check first if your importer reported success but the last batch was missing? Share the failure case you would add to the test suite.
Top comments (0)