"""Controlled FTS5 external-content cases; never accepts an existing database.""" 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 TOKENS = ("alpha", "beta", "gamma", "delta", "epsilon") MATCH_SQL = "SELECT rowid, body FROM search WHERE search MATCH ? ORDER BY rowid" SCHEMA = """ PRAGMA journal_mode=DELETE; CREATE TABLE docs(id INTEGER PRIMARY KEY, body TEXT NOT NULL); INSERT INTO docs VALUES(1, 'alpha'), (2, 'beta'); CREATE VIRTUAL TABLE search USING fts5(body, content='docs', content_rowid='id'); CREATE TRIGGER docs_ai AFTER INSERT ON docs BEGIN INSERT INTO search(rowid, body) VALUES(new.id, new.body); END; CREATE TRIGGER docs_ad AFTER DELETE ON docs BEGIN INSERT INTO search(search, rowid, body) VALUES('delete', old.id, old.body); END; CREATE TRIGGER docs_au AFTER UPDATE ON docs BEGIN INSERT INTO search(search, rowid, body) VALUES('delete', old.id, old.body); INSERT INTO search(rowid, body) VALUES(new.id, new.body); END; """ STEPS = [ ("unbackfilled", SCHEMA), ("future-insert", "INSERT INTO docs VALUES(3, 'gamma');"), ("rebuilt", "INSERT INTO search(search) VALUES('rebuild');"), ("maintained", "UPDATE docs SET body='delta' WHERE id=1; DELETE FROM docs WHERE id=2;"), ("stale", "DROP TRIGGER docs_au; UPDATE docs SET body='epsilon' WHERE id=1;"), ("reindex", "REINDEX;"), ] CHECKS = { "quick": "PRAGMA quick_check", "full": "PRAGMA integrity_check", "ftsInternal": "INSERT INTO search(search) VALUES('integrity-check')", "ftsExternal": "INSERT INTO search(search, rank) VALUES('integrity-check', 1)", } def require(condition, message): if not condition: raise RuntimeError(message) def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def run_check(db, sql): db.execute("SAVEPOINT diagnostic") try: rows = [list(row) for row in db.execute(sql)] return {"ok": True, "rows": rows} except sqlite3.DatabaseError as error: return {"ok": False, "error": str(error), "errorCode": error.sqlite_errorcode, "errorName": error.sqlite_errorname} finally: db.execute("ROLLBACK TO diagnostic") db.execute("RELEASE diagnostic") def observe(path, stage): before = digest(path) with closing(sqlite3.connect(path)) as db: rows = [list(row) for row in db.execute("SELECT id, body FROM docs ORDER BY id")] plain = [list(row) for row in db.execute("SELECT rowid, body FROM search ORDER BY rowid")] matches = {token: [list(row) for row in db.execute(MATCH_SQL, (token,))] for token in TOKENS} # Each document is one lowercase ASCII token: this is an independent oracle, # not a general replacement for FTS5 tokenization. expected = {token: [row for row in rows if row[1] == token] for token in TOKENS} checks = {name: run_check(db, sql) for name, sql in CHECKS.items()} after = digest(path) require(before == after, "Diagnostics unexpectedly changed database bytes") return {"stage": stage, "rows": rows, "plainFtsRows": plain, "matches": matches, "expectedMatches": expected, "mismatchedTokens": [t for t in TOKENS if matches[t] != expected[t]], "checks": checks, "sha256Before": before, "sha256After": after} def validate(report): cases = {row["stage"]: row for row in report["cases"]} require(list(cases) == [s for s, _ in STEPS] + ["backup", "backup-rebuilt"], "Unexpected or missing cases") expected_rows = { "unbackfilled": [[1, "alpha"], [2, "beta"]], "future-insert": [[1, "alpha"], [2, "beta"], [3, "gamma"]], "rebuilt": [[1, "alpha"], [2, "beta"], [3, "gamma"]], "maintained": [[1, "delta"], [3, "gamma"]], } mismatch = {"unbackfilled": ["alpha", "beta"], "future-insert": ["alpha", "beta"], "rebuilt": [], "maintained": [], "stale": ["delta", "epsilon"], "reindex": ["delta", "epsilon"], "backup": ["delta", "epsilon"], "backup-rebuilt": []} for stage, row in cases.items(): require(row["rows"] == expected_rows.get(stage, [[1, "epsilon"], [3, "gamma"]]), stage + ": wrong base rows") require(row["plainFtsRows"] == row["rows"], stage + ": wrong passthrough rows") require(row["mismatchedTokens"] == mismatch[stage], stage + ": wrong mismatch set") require(row["sha256Before"] == row["sha256After"], stage + ": changed bytes") for name in ("quick", "full"): require(row["checks"][name] == {"ok": True, "rows": [["ok"]]}, stage + ": unexpected PRAGMA result") require(row["checks"]["ftsInternal"] == {"ok": True, "rows": []}, stage + ": internal check failed") external = row["checks"]["ftsExternal"] if mismatch[stage]: require(not external["ok"] and external["errorCode"] == sqlite3.SQLITE_CORRUPT_VTAB, stage + ": expected external-content error") else: require(external == {"ok": True, "rows": []}, stage + ": external check failed") expected_matches = {t: [r for r in row["rows"] if r[1] == t] for t in TOKENS} if stage in ("unbackfilled", "future-insert"): expected_matches["alpha"] = [] expected_matches["beta"] = [] if stage in ("stale", "reindex", "backup"): expected_matches["delta"] = [[1, "epsilon"]] expected_matches["epsilon"] = [] require(row["matches"] == expected_matches, stage + ": wrong full MATCH rows") require(report["backupProgress"][-1]["status"] == sqlite3.SQLITE_DONE and report["backupProgress"][-1]["remaining"] == 0, "Backup incomplete") require(report["sourceHashBeforeBackup"] == report["sourceHashAfterBackup"], "Backup or destination repair changed source") for field in ("rows", "matches", "checks"): require(cases["backup"][field] == cases["reindex"][field], "Copy changed " + field) def experiment(work_root): with tempfile.TemporaryDirectory(prefix="hesela-fts5-", dir=work_root) as temp: source, target = Path(temp) / "source.db", Path(temp) / "backup.db" report = { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "kind": "controlled software experiment", "environment": {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version}, "method": "Eight closed/reopened DELETE-journal states; default FTS5 tokenizer; five single-ASCII-token queries; explicit full-row expectations; rolled-back diagnostic savepoints.", "limits": "Deliberately omitted backfill and update trigger. No crash, concurrency, hardware corruption, general tokenizer oracle or incident-rate estimate.", "sql": {"steps": STEPS, "checks": CHECKS, "match": MATCH_SQL, "backupRebuild": "INSERT INTO search(search) VALUES('rebuild');"}, "cases": [], "backupProgress": [], } for stage, sql in STEPS: with closing(sqlite3.connect(source)) as db: db.executescript(sql) db.commit() if stage == "unbackfilled": report["environment"]["sourceId"] = db.execute("SELECT sqlite_source_id()").fetchone()[0] report["environment"]["compileOptions"] = [r[0] for r in db.execute("PRAGMA compile_options")] report["cases"].append(observe(source, stage)) report["sourceHashBeforeBackup"] = digest(source) with closing(sqlite3.connect(source.as_uri() + "?mode=ro", uri=True)) as src: with closing(sqlite3.connect(target)) as dst: src.backup(dst, pages=1, progress=lambda status, remaining, total: report["backupProgress"].append( {"status": status, "remaining": remaining, "total": total})) report["cases"].append(observe(target, "backup")) with closing(sqlite3.connect(target)) as db: db.execute(report["sql"]["backupRebuild"]) db.commit() report["cases"].append(observe(target, "backup-rebuilt")) report["sourceHashAfterBackup"] = digest(source) report["harnessSha256"] = digest(__file__) validate(report) return report 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(): parser.error("Refusing to overwrite existing output") report = experiment(args.work_root.resolve()) with args.output.open("x", encoding="utf-8") as handle: json.dump(report, handle, indent=2) handle.write("\n") if __name__ == "__main__": main()