#!/usr/bin/env python3 """Measure generated-column SQL replay and explicit error finalization.""" 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 SCHEMA = """CREATE TABLE sample( id INTEGER PRIMARY KEY, x INTEGER NOT NULL, stored INTEGER GENERATED ALWAYS AS(score(x)) STORED UNIQUE);""" ROWS = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] STAGES = ("original", "changed-rollback", "changed-commit") QUERY = "SELECT id,x,stored FROM sample ORDER BY id" def require(ok, message): if not ok: raise RuntimeError(message) def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def register(db, changed): db.create_function("score", 1, (lambda x: (x - 1) // 2) if changed else (lambda x: x), deterministic=True) def snapshot(db): present = db.execute("SELECT count(*) FROM sqlite_schema WHERE name='sample'").fetchone()[0] == 1 return { "tablePresent": present, "rows": [list(row) for row in db.execute(QUERY)] if present else [], "sentinel": [list(row) for row in db.execute("SELECT value FROM sentinel")], "inTransaction": db.in_transaction, "integrityCheck": [row[0] for row in db.execute("PRAGMA integrity_check")], } def validate(result): require(result["kind"] == "controlled-software-experiment", "kind") require([case["stage"] for case in result["cases"]] == list(STAGES), "coverage") require(result["sourceRows"] == ROWS, "source rows") require(result["sourceSha256Before"] == result["sourceSha256After"], "source preserved") require(result["dumpSha256"] == hashlib.sha256(result["dumpSql"].encode()).hexdigest(), "dump hash") require(result["fixtureSchema"] == SCHEMA, "schema") inserts = [line for line in result["dumpSql"].splitlines() if line.startswith("INSERT INTO")] require(inserts == ['INSERT INTO "sample" VALUES(1,1);', 'INSERT INTO "sample" VALUES(2,2);', 'INSERT INTO "sample" VALUES(3,3);'], "dump inputs") require(result["dumpSql"].startswith("BEGIN TRANSACTION;\n") and result["dumpSql"].endswith("COMMIT;\n"), "explicit transaction") for case in result["cases"]: original = case["stage"] == "original" rollback = case["stage"] == "changed-rollback" require(case["callback"] == ("x" if original else "(x - 1) // 2"), "callback") require(case["finalizer"] == ("rollback" if rollback else "commit"), "finalizer") require(case["error"] == (None if original else { "name": "SQLITE_CONSTRAINT_UNIQUE", "code": 2067, "message": "UNIQUE constraint failed: sample.stored"}), "error identity") pending = ROWS if original else [[1, 1, 0]] require(case["beforeFinalizer"] == { "tablePresent": True, "rows": pending, "sentinel": [["keep"]], "inTransaction": not original, "integrityCheck": ["ok"]}, "pending state") expected = {"tablePresent": not rollback, "rows": [] if rollback else pending, "sentinel": [["keep"]], "inTransaction": False, "integrityCheck": ["ok"]} require(case["afterFinalizer"] == expected and case["reopened"] == expected, "committed/rolled back state") require(case["reopenSha256Before"] == case["reopenSha256After"], "read-only check") for key in ("sourceSha256Before", "sourceSha256After", "harnessSha256"): value = result[key] require(len(value) == 64 and all(c in "0123456789abcdef" for c in value), "hash syntax") def run(work_root): with tempfile.TemporaryDirectory(prefix="hesela-replay-", dir=work_root) as folder: root = Path(folder) source = root / "source.db" with closing(sqlite3.connect(source)) as db: register(db, False) require(db.execute("PRAGMA journal_mode=DELETE").fetchone()[0] == "delete", "journal") db.executescript(SCHEMA) db.executemany("INSERT INTO sample(id,x) VALUES(?,?)", [(1, 1), (2, 2), (3, 3)]) db.commit() source_rows = [list(row) for row in db.execute(QUERY)] dump = "\n".join(db.iterdump()) + "\n" environment = { "python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqliteSourceId": db.execute("SELECT sqlite_source_id()").fetchone()[0], "compileOptions": [row[0] for row in db.execute("PRAGMA compile_options")], "platform": platform.system(), "machine": platform.machine(), } source_hash = sha(source) cases = [] for stage in STAGES: target = root / (stage + ".db") changed = stage != "original" finalizer = "rollback" if stage == "changed-rollback" else "commit" with closing(sqlite3.connect(target)) as db: register(db, changed) require(db.execute("PRAGMA journal_mode=DELETE").fetchone()[0] == "delete", "target journal") db.execute("CREATE TABLE sentinel(value TEXT)") db.execute("INSERT INTO sentinel VALUES('keep')") db.commit() error = None try: db.executescript(dump) except sqlite3.IntegrityError as exc: error = {"name": exc.sqlite_errorname, "code": exc.sqlite_errorcode, "message": str(exc)} before = snapshot(db) # Both actions are measured controls. Commit after failure is deliberately unsafe. if finalizer == "rollback": db.rollback() else: db.commit() after = snapshot(db) before_read = sha(target) with closing(sqlite3.connect(target.resolve().as_uri() + "?mode=ro", uri=True)) as db: register(db, changed) reopened = snapshot(db) cases.append({ "stage": stage, "callback": "(x - 1) // 2" if changed else "x", "finalizer": finalizer, "error": error, "beforeFinalizer": before, "afterFinalizer": after, "reopened": reopened, "reopenSha256Before": before_read, "reopenSha256After": sha(target), }) result = { "schemaVersion": 1, "kind": "controlled-software-experiment", "generatedAt": datetime.now(timezone.utc).isoformat(), "harnessSha256": sha(__file__), "environment": environment, "fixtureSchema": SCHEMA, "sourceRows": source_rows, "query": QUERY, "dumpSql": dump, "dumpSha256": hashlib.sha256(dump.encode()).hexdigest(), "sourceSha256Before": source_hash, "sourceSha256After": sha(source), "cases": cases, "limitations": [ "Three constructed replay outcomes; deliberate callback incompatibility, not an engine defect.", "Python iterdump/executescript with default legacy transaction control and explicit dump BEGIN.", "Default UNIQUE ABORT semantics, separate INSERT statements, no custom conflict algorithms.", "Closed disposable DELETE-journal files, no concurrent writers, WAL, crash or power loss.", "Committing after a replay exception is a negative control, not recovery advice.", "No frequency, performance or cross-version generalization." ], } 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("refusing to overwrite an output path") result = run(args.work_root) with args.output.open("x", encoding="utf-8") as output: json.dump(result, output, indent=2) output.write("\n") print("Verified 3 UNIQUE replay outcomes") if __name__ == "__main__": main()