"""Controlled SQLite connection-lifetime, schema and cross-process observations.""" import argparse import hashlib import json import os import platform import sqlite3 import subprocess import sys import tempfile from contextlib import ExitStack, closing from datetime import datetime, timezone from pathlib import Path CASES = [(m, s) for m in ("DELETE", "WAL") for s in ("reconnect", "attached_main", "attached_aux")] + [("WAL", "process_snapshot")] def require(ok, message): if not ok: raise ValueError(message) def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def source_id(c): return c.execute("SELECT sqlite_source_id()").fetchone()[0] def setup(path, mode): with closing(sqlite3.connect(path, isolation_level=None)) as c: require(c.execute("PRAGMA journal_mode=" + mode).fetchone()[0].upper() == mode, "journal mode") c.executescript("CREATE TABLE item(id INTEGER PRIMARY KEY, value INTEGER); INSERT INTO item VALUES(1,0);") def connect(path, trace, name, readonly=False): c = sqlite3.connect(path.resolve().as_uri() + ("?mode=ro" if readonly else "?mode=rw"), uri=True, isolation_level=None, timeout=1) c.set_trace_callback(lambda sql: trace.append({"connection": name, "sql": sql})) c.execute("PRAGMA synchronous=FULL") c.execute("PRAGMA wal_autocheckpoint=0") return c def state(c, schema="main"): require(schema in ("main", "aux"), "schema") return {"token": c.execute("PRAGMA " + schema + ".data_version").fetchone()[0], "rows": [list(r) for r in c.execute("SELECT id,value FROM " + schema + ".item ORDER BY id")], "transaction": c.in_transaction} def child_write(path): trace = [] with closing(connect(path, trace, "child")) as c: c.execute("BEGIN") c.execute("UPDATE item SET value=1 WHERE id=1") c.execute("COMMIT") return {"pid": os.getpid(), "sourceId": source_id(c), "trace": trace, "afterCommit": state(c)} def run_case(root, mode, scenario, rep): main, aux = root / "main.db", root / "aux.db" setup(main, mode) r = {"mode": mode, "scenario": scenario, "repetition": rep, "trace": []} with ExitStack() as stack: observer = stack.enter_context(closing(connect(main, r["trace"], "observer_1", True))) if scenario == "reconnect": writer = stack.enter_context(closing(connect(main, r["trace"], "writer"))) r["before"] = state(observer) observer.close() writer.execute("UPDATE item SET value=1 WHERE id=1") replacement = stack.enter_context(closing(connect(main, r["trace"], "observer_2", True))) r["replacement"] = state(replacement) r["naiveWouldReload"] = r["before"]["token"] != r["replacement"]["token"] r["identityAwareWouldReload"] = True elif scenario.startswith("attached_"): setup(aux, mode) observer.execute("ATTACH DATABASE ? AS aux", (aux.resolve().as_uri() + "?mode=ro",)) target = scenario.removeprefix("attached_") writer = stack.enter_context(closing(connect(main if target == "main" else aux, r["trace"], "writer"))) r["before"] = {s: state(observer, s) for s in ("main", "aux")} writer.execute("UPDATE item SET value=1 WHERE id=1") r["after"] = {s: state(observer, s) for s in ("main", "aux")} r["changedSchema"] = target else: observer.execute("BEGIN") r["pinned"] = state(observer) child = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--writer", str(main)], check=True, capture_output=True, text=True, timeout=30) r["child"], r["parentPid"] = json.loads(child.stdout), os.getpid() r["held"] = state(observer) observer.execute("COMMIT") r["released"] = state(observer) r["reopened"] = {} for name, path in (("main", main), ("aux", aux)): if path.exists(): with closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)) as c: r["reopened"][name] = {"rows": [list(x) for x in c.execute("SELECT id,value FROM item ORDER BY id")], "integrityCheck": [x[0] for x in c.execute("PRAGMA integrity_check")]} r["reopened"][name]["sha256"] = sha(path) return r def validate(report): reps = report["repetitions"] require(type(reps) is int and 1 <= reps <= 10, "repetition bounds") require(report["schemaVersion"] == 1 and report["environment"]["sourceId"], "runtime identity") expected = {(m, s, i) for m, s in CASES for i in range(1, reps + 1)} actual = [(c["mode"], c["scenario"], c["repetition"]) for c in report["cases"]] require(len(actual) == len(set(actual)) and set(actual) == expected, "case coverage") for c in report["cases"]: scenario = c["scenario"] require(len(c["trace"]) > 5, "trace") attached = scenario.startswith("attached_") require(set(c["reopened"]) == ({"main", "aux"} if attached else {"main"}), "database coverage") for name, value in c["reopened"].items(): require(value["rows"] == [[1, int(not attached or scenario == "attached_" + name)]], "reopened rows") require(value["integrityCheck"] == ["ok"] and len(value["sha256"]) == 64, "integrity and hash") if scenario == "reconnect": require(c["before"]["rows"] == [[1, 0]] and c["replacement"]["rows"] == [[1, 1]], "reconnect rows") require(not c["before"]["transaction"] and not c["replacement"]["transaction"], "reconnect transaction") require(type(c["naiveWouldReload"]) is bool and c["naiveWouldReload"] == (c["before"]["token"] != c["replacement"]["token"]), "naive decision") require(c["identityAwareWouldReload"] is True, "identity control") elif attached: target = scenario.removeprefix("attached_") require(c["changedSchema"] == target, "schema label") require(set(c["before"]) == set(c["after"]) == {"main", "aux"}, "schema coverage") for name in ("main", "aux"): b, a = c["before"][name], c["after"][name] require(b["rows"] == [[1, 0]] and a["rows"] == [[1, int(name == target)]], "attached rows") require((b["token"] != a["token"]) == (name == target), "schema token") require(not b["transaction"] and not a["transaction"], "attached transaction") else: require(c["parentPid"] != c["child"]["pid"], "separate process") require(c["child"]["sourceId"] == report["environment"]["sourceId"], "child runtime") require(c["child"]["afterCommit"]["rows"] == [[1, 1]] and not c["child"]["afterCommit"]["transaction"], "child commit") require("COMMIT" in [x["sql"] for x in c["child"]["trace"]], "commit trace") for phase in ("pinned", "held"): require(c[phase]["rows"] == [[1, 0]] and c[phase]["transaction"], "snapshot") require(c["pinned"]["token"] == c["held"]["token"], "held token") require(c["released"]["token"] != c["held"]["token"] and c["released"]["rows"] == [[1, 1]] and not c["released"]["transaction"], "release") def observe(root, repetitions=3): require(type(repetitions) is int and 1 <= repetitions <= 10, "repetition bounds") with closing(sqlite3.connect(":memory:")) as c: environment = {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sourceId": source_id(c), "system": platform.system(), "kernel": platform.release(), "compileOptions": [r[0] for r in c.execute("PRAGMA compile_options")]} report = {"schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "classification": "controlled synthetic observer-lifetime schedules", "environment": environment, "repetitions": repetitions, "harnessSha256": sha(Path(__file__)), "cases": [], "settings": {"synchronous": "FULL", "walAutocheckpoint": 0, "busyTimeoutMs": 1000, "sharedCache": False, "schedule": "ordered calls; child joined after commit; no simultaneous SQL calls"}} for mode, scenario in CASES: for rep in range(1, repetitions + 1): with tempfile.TemporaryDirectory(prefix="sqlite-observer-lifetime-", dir=root) as tmp: report["cases"].append(run_case(Path(tmp), mode, scenario, rep)) validate(report) return report def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, default=Path(".")) parser.add_argument("--output", type=Path) parser.add_argument("--repetitions", type=int, default=3) parser.add_argument("--writer", type=Path, help=argparse.SUPPRESS) args = parser.parse_args() if args.writer: print(json.dumps(child_write(args.writer))) return require(args.output is not None and not args.output.exists(), "output required and must not exist") report = observe(args.work_root, args.repetitions) with args.output.open("x") as f: json.dump(report, f, indent=2, allow_nan=False) f.write("\n") print(json.dumps({"cases": len(report["cases"]), "sqlite": sqlite3.sqlite_version})) if __name__ == "__main__": main()