"""Replay three deliveries and verify the two report rows that survive.""" import sqlite3 from contextlib import closing from pathlib import Path from tempfile import TemporaryDirectory with closing(sqlite3.connect(":memory:")) as db, db: db.execute(""" CREATE TABLE reports ( workspace TEXT NOT NULL, job TEXT NOT NULL, output TEXT NOT NULL, PRIMARY KEY (workspace, job) ) """) deliveries = ( ("north", "R-104", "north/first.csv", 1), ("north", "R-104", "north/retry.csv", 0), ("west", "R-104", "west/first.csv", 1), ) for workspace, job, candidate, expected in deliveries: result = db.execute(""" INSERT INTO reports (workspace, job, output) VALUES (?, ?, ?) ON CONFLICT (workspace, job) DO NOTHING """, (workspace, job, candidate)) assert result.rowcount == expected, (workspace, job, result.rowcount) saved, = db.execute( "SELECT output FROM reports WHERE workspace = ? AND job = ?", (workspace, job) ).fetchone() print(f"{workspace:5} {job} inserted={result.rowcount} visible={saved}") rows = db.execute("SELECT workspace, job, output FROM reports ORDER BY workspace").fetchall() assert rows == [("north", "R-104", "north/first.csv"), ("west", "R-104", "west/first.csv")] print("3 deliveries, 2 results.") # A second run models a worker that stops after creating a pending record. with TemporaryDirectory() as folder, closing(sqlite3.connect(":memory:")) as db, db: db.execute("CREATE TABLE jobs (key TEXT PRIMARY KEY, status TEXT NOT NULL)") key = "north/R-104.csv" output_path = Path(folder) / key db.execute("INSERT INTO jobs VALUES (?, 'pending')", (key,)) db.commit() assert db.execute("SELECT key FROM jobs WHERE status = 'ready'").fetchall() == [] assert not output_path.exists() print("After interruption: pending, 0 visible results.") status, = db.execute("SELECT status FROM jobs WHERE key = ?", (key,)).fetchone() assert status == "pending" output_path.parent.mkdir() output_path.write_text("workspace,job\nnorth,R-104\n", encoding="utf-8") db.execute("UPDATE jobs SET status = 'ready' WHERE key = ?", (key,)) assert db.execute("SELECT key FROM jobs WHERE status = 'ready'").fetchall() == [(key,)] assert output_path.read_text(encoding="utf-8").endswith("north,R-104\n") print("After retry: ready, 1 visible result at", key)