"""Four prescribed SQLite WAL schedules; no timing, crash or fault injection.""" import argparse from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import sqlite3 import tempfile CASES = ("detached-literal", "atomic-increment", "version-guard", "snapshot-upgrade") def connect(path): options = {"isolation_level": None, "timeout": 0} if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"): options["autocommit"] = True return sqlite3.connect(path, **options) def run_case(kind, initial=0): if kind not in CASES: raise ValueError("unknown schedule") if type(initial) is not int or not 0 <= initial <= 1000000: raise ValueError("initial must be an integer from 0 to 1000000") with tempfile.TemporaryDirectory(prefix="hesela-lost-update-") as temp: path = Path(temp) / "counter.sqlite" a, b = connect(path), None events = [] def sql(actor, connection, statement, params=()): event = {"actor": actor, "sql": statement, "parameters": list(params), "transaction_before": connection.in_transaction} cursor = None try: cursor = connection.execute(statement, params) rows = [list(row) for row in cursor.fetchall()] event.update(rows=rows, rowcount=cursor.rowcount, error=None) return rows except sqlite3.Error as error: event.update(error={"name": error.sqlite_errorname, "code": error.sqlite_errorcode}) raise finally: if cursor is not None: cursor.close() event["transaction_after"] = connection.in_transaction events.append(event) try: journal = a.execute("PRAGMA journal_mode=WAL").fetchone()[0] if journal != "wal": raise RuntimeError("WAL mode unavailable") a.execute("PRAGMA synchronous=FULL").close() a.execute("CREATE TABLE counter(id INTEGER PRIMARY KEY, value INTEGER NOT NULL, version INTEGER NOT NULL)").close() a.execute("INSERT INTO counter VALUES(1, ?, 0)", (initial,)).close() b = connect(path) b.execute("PRAGMA synchronous=FULL").close() settings = {} for name, connection in (("A", a), ("B", b)): settings[name] = {key: connection.execute("PRAGMA " + key).fetchone()[0] for key in ("journal_mode", "synchronous", "read_uncommitted")} if kind == "snapshot-upgrade": sql("A", a, "BEGIN") sql("B", b, "BEGIN") if kind != "atomic-increment": old_a = sql("A", a, "SELECT value, version FROM counter WHERE id=1")[0] old_b = sql("B", b, "SELECT value, version FROM counter WHERE id=1")[0] if kind == "detached-literal": sql("A", a, "UPDATE counter SET value=? WHERE id=1", (old_a[0] + 1,)) sql("B", b, "UPDATE counter SET value=? WHERE id=1", (old_b[0] + 1,)) elif kind == "atomic-increment": for name, connection in (("A", a), ("B", b)): sql(name, connection, "UPDATE counter SET value=value+1 WHERE id=1") elif kind == "version-guard": for name, connection, old in (("A", a, old_a), ("B", b, old_b)): sql(name, connection, "UPDATE counter SET value=?, version=version+1 WHERE id=1 AND version=?", (old[0] + 1, old[1])) else: sql("A", a, "UPDATE counter SET value=? WHERE id=1", (old_a[0] + 1,)) sql("A", a, "COMMIT") try: sql("B", b, "UPDATE counter SET value=? WHERE id=1", (old_b[0] + 1,)) except sqlite3.OperationalError as error: if error.sqlite_errorcode != sqlite3.SQLITE_BUSY_SNAPSHOT: raise else: raise RuntimeError("stale snapshot unexpectedly promoted") sql("B", b, "ROLLBACK") final = sql("observer", a, "SELECT value, version FROM counter WHERE id=1")[0] integrity = sql("observer", a, "PRAGMA integrity_check")[0][0] return {"id": kind, "initial": initial, "settings": settings, "events": events, "final": final, "integrity_check": integrity} finally: if b is not None: b.close() a.close() def packet(): with sqlite3.connect(":memory:") as connection: source_id = connection.execute("SELECT sqlite_source_id()").fetchone()[0] return { "schema_version": 1, "generated_at": datetime.now(timezone.utc).isoformat(), "method": "Two connections, four prescribed schedules, one fresh database per case; no threads or injected failures.", "limits": ["Not a benchmark, prevalence estimate, crash test or general isolation conformance test.", "Detached reads and writes are separate transactions; rejected increments are not retried.", "One trigger-free row, WAL, synchronous FULL, private connection caches."], "runtime": {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqlite_source_id": source_id}, "probe_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "cases": [run_case(kind) for kind in CASES], } def verify(recorded, replay): for key in ("schema_version", "method", "limits", "probe_sha256", "cases"): # JSON serialization preserves the bool/int distinction lost by Python equality. if json.dumps(recorded.get(key), sort_keys=True) != json.dumps(replay[key], sort_keys=True): raise ValueError("replay mismatch: " + key) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path) parser.add_argument("--check", type=Path) args = parser.parse_args() if args.output and args.check: parser.error("choose either --output or --check") result = packet() if args.check: recorded = json.loads(args.check.read_text()) try: verify(recorded, result) except ValueError as error: raise SystemExit(str(error)) from error print(json.dumps({"replay": "PASS", "runtime": result["runtime"], "recorded_runtime": recorded["runtime"]}, indent=2)) elif args.output: with args.output.open("x") as output: output.write(json.dumps(result, indent=2) + "\n") else: print(json.dumps(result, indent=2))