sqlprove 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlprove/__init__.py +28 -0
- sqlprove/algebra.py +1302 -0
- sqlprove/audit.py +347 -0
- sqlprove/cli.py +281 -0
- sqlprove/corpus.py +448 -0
- sqlprove/cost.py +92 -0
- sqlprove/dbt_manifest.py +582 -0
- sqlprove/fuzzer.py +312 -0
- sqlprove/prover.py +1568 -0
- sqlprove/rewrites.py +819 -0
- sqlprove/schema.py +430 -0
- sqlprove/targets.py +482 -0
- sqlprove-0.1.0.dist-info/LICENSE +21 -0
- sqlprove-0.1.0.dist-info/METADATA +99 -0
- sqlprove-0.1.0.dist-info/RECORD +18 -0
- sqlprove-0.1.0.dist-info/WHEEL +5 -0
- sqlprove-0.1.0.dist-info/entry_points.txt +2 -0
- sqlprove-0.1.0.dist-info/top_level.txt +1 -0
sqlprove/audit.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""End-to-end dbt manifest audit orchestrator: compiled SQL + view unfolding + formal proof + warehouse gating."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from sqlprove.dbt_manifest import (
|
|
10
|
+
DbtManifest,
|
|
11
|
+
build_schema_for_query,
|
|
12
|
+
load_dbt_manifest,
|
|
13
|
+
unfold_upstream_views,
|
|
14
|
+
)
|
|
15
|
+
from sqlprove.prover import ProofStatus
|
|
16
|
+
from sqlprove.rewrites import (
|
|
17
|
+
RewriteCandidate,
|
|
18
|
+
only_verified,
|
|
19
|
+
verify_rewrites,
|
|
20
|
+
verify_rewrites_with_ctes,
|
|
21
|
+
)
|
|
22
|
+
from sqlprove.schema import DbtModelConstraints, load_dbt_schema_constraints
|
|
23
|
+
from sqlprove.targets import TargetDecision, WarehouseTarget
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class ModelAuditFinding:
|
|
28
|
+
model_name: str
|
|
29
|
+
file_path: str
|
|
30
|
+
materialized: str
|
|
31
|
+
unfolded_views: tuple[str, ...]
|
|
32
|
+
skipped_views: tuple[str, ...]
|
|
33
|
+
recommended: tuple[RewriteCandidate, ...]
|
|
34
|
+
neutral: tuple[RewriteCandidate, ...]
|
|
35
|
+
blocked: tuple[RewriteCandidate, ...]
|
|
36
|
+
unsafe_counterexamples: int
|
|
37
|
+
unsupported: int
|
|
38
|
+
error: str | None = None
|
|
39
|
+
|
|
40
|
+
def to_dict(self) -> dict[str, Any]:
|
|
41
|
+
def _ser(c: RewriteCandidate) -> dict[str, Any]:
|
|
42
|
+
return {
|
|
43
|
+
"rule": c.rule,
|
|
44
|
+
"proof_status": c.verification.status.value,
|
|
45
|
+
"proof_rule": c.verification.rule_name,
|
|
46
|
+
"proof_reason": c.verification.reason,
|
|
47
|
+
"target_decision": c.target_advice.decision.value if c.target_advice else None,
|
|
48
|
+
"expected_impact": c.target_advice.expected_impact if c.target_advice else None,
|
|
49
|
+
"target_rationale": c.target_advice.rationale if c.target_advice else None,
|
|
50
|
+
"rewritten_sql": c.rewritten_sql,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
"model_name": self.model_name,
|
|
55
|
+
"file_path": self.file_path,
|
|
56
|
+
"materialized": self.materialized,
|
|
57
|
+
"unfolded_views": list(self.unfolded_views),
|
|
58
|
+
"skipped_views": list(self.skipped_views),
|
|
59
|
+
"recommended": [_ser(c) for c in self.recommended],
|
|
60
|
+
"neutral": [_ser(c) for c in self.neutral],
|
|
61
|
+
"blocked": [_ser(c) for c in self.blocked],
|
|
62
|
+
"unsafe_counterexamples": self.unsafe_counterexamples,
|
|
63
|
+
"unsupported": self.unsupported,
|
|
64
|
+
"error": self.error,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class ManifestAuditReport:
|
|
70
|
+
manifest_path: str
|
|
71
|
+
target: WarehouseTarget
|
|
72
|
+
dialect: str
|
|
73
|
+
models_total: int
|
|
74
|
+
models_compiled: int
|
|
75
|
+
models_audited: int
|
|
76
|
+
models_with_recommended: int
|
|
77
|
+
total_recommended: int
|
|
78
|
+
total_neutral: int
|
|
79
|
+
total_blocked_by_target: int
|
|
80
|
+
total_unsafe_counterexamples: int
|
|
81
|
+
total_unsupported: int
|
|
82
|
+
findings: tuple[ModelAuditFinding, ...]
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict[str, Any]:
|
|
85
|
+
return {
|
|
86
|
+
"manifest_path": self.manifest_path,
|
|
87
|
+
"target": self.target.value,
|
|
88
|
+
"dialect": self.dialect,
|
|
89
|
+
"summary": {
|
|
90
|
+
"models_total": self.models_total,
|
|
91
|
+
"models_compiled": self.models_compiled,
|
|
92
|
+
"models_audited": self.models_audited,
|
|
93
|
+
"models_with_recommended": self.models_with_recommended,
|
|
94
|
+
"total_recommended": self.total_recommended,
|
|
95
|
+
"total_neutral": self.total_neutral,
|
|
96
|
+
"total_blocked_by_target": self.total_blocked_by_target,
|
|
97
|
+
"total_unsafe_counterexamples": self.total_unsafe_counterexamples,
|
|
98
|
+
"total_unsupported": self.total_unsupported,
|
|
99
|
+
},
|
|
100
|
+
"findings": [f.to_dict() for f in self.findings],
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
def to_text(self, *, show_all: bool = False) -> str:
|
|
104
|
+
lines = [
|
|
105
|
+
f"sqlprove audit — target={self.target.value} dialect={self.dialect}",
|
|
106
|
+
f"Manifest: {self.manifest_path}",
|
|
107
|
+
(
|
|
108
|
+
f"Models: {self.models_audited}/{self.models_total} audited ({self.models_compiled} compiled) | "
|
|
109
|
+
f"RECOMMENDED: {self.total_recommended} (across {self.models_with_recommended} models) | "
|
|
110
|
+
f"NEUTRAL: {self.total_neutral} | BLOCKED(target): {self.total_blocked_by_target} | "
|
|
111
|
+
f"UNSAFE(counterexample): {self.total_unsafe_counterexamples}"
|
|
112
|
+
),
|
|
113
|
+
"",
|
|
114
|
+
]
|
|
115
|
+
shown = 0
|
|
116
|
+
for f in self.findings:
|
|
117
|
+
cands = list(f.recommended)
|
|
118
|
+
if show_all:
|
|
119
|
+
cands.extend(f.neutral)
|
|
120
|
+
cands.extend(f.blocked)
|
|
121
|
+
if not cands:
|
|
122
|
+
continue
|
|
123
|
+
shown += 1
|
|
124
|
+
unfold_note = f" [unfolded views: {', '.join(f.unfolded_views)}]" if f.unfolded_views else ""
|
|
125
|
+
lines.append(f"Model: {f.model_name} ({f.file_path}, {f.materialized}){unfold_note}")
|
|
126
|
+
for c in cands:
|
|
127
|
+
dec = c.target_advice.decision.value if c.target_advice else "VERIFIED"
|
|
128
|
+
imp = c.target_advice.expected_impact if c.target_advice else ""
|
|
129
|
+
lines.append(
|
|
130
|
+
f" [{dec:11s}] [{c.verification.status.value}] {c.rule}"
|
|
131
|
+
)
|
|
132
|
+
if imp:
|
|
133
|
+
lines.append(f" Impact : {imp}")
|
|
134
|
+
lines.append(f" Proof : {c.verification.reason}")
|
|
135
|
+
lines.append(f" SQL : {c.rewritten_sql}")
|
|
136
|
+
lines.append("")
|
|
137
|
+
if shown == 0:
|
|
138
|
+
lines.append("No target-recommended verified rewrites found (use --show-all to inspect neutral/blocked verified rewrites).")
|
|
139
|
+
return "\n".join(lines).rstrip()
|
|
140
|
+
|
|
141
|
+
def to_markdown(self, *, show_all: bool = False) -> str:
|
|
142
|
+
lines = [
|
|
143
|
+
f"## `sqlprove` Audit Report (`target={self.target.value}`, `dialect={self.dialect}`)",
|
|
144
|
+
"",
|
|
145
|
+
f"- **Models audited:** {self.models_audited} / {self.models_total} ({self.models_compiled} compiled)",
|
|
146
|
+
f"- **Recommended verified rewrites:** **{self.total_recommended}** across **{self.models_with_recommended}** model(s)",
|
|
147
|
+
f"- **Neutral on `{self.target.value}`:** {self.total_neutral} | **Blocked (measured regression):** {self.total_blocked_by_target}",
|
|
148
|
+
f"- **Unsafe candidates auto-blocked (`COUNTEREXAMPLE_FOUND`):** {self.total_unsafe_counterexamples}",
|
|
149
|
+
"",
|
|
150
|
+
]
|
|
151
|
+
rows: list[str] = []
|
|
152
|
+
for f in self.findings:
|
|
153
|
+
cands = list(f.recommended) + (list(f.neutral) + list(f.blocked) if show_all else [])
|
|
154
|
+
for c in cands:
|
|
155
|
+
dec = c.target_advice.decision.value if c.target_advice else "VERIFIED"
|
|
156
|
+
imp = c.target_advice.expected_impact if c.target_advice else ""
|
|
157
|
+
rows.append(
|
|
158
|
+
f"| `{f.model_name}` | `{dec}` | `{c.verification.status.value}` | `{c.rule}` | {imp} |"
|
|
159
|
+
)
|
|
160
|
+
if rows:
|
|
161
|
+
lines.extend(
|
|
162
|
+
[
|
|
163
|
+
"| Model | Target Verdict | Proof Tier | Rewrite Rule | Expected Warehouse Impact |",
|
|
164
|
+
"|---|---|---|---|---|",
|
|
165
|
+
*rows,
|
|
166
|
+
]
|
|
167
|
+
)
|
|
168
|
+
else:
|
|
169
|
+
lines.append("_No target-recommended verified rewrites found._")
|
|
170
|
+
return "\n".join(lines)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _infer_dialect(target: WarehouseTarget, manifest: DbtManifest, explicit_dialect: str | None) -> str:
|
|
174
|
+
if explicit_dialect:
|
|
175
|
+
return explicit_dialect
|
|
176
|
+
if target != WarehouseTarget.ALL:
|
|
177
|
+
return target.default_dialect
|
|
178
|
+
adapter = (manifest.adapter_type or "").lower()
|
|
179
|
+
if adapter in ("bigquery", "snowflake", "duckdb", "postgres", "redshift", "spark", "databricks", "trino"):
|
|
180
|
+
return adapter
|
|
181
|
+
return "duckdb"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def resolve_manifest_path(path: str | Path) -> Path:
|
|
185
|
+
"""Accept either a manifest.json file or a dbt project directory containing target/manifest.json."""
|
|
186
|
+
p = Path(path)
|
|
187
|
+
if p.is_file():
|
|
188
|
+
return p
|
|
189
|
+
cand = p / "target" / "manifest.json"
|
|
190
|
+
if cand.is_file():
|
|
191
|
+
return cand
|
|
192
|
+
raise FileNotFoundError(
|
|
193
|
+
f"Could not find dbt manifest.json at '{p}' or '{cand}'. Run `dbt compile` first."
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def audit_dbt_manifest(
|
|
198
|
+
path: str | Path,
|
|
199
|
+
*,
|
|
200
|
+
target: WarehouseTarget | str = WarehouseTarget.ALL,
|
|
201
|
+
dialect: str | None = None,
|
|
202
|
+
models: set[str] | None = None,
|
|
203
|
+
unfold_views: bool = True,
|
|
204
|
+
extra_dbt_schema: str | Path | None = None,
|
|
205
|
+
bound: int = 2,
|
|
206
|
+
timeout_ms: int = 5_000,
|
|
207
|
+
confirm_in_duckdb: bool = True,
|
|
208
|
+
) -> ManifestAuditReport:
|
|
209
|
+
"""Audit compiled models in a dbt `target/manifest.json` with formal proofs and warehouse gating."""
|
|
210
|
+
tgt = target if isinstance(target, WarehouseTarget) else WarehouseTarget(target)
|
|
211
|
+
manifest_path = resolve_manifest_path(path)
|
|
212
|
+
manifest = load_dbt_manifest(manifest_path)
|
|
213
|
+
eff_dialect = _infer_dialect(tgt, manifest, dialect)
|
|
214
|
+
|
|
215
|
+
extra_constraints: dict[str, DbtModelConstraints] | None = None
|
|
216
|
+
if extra_dbt_schema is not None:
|
|
217
|
+
extra_constraints = load_dbt_schema_constraints(extra_dbt_schema)
|
|
218
|
+
|
|
219
|
+
selected = sorted(manifest.models.values(), key=lambda m: (m.original_file_path, m.name))
|
|
220
|
+
if models:
|
|
221
|
+
wanted = {m.strip().lower() for m in models if m.strip()}
|
|
222
|
+
selected = [m for m in selected if m.name.lower() in wanted or m.alias.lower() in wanted]
|
|
223
|
+
|
|
224
|
+
findings: list[ModelAuditFinding] = []
|
|
225
|
+
models_compiled = 0
|
|
226
|
+
models_audited = 0
|
|
227
|
+
|
|
228
|
+
for model in selected:
|
|
229
|
+
if not model.compiled_sql or not model.compiled_sql.strip():
|
|
230
|
+
findings.append(
|
|
231
|
+
ModelAuditFinding(
|
|
232
|
+
model_name=model.name,
|
|
233
|
+
file_path=model.original_file_path,
|
|
234
|
+
materialized=model.materialized,
|
|
235
|
+
unfolded_views=(),
|
|
236
|
+
skipped_views=(),
|
|
237
|
+
recommended=(),
|
|
238
|
+
neutral=(),
|
|
239
|
+
blocked=(),
|
|
240
|
+
unsafe_counterexamples=0,
|
|
241
|
+
unsupported=0,
|
|
242
|
+
error="Not compiled (run `dbt compile` to populate compiled_code)",
|
|
243
|
+
)
|
|
244
|
+
)
|
|
245
|
+
continue
|
|
246
|
+
|
|
247
|
+
models_compiled += 1
|
|
248
|
+
all_cands: list[RewriteCandidate] = []
|
|
249
|
+
unfolded_views: tuple[str, ...] = ()
|
|
250
|
+
skipped_views: tuple[str, ...] = ()
|
|
251
|
+
parse_err: str | None = None
|
|
252
|
+
|
|
253
|
+
try:
|
|
254
|
+
# 1. Single-model + own-CTE rewrites on compiled SQL
|
|
255
|
+
base_schema = build_schema_for_query(
|
|
256
|
+
model.compiled_sql,
|
|
257
|
+
manifest,
|
|
258
|
+
dialect=eff_dialect,
|
|
259
|
+
extra_dbt_constraints=extra_constraints,
|
|
260
|
+
)
|
|
261
|
+
if base_schema is not None:
|
|
262
|
+
all_cands.extend(
|
|
263
|
+
verify_rewrites_with_ctes(
|
|
264
|
+
model.compiled_sql,
|
|
265
|
+
base_schema,
|
|
266
|
+
dialect=eff_dialect,
|
|
267
|
+
target=tgt,
|
|
268
|
+
bound=bound,
|
|
269
|
+
timeout_ms=timeout_ms,
|
|
270
|
+
confirm_in_duckdb=confirm_in_duckdb,
|
|
271
|
+
)
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
# 2. Cross-model view unfolding (top-level rewrites only to avoid duplicating upstream view rules)
|
|
275
|
+
if unfold_views:
|
|
276
|
+
unfolded = unfold_upstream_views(model, manifest, dialect=eff_dialect)
|
|
277
|
+
unfolded_views = unfolded.unfolded_views
|
|
278
|
+
skipped_views = unfolded.skipped_views
|
|
279
|
+
if unfolded_views and unfolded.sql:
|
|
280
|
+
unfolded_schema = build_schema_for_query(
|
|
281
|
+
unfolded.sql,
|
|
282
|
+
manifest,
|
|
283
|
+
dialect=eff_dialect,
|
|
284
|
+
extra_dbt_constraints=extra_constraints,
|
|
285
|
+
)
|
|
286
|
+
if unfolded_schema is not None:
|
|
287
|
+
seen_sql = {c.rewritten_sql for c in all_cands}
|
|
288
|
+
for c in verify_rewrites(
|
|
289
|
+
unfolded.sql,
|
|
290
|
+
unfolded_schema,
|
|
291
|
+
dialect=eff_dialect,
|
|
292
|
+
target=tgt,
|
|
293
|
+
bound=bound,
|
|
294
|
+
timeout_ms=timeout_ms,
|
|
295
|
+
confirm_in_duckdb=confirm_in_duckdb,
|
|
296
|
+
):
|
|
297
|
+
if c.rewritten_sql not in seen_sql:
|
|
298
|
+
all_cands.append(c)
|
|
299
|
+
seen_sql.add(c.rewritten_sql)
|
|
300
|
+
models_audited += 1
|
|
301
|
+
except Exception as exc:
|
|
302
|
+
parse_err = f"{type(exc).__name__}: {exc}"
|
|
303
|
+
|
|
304
|
+
verified = only_verified(all_cands)
|
|
305
|
+
rec = tuple(
|
|
306
|
+
c for c in verified if c.target_advice is None or c.target_advice.decision == TargetDecision.RECOMMENDED
|
|
307
|
+
)
|
|
308
|
+
neu = tuple(
|
|
309
|
+
c for c in verified if c.target_advice is not None and c.target_advice.decision == TargetDecision.NEUTRAL
|
|
310
|
+
)
|
|
311
|
+
blk = tuple(
|
|
312
|
+
c for c in verified if c.target_advice is not None and c.target_advice.decision == TargetDecision.BLOCKED
|
|
313
|
+
)
|
|
314
|
+
ce_cnt = sum(1 for c in all_cands if c.verification.status == ProofStatus.COUNTEREXAMPLE_FOUND)
|
|
315
|
+
unsup_cnt = sum(1 for c in all_cands if c.verification.status == ProofStatus.UNSUPPORTED)
|
|
316
|
+
|
|
317
|
+
findings.append(
|
|
318
|
+
ModelAuditFinding(
|
|
319
|
+
model_name=model.name,
|
|
320
|
+
file_path=model.original_file_path,
|
|
321
|
+
materialized=model.materialized,
|
|
322
|
+
unfolded_views=unfolded_views,
|
|
323
|
+
skipped_views=skipped_views,
|
|
324
|
+
recommended=rec,
|
|
325
|
+
neutral=neu,
|
|
326
|
+
blocked=blk,
|
|
327
|
+
unsafe_counterexamples=ce_cnt,
|
|
328
|
+
unsupported=unsup_cnt,
|
|
329
|
+
error=parse_err,
|
|
330
|
+
)
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
return ManifestAuditReport(
|
|
334
|
+
manifest_path=str(manifest_path),
|
|
335
|
+
target=tgt,
|
|
336
|
+
dialect=eff_dialect,
|
|
337
|
+
models_total=len(selected),
|
|
338
|
+
models_compiled=models_compiled,
|
|
339
|
+
models_audited=models_audited,
|
|
340
|
+
models_with_recommended=sum(1 for f in findings if f.recommended),
|
|
341
|
+
total_recommended=sum(len(f.recommended) for f in findings),
|
|
342
|
+
total_neutral=sum(len(f.neutral) for f in findings),
|
|
343
|
+
total_blocked_by_target=sum(len(f.blocked) for f in findings),
|
|
344
|
+
total_unsafe_counterexamples=sum(f.unsafe_counterexamples for f in findings),
|
|
345
|
+
total_unsupported=sum(f.unsupported for f in findings),
|
|
346
|
+
findings=tuple(findings),
|
|
347
|
+
)
|
sqlprove/cli.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""CLI entrypoint for sqlprove."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from sqlprove import __version__
|
|
11
|
+
from sqlprove.audit import audit_dbt_manifest
|
|
12
|
+
from sqlprove.corpus import scan_directory
|
|
13
|
+
from sqlprove.prover import ProofStatus, prove_equivalence
|
|
14
|
+
from sqlprove.rewrites import only_recommended, only_verified, verify_rewrites_with_ctes
|
|
15
|
+
from sqlprove.schema import ColumnSpec, Schema, TableSpec, load_dbt_schema_constraints
|
|
16
|
+
from sqlprove.targets import WarehouseTarget
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _run_demo() -> int:
|
|
20
|
+
schema_with_uk = Schema(
|
|
21
|
+
tables={
|
|
22
|
+
"orders": TableSpec(
|
|
23
|
+
name="orders",
|
|
24
|
+
columns=(
|
|
25
|
+
ColumnSpec("id", nullable=False),
|
|
26
|
+
ColumnSpec("customer_id", nullable=True),
|
|
27
|
+
ColumnSpec("amount", nullable=True),
|
|
28
|
+
),
|
|
29
|
+
primary_key=("id",),
|
|
30
|
+
),
|
|
31
|
+
"customers": TableSpec(
|
|
32
|
+
name="customers",
|
|
33
|
+
columns=(
|
|
34
|
+
ColumnSpec("id", nullable=False),
|
|
35
|
+
ColumnSpec("tier", nullable=True),
|
|
36
|
+
),
|
|
37
|
+
primary_key=("id",),
|
|
38
|
+
),
|
|
39
|
+
"blocked": TableSpec(
|
|
40
|
+
name="blocked",
|
|
41
|
+
columns=(ColumnSpec("customer_id", nullable=True),),
|
|
42
|
+
),
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
schema_no_uk = Schema(
|
|
46
|
+
tables={
|
|
47
|
+
**schema_with_uk.tables,
|
|
48
|
+
"customers": TableSpec(
|
|
49
|
+
name="customers",
|
|
50
|
+
columns=(
|
|
51
|
+
ColumnSpec("id", nullable=True),
|
|
52
|
+
ColumnSpec("tier", nullable=True),
|
|
53
|
+
),
|
|
54
|
+
),
|
|
55
|
+
}
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
cases = [
|
|
59
|
+
(
|
|
60
|
+
"SAFE: Drop unused LEFT JOIN when RHS key is UNIQUE (dbt unique test)",
|
|
61
|
+
schema_with_uk,
|
|
62
|
+
"SELECT o.id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.id",
|
|
63
|
+
"SELECT o.id, o.amount FROM orders o",
|
|
64
|
+
),
|
|
65
|
+
(
|
|
66
|
+
"BUG CAUGHT: Dropping unused LEFT JOIN WITHOUT UNIQUE constraint (join multiplication!)",
|
|
67
|
+
schema_no_uk,
|
|
68
|
+
"SELECT o.id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.id",
|
|
69
|
+
"SELECT o.id, o.amount FROM orders o",
|
|
70
|
+
),
|
|
71
|
+
(
|
|
72
|
+
"BUG CAUGHT: LLM moves LEFT JOIN ON-predicate into WHERE (drops unmatched NULL rows!)",
|
|
73
|
+
schema_with_uk,
|
|
74
|
+
"SELECT o.id FROM orders o LEFT JOIN customers c ON o.customer_id = c.id AND c.tier = 1",
|
|
75
|
+
"SELECT o.id FROM orders o LEFT JOIN customers c ON o.customer_id = c.id WHERE c.tier = 1",
|
|
76
|
+
),
|
|
77
|
+
(
|
|
78
|
+
"BUG CAUGHT: LLM rewrites NOT IN subquery to NOT EXISTS (3-valued NULL trap!)",
|
|
79
|
+
schema_with_uk,
|
|
80
|
+
"SELECT o.id FROM orders o WHERE o.customer_id NOT IN (SELECT b.customer_id FROM blocked b)",
|
|
81
|
+
"SELECT o.id FROM orders o WHERE NOT EXISTS (SELECT 1 FROM blocked b WHERE b.customer_id = o.customer_id)",
|
|
82
|
+
),
|
|
83
|
+
(
|
|
84
|
+
"SAFE: Drop redundant DISTINCT with GROUP BY",
|
|
85
|
+
schema_with_uk,
|
|
86
|
+
"SELECT DISTINCT o.customer_id, COUNT(*) AS n FROM orders o GROUP BY o.customer_id",
|
|
87
|
+
"SELECT o.customer_id, COUNT(*) AS n FROM orders o GROUP BY o.customer_id",
|
|
88
|
+
),
|
|
89
|
+
(
|
|
90
|
+
"BUG CAUGHT: LLM simplifies `x = 1 OR x <> 1` to TRUE (drops NULL rows!)",
|
|
91
|
+
schema_with_uk,
|
|
92
|
+
"SELECT o.id FROM orders o WHERE o.amount = 1 OR o.amount <> 1",
|
|
93
|
+
"SELECT o.id FROM orders o",
|
|
94
|
+
),
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
print("sqlprove demo — Z3 SMT bag-semantics + 3-valued NULL prover + DuckDB confirmation\n")
|
|
98
|
+
for title, schema, q1, q2 in cases:
|
|
99
|
+
res = prove_equivalence(q1, q2, schema, bound=3)
|
|
100
|
+
print(f"=== {title} ===")
|
|
101
|
+
print(f" Status : {res.status.value} ({res.reason})")
|
|
102
|
+
if res.status == ProofStatus.COUNTEREXAMPLE_FOUND:
|
|
103
|
+
print(f" DuckDB : confirmed={res.duckdb_confirmed} | Q1={res.duckdb_q1_rows} vs Q2={res.duckdb_q2_rows}")
|
|
104
|
+
print(f" Inputs : {json.dumps(res.counterexample)}")
|
|
105
|
+
print()
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main(argv: list[str] | None = None) -> int:
|
|
110
|
+
target_choices = [t.value for t in WarehouseTarget]
|
|
111
|
+
parser = argparse.ArgumentParser(prog="sqlprove", description="Proof-carrying SQL cost optimizer")
|
|
112
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
113
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
114
|
+
|
|
115
|
+
sub.add_parser("demo", help="Run built-in Z3 + DuckDB equivalence & LLM bug-catch demo")
|
|
116
|
+
|
|
117
|
+
scan_p = sub.add_parser("scan", help="Scan a raw SQL/dbt directory for optimization patterns")
|
|
118
|
+
scan_p.add_argument("path", type=Path, help="Directory containing .sql files")
|
|
119
|
+
scan_p.add_argument("--dialect", default="bigquery", help="SQL dialect (bigquery, snowflake, duckdb)")
|
|
120
|
+
scan_p.add_argument("--models-only", action="store_true", help="Exclude macros/, tests/, snapshots/, seeds/")
|
|
121
|
+
scan_p.add_argument("--json", action="store_true", help="Output JSON report")
|
|
122
|
+
|
|
123
|
+
prove_p = sub.add_parser("prove", help="Check equivalence of two SQL queries")
|
|
124
|
+
prove_p.add_argument("--q1", required=True, help="Original SQL query")
|
|
125
|
+
prove_p.add_argument("--q2", required=True, help="Rewritten SQL query")
|
|
126
|
+
prove_p.add_argument("--schema", required=True, type=Path, help="Path to schema JSON file")
|
|
127
|
+
prove_p.add_argument(
|
|
128
|
+
"--dbt-schema",
|
|
129
|
+
type=Path,
|
|
130
|
+
default=None,
|
|
131
|
+
help="Optional dbt schema.yml file or directory to overlay unique/not_null/relationships tests",
|
|
132
|
+
)
|
|
133
|
+
prove_p.add_argument("--dialect", default="duckdb")
|
|
134
|
+
prove_p.add_argument("--bound", type=int, default=3)
|
|
135
|
+
|
|
136
|
+
rew_p = sub.add_parser("rewrite", help="Propose, formally verify, and target-gate cost-saving SQL rewrites")
|
|
137
|
+
rew_p.add_argument("--sql", required=True, help="Input SQL query")
|
|
138
|
+
rew_p.add_argument("--schema", required=True, type=Path, help="Path to schema JSON file")
|
|
139
|
+
rew_p.add_argument("--dbt-schema", type=Path, default=None, help="Optional dbt schema.yml file or directory")
|
|
140
|
+
rew_p.add_argument(
|
|
141
|
+
"--target",
|
|
142
|
+
choices=target_choices,
|
|
143
|
+
default=WarehouseTarget.ALL.value,
|
|
144
|
+
help="Warehouse billing target for empirical cost gating (default: all)",
|
|
145
|
+
)
|
|
146
|
+
rew_p.add_argument("--dialect", default=None, help="SQL dialect (defaults to --target dialect)")
|
|
147
|
+
rew_p.add_argument("--bound", type=int, default=3)
|
|
148
|
+
|
|
149
|
+
audit_p = sub.add_parser(
|
|
150
|
+
"audit",
|
|
151
|
+
help="Audit compiled dbt models from target/manifest.json with view unfolding, formal proofs & warehouse gating",
|
|
152
|
+
)
|
|
153
|
+
audit_p.add_argument(
|
|
154
|
+
"path",
|
|
155
|
+
type=Path,
|
|
156
|
+
nargs="?",
|
|
157
|
+
default=Path("."),
|
|
158
|
+
help="Path to dbt target/manifest.json or dbt project root (default: .)",
|
|
159
|
+
)
|
|
160
|
+
audit_p.add_argument(
|
|
161
|
+
"--target",
|
|
162
|
+
choices=target_choices,
|
|
163
|
+
default=WarehouseTarget.ALL.value,
|
|
164
|
+
help="Target warehouse & billing model (bigquery-ondemand, bigquery-editions, snowflake, duckdb, all)",
|
|
165
|
+
)
|
|
166
|
+
audit_p.add_argument("--dialect", default=None, help="Override SQL dialect (defaults from --target or manifest)")
|
|
167
|
+
audit_p.add_argument("--dbt-schema", type=Path, default=None, help="Optional extra dbt schema.yml file/dir overlay")
|
|
168
|
+
audit_p.add_argument("--models", default=None, help="Comma-separated list of model names to audit")
|
|
169
|
+
audit_p.add_argument("--no-unfold-views", action="store_true", help="Disable cross-model upstream view unfolding")
|
|
170
|
+
audit_p.add_argument("--show-all", action="store_true", help="Include NEUTRAL and target-BLOCKED verified rewrites")
|
|
171
|
+
audit_p.add_argument("--format", choices=("text", "markdown", "json"), default="text", help="Output format")
|
|
172
|
+
audit_p.add_argument("--bound", type=int, default=2)
|
|
173
|
+
|
|
174
|
+
args = parser.parse_args(argv)
|
|
175
|
+
|
|
176
|
+
if args.cmd == "demo":
|
|
177
|
+
return _run_demo()
|
|
178
|
+
|
|
179
|
+
if args.cmd == "scan":
|
|
180
|
+
report = scan_directory(args.path, dialect=args.dialect, models_only=args.models_only)
|
|
181
|
+
if args.json:
|
|
182
|
+
print(json.dumps(report.to_dict(), indent=2))
|
|
183
|
+
else:
|
|
184
|
+
print(f"Scanned {report.total_files} SQL files ({report.parsed_files} parsed) [{report.dialect}]")
|
|
185
|
+
for pat, count in report.pattern_counts.items():
|
|
186
|
+
print(f" {pat:34s} {count}")
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
if args.cmd == "prove":
|
|
190
|
+
schema = Schema.from_json_file(args.schema)
|
|
191
|
+
if args.dbt_schema is not None:
|
|
192
|
+
schema = schema.with_dbt_constraints(load_dbt_schema_constraints(args.dbt_schema))
|
|
193
|
+
res = prove_equivalence(args.q1, args.q2, schema, dialect=args.dialect, bound=args.bound)
|
|
194
|
+
print(
|
|
195
|
+
json.dumps(
|
|
196
|
+
{
|
|
197
|
+
"status": res.status.value,
|
|
198
|
+
"rule_name": res.rule_name,
|
|
199
|
+
"bound": res.bound,
|
|
200
|
+
"reason": res.reason,
|
|
201
|
+
"duckdb_confirmed": res.duckdb_confirmed,
|
|
202
|
+
"counterexample": res.counterexample,
|
|
203
|
+
"duckdb_q1_rows": res.duckdb_q1_rows,
|
|
204
|
+
"duckdb_q2_rows": res.duckdb_q2_rows,
|
|
205
|
+
},
|
|
206
|
+
indent=2,
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
return 0 if res.status in (ProofStatus.BOUNDED_VERIFIED, ProofStatus.ALGEBRAICALLY_PROVEN) else 1
|
|
210
|
+
|
|
211
|
+
if args.cmd == "rewrite":
|
|
212
|
+
tgt = WarehouseTarget(args.target)
|
|
213
|
+
dialect = args.dialect or (tgt.default_dialect if tgt != WarehouseTarget.ALL else "duckdb")
|
|
214
|
+
schema = Schema.from_json_file(args.schema)
|
|
215
|
+
if args.dbt_schema is not None:
|
|
216
|
+
schema = schema.with_dbt_constraints(load_dbt_schema_constraints(args.dbt_schema))
|
|
217
|
+
cands = verify_rewrites_with_ctes(
|
|
218
|
+
args.sql,
|
|
219
|
+
schema,
|
|
220
|
+
dialect=dialect,
|
|
221
|
+
target=tgt,
|
|
222
|
+
bound=args.bound,
|
|
223
|
+
)
|
|
224
|
+
verified = only_verified(cands)
|
|
225
|
+
recommended = only_recommended(cands)
|
|
226
|
+
print(
|
|
227
|
+
json.dumps(
|
|
228
|
+
{
|
|
229
|
+
"target": tgt.value,
|
|
230
|
+
"dialect": dialect,
|
|
231
|
+
"proposed": len(cands),
|
|
232
|
+
"verified": len(verified),
|
|
233
|
+
"recommended": len(recommended),
|
|
234
|
+
"rewrites": [
|
|
235
|
+
{
|
|
236
|
+
"rule": c.rule,
|
|
237
|
+
"status": c.verification.status.value,
|
|
238
|
+
"rule_name": c.verification.rule_name,
|
|
239
|
+
"reason": c.verification.reason,
|
|
240
|
+
"target_decision": c.target_advice.decision.value if c.target_advice else None,
|
|
241
|
+
"expected_impact": c.target_advice.expected_impact if c.target_advice else None,
|
|
242
|
+
"target_rationale": c.target_advice.rationale if c.target_advice else None,
|
|
243
|
+
"rewritten_sql": c.rewritten_sql,
|
|
244
|
+
}
|
|
245
|
+
for c in cands
|
|
246
|
+
],
|
|
247
|
+
},
|
|
248
|
+
indent=2,
|
|
249
|
+
)
|
|
250
|
+
)
|
|
251
|
+
return 0
|
|
252
|
+
|
|
253
|
+
if args.cmd == "audit":
|
|
254
|
+
model_filter = {m.strip() for m in args.models.split(",") if m.strip()} if args.models else None
|
|
255
|
+
try:
|
|
256
|
+
report = audit_dbt_manifest(
|
|
257
|
+
args.path,
|
|
258
|
+
target=args.target,
|
|
259
|
+
dialect=args.dialect,
|
|
260
|
+
models=model_filter,
|
|
261
|
+
unfold_views=not args.no_unfold_views,
|
|
262
|
+
extra_dbt_schema=args.dbt_schema,
|
|
263
|
+
bound=args.bound,
|
|
264
|
+
)
|
|
265
|
+
except FileNotFoundError as exc:
|
|
266
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
267
|
+
return 2
|
|
268
|
+
|
|
269
|
+
if args.format == "json":
|
|
270
|
+
print(json.dumps(report.to_dict(), indent=2))
|
|
271
|
+
elif args.format == "markdown":
|
|
272
|
+
print(report.to_markdown(show_all=args.show_all))
|
|
273
|
+
else:
|
|
274
|
+
print(report.to_text(show_all=args.show_all))
|
|
275
|
+
return 0
|
|
276
|
+
|
|
277
|
+
return 2
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
if __name__ == "__main__":
|
|
281
|
+
sys.exit(main())
|