Freeze the Input Before a Resumable Import
DEV Community

Freeze the Input Before a Resumable Import

An import is supposed to process the labels present when it starts. In this example, the source contains IDs 3, 7, and 12. The runner saves 12 as the upper limit and processes ID 3.

Before it fetches the next page, someone edits label 7, inserts ID 9, and deletes ID 12. The next query still asks for id > 3 AND id <= 12. It returns the edited 7 and the new 9. The original 12 has disappeared from the run.

The saved limit caps the IDs you can read. A copy of the input captures the rows and values the run actually agreed to process.

Save the inputs when you create the run

Copy the IDs and labels into an input table owned by the run, in the same transaction that creates its progress row. Every later page reads that table. The results and position still commit together, as in the previous tutorial.

Source change after capture

What this run processes:

  • ID 7 changes from blue to green - The captured blue
  • ID 9 arrives under the original ceiling - No ID 9 in this run
  • ID 12 is deleted - The captured label for 12

capture() runs inside a single SQLite write transaction. A second call with the same run ID keeps the copy that already committed. A fresh run ID takes a new copy. Once capture commits, the importer releases the write transaction and uses short transactions for the individual pages.

SQLite isolation documentation

Run the five tests

Save the example as import_snapshot.py and run python import_snapshot.py. It uses Python's standard library and temporary SQLite files. The first test demonstrates the failure with an ID ceiling. The recovery test closes the original connection, mutates the source through a different connection, and then resumes the run from disk.

import sqlite3
import tempfile
import unittest
from contextlib import closing, contextmanager
from pathlib import Path

def open_db(path):
    db = sqlite3.connect(path, isolation_level=None)
    db.execute('PRAGMA foreign_keys = ON')
    db.execute('PRAGMA busy_timeout = 5000')
    return db

def setup(db):
    db.executescript('''
        CREATE TABLE source(id INTEGER PRIMARY KEY CHECK(id > 0), label TEXT NOT NULL);
        CREATE TABLE run(run_id TEXT PRIMARY KEY, last_id INTEGER NOT NULL);
        CREATE TABLE input(
            run_id TEXT NOT NULL REFERENCES run,
            id INTEGER NOT NULL,
            label TEXT NOT NULL,
            PRIMARY KEY (run_id, id)
        );
        CREATE TABLE result(
            run_id TEXT NOT NULL,
            id INTEGER NOT NULL,
            label TEXT NOT NULL,
            PRIMARY KEY (run_id, id),
            FOREIGN KEY (run_id, id) REFERENCES input
        );
        INSERT INTO source VALUES (3, ' amber '), (7, ' blue '), (12, ' clay ');
    ''')

@contextmanager
def write_transaction(db):
    db.execute('BEGIN IMMEDIATE')
    try:
        yield
        db.execute('COMMIT')
    except BaseException:
        if db.in_transaction:
            db.execute('ROLLBACK')
        raise

def capture(db, run_id):
    with write_transaction(db):
        if db.execute('SELECT 1 FROM run WHERE run_id = ?', (run_id,)).fetchone():
            return False
        db.execute('INSERT INTO run VALUES (?, 0)', (run_id,))
        db.execute('INSERT INTO input SELECT ?, id, label FROM source', (run_id,))
        return True

def process_page(db, run_id, size):
    if size <= 0:
        raise ValueError('page size must be positive')
    with write_transaction(db):
        progress = db.execute('SELECT last_id FROM run WHERE run_id = ?', (run_id,)).fetchone()
        if progress is None:
            raise KeyError(run_id)
        rows = db.execute('''
            SELECT id, label FROM input WHERE run_id = ? AND id > ? ORDER BY id LIMIT ?
        ''', (run_id, progress[0], size)).fetchall()
        if rows:
            db.executemany('INSERT INTO result VALUES (?, ?, ?)', [(run_id, row_id, label.strip()) for row_id, label in rows])
            db.execute('UPDATE run SET last_id = ? WHERE run_id = ?', (rows[-1][0], run_id))
        return len(rows)

class SnapshotTests(unittest.TestCase):
    def setUp(self):
        directory = tempfile.TemporaryDirectory()
        self.addCleanup(directory.cleanup)
        self.path = Path(directory.name) / 'import.sqlite'
        with closing(open_db(self.path)) as db:
            setup(db)

    def rows(self, db, run_id):
        return db.execute('SELECT id, label FROM result WHERE run_id = ? ORDER BY id', (run_id,)).fetchall()

    def test_ceiling_alone_does_not_freeze_rows_or_values(self):
        with closing(open_db(self.path)) as db:
            ceiling = db.execute('SELECT MAX(id) FROM source').fetchone()[0]
            db.executescript("UPDATE source SET label = 'green' WHERE id = 7;" "INSERT INTO source VALUES (9, 'new');" "DELETE FROM source WHERE id = 12;")
            later = db.execute('SELECT id, label FROM source WHERE id > 3 AND id <= ? ORDER BY id', (ceiling,)).fetchall()
            self.assertEqual(later, [(7, 'green'), (9, 'new')])

    def test_resume_uses_frozen_payload_and_membership(self):
        with closing(open_db(self.path)) as db:
            capture(db, 'report-1')
            self.assertEqual(process_page(db, 'report-1', 1), 1)
        with closing(open_db(self.path)) as producer:
            producer.executescript("INSERT INTO source VALUES (2, 'late'), (9, 'new'), (15, 'later');" "UPDATE source SET label = 'green' WHERE id = 7;" "DELETE FROM source WHERE id = 12;")
        with closing(open_db(self.path)) as db:
            self.assertEqual(process_page(db, 'report-1', 2), 2)
            self.assertEqual(process_page(db, 'report-1', 2), 0)
            self.assertEqual(self.rows(db, 'report-1'), [(3, 'amber'), (7, 'blue'), (12, 'clay')])

    def test_retry_capture_keeps_input_and_another_run_reads_new_input(self):
        with closing(open_db(self.path)) as db:
            self.assertTrue(capture(db, 'report-1'))
            db.execute("UPDATE source SET label = 'green' WHERE id = 7")
            self.assertFalse(capture(db, 'report-1'))
            self.assertTrue(capture(db, 'report-2'))
            for name in ['report-1', 'report-2']:
                process_page(db, name, 5)
            self.assertEqual(self.rows(db, 'report-1')[1], (7, 'blue'))
            self.assertEqual(self.rows(db, 'report-2')[1], (7, 'green'))

    def test_failed_capture_exposes_no_run(self):
        with closing(open_db(self.path)) as db:
            db.executescript('''
                CREATE TEMP TRIGGER fail_copy BEFORE INSERT ON input WHEN NEW.id = 7 BEGIN SELECT RAISE(ABORT, 'snapshot write failed'); END;
            ''')
            with self.assertRaisesRegex(sqlite3.IntegrityError, 'snapshot write failed'):
                capture(db, 'report-1')
        with closing(open_db(self.path)) as db:
            self.assertEqual(db.execute('SELECT * FROM run').fetchall(), [])
            self.assertEqual(db.execute('SELECT * FROM input').fetchall(), [])
            with self.assertRaises(KeyError):
                process_page(db, 'report-1', 2)
            self.assertTrue(capture(db, 'report-1'))

    def test_empty_snapshot_stays_empty_when_source_grows(self):
        with closing(open_db(self.path)) as db:
            db.execute('DELETE FROM source')
            capture(db, 'empty-run')
            db.execute("INSERT INTO source VALUES (3, 'copper')")
            self.assertEqual(process_page(db, 'empty-run', 2), 0)
            self.assertEqual(self.rows(db, 'empty-run'), [])

if __name__ == '__main__':
    unittest.main(verbosity=2)

Decide when a copy is worth it

An upper ID bound is enough if the upstream contract guarantees existing rows stay unchanged, IDs arrive in increasing order, and the import only needs to exclude later arrivals. Use a copy when the run must keep the original membership and values across reconnects.

Copy every field that affects the result and keep the copy for as long as retries are possible. This example copies a small local table. A large copy holds SQLite's writer lock and uses disk space. For larger sources, consider reading an immutable export or a source version the importer can reopen. If a business rule requires a later deletion to take effect immediately, reconcile that rule before publishing results from a captured row.

What should your importer do if someone edits or deletes a source row halfway through a run? Share the contract your team uses and the test that checks it.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.