#!/usr/bin/env python3 """Synthetic finite models plus native SQLite semantics; not a bitmap engine.""" import argparse import itertools import json import platform import sqlite3 import tempfile from pathlib import Path PREDICATES = { "equal": "x = 5", "null_comparison": "x = NULL", "or_null": "(x = 5) OR (x IS NULL)", "and_false": "(x = 5) AND 0", "in_with_null": "x IN (SELECT value FROM rhs)", "in_empty": "x IN (SELECT value FROM rhs WHERE 0)", "is_null": "x IS NULL", } ROWS = [(0, 5), (2, 6), (4, None), (6, 7)] def require(condition, message): if not condition: raise ValueError(message) def mask(ids): value = 0 for i in ids: require(type(i) is int and i >= 0, "IDs must be nonnegative integers") value |= 1 << i return value def ids(value): require(type(value) is int and value >= 0, "Mask must be nonnegative integer") return [i for i in range(value.bit_length()) if value & (1 << i)] def sql_not(universe, true, unknown): for value in (universe, true, unknown): require(type(value) is int and value >= 0, "Invalid mask") require(not (true & unknown), "True and unknown must be disjoint") require((true | unknown) & ~universe == 0, "Mask exceeds universe") return universe & ~(true | unknown) def exhaustive(): truth_count = bad_truth = 0 for states in itertools.product(range(4), repeat=8): # 0 absent, 1 false, 2 true, 3 unknown; set oracle is independent of NOT. universe = mask(i for i, s in enumerate(states) if s != 0) true = mask(i for i, s in enumerate(states) if s == 2) unknown = mask(i for i, s in enumerate(states) if s == 3) expected = {i for i, s in enumerate(states) if s == 1} require(set(ids(sql_not(universe, true, unknown))) == expected, "Truth oracle") bad_truth += set(ids(universe & ~true)) != expected truth_count += 1 candidate_count = bad_candidate = 0 for states in itertools.product(range(3), repeat=8): # 0 false outside C, 1 false inside C, 2 true inside C. true = {i for i, s in enumerate(states) if s == 2} candidates = {i for i, s in enumerate(states) if s != 0} universe = set(range(8)) actual_negative = universe - true inverted_candidates = universe - candidates require(inverted_candidates <= actual_negative, "Complement reverses inclusion") require(actual_negative - inverted_candidates == candidates - true, "Lost rows") require(inverted_candidates & actual_negative == inverted_candidates, "Recheck cannot add") bad_candidate += inverted_candidates != actual_negative candidate_count += 1 bounds_count = 0 for states in itertools.product(range(5), repeat=6): # False outside H; false inside H; true H-only; true in L; unknown. universe = mask(range(6)) low = mask(i for i, s in enumerate(states) if s == 3) high = mask(i for i, s in enumerate(states) if s in (1, 2, 3)) true = mask(i for i, s in enumerate(states) if s in (2, 3)) unknown = mask(i for i, s in enumerate(states) if s == 4) false = mask(i for i, s in enumerate(states) if s in (0, 1)) lower_false = universe & ~(high | unknown) upper_false = universe & ~(low | unknown) require(lower_false & ~false == 0 and false & ~upper_false == 0, "Negative bounds") require(sql_not(universe, true, unknown) == false, "Bound oracle") bounds_count += 1 return { "truth_universe": {"slots": 8, "configurations": truth_count, "incorrect_if_unknown_mask_omitted": bad_truth}, "candidate_complement": {"slots": 8, "configurations": candidate_count, "incomplete_negative_result": bad_candidate}, "dual_bounds": {"slots": 6, "configurations": bounds_count}, } def setup(conn): conn.executescript("CREATE TABLE t(id INTEGER PRIMARY KEY, x INTEGER);" "CREATE TABLE rhs(value INTEGER); INSERT INTO rhs VALUES(5),(NULL);") conn.executemany("INSERT INTO t VALUES (?,?)", ROWS) def selected(conn, expression): return [row[0] for row in conn.execute( "SELECT id FROM t WHERE (" + expression + ") ORDER BY id")] def observe(conn, expression): rows = [list(r) for r in conn.execute("SELECT id,x FROM t ORDER BY id")] truth = [list(r) for r in conn.execute( "SELECT id,(" + expression + ") FROM t ORDER BY id")] universe = mask(r[0] for r in rows) true = mask(r[0] for r in truth if r[1] == 1) unknown = mask(r[0] for r in truth if r[1] is None) negative = selected(conn, "NOT (" + expression + ")") not_true = selected(conn, "(" + expression + ") IS NOT TRUE") require(ids(sql_not(universe, true, unknown)) == negative, "Native NOT mismatch") require(ids(universe & ~true) == not_true, "Native IS NOT TRUE mismatch") return {"rows": rows, "truth_values": truth, "universe": ids(universe), "true": ids(true), "unknown": ids(unknown), "sql_not": negative, "sql_is_not_true": not_true} def native_matrix(): result = [] conn = sqlite3.connect(":memory:", isolation_level=None) try: setup(conn) for indexed in (False, True): if indexed: conn.execute("CREATE INDEX t_x ON t(x)") for name, expression in PREDICATES.items(): result.append({"index_present": indexed, "predicate": name, "expression": expression, **observe(conn, expression)}) finally: conn.close() return result def native_candidate_case(): conn = sqlite3.connect(":memory:", isolation_level=None) try: setup(conn) conn.executescript("CREATE TABLE candidate(id INTEGER PRIMARY KEY);" "INSERT INTO candidate VALUES(0),(2);") actual = selected(conn, "NOT (x=5)") inverted = selected(conn, "x IS NOT NULL AND id NOT IN (SELECT id FROM candidate)") rechecked = selected(conn, "NOT (x=5) AND id NOT IN (SELECT id FROM candidate)") refined = selected(conn, "x IS NOT NULL AND id NOT IN " "(SELECT t.id FROM t JOIN candidate USING(id) WHERE x=5)") require(actual == [2, 6] and inverted == [6], "Candidate fixture") require(rechecked == [6] and refined == actual, "Candidate refinement") return {"positive_true": selected(conn, "x=5"), "positive_candidate": [r[0] for r in conn.execute("SELECT id FROM candidate ORDER BY id")], "unknown": selected(conn, "x IS NULL"), "native_negative": actual, "inverted_candidate_with_unknown_removed": inverted, "native_rechecked_survivors": rechecked, "native_negative_after_refining_positive_candidate": refined} finally: conn.close() def snapshot_case(): with tempfile.TemporaryDirectory(prefix="hesela-bitmap-negation-") as temp: path = str(Path(temp) / "probe.db") writer = sqlite3.connect(path, isolation_level=None) reader = sqlite3.connect(path, isolation_level=None) try: require(writer.execute("PRAGMA journal_mode=WAL").fetchone()[0] == "wal", "WAL required") setup(writer) reader.execute("BEGIN") before = observe(reader, "x = 5") # First read establishes the snapshot. writer.executescript("BEGIN IMMEDIATE;" "UPDATE t SET x=5 WHERE id=2;" "DELETE FROM t WHERE id=6;" "INSERT INTO t VALUES(3,7);" "UPDATE t SET x=7 WHERE id=4; COMMIT;") held = observe(reader, "x = 5") current = observe(writer, "x = 5") require(before == held, "Reader snapshot changed") reader.execute("COMMIT") after = observe(reader, "x = 5") require(after == current, "Released reader did not see committed state") states = [before, current] mixes = [] for e, t, n in itertools.product(range(2), repeat=3): # Deliberate application error: combine exports from different snapshots. universe = mask(states[e]["universe"]) true = mask(states[t]["true"]) unknown = mask(states[n]["unknown"]) mixed = ids(universe & ~(true | unknown)) desired = set(current["sql_not"]) placeholders = ",".join("?" for _ in mixed) or "NULL" rechecked = [r[0] for r in writer.execute( "SELECT id FROM t WHERE NOT (x=5) AND id IN (" + placeholders + ") ORDER BY id", mixed)] require(rechecked == sorted(set(mixed) & desired), "Native restricted recheck differs from set oracle") mixes.append({"universe_snapshot": e, "true_snapshot": t, "unknown_snapshot": n, "mixed_result": mixed, "current_false_positives": sorted(set(mixed) - desired), "current_missing_rows": sorted(desired - set(mixed)), "after_current_predicate_recheck": rechecked}) return {"before": before, "held_after_commit": held, "current": current, "reader_after_release": after, "mixed_masks": mixes} finally: reader.close() writer.close() def collect(): conn = sqlite3.connect(":memory:") try: source_id = conn.execute("SELECT sqlite_source_id()").fetchone()[0] options = [r[0] for r in conn.execute("PRAGMA compile_options")] finally: conn.close() return { "schema_version": 1, "evidence_kind": "synthetic_finite_model_and_native_sqlite_semantics", "environment": {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqlite_source_id": source_id, "compile_options": options}, "exhaustive": exhaustive(), "native_predicates": native_matrix(), "native_candidate_complement": native_candidate_case(), "wal_snapshots": snapshot_case(), } def serialize(value): return json.dumps(value, indent=2, sort_keys=True) + "\n" def main(): parser = argparse.ArgumentParser() parser.add_argument("--output", type=Path) parser.add_argument("--verify", type=Path) args = parser.parse_args() result = collect() if args.verify: expected = json.loads(args.verify.read_text()) require(result == expected, "Evidence differs, including environment") print("Exact replay passed") if args.output: args.output.write_text(serialize(result)) if not args.output and not args.verify: print(serialize(result), end="") if __name__ == "__main__": main()