Download scripts/verify_sqlite_bundles.py from mokner99/environmentexpander-20261118: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/mokner99/environmentexpander-20261118/resolve/main/scripts/verify_sqlite_bundles.py
- Command line
-
hf download hf://datasets/mokner99/environmentexpander-20261118/scripts/verify_sqlite_bundles.py
-
curl -L -o verify_sqlite_bundles.py https://huggingface.co/datasets/mokner99/environmentexpander-20261118/resolve/main/scripts/verify_sqlite_bundles.py
12.9 kB
| """Run the SQLite bundle acceptance probes against the three saved audit fixtures.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import shutil | |
| import sqlite3 | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| def cli(*args, status=0): | |
| result = subprocess.run( | |
| [sys.executable, "-m", "expander.cli", *map(str, args)], | |
| capture_output=True, | |
| text=True, | |
| check=False, | |
| ) | |
| if result.returncode != status: | |
| raise RuntimeError(result.stderr or result.stdout) | |
| return result.stdout if status in (0, 1) else result.stderr | |
| def configure(recipe, budgets, owned, references, overrides): | |
| entities = {entity["table"]: entity for entity in recipe["entities"]} | |
| for table, count in budgets.items(): | |
| entities[table]["target_count"] += count | |
| for rule in owned: | |
| for field in rule["fields"] | rule.get("copied_fields", {}): | |
| entities[rule["child"]]["generators"][field] = {"kind": "bound"} | |
| for total in rule.get("totals", []): | |
| entities[rule["parent"]]["generators"][total["field"]] = {"kind": "bound"} | |
| for rule in references: | |
| for field in rule["fields"]: | |
| entities[rule["table"]]["generators"][field] = {"kind": "bound"} | |
| for (table, field), settings in overrides.items(): | |
| entities[table]["generators"][field].update(settings) | |
| recipe["owned_children"] = owned | |
| recipe["eligible_references"] = references | |
| def ownership(id_, parent, child, fields, count, total=None, coverage=None): | |
| return { | |
| "id": id_, | |
| "parent": parent, | |
| "child": child, | |
| "fields": fields, | |
| "source": "schema", | |
| "evidence": "Declared SQLite foreign key", | |
| "confirmed": True, | |
| "count": count, | |
| "totals": [total] if total else [], | |
| "coverage": coverage or [], | |
| } | |
| def reference(id_, table, target, fields, scope, evidence): | |
| return { | |
| "id": id_, | |
| "table": table, | |
| "target_table": target, | |
| "fields": fields, | |
| "scope": scope, | |
| "source": "manual", | |
| "evidence": evidence, | |
| "confirmed": True, | |
| } | |
| def total(field, *factors): | |
| return {"field": field, "factors": factors, "precision": 2, "rounding": "half_up"} | |
| def fixture_specs(root): | |
| with sqlite3.connect(root / "chinook.sqlite") as db: | |
| seed_invoice = db.execute("SELECT max(InvoiceId) FROM Invoice").fetchone()[0] | |
| seed_line = db.execute("SELECT max(InvoiceLineId) FROM InvoiceLine").fetchone()[0] | |
| chinook_checks = { | |
| "wrong_total": f""" | |
| SELECT count(*) FROM ( | |
| SELECT i.InvoiceId FROM Invoice i LEFT JOIN InvoiceLine l USING (InvoiceId) | |
| WHERE i.InvoiceId > {seed_invoice} OR l.InvoiceLineId > {seed_line} | |
| GROUP BY i.InvoiceId HAVING i.Total != round(coalesce(sum(l.UnitPrice*l.Quantity),0),2) | |
| ) | |
| """, | |
| "affected_seed": f""" | |
| SELECT count(*) FROM InvoiceLine | |
| WHERE InvoiceId <= {seed_invoice} AND InvoiceLineId > {seed_line} | |
| """, | |
| "wrong_price": f""" | |
| SELECT count(*) FROM InvoiceLine l JOIN Track t USING (TrackId) | |
| WHERE l.InvoiceLineId > {seed_line} AND l.UnitPrice != t.UnitPrice | |
| """, | |
| } | |
| yield { | |
| "name": "chinook", | |
| "file": "chinook.sqlite", | |
| "budgets": {"Invoice": 100, "InvoiceLine": 500}, | |
| "owned": [ | |
| ownership( | |
| "invoice-lines", | |
| "Invoice", | |
| "InvoiceLine", | |
| {"InvoiceId": "InvoiceId"}, | |
| {"minimum": 1, "maximum": 14, "evidence": "Observed lines per Chinook invoice"}, | |
| total("Total", "UnitPrice", "Quantity"), | |
| [{"parent_fields": ["BillingCountry"], "child_fields": ["UnitPrice"]}], | |
| ) | |
| ], | |
| "refs": [ | |
| reference( | |
| "track-price", | |
| "InvoiceLine", | |
| "Track", | |
| {"TrackId": "TrackId", "UnitPrice": "UnitPrice"}, | |
| "seed", | |
| "New lines in this probe use the reference track's catalog price", | |
| ) | |
| ], | |
| "overrides": {}, | |
| "child_counts": { | |
| "invoice-lines": f""" | |
| SELECT count(l.InvoiceLineId) AS n | |
| FROM Invoice i LEFT JOIN InvoiceLine l USING (InvoiceId) | |
| WHERE i.InvoiceId > {seed_invoice} GROUP BY i.InvoiceId | |
| """, | |
| }, | |
| "checks": chinook_checks, | |
| "corruptions": { | |
| "wrong_total": f"UPDATE Invoice SET Total=Total+1 WHERE InvoiceId={seed_invoice + 1}", | |
| "affected_seed": f"UPDATE InvoiceLine SET InvoiceId={seed_invoice} WHERE InvoiceLineId={seed_line + 1}", | |
| "wrong_price": f"UPDATE InvoiceLine SET UnitPrice=UnitPrice+1 WHERE InvoiceLineId={seed_line + 1}", | |
| }, | |
| } | |
| yield { | |
| "name": "telecom", | |
| "file": "telecom-minimal.sqlite", | |
| "budgets": {"customer": 20, "bill": 20, "bill_item": 50, "device": 30, "line": 30}, | |
| "owned": [ | |
| ownership( | |
| "bill-items", | |
| "bill", | |
| "bill_item", | |
| {"bill_id": "id"}, | |
| { | |
| "minimum": 0, | |
| "maximum": 4, | |
| "weights": {0: 1, 1: 2, 2: 2, 3: 2, 4: 3}, | |
| "evidence": "Reviewed probe weights for sparse projection, including empty bills", | |
| }, | |
| total("total", "amount"), | |
| [{"parent_fields": ["status"]}], | |
| ), | |
| ownership( | |
| "assigned-device", | |
| "device", | |
| "line", | |
| {"device_id": "id"}, | |
| { | |
| "minimum": 1, | |
| "maximum": 1, | |
| "evidence": "Probe policy: dedicate one device to each new line", | |
| }, | |
| ), | |
| ], | |
| "refs": [], | |
| "overrides": {("bill", "customer_id"): {"reference_scope": "generated"}}, | |
| "child_counts": { | |
| "bill-items": """ | |
| SELECT count(i.id) AS n FROM bill b LEFT JOIN bill_item i ON i.bill_id=b.id | |
| WHERE b.id LIKE 'expanded-%' GROUP BY b.id | |
| """, | |
| "assigned-device": """ | |
| SELECT count(l.id) AS n FROM device d LEFT JOIN line l ON l.device_id=d.id | |
| WHERE d.id LIKE 'expanded-%' GROUP BY d.id | |
| """, | |
| }, | |
| "checks": { | |
| "wrong_total": """ | |
| SELECT count(*) FROM ( | |
| SELECT b.id FROM bill b LEFT JOIN bill_item i ON i.bill_id=b.id | |
| GROUP BY b.id HAVING b.total != round(coalesce(sum(i.amount),0),2) | |
| ) | |
| """, | |
| "affected_seed": """ | |
| SELECT count(*) FROM bill_item WHERE id>12 AND bill_id NOT LIKE 'expanded-%' | |
| """, | |
| "reused_device": """ | |
| SELECT count(*) FROM line WHERE id LIKE 'expanded-%' AND device_id NOT LIKE 'expanded-%' | |
| """, | |
| }, | |
| "corruptions": { | |
| "wrong_total": """ | |
| UPDATE bill SET total=total+1 | |
| WHERE id=(SELECT min(id) FROM bill WHERE id LIKE 'expanded-%') | |
| """, | |
| "affected_seed": "UPDATE bill_item SET bill_id='B1001' WHERE id=13", | |
| "reused_device": """ | |
| UPDATE line SET device_id=(SELECT min(id) FROM device WHERE id NOT LIKE 'expanded-%') | |
| WHERE id=(SELECT min(id) FROM line WHERE id LIKE 'expanded-%') | |
| """, | |
| }, | |
| } | |
| yield { | |
| "name": "banking", | |
| "file": "bank-ownership-projection.sqlite", | |
| "budgets": {"person": 20, "account": 30, "payment": 100}, | |
| "owned": [], | |
| "refs": [ | |
| reference( | |
| "payment-account-owner", | |
| "payment", | |
| "account", | |
| {"account_id": "id", "owner_id": "owner_id"}, | |
| "generated", | |
| "The card account determines the payment owner; the projection has two independent foreign keys", | |
| ) | |
| ], | |
| "overrides": {("account", "owner_id"): {"reference_scope": "generated"}}, | |
| "child_counts": {}, | |
| "checks": { | |
| "wrong_owner": """ | |
| SELECT count(*) FROM payment p JOIN account a ON a.id=p.account_id | |
| WHERE p.owner_id != a.owner_id | |
| """, | |
| "wrong_scope": """ | |
| SELECT count(*) FROM payment WHERE id LIKE 'expanded-%' AND account_id NOT LIKE 'expanded-%' | |
| """, | |
| }, | |
| "corruptions": { | |
| "wrong_owner": """ | |
| UPDATE payment SET owner_id=(SELECT min(id) FROM person WHERE id != payment.owner_id) | |
| WHERE id=(SELECT min(id) FROM payment WHERE id LIKE 'expanded-%') | |
| """, | |
| "wrong_scope": """ | |
| UPDATE payment SET | |
| account_id=(SELECT min(id) FROM account WHERE id NOT LIKE 'expanded-%'), | |
| owner_id=(SELECT owner_id FROM account WHERE id NOT LIKE 'expanded-%' ORDER BY id LIMIT 1) | |
| WHERE id=(SELECT min(id) FROM payment WHERE id LIKE 'expanded-%') | |
| """, | |
| }, | |
| } | |
| def probe(root, destination, spec): | |
| source = root / spec["file"] | |
| source_hash = hashlib.sha256(source.read_bytes()).hexdigest() | |
| target = destination / spec["name"] | |
| target.mkdir() | |
| environment = target / "environment" | |
| recipe_file = environment / "recipe.json" | |
| cli("import", source, environment) | |
| recipe = json.loads(recipe_file.read_text()) | |
| configure(recipe, spec["budgets"], spec["owned"], spec["refs"], spec["overrides"]) | |
| recipe_file.write_text(json.dumps(recipe, indent=2) + "\n") | |
| builds = target / "builds" | |
| build = json.loads(cli("build", environment, recipe_file, "--no-model", "--output", builds)) | |
| clean = builds / build["id"] / "clean.sqlite" | |
| child_counts = {} | |
| schema = "SELECT type,name,tbl_name,sql FROM sqlite_schema ORDER BY name" | |
| with sqlite3.connect(clean) as db, sqlite3.connect(source) as original: | |
| assert db.execute(schema).fetchall() == original.execute(schema).fetchall() | |
| assert not db.execute("PRAGMA foreign_key_check").fetchall() | |
| counts = {name: db.execute(sql).fetchone()[0] for name, sql in spec["checks"].items()} | |
| assert not any(counts.values()), counts | |
| for name, sql in spec["child_counts"].items(): | |
| rows = db.execute( | |
| f"SELECT n, count(*) FROM ({sql}) AS allocations GROUP BY n ORDER BY n" | |
| ).fetchall() | |
| child_counts[name] = {str(n): count for n, count in rows} | |
| for table, added in spec["budgets"].items(): | |
| quoted = '"' + table.replace('"', '""') + '"' | |
| sql = f"SELECT count(*) FROM {quoted}" | |
| assert db.execute(sql).fetchone()[0] - original.execute(sql).fetchone()[0] == added | |
| assert child_counts == { | |
| check["id"]: check["generated_child_counts"] | |
| for check in build["report"]["joined_audit"]["owned_children"] | |
| } | |
| assert json.loads(cli("audit", environment, recipe_file, clean))["hard_pass"] | |
| corruptions = {} | |
| for name, edit in spec["corruptions"].items(): | |
| corrupt = target / f"{name}.sqlite" | |
| shutil.copyfile(clean, corrupt) | |
| with sqlite3.connect(corrupt) as db: | |
| db.execute(edit) | |
| assert not db.execute("PRAGMA foreign_key_check").fetchall() | |
| corruptions[name] = db.execute(spec["checks"][name]).fetchone()[0] | |
| assert corruptions[name] > 0 | |
| audit = json.loads(cli("audit", environment, recipe_file, corrupt, status=1)) | |
| assert not audit["joined"]["hard_pass"] | |
| (target / f"{name}-audit.json").write_text(json.dumps(audit, indent=2) + "\n") | |
| assert hashlib.sha256(source.read_bytes()).hexdigest() == source_hash | |
| return { | |
| "source_sha256": source_hash, | |
| "build": str(clean), | |
| "added": spec["budgets"], | |
| "independent_sql_violations": counts, | |
| "deliberate_corruptions_detected": corruptions, | |
| "independent_sql_child_counts": child_counts, | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "audit_fixtures", type=Path, help="Directory containing the three audited databases" | |
| ) | |
| parser.add_argument( | |
| "destination", type=Path, help="New directory for build and corruption receipts" | |
| ) | |
| args = parser.parse_args() | |
| args.destination.mkdir(parents=True) | |
| receipts = { | |
| spec["name"]: probe(args.audit_fixtures, args.destination, spec) | |
| for spec in fixture_specs(args.audit_fixtures) | |
| } | |
| (args.destination / "verification.json").write_text(json.dumps(receipts, indent=2) + "\n") | |
| print(json.dumps(receipts, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |