"""Observe SQLite data_version across attachment lifetimes on one connection.""" import argparse import hashlib import json import platform import re import sqlite3 import tempfile from contextlib import closing from datetime import datetime, timezone from pathlib import Path SCENARIOS = ("attached_write", "reattach_changed", "reattach_unchanged", "replace_database") CASES = [(m, s) for m in ("DELETE", "WAL") for s in SCENARIOS] SETTINGS = {"sharedCache": False, "schedule": "ordered calls; no simultaneous SQL", "synchronous": "FULL", "busyTimeoutMs": 1000, "walAutocheckpoint": 0} def require(ok, message): if not ok: raise ValueError(message) def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def rows(value): return [[1, value], [2, -value]] def open_db(path): return sqlite3.connect(path.resolve().as_uri() + "?mode=rw", uri=True, isolation_level=None, timeout=1) def setup(path, mode, value): with closing(sqlite3.connect(path, isolation_level=None)) as c: require(c.execute("PRAGMA journal_mode=" + mode).fetchone()[0].upper() == mode, "mode") c.execute("CREATE TABLE item(id INTEGER PRIMARY KEY, value INTEGER NOT NULL)") c.executemany("INSERT INTO item VALUES(?,?)", rows(value)) def sample(c, root, generation): databases = {name: Path(path).relative_to(root).as_posix() for _, name, path in c.execute("PRAGMA database_list") if name != "temp"} return {"connection": "observer", "attachmentGeneration": generation, "database": databases["aux"], "databaseList": databases, "token": c.execute("PRAGMA aux.data_version").fetchone()[0], "rows": [list(r) for r in c.execute("SELECT id,value FROM aux.item ORDER BY id")], "transaction": c.in_transaction, "journalMode": c.execute("PRAGMA aux.journal_mode").fetchone()[0].upper()} def run_case(root, mode, scenario, repetition): main, first, second = (root / n for n in ("main.db", "first.db", "second.db")) setup(main, mode, 0) setup(first, mode, 0) if scenario == "replace_database": setup(second, mode, 7) r = {"mode": mode, "scenario": scenario, "repetition": repetition, "trace": []} with closing(open_db(main)) as observer: # This object stays open; DETACH ends only the auxiliary database handle. observer_id = id(observer) observer.set_trace_callback(lambda sql: r["trace"].append( {"connection": "observer", "sql": sql.replace(str(root), "")})) observer.execute("ATTACH DATABASE ? AS aux", (first.resolve().as_uri() + "?mode=ro",)) r["before"] = sample(observer, root, 1) detached = scenario != "attached_write" if detached: observer.execute("DETACH DATABASE aux") r["whileDetached"] = [n for _, n, _ in observer.execute("PRAGMA database_list")] if scenario in ("attached_write", "reattach_changed"): with closing(open_db(first)) as writer: writer.set_trace_callback(lambda sql: r["trace"].append({"connection": "writer", "sql": sql})) writer.execute("PRAGMA synchronous=FULL") writer.execute("PRAGMA wal_autocheckpoint=0") writer.execute("BEGIN") writer.execute("UPDATE item SET value=CASE id WHEN 1 THEN 7 ELSE -7 END") writer.execute("COMMIT") target = second if scenario == "replace_database" else first if detached: observer.execute("ATTACH DATABASE ? AS aux", (target.resolve().as_uri() + "?mode=ro",)) r["after"] = sample(observer, root, 2 if detached else 1) r["sameConnectionObject"] = id(observer) == observer_id b, a = r["before"], r["after"] r["naiveWouldReload"] = b["token"] != a["token"] r["generationAwareWouldReload"] = ( b["attachmentGeneration"] != a["attachmentGeneration"] or r["naiveWouldReload"]) r["reopened"] = {} for path in (main, first, second): if path.exists(): with closing(open_db(path)) as c: r["reopened"][path.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"][path.name]["sha256"] = digest(path) return r def validate(report): reps = report["repetitions"] require(type(reps) is int and 1 <= reps <= 10, "repetitions") require(type(report["schemaVersion"]) is int and report["schemaVersion"] == 1, "schema") require(report["settings"] == SETTINGS and report["environment"]["sourceId"], "method") expected = {(m, s, r) for m, s in CASES for r 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, "coverage") for c in report["cases"]: scenario = c["scenario"] detached, changed = scenario != "attached_write", scenario != "reattach_unchanged" b, a = c["before"], c["after"] require(c["sameConnectionObject"] is True, "connection continuity") require(b["rows"] == rows(0) and a["rows"] == rows(7 if changed else 0), "row oracle") for p, gen, database in ((b, 1, "first.db"), (a, 2 if detached else 1, "second.db" if scenario == "replace_database" else "first.db")): require(p["connection"] == "observer" and p["transaction"] is False, "observer state") require(type(p["token"]) is int and type(p["attachmentGeneration"]) is int, "token types") require(p["attachmentGeneration"] == gen and p["database"] == database, "attachment identity") require(p["databaseList"] == {"main": "main.db", "aux": database}, "database list") require(p["journalMode"] == c["mode"], "effective mode") sql = [x["sql"] for x in c["trace"] if x["connection"] == "observer"] require(sum(s.startswith("ATTACH DATABASE ") for s in sql) == (2 if detached else 1), "attach trace") require(sql.count("DETACH DATABASE aux") == int(detached), "detach trace") if detached: require(c["whileDetached"] == ["main"], "detached schema") else: require("whileDetached" not in c and b["token"] != a["token"], "attached control") require(type(c["naiveWouldReload"]) is bool and c["naiveWouldReload"] == (b["token"] != a["token"]), "numeric decision") require(type(c["generationAwareWouldReload"]) is bool and c["generationAwareWouldReload"] == (detached or c["naiveWouldReload"]), "generation decision") writer_sql = [x["sql"] for x in c["trace"] if x["connection"] == "writer"] require(writer_sql == (["PRAGMA synchronous=FULL", "PRAGMA wal_autocheckpoint=0", "BEGIN", "UPDATE item SET value=CASE id WHEN 1 THEN 7 ELSE -7 END", "COMMIT"] if scenario in ("attached_write", "reattach_changed") else []), "writer schedule") expected_files = {"main.db": rows(0), "first.db": rows(7 if scenario in ("attached_write", "reattach_changed") else 0)} if scenario == "replace_database": expected_files["second.db"] = rows(7) require(set(c["reopened"]) == set(expected_files), "file coverage") for name, expected_rows in expected_files.items(): e = c["reopened"][name] require(e["rows"] == expected_rows and e["integrityCheck"] == ["ok"], "reopened oracle") require(re.fullmatch("[0-9a-f]{64}", e["sha256"]) is not None, "file hash") def observe(root, repetitions=3): require(type(repetitions) is int and 1 <= repetitions <= 10, "repetitions") with closing(sqlite3.connect(":memory:")) as c: environment = {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sourceId": c.execute("SELECT sqlite_source_id()").fetchone()[0], "system": platform.system(), "kernel": platform.release(), "compileOptions": [r[0] for r in c.execute("PRAGMA compile_options")]} r = {"schemaVersion": 1, "classification": "controlled synthetic attachment-lifetime schedules", "generatedAt": datetime.now(timezone.utc).isoformat(), "environment": environment, "harnessSha256": digest(Path(__file__)), "repetitions": repetitions, "settings": dict(SETTINGS), "cases": []} for mode, scenario in CASES: for repetition in range(1, repetitions + 1): with tempfile.TemporaryDirectory(prefix="sqlite-attachment-", dir=root) as tmp: r["cases"].append(run_case(Path(tmp), mode, scenario, repetition)) validate(r) return r def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, default=Path(".")) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--repetitions", type=int, default=3) args = parser.parse_args() require(not args.output.exists(), "output exists") r = observe(args.work_root.resolve(), args.repetitions) with args.output.open("x") as f: json.dump(r, f, indent=2, allow_nan=False) f.write("\n") print(json.dumps({"cases": len(r["cases"]), "sqlite": sqlite3.sqlite_version, "missedChangedViews": sum(c["before"]["rows"] != c["after"]["rows"] and not c["naiveWouldReload"] for c in r["cases"])})) if __name__ == "__main__": main()