File size: 12,939 Bytes
ff376c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""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()