#!/usr/bin/env python3 """Disposable SQLite reader-contract experiment; Python 3.11+, stdlib only.""" import argparse from contextlib import ExitStack, closing from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import re import sqlite3 import tempfile ROWS = 4 PAYLOAD_BYTES = 512 MODES = ("mode-ro", "query-only", "immutable") METHOD = {"rowsPerDatabase": ROWS, "payloadBytesPerRow": PAYLOAD_BYTES, "pageSizeBytes": 4096, "mmapSizeBytes": 0, "privateCaches": True, "sequentialCalls": True, "writerSynchronous": "FULL", "walAutocheckpoint": 0, "busyTimeoutMs": 0, "rowDigestEncoding": "ASCII compact JSON of ordered [id,generation,payload_hex] rows"} def require(condition, message): if not condition: raise RuntimeError(message) def expected(generation): return [(i, generation, bytes([65 + generation, i]) * (PAYLOAD_BYTES // 2)) for i in range(1, ROWS + 1)] def connect(path, reader=None): query = "mode=rw&cache=private" if reader == "mode-ro": query = "mode=ro&cache=private" elif reader == "immutable": query = "mode=ro&immutable=1&cache=private" con = sqlite3.connect(path.as_uri() + "?" + query, uri=True, isolation_level=None, timeout=0) con.execute("PRAGMA mmap_size=0").close() con.execute("PRAGMA read_uncommitted=0").close() if reader == "query-only": con.execute("PRAGMA query_only=ON").close() return con def scalar(con, sql): with closing(con.execute(sql)) as cursor: return cursor.fetchone()[0] def observe(con, generation, phase): with closing(con.execute("SELECT id,generation,payload FROM records ORDER BY id")) as cursor: rows = cursor.fetchall() require(rows == expected(generation), phase + ": full-row oracle failed") with closing(con.execute("PRAGMA integrity_check")) as cursor: integrity = [row[0] for row in cursor.fetchall()] require(integrity == ["ok"], phase + ": integrity check failed") encoded = json.dumps([[i, g, p.hex()] for i, g, p in rows], separators=(",", ":")).encode("ascii") return {"phase": phase, "generation": generation, "rows": len(rows), "payloadBytesCompared": sum(len(row[2]) for row in rows), "rowDigestSha256": hashlib.sha256(encoded).hexdigest(), "fullRowsMatch": True, "integrityCheck": integrity, "inTransaction": con.in_transaction} def commit_generation(con, generation): con.execute("BEGIN IMMEDIATE").close() con.executemany("UPDATE records SET generation=?,payload=? WHERE id=?", [(g, p, i) for i, g, p in expected(generation)]).close() con.execute("COMMIT").close() require(not con.in_transaction, "writer still in transaction") def file_state(path): wal = Path(str(path) + "-wal") return {"mainSha256": hashlib.sha256(path.read_bytes()).hexdigest(), "mainBytes": path.stat().st_size, "walBytes": wal.stat().st_size if wal.exists() else 0} def prepare(path, journal): con = sqlite3.connect(path, isolation_level=None, timeout=0) con.execute("PRAGMA page_size=4096").close() require(scalar(con, "PRAGMA journal_mode=" + journal) == journal.lower(), "journal mode not applied") con.execute("PRAGMA synchronous=FULL").close() con.execute("PRAGMA wal_autocheckpoint=0").close() con.execute("PRAGMA mmap_size=0").close() con.execute("CREATE TABLE records(id INTEGER PRIMARY KEY,generation INTEGER,payload BLOB)").close() con.execute("BEGIN").close() con.executemany("INSERT INTO records VALUES(?,?,?)", expected(0)).close() con.execute("COMMIT").close() if journal == "WAL": require(con.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone() == (0, 0, 0), "initial checkpoint did not finish") return con def reject_write(con): try: con.execute("UPDATE records SET generation=99 WHERE id=1").close() except sqlite3.DatabaseError as error: require(error.sqlite_errorcode == sqlite3.SQLITE_READONLY, "unexpected write-rejection code") return {"code": error.sqlite_errorcode, "name": error.sqlite_errorname} raise RuntimeError("reader unexpectedly permitted the main-table write") def run_case(root, journal, mode, pinned=False, static=False, checkpoint=False): label = journal.lower() + "-" + mode if pinned: label += "-pinned" if static: label += "-static" if checkpoint: label += "-checkpoint" path = root / (label + ".db") with ExitStack() as stack: writer = stack.enter_context(closing(prepare(path, journal))) baseline = file_state(path) if journal == "WAL" and not static: commit_generation(writer, 1) reader = stack.enter_context(closing(connect(path, mode))) first = 0 if mode == "immutable" or journal == "DELETE" else 1 write_error = reject_write(reader) if pinned: reader.execute("BEGIN").close() observations = [observe(reader, first, "reader-before")] target = 0 if static else (2 if journal == "WAL" else 1) if not static: commit_generation(writer, target) observations.append(observe(writer, target, "writer-after")) current = file_state(path) if journal == "WAL" and not static: require(current["mainSha256"] == baseline["mainSha256"], "WAL setup changed the main image") require(current["walBytes"] > 32, "no committed WAL payload") after = first if mode == "immutable" or pinned else target observations.append(observe(reader, after, "reader-after")) if pinned: reader.execute("ROLLBACK").close() observations.append(observe(reader, target, "reader-after-release")) checkpoint_result = None checkpoint_files = None if checkpoint: checkpoint_result = list(reader.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()) require(checkpoint_result == [0, 0, 0], "query_only checkpoint failed") checkpoint_files = file_state(path) require(checkpoint_files["mainSha256"] != current["mainSha256"], "checkpoint did not change main-file bytes") require(checkpoint_files["walBytes"] == 0, "WAL not truncated") observations.append(observe(reader, target, "reader-after-checkpoint")) with closing(connect(path, mode)) as fresh: fresh_expected = 0 if mode == "immutable" and journal == "WAL" else target observations.append(observe(fresh, fresh_expected, "fresh-reader")) return {"id": label, "journal": journal, "readerMode": mode, "deliberatelyFalseImmutablePromise": mode == "immutable" and not static, "pinnedTransaction": pinned, "staticControl": static, "writerGeneration": target, "writeRejected": write_error, "checkpointRequested": checkpoint, "checkpointResult": checkpoint_result, "checkpointFiles": checkpoint_files, "baselineFiles": baseline, "afterFiles": current, "observations": observations} def validate_files(state): require(isinstance(state, dict), "missing file-state evidence") require(isinstance(state.get("mainSha256"), str) and re.fullmatch(r"[0-9a-f]{64}", state["mainSha256"]) is not None, "invalid main-file hash") require(type(state.get("mainBytes")) is int and state["mainBytes"] > 0 and state["mainBytes"] % METHOD["pageSizeBytes"] == 0, "invalid main-file length") wal_bytes = state.get("walBytes") require(type(wal_bytes) is int and (wal_bytes == 0 or (wal_bytes > 32 and (wal_bytes - 32) % (METHOD["pageSizeBytes"] + 24) == 0)), "invalid WAL length") def validate(document): require(type(document.get("schemaVersion")) is int and document["schemaVersion"] == 1, "unsupported schema") method = document.get("method") require(isinstance(method, dict) and method.keys() == METHOD.keys(), "method fields mismatch") for key, value in METHOD.items(): require(type(method[key]) is type(value) and method[key] == value, "method mismatch: " + key) cases = document.get("cases", []) ids = [j.lower() + "-" + mode for j in ("DELETE", "WAL") for mode in MODES] ids += ["wal-mode-ro-pinned", "delete-immutable-static", "wal-query-only-checkpoint"] require([case.get("id") for case in cases] == ids, "case set/order mismatch") for case in cases: mode = case["readerMode"] wal = case["journal"] == "WAL" pinned = case["pinnedTransaction"] static = case["staticControl"] checkpoint = case["checkpointRequested"] expected_journal = "WAL" if case["id"].startswith("wal-") else "DELETE" expected_mode = next(candidate for candidate in MODES if case["id"].startswith(expected_journal.lower() + "-" + candidate)) require(case["journal"] == expected_journal and mode == expected_mode, "case identity mismatch") for field in ("baselineFiles", "afterFiles"): validate_files(case[field]) require(case["baselineFiles"]["walBytes"] == 0, "baseline WAL not empty") require(case["baselineFiles"]["mainBytes"] == case["afterFiles"]["mainBytes"], "unexpected main-file size change") require(pinned is (case["id"] == "wal-mode-ro-pinned"), "pinned label mismatch") require(static is (case["id"] == "delete-immutable-static"), "static label mismatch") require(checkpoint is (case["id"] == "wal-query-only-checkpoint"), "checkpoint label mismatch") require(case["deliberatelyFalseImmutablePromise"] is (mode == "immutable" and not static), "immutable precondition label mismatch") require(case["writeRejected"] == {"code": 8, "name": "SQLITE_READONLY"}, "write rejection mismatch") first = 0 if mode == "immutable" or not wal else 1 target = 0 if static else (2 if wal else 1) phases = ["reader-before", "writer-after", "reader-after"] generations = [first, target, first if mode == "immutable" or pinned else target] if pinned: phases += ["reader-after-release"] generations += [target] if checkpoint: phases += ["reader-after-checkpoint"] generations += [target] require(case["checkpointResult"] == [0, 0, 0] and all(type(n) is int for n in case["checkpointResult"]), "checkpoint result mismatch") validate_files(case["checkpointFiles"]) require(case["checkpointFiles"]["mainBytes"] == case["afterFiles"]["mainBytes"], "checkpoint main-file size change") require(case["checkpointFiles"]["walBytes"] == 0, "checkpoint WAL not empty") require(case["checkpointFiles"]["mainSha256"] != case["afterFiles"]["mainSha256"], "checkpoint main hash not changed") else: require(case["checkpointResult"] is None and case["checkpointFiles"] is None, "unexpected checkpoint evidence") if wal: require(case["baselineFiles"]["mainSha256"] == case["afterFiles"]["mainSha256"], "WAL scenario main-file change") require(case["afterFiles"]["walBytes"] > 32, "missing WAL payload") else: require(case["afterFiles"]["walBytes"] == 0, "DELETE case has WAL bytes") same_image = case["baselineFiles"]["mainSha256"] == case["afterFiles"]["mainSha256"] require(same_image is static, "DELETE mutation/static file mismatch") phases += ["fresh-reader"] generations += [0 if mode == "immutable" and wal else target] observations = case["observations"] require([o["phase"] for o in observations] == phases, "phase set mismatch") require([o["generation"] for o in observations] == generations, "generation mismatch") require(case["writerGeneration"] == target, "writer generation mismatch") for observation in observations: require(observation["rows"] == ROWS and observation["fullRowsMatch"] is True, "incomplete rows") require(observation["payloadBytesCompared"] == ROWS * PAYLOAD_BYTES, "incomplete payload comparison") require(observation["integrityCheck"] == ["ok"], "integrity mismatch") encoded = json.dumps([[i, g, p.hex()] for i, g, p in expected(observation["generation"])], separators=(",", ":")).encode("ascii") require(observation["rowDigestSha256"] == hashlib.sha256(encoded).hexdigest(), "row digest mismatch") transaction = pinned and observation["phase"] in ("reader-before", "reader-after") require(observation["inTransaction"] is transaction, "transaction state mismatch") def run(): with tempfile.TemporaryDirectory(prefix="hesela-sqlite-immutable-") as temporary: root = Path(temporary) cases = [run_case(root, journal, mode) for journal in ("DELETE", "WAL") for mode in MODES] cases += [run_case(root, "WAL", "mode-ro", pinned=True), run_case(root, "DELETE", "immutable", static=True), run_case(root, "WAL", "query-only", checkpoint=True)] with closing(sqlite3.connect(":memory:")) as con: environment = {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqliteSourceId": scalar(con, "SELECT sqlite_source_id()"), "os": platform.system(), "kernel": platform.release(), "machine": platform.machine(), "compileOptions": sorted(row[0] for row in con.execute("PRAGMA compile_options"))} result = {"schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "evidenceType": "measured behavior under constructed schedules", "environment": environment, "scriptSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "method": dict(METHOD), "limits": [ "Immutable mutation cases deliberately violate the API precondition; no SQLite defect is claimed.", "No process crash, power loss, hardware fault, network filesystem, simultaneous calls or timing measurement.", "Exact outcomes describe this build and schedule, not a production frequency or behavior guaranteed after misuse.", "The installed version identifies evidence; it is not a current-patch recommendation.", "Read-only statements are not evidence of zero filesystem writes; no VFS or syscall tracing was performed." ], "cases": cases} validate(result) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists() or args.output.is_symlink(): parser.error("refusing existing output") result = run() validate(result) with args.output.open("x", encoding="utf-8") as output: json.dump(result, output, indent=2) output.write("\n") print("Validated 9 cases; output:", args.output) if __name__ == "__main__": main()