#!/usr/bin/env python3 """Observe row identity in disposable SQLite databases. SPDX-License-Identifier: MIT.""" import argparse from contextlib import closing from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import shutil import sqlite3 import tempfile SCHEMAS = { "hidden": "CREATE TABLE item (payload TEXT NOT NULL)", "explicit": "CREATE TABLE item (id INTEGER PRIMARY KEY, payload TEXT NOT NULL)", } METHODS = ("backup", "vacuum-into", "vacuum", "python-iterdump") def require(condition, message): if not condition: raise ValueError(message) def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def rows(db, sql): return [list(row) for row in db.execute(sql)] def inspect(path): with closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)) as db: has_id = any(row[1] == "id" for row in db.execute("PRAGMA table_info(item)")) has_sequence = db.execute( "SELECT 1 FROM sqlite_schema WHERE name='sqlite_sequence'" ).fetchone() return { "rowidPayload": rows(db, "SELECT rowid,payload FROM item ORDER BY rowid"), "declaredRows": rows(db, "SELECT * FROM item ORDER BY payload"), "lookup2": rows(db, "SELECT payload FROM item WHERE rowid=2"), "declaredIdPayload": rows(db, "SELECT id,payload FROM item ORDER BY id") if has_id else None, "integrityCheck": rows(db, "PRAGMA integrity_check"), "sequence": rows(db, "SELECT name,seq FROM sqlite_sequence ORDER BY name") if has_sequence else [], "sha256": digest(path), } def make_fixture(path, kind): with closing(sqlite3.connect(path)) as db: db.execute("PRAGMA journal_mode=DELETE") db.execute(SCHEMAS[kind]) db.executemany("INSERT INTO item(payload) VALUES (?)", [("alpha",), ("beta",), ("gamma",)]) db.execute("DELETE FROM item WHERE rowid=1") db.commit() def backup(source, destination): events = [] with closing(sqlite3.connect(source)) as src, closing(sqlite3.connect(destination)) as dst: src.backup(dst, pages=1, progress=lambda status, remaining, total: events.append({ "status": status, "remaining": remaining, "total": total, })) require(bool(events) and events[-1]["status"] == sqlite3.SQLITE_DONE, "backup did not finish") return events def copy_case(root, kind, method): source = root / (kind + "-" + method + "-source.db") destination = root / (kind + "-" + method + "-output.db") make_fixture(source, kind) before = inspect(source) detail = {} if method == "backup": detail["progress"] = backup(source, destination) elif method == "vacuum-into": with closing(sqlite3.connect(source)) as db: db.execute("VACUUM INTO ?", (str(destination),)) elif method == "vacuum": # The in-place operation runs on a closed fixture copy, never a caller's database. shutil.copyfile(source, destination) with closing(sqlite3.connect(destination)) as db: db.execute("VACUUM") elif method == "python-iterdump": with closing(sqlite3.connect(source)) as src: script = "\n".join(src.iterdump()) detail["dumpSql"] = script with closing(sqlite3.connect(destination)) as dst: dst.executescript(script) after = inspect(destination) unchanged = inspect(source) require(unchanged == before, "source fixture was modified") require(before["declaredRows"] == after["declaredRows"], "declared data changed") return { "schema": kind, "method": method, "ddl": SCHEMAS[kind], "before": before, "after": after, "sourceAfter": unchanged, "detail": detail, "declaredRowsPreserved": before["declaredRows"] == after["declaredRows"], "rowidsPreserved": before["rowidPayload"] == after["rowidPayload"], "savedReferenceStillBeta": after["lookup2"] == [["beta"]], } def reuse_case(root, autoincrement, schedule): tag = ("auto" if autoincrement else "plain") + "-" + schedule source, saved = root / (tag + ".db"), root / (tag + "-saved.db") ddl = "CREATE TABLE item(id INTEGER PRIMARY KEY" + (" AUTOINCREMENT" if autoincrement else "") + ", payload TEXT NOT NULL)" with closing(sqlite3.connect(source)) as db: db.execute("PRAGMA journal_mode=DELETE") db.execute(ddl) db.execute("INSERT INTO item(payload) VALUES ('alpha')") db.commit() progress = backup(source, saved) if schedule == "restore-old" else [] saved_before = inspect(saved) if schedule == "restore-old" else None with closing(sqlite3.connect(source)) as db: beta = db.execute("INSERT INTO item(payload) VALUES ('beta')").lastrowid db.commit() issued = inspect(source) target = saved if schedule == "restore-old" else source with closing(sqlite3.connect(target)) as db: if schedule == "delete-highest": db.execute("DELETE FROM item WHERE id=?", (beta,)) db.commit() replacement = db.execute("INSERT INTO item(payload) VALUES ('delta')").lastrowid db.commit() return { "autoincrement": autoincrement, "schedule": schedule, "ddl": ddl, "backupProgress": progress, "backupBefore": saved_before, "issuedState": issued, "issuedId": beta, "newId": replacement, "after": inspect(target), "reusedIssuedId": beta == replacement, } def validate(result): require(result["schemaVersion"] == 1, "schema version") require(result["evidenceType"] == "controlled-software-experiment", "evidence type") require(len(result["cases"]) == 8 and len(result["reuse"]) == 4, "case counts") require({(r["schema"], r["method"]) for r in result["cases"]} == {(k, m) for k in SCHEMAS for m in METHODS}, "copy coverage") require({(r["autoincrement"], r["schedule"]) for r in result["reuse"]} == {(a, s) for a in (False, True) for s in ("delete-highest", "restore-old")}, "reuse coverage") for r in result["cases"]: before, after = r["before"], r["after"] require(r["ddl"] == SCHEMAS[r["schema"]], "schema identity") require(before["rowidPayload"] == [[2, "beta"], [3, "gamma"]], "initial identities") require(before["lookup2"] == [["beta"]], "initial reference") expected_declared = [["beta"], ["gamma"]] if r["schema"] == "hidden" else [[2, "beta"], [3, "gamma"]] require(before["declaredRows"] == after["declaredRows"] == expected_declared, "declared rows") require(r["sourceAfter"] == before, "source invariant") same = before["rowidPayload"] == after["rowidPayload"] require(type(r["rowidsPreserved"]) is bool and r["rowidsPreserved"] == same, "identity flag") require(r["declaredRowsPreserved"] is True, "declared flag") require(r["savedReferenceStillBeta"] is (after["lookup2"] == [["beta"]]), "reference flag") require(after["lookup2"] == [[v] for key, v in after["rowidPayload"] if key == 2], "reference rows") require(sorted(v for _, v in after["rowidPayload"]) == ["beta", "gamma"], "all payloads") if r["schema"] == "explicit" or r["method"] == "backup": require(same, "stable control") if r["method"] == "backup": require(r["detail"]["progress"][-1]["status"] == sqlite3.SQLITE_DONE and r["detail"]["progress"][-1]["remaining"] == 0, "completion") for state in (before, after): require(state["integrityCheck"] == [["ok"]], "integrity result") require(len(state["sha256"]) == 64 and all(c in "0123456789abcdef" for c in state["sha256"]), "hash") require(state["declaredIdPayload"] == ([[2, "beta"], [3, "gamma"]] if r["schema"] == "explicit" else None), "explicit keys") for r in result["reuse"]: expected = 3 if r["autoincrement"] and r["schedule"] == "delete-highest" else 2 require(r["issuedId"] == 2 and r["newId"] == expected, "allocation oracle") require(r["reusedIssuedId"] is (expected == 2), "reuse flag") require(r["issuedState"]["rowidPayload"] == [[1, "alpha"], [2, "beta"]], "committed history") require(r["after"]["rowidPayload"] == [[1, "alpha"], [expected, "delta"]], "replacement rows") require(r["after"]["integrityCheck"] == [["ok"]], "reuse integrity") if r["schedule"] == "restore-old": require(r["backupBefore"]["rowidPayload"] == [[1, "alpha"]], "older snapshot") require(r["backupProgress"][-1]["status"] == sqlite3.SQLITE_DONE, "older backup completion") for name, expected_seq in (("issuedState", 2), ("after", expected), ("backupBefore", 1)): if r[name] is not None: require(r[name]["sequence"] == ([["item", expected_seq]] if r["autoincrement"] else []), "sequence state") return result def observe(work_root): with tempfile.TemporaryDirectory(prefix="hesela-identity-", dir=work_root) as tmp: root = Path(tmp) with closing(sqlite3.connect(":memory:")) as db: environment = { "python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqliteSourceId": db.execute("SELECT sqlite_source_id()").fetchone()[0], "compileOptions": [r[0] for r in db.execute("PRAGMA compile_options")], "system": platform.system(), "kernel": platform.release(), } result = { "schemaVersion": 1, "evidenceType": "controlled-software-experiment", "generatedAt": datetime.now(timezone.utc).isoformat(), "sourceSha256": digest(__file__), "environment": environment, "method": { "sourceJournal": "DELETE", "writersDuringCopy": 0, "fixture": "Insert alpha/beta/gamma, commit deletion of row 1; saved reference is rowid 2 -> beta.", "reuse": "Compare committed highest-ID deletion with restoring a backup predating the committed issuance of ID 2.", "limits": ["Designed fixtures, not sampled failures.", "No crash, power loss, network filesystem, WAL or whole-application recovery.", "Python iterdump is tested, not every SQL exporter.", "No guarantee that every VACUUM changes implicit rowids."], }, "cases": [copy_case(root, kind, method) for kind in SCHEMAS for method in METHODS], "reuse": [reuse_case(root, auto, schedule) for auto in (False, True) for schedule in ("delete-highest", "restore-old")], } return validate(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() require(args.work_root.is_dir(), "work root must exist") # Reserve the output exclusively before doing work; no silent result replacement. with args.output.open("x", encoding="utf-8") as target: json.dump(observe(args.work_root.resolve()), target, indent=2) target.write("\n") if __name__ == "__main__": main()