#!/usr/bin/env python3 """Observe SQLite backup source snapshots using disposable WAL databases. No production path is accepted. Uses only the Python standard library. This is an ordered software experiment, not a power-loss or performance test. """ import argparse from contextlib import ExitStack, closing from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import sqlite3 import tempfile ROW_COUNT = 64 CASES = [ ("pinned-read", "BEGIN and SELECT before the writer commit", 1), ("fresh-source", "Open source after the writer commit", 2), ("released-read", "End the old read transaction before backup", 2), ("deferred-no-read", "BEGIN before commit, but no database read until backup", 2), ] def require(condition, message): if not condition: raise RuntimeError(message) def expected_rows(generation): return [(i, generation, (f"row={i:03d};generation={generation};" + "x" * 512)) for i in range(ROW_COUNT)] def read_rows(connection): return connection.execute( "SELECT id, generation, payload FROM records ORDER BY id" ).fetchall() def digest(rows): return hashlib.sha256( json.dumps(rows, separators=(",", ":"), ensure_ascii=True).encode() ).hexdigest() def connect(path): connection = sqlite3.connect(str(path), isolation_level=None, timeout=0) connection.execute("PRAGMA busy_timeout=0") connection.execute("PRAGMA read_uncommitted=0") connection.execute("PRAGMA wal_autocheckpoint=0") connection.execute("PRAGMA synchronous=FULL") return connection def observe_case(root, case_id, schedule, expected_generation): case_dir = root / case_id case_dir.mkdir() database = case_dir / "source.db" destination_path = case_dir / "backup.db" with ExitStack() as stack: writer = stack.enter_context(closing(connect(database))) writer.execute("PRAGMA page_size=4096") mode = writer.execute("PRAGMA journal_mode=WAL").fetchone()[0] require(mode == "wal", "WAL mode unavailable") writer.execute("CREATE TABLE records(id INTEGER PRIMARY KEY, generation INTEGER, payload TEXT)") writer.execute("BEGIN IMMEDIATE") writer.executemany("INSERT INTO records VALUES (?, ?, ?)", expected_rows(1)) writer.execute("COMMIT") source = None if case_id != "fresh-source": source = stack.enter_context(closing(connect(database))) source.execute("BEGIN") if case_id in ("pinned-read", "released-read"): require(read_rows(source) == expected_rows(1), "Failed to pin generation 1") writer.execute("BEGIN IMMEDIATE") writer.executemany( "UPDATE records SET generation=?, payload=? WHERE id=?", [(g, payload, i) for i, g, payload in expected_rows(2)], ) writer.execute("COMMIT") writer_rows = read_rows(writer) require(writer_rows == expected_rows(2), "Writer commit oracle failed") if source is None: source = stack.enter_context(closing(connect(database))) if case_id == "released-read": source.execute("ROLLBACK") before = source.in_transaction progress = [] def on_progress(status, remaining, total): progress.append({"status": status, "remainingPages": remaining, "totalPages": total}) require(status in (sqlite3.SQLITE_OK, sqlite3.SQLITE_DONE), f"Unexpected backup status {status}; do not retry indefinitely") require(len(progress) < 10000, "Backup iteration safety limit reached") with closing(connect(destination_path)) as destination: source.backup(destination, pages=1, progress=on_progress, sleep=0) require(progress and progress[-1]["status"] == sqlite3.SQLITE_DONE, "No SQLITE_DONE completion evidence") require(progress[-1]["remainingPages"] == 0, "Incomplete backup") after = source.in_transaction source_rows = read_rows(source) require(source_rows == expected_rows(expected_generation), "Source view mismatch") with closing(sqlite3.connect(destination_path.as_uri() + "?mode=ro", uri=True, isolation_level=None)) as reopened: backup_rows = read_rows(reopened) integrity = [row[0] for row in reopened.execute("PRAGMA integrity_check")] require(backup_rows == expected_rows(expected_generation), "Backup content mismatch") require(integrity == ["ok"], "Backup integrity failure") require(read_rows(writer) == expected_rows(2), "Writer changed unexpectedly") settings = {name: writer.execute("PRAGMA " + name).fetchone()[0] for name in ("journal_mode", "page_size", "synchronous", "wal_autocheckpoint", "busy_timeout", "read_uncommitted")} return { "case": case_id, "schedule": schedule, "committedGenerationBeforeBackup": 2, "sourceInTransactionBeforeBackup": before, "sourceInTransactionAfterBackup": after, "sourceGenerationAfterBackup": source_rows[0][1], "backupGeneration": backup_rows[0][1], "rowCount": len(backup_rows), "allRowsAndPayloadsMatched": True, "matchesLatestCommittedRows": backup_rows == writer_rows, "integrityCheck": integrity, "reopenedReadOnly": True, "sourceRowsSha256": digest(source_rows), "backupRowsSha256": digest(backup_rows), "latestCommittedRowsSha256": digest(writer_rows), "backupFileSha256": hashlib.sha256(destination_path.read_bytes()).hexdigest(), "progress": progress, "settings": settings, } def experiment(work_root): with tempfile.TemporaryDirectory(prefix="hesela-sqlite-backup-", dir=work_root) as tmp: rows = [observe_case(Path(tmp), *case) for case in CASES] with closing(sqlite3.connect(":memory:")) as connection: source_id = connection.execute("SELECT sqlite_source_id()").fetchone()[0] compile_options = [r[0] for r in connection.execute("PRAGMA compile_options")] return { "schemaVersion": 1, "experiment": "sqlite-backup-source-snapshot", "generatedAt": datetime.now(timezone.utc).isoformat(), "evidenceType": "measured-software-behavior-on-constructed-data", "environment": {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqliteSourceId": source_id, "compileOptions": compile_options, "os": platform.system(), "kernel": platform.release(), "machine": platform.machine()}, "scriptSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "method": "Four fresh WAL databases; ordered calls on one thread. Generation 2 commits before each backup starts. No writer runs during backup. Every destination is closed and reopened read-only.", "data": {"origin": "deterministically constructed, not production data", "rowsPerCase": ROW_COUNT, "seed": None, "comparison": "Every ordered id, generation and full payload; hashes are supplemental."}, "cases": rows, "limitations": [ "Single installed SQLite build; not a version survey or patch recommendation.", "No crash, power loss, concurrent writer during backup, throughput or recovery-time measurement.", "No statistical sampling; case counts are not failure probabilities.", "No claim that fresh-source backup always contains commits arriving during or after its execution.", "A deliberately old consistent snapshot can be intended; freshness is a separate application requirement.", ], } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() require(args.work_root.is_dir(), "work-root must be an existing directory") require(not args.output.exists(), "Refusing an existing output path") result = experiment(args.work_root.resolve()) with args.output.open("x", encoding="utf-8") as stream: json.dump(result, stream, indent=2) stream.write("\n") print(json.dumps({"sqlite": result["environment"]["sqlite"], "cases": [{"case": r["case"], "generation": r["backupGeneration"], "integrity": r["integrityCheck"]} for r in result["cases"]]})) if __name__ == "__main__": main()