#!/usr/bin/env python3 """Controlled SQLite backup validation cases; no production paths accepted.""" import argparse from contextlib import closing from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import sqlite3 import tempfile CASES = ("valid", "orphan-off", "enable-in-transaction", "wrong-parent", "nullable") PARENTS = [(1, "required owner"), (2, "other existing owner")] PAYLOAD = "constructed recovery record" EXPECTED = [(1, 1, PAYLOAD)] def require(condition, message): if not condition: raise RuntimeError(message) def rows(db): return { "parents": [list(row) for row in db.execute("SELECT * FROM parent ORDER BY id")], "children": [list(row) for row in db.execute("SELECT * FROM child ORDER BY id")], } def snapshot_digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() def observe(root, mode, case): source = root / (mode + "-" + case + "-source.db") destination = root / (mode + "-" + case + "-copy.db") with closing(sqlite3.connect(source, isolation_level=None)) as db: require(db.execute("PRAGMA journal_mode=" + mode).fetchone()[0].upper() == mode, "Requested source journal mode not available") db.execute("PRAGMA synchronous=FULL") db.execute("PRAGMA wal_autocheckpoint=0") db.execute("PRAGMA foreign_keys=OFF") require(db.execute("PRAGMA foreign_keys").fetchone() == (0,), "FK support missing") db.executescript(""" CREATE TABLE parent(id INTEGER PRIMARY KEY, label TEXT NOT NULL); CREATE TABLE child(id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES parent(id), payload TEXT NOT NULL); """) db.executemany("INSERT INTO parent VALUES (?, ?)", PARENTS) if case in ("valid", "wrong-parent", "nullable"): db.execute("PRAGMA foreign_keys=ON") db.execute("BEGIN") if case == "enable-in-transaction": db.execute("PRAGMA foreign_keys=ON") during = db.execute("PRAGMA foreign_keys").fetchone()[0] parent = {"valid": 1, "orphan-off": 999, "enable-in-transaction": 999, "wrong-parent": 2, "nullable": None}[case] db.execute("INSERT INTO child VALUES (1, ?, ?)", (parent, PAYLOAD)) db.execute("COMMIT") db.execute("PRAGMA foreign_keys=ON") after = db.execute("PRAGMA foreign_keys").fetchone()[0] require(after == 1, "FK enforcement could not be enabled") # This separate failed statement proves future enforcement, not repair. guard_error = None try: db.execute("INSERT INTO child VALUES (2, 999, 'rejected guard')") except sqlite3.IntegrityError as exc: guard_error = {"code": exc.sqlite_errorcode, "name": exc.sqlite_errorname} require(guard_error is not None, "Invalid guard insert unexpectedly succeeded") require(guard_error["code"] == sqlite3.SQLITE_CONSTRAINT_FOREIGNKEY, "Guard failed for a different reason") source_rows = rows(db) require(len(source_rows["children"]) == 1, "Guard altered the source") progress = [] def tick(status, remaining, total): progress.append([status, remaining, total]) require(len(progress) <= 100, "Backup exceeded bounded step budget") require(status in (sqlite3.SQLITE_OK, sqlite3.SQLITE_DONE), "Unexpected backup status") with closing(sqlite3.connect(destination, isolation_level=None)) as out: db.backup(out, pages=1, progress=tick, sleep=0) require(progress and progress[-1][0:2] == [sqlite3.SQLITE_DONE, 0], "Backup did not reach DONE") with closing(sqlite3.connect(destination.as_uri() + "?mode=ro", uri=True, isolation_level=None)) as copied: copied.execute("PRAGMA foreign_keys=ON") destination_rows = rows(copied) result = { "sourceMode": mode, "case": case, "foreignKeysDuringInsert": during, "foreignKeysAfterCommit": after, "newInvalidInsertError": guard_error, "backupProgress": progress, "destinationJournalMode": copied.execute("PRAGMA journal_mode").fetchone()[0], "sourceRows": source_rows, "destinationRows": destination_rows, "fullRowsEqual": destination_rows == source_rows, "sourceLogicalSha256": snapshot_digest(source_rows), "destinationLogicalSha256": snapshot_digest(destination_rows), "integrityCheck": [r[0] for r in copied.execute("PRAGMA integrity_check")], "foreignKeyCheck": [list(r) for r in copied.execute("PRAGMA foreign_key_check")], "applicationExpectedChildren": [list(r) for r in EXPECTED], "applicationAccepted": destination_rows["children"] == [list(r) for r in EXPECTED], } return result def validate(result): cases = result["cases"] require(len(cases) == 10, "Expected ten separate designed cases") require({(r["sourceMode"], r["case"]) for r in cases} == {(m, c) for m in ("DELETE", "WAL") for c in CASES}, "Case matrix differs") for r in cases: orphan = r["case"] in ("orphan-off", "enable-in-transaction") parent = {"valid": 1, "orphan-off": 999, "enable-in-transaction": 999, "wrong-parent": 2, "nullable": None}[r["case"]] expected_rows = {"parents": [list(p) for p in PARENTS], "children": [[1, parent, PAYLOAD]]} require(r["sourceRows"] == expected_rows, "Source construction changed") require(r["destinationRows"] == expected_rows and r["fullRowsEqual"], "Copy differs from complete source row set") require(r["integrityCheck"] == ["ok"], "Unexpected structural-check result") require(r["foreignKeyCheck"] == ([["child", 1, "parent", 0]] if orphan else []), "Unexpected foreign-key result") require(r["foreignKeysDuringInsert"] == (0 if orphan else 1), "Wrong enforcement state") require(r["foreignKeysAfterCommit"] == 1, "Enforcement not enabled after commit") require(r["newInvalidInsertError"]["name"] == "SQLITE_CONSTRAINT_FOREIGNKEY", "Future-write guard did not fail as expected") require(r["applicationAccepted"] == (r["case"] == "valid"), "Wrong application verdict") require(r["applicationExpectedChildren"] == [list(x) for x in EXPECTED], "Acceptance expectation was changed") require(r["backupProgress"][-1][0:2] == [sqlite3.SQLITE_DONE, 0], "Copy not completed") for side in ("source", "destination"): require(r[side + "LogicalSha256"] == snapshot_digest(r[side + "Rows"]), "Logical data hash mismatch") def run(work_root): with closing(sqlite3.connect(":memory:")) as db: source_id = db.execute("SELECT sqlite_source_id()").fetchone()[0] options = sorted(r[0] for r in db.execute("PRAGMA compile_options")) with tempfile.TemporaryDirectory(prefix="hesela-sqlite-validation-", dir=work_root) as temp: cases = [observe(Path(temp).resolve(), mode, case) for mode in ("DELETE", "WAL") for case in CASES] result = { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "evidenceType": "executed-software-experiment-on-constructed-data", "environment": {"sqlite": sqlite3.sqlite_version, "sqliteSourceId": source_id, "python": platform.python_version(), "platform": platform.platform(), "compileOptions": options}, "scriptSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "method": { "sourceJournalModes": ["DELETE", "WAL"], "casesPerMode": 5, "parentRowsPerCase": 2, "childRowsPerCase": 1, "backupDatabase": "main", "backupPagesPerStep": 1, "acceptanceRule": "Child row 1 must reference parent 1 and retain the exact payload.", "acceptanceOrigin": "Fixed fixture expectation defined before constructing or reading databases.", "sourceSynchronous": "FULL", "automaticWalCheckpoint": 0, "validation": "Close and reopen destination read-only; compare all rows, integrity_check and foreign_key_check.", }, "limits": [ "Designed schedules on one installed library, not a failure-rate sample.", "No crash, power loss, concurrent writer, performance or full application recovery test.", "Nullable foreign key is deliberate; the application rule is stricter than this schema.", "No claim that undeclared application rules can be inferred by a database checker.", "Library version identifies the observation, not an upgrade or security recommendation.", ], "sources": [ "https://www.sqlite.org/pragma.html#pragma_integrity_check", "https://www.sqlite.org/pragma.html#pragma_foreign_key_check", "https://www.sqlite.org/foreignkeys.html", "https://www.sqlite.org/backup.html", ], "sourceAccessed": "2026-10-17", "cases": cases, } validate(result) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, default=Path(".")) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists() or args.output.is_symlink(): parser.error("Output already exists; refusing to overwrite") result = run(args.work_root) with args.output.open("x", encoding="utf-8") as stream: json.dump(result, stream, indent=2) stream.write("\n") if __name__ == "__main__": main()