sqlprove 0.1.0__tar.gz → 0.2.0__tar.gz

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.
Files changed (32) hide show
  1. sqlprove-0.2.0/PKG-INFO +151 -0
  2. sqlprove-0.2.0/README.md +125 -0
  3. {sqlprove-0.1.0 → sqlprove-0.2.0}/pyproject.toml +1 -1
  4. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/__init__.py +15 -3
  5. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/audit.py +115 -6
  6. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/cli.py +215 -6
  7. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/rewrites.py +4 -4
  8. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/schema.py +181 -0
  9. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/targets.py +167 -0
  10. sqlprove-0.2.0/src/sqlprove.egg-info/PKG-INFO +151 -0
  11. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove.egg-info/SOURCES.txt +2 -1
  12. sqlprove-0.2.0/tests/test_v02_check_and_pr.py +223 -0
  13. sqlprove-0.1.0/PKG-INFO +0 -93
  14. sqlprove-0.1.0/README.md +0 -67
  15. sqlprove-0.1.0/src/sqlprove.egg-info/PKG-INFO +0 -93
  16. {sqlprove-0.1.0 → sqlprove-0.2.0}/LICENSE +0 -0
  17. {sqlprove-0.1.0 → sqlprove-0.2.0}/MANIFEST.in +0 -0
  18. {sqlprove-0.1.0 → sqlprove-0.2.0}/setup.cfg +0 -0
  19. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/algebra.py +0 -0
  20. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/corpus.py +0 -0
  21. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/cost.py +0 -0
  22. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/dbt_manifest.py +0 -0
  23. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/fuzzer.py +0 -0
  24. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove/prover.py +0 -0
  25. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove.egg-info/dependency_links.txt +0 -0
  26. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove.egg-info/entry_points.txt +0 -0
  27. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove.egg-info/requires.txt +0 -0
  28. {sqlprove-0.1.0 → sqlprove-0.2.0}/src/sqlprove.egg-info/top_level.txt +0 -0
  29. {sqlprove-0.1.0 → sqlprove-0.2.0}/tests/test_corpus.py +0 -0
  30. {sqlprove-0.1.0 → sqlprove-0.2.0}/tests/test_prover.py +0 -0
  31. {sqlprove-0.1.0 → sqlprove-0.2.0}/tests/test_rewrites_and_schema.py +0 -0
  32. {sqlprove-0.1.0 → sqlprove-0.2.0}/tests/test_targets_and_manifest.py +0 -0
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.1
2
+ Name: sqlprove
3
+ Version: 0.2.0
4
+ Summary: Proof-carrying SQL cost optimizer for BigQuery, Snowflake, and dbt using Z3 SMT and DuckDB verification
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/MarklarSystems/sqlprove
7
+ Project-URL: Repository, https://github.com/MarklarSystems/sqlprove
8
+ Project-URL: Issues, https://github.com/MarklarSystems/sqlprove/issues
9
+ Keywords: sql,dbt,bigquery,snowflake,duckdb,z3,smt,formal-verification,query-optimization,finops
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Topic :: Software Development :: Quality Assurance
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ Provides-Extra: dev
25
+ License-File: LICENSE
26
+
27
+ # sqlprove
28
+
29
+ **Formally verified SQL cost optimizer for BigQuery, Snowflake, and dbt — 100% local, zero PII.**
30
+
31
+ Blind LLM SQL rewrites look clean in PR reviews — and silently break dashboards. In our [120-rewrite blind benchmark](https://github.com/MarklarSystems/sqlprove/blob/main/benchmarks/day5-llm-bug-catch.json) across 40 real dbt-derived queries, unverified LLMs introduced **17.5%–34.4% silent semantic bugs** (`NULL` traps, duplicate-row fan-out, dropped all-`NULL` groups).
32
+
33
+ `sqlprove` pairs rewrite discovery with **unbounded algebraic proofs (`A0`–`A9`)**, a **Z3 SMT equivalence prover** (bag semantics + 3-valued `NULL` logic + dbt `schema.yml`/`manifest.json` constraints), **DuckDB counterexample confirmation**, and **warehouse-specific cost gating** measured live on Google BigQuery and Snowflake.
34
+
35
+ ---
36
+
37
+ ## Try in 10 Seconds (Zero Config, No dbt Needed)
38
+
39
+ ```bash
40
+ pip install sqlprove
41
+
42
+ # 1. Watch Z3 + DuckDB catch subtle NULL & join-multiplication bugs live
43
+ sqlprove demo
44
+
45
+ # 2. Check any raw query on the spot (conservative inferred schema)
46
+ sqlprove check "SELECT event_id, amount FROM events WHERE EXTRACT(YEAR FROM created_at) = 2025 AND EXTRACT(MONTH FROM created_at) = 12" \
47
+ --target bigquery-ondemand --table-gb 500 --runs-per-month 30
48
+
49
+ # 3. Watch Z3 refuse an unsafe dead-join drop with a concrete DuckDB counterexample,
50
+ # then unlock an unbounded proof once you declare --unique customers.id:
51
+ sqlprove check "SELECT o.id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.id" --target snowflake
52
+ sqlprove check "SELECT o.id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.id" --target snowflake --unique customers.id
53
+ ```
54
+
55
+ ---
56
+
57
+ ## Live Cloud Benchmark Summary (Cold Runs, Zero Cache)
58
+
59
+ Measured on live **Google BigQuery** (2M rows/table, 365 partitions, clustered) and **Snowflake** (6M rows/table, ~100 micro-partitions, `USE_CACHED_RESULT = FALSE`). Full data & reproducible SQL scripts: [`benchmarks/week2-cloud-validation.md`](https://github.com/MarklarSystems/sqlprove/blob/main/benchmarks/week2-cloud-validation.md).
60
+
61
+ | Formally Proven Rewrite Pattern | BigQuery On-Demand (`$/TB`) | BigQuery Editions (`slot_ms`) | Snowflake Scan (`MB`) | Snowflake Compute (`ms`) |
62
+ |---|---:|---:|---:|---:|
63
+ | Cross-view dead `LEFT JOIN` + nested `DISTINCT` (`A4`) | `-20.0%` | `-5.8%` | `-13.1%` | **-95.9%** (24.4×) |
64
+ | Redundant `DISTINCT` via dbt `unique`+`not_null` (`A3b`) | `-10.3%` | **-79.7%** | `0.0%` | **-60.7%** |
65
+ | Dead `INNER JOIN` via dbt `relationships` FK (`A2`) | `-4.3%` | **-65.6%** | `-13.1%` | **-31.6%** |
66
+ | `COALESCE(bool, FALSE)` / `NOT COALESCE` / `<> sentinel` (`A5`) | **-76.9% to -87.1%** | **-21% to -37.5%** | `0%` / `+4.1%` | **-10% to -31.3%** |
67
+ | `EXTRACT(YEAR/MONTH)` → `[lo, hi)` range (`A7`) | **-91.3%** | **-92.5%** | `-3.1%` | `-12.3%` |
68
+ | 2× repeated CTE `UNION ALL` → single pass (`A8`) | `0.0%` | **-61.2%** | `0.0%` | **-70.4%** (3.4×) |
69
+ | 4× disjoint `UNION ALL` `GROUP BY` → 1 scan (`A9`) | `0.0%` | **-74.8%** | **-75.0%** | **-62.7%** |
70
+ | Cross-col `OR` → disjoint `UNION ALL` w/ `IS NULL` (`A6`) | `0.0%` | **-75.6%** | `+16.5%` *(auto-blocked on Snowflake!)* | `+1.9%` |
71
+
72
+ ---
73
+
74
+ ## Audit a dbt Project (`target/manifest.json`)
75
+
76
+ ```bash
77
+ dbt compile
78
+
79
+ # Audit compiled models + automatically unfold upstream logical views (`view`/`ephemeral`)
80
+ sqlprove audit . --target snowflake --format github-pr
81
+ sqlprove audit . --target bigquery-ondemand --table-gb 500 --runs-per-month 30 --format github-pr
82
+ sqlprove audit . --target bigquery-editions --show-all
83
+ ```
84
+
85
+ ### Drop-in GitHub Action (PR Comments with Proof Badges & Collapsible Diffs)
86
+
87
+ Save as `.github/workflows/sqlprove.yml` in your dbt repo:
88
+
89
+ ```yaml
90
+ name: sqlprove SQL Cost Audit
91
+ on:
92
+ pull_request:
93
+ paths: ["models/**/*.sql", "models/**/*.yml"]
94
+
95
+ permissions:
96
+ pull-requests: write
97
+
98
+ jobs:
99
+ sqlprove:
100
+ runs-on: ubuntu-latest
101
+ steps:
102
+ - uses: actions/checkout@v4
103
+ - uses: actions/setup-python@v5
104
+ with:
105
+ python-version: "3.12"
106
+ - run: pip install sqlprove
107
+ # Run your existing `dbt compile` step (or point sqlprove at a cached target/manifest.json)
108
+ - name: Run sqlprove audit
109
+ run: |
110
+ sqlprove audit . \
111
+ --target bigquery-ondemand \
112
+ --format github-pr > sqlprove-report.md
113
+ - name: Comment on PR
114
+ env:
115
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
116
+ run: gh pr comment "${{ github.event.pull_request.number }}" --body-file sqlprove-report.md
117
+ ```
118
+
119
+ ---
120
+
121
+ ## Verification Tiers (Fail-Closed)
122
+
123
+ - **`ALGEBRAICALLY_PROVEN`** — Unbounded equivalence established by a sound schema-aware rule (`A0`–`A9`).
124
+ - **`BOUNDED_VERIFIED`** — Z3 proved `UNSAT` for every symbolic database up to `bound` rows per table (including arbitrary `NULL`s and duplicates).
125
+ - **`COUNTEREXAMPLE_FOUND`** — Z3 synthesized concrete input tables where the queries return different multisets, independently confirmed in DuckDB.
126
+ - **`UNSUPPORTED` / `UNKNOWN`** — Fails closed; never emitted as a proven rewrite.
127
+ - **0 false positives across 35,900 randomized `NULL`/duplicate/FK DuckDB fuzz trials.**
128
+
129
+ ## Zero-PII Top-20 Warehouse Spend Audit (Pilot)
130
+
131
+ Spending **$10k+/mo on BigQuery or Snowflake**? Send your `target/manifest.json` + a 30-day query cost rollup (`model_name, bytes_billed/credits, runs_per_month` — zero customer rows or PII) to **`marklar@marklar.systems`** for a free audit returning formally verified PR diffs ranked by real monthly spend.
132
+
133
+ ## Layout
134
+
135
+ ```text
136
+ sqlprove/
137
+ src/sqlprove/
138
+ cli.py # CLI: demo, check, audit, rewrite, prove, scan
139
+ audit.py # Compiled dbt manifest audit & github-pr / markdown / json / text formatters
140
+ dbt_manifest.py # target/manifest.json loader, constraint extractor & sound view unfolder
141
+ targets.py # Live-benchmarked warehouse cost gating & parameterized $/mo estimator
142
+ algebra.py # Unbounded sound algebraic equivalence rules (A0-A9)
143
+ prover.py # Z3 SMT 3-valued NULL + bag-semantics equivalence checker
144
+ rewrites.py # Dialect-native candidate rewrites + CTE congruence verification
145
+ schema.py # Schema constraints, conservative inference & dbt schema.yml parser
146
+ fuzzer.py # DuckDB counterexample confirmer & randomized differential fuzzer
147
+ corpus.py # Raw dbt/SQL repository pattern scanner
148
+ cost.py # DuckDB EXPLAIN (ANALYZE, FORMAT JSON) profiler
149
+ benchmarks/ # Corpus audit, blind LLM bug-catch, 1M-row scale, and $0 live BQ/SF scripts & results
150
+ tests/ # Unit, soundness, manifest, view-unfolding, PR formatter & fuzz tests
151
+ ```
@@ -0,0 +1,125 @@
1
+ # sqlprove
2
+
3
+ **Formally verified SQL cost optimizer for BigQuery, Snowflake, and dbt — 100% local, zero PII.**
4
+
5
+ Blind LLM SQL rewrites look clean in PR reviews — and silently break dashboards. In our [120-rewrite blind benchmark](https://github.com/MarklarSystems/sqlprove/blob/main/benchmarks/day5-llm-bug-catch.json) across 40 real dbt-derived queries, unverified LLMs introduced **17.5%–34.4% silent semantic bugs** (`NULL` traps, duplicate-row fan-out, dropped all-`NULL` groups).
6
+
7
+ `sqlprove` pairs rewrite discovery with **unbounded algebraic proofs (`A0`–`A9`)**, a **Z3 SMT equivalence prover** (bag semantics + 3-valued `NULL` logic + dbt `schema.yml`/`manifest.json` constraints), **DuckDB counterexample confirmation**, and **warehouse-specific cost gating** measured live on Google BigQuery and Snowflake.
8
+
9
+ ---
10
+
11
+ ## Try in 10 Seconds (Zero Config, No dbt Needed)
12
+
13
+ ```bash
14
+ pip install sqlprove
15
+
16
+ # 1. Watch Z3 + DuckDB catch subtle NULL & join-multiplication bugs live
17
+ sqlprove demo
18
+
19
+ # 2. Check any raw query on the spot (conservative inferred schema)
20
+ sqlprove check "SELECT event_id, amount FROM events WHERE EXTRACT(YEAR FROM created_at) = 2025 AND EXTRACT(MONTH FROM created_at) = 12" \
21
+ --target bigquery-ondemand --table-gb 500 --runs-per-month 30
22
+
23
+ # 3. Watch Z3 refuse an unsafe dead-join drop with a concrete DuckDB counterexample,
24
+ # then unlock an unbounded proof once you declare --unique customers.id:
25
+ sqlprove check "SELECT o.id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.id" --target snowflake
26
+ sqlprove check "SELECT o.id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.id" --target snowflake --unique customers.id
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Live Cloud Benchmark Summary (Cold Runs, Zero Cache)
32
+
33
+ Measured on live **Google BigQuery** (2M rows/table, 365 partitions, clustered) and **Snowflake** (6M rows/table, ~100 micro-partitions, `USE_CACHED_RESULT = FALSE`). Full data & reproducible SQL scripts: [`benchmarks/week2-cloud-validation.md`](https://github.com/MarklarSystems/sqlprove/blob/main/benchmarks/week2-cloud-validation.md).
34
+
35
+ | Formally Proven Rewrite Pattern | BigQuery On-Demand (`$/TB`) | BigQuery Editions (`slot_ms`) | Snowflake Scan (`MB`) | Snowflake Compute (`ms`) |
36
+ |---|---:|---:|---:|---:|
37
+ | Cross-view dead `LEFT JOIN` + nested `DISTINCT` (`A4`) | `-20.0%` | `-5.8%` | `-13.1%` | **-95.9%** (24.4×) |
38
+ | Redundant `DISTINCT` via dbt `unique`+`not_null` (`A3b`) | `-10.3%` | **-79.7%** | `0.0%` | **-60.7%** |
39
+ | Dead `INNER JOIN` via dbt `relationships` FK (`A2`) | `-4.3%` | **-65.6%** | `-13.1%` | **-31.6%** |
40
+ | `COALESCE(bool, FALSE)` / `NOT COALESCE` / `<> sentinel` (`A5`) | **-76.9% to -87.1%** | **-21% to -37.5%** | `0%` / `+4.1%` | **-10% to -31.3%** |
41
+ | `EXTRACT(YEAR/MONTH)` → `[lo, hi)` range (`A7`) | **-91.3%** | **-92.5%** | `-3.1%` | `-12.3%` |
42
+ | 2× repeated CTE `UNION ALL` → single pass (`A8`) | `0.0%` | **-61.2%** | `0.0%` | **-70.4%** (3.4×) |
43
+ | 4× disjoint `UNION ALL` `GROUP BY` → 1 scan (`A9`) | `0.0%` | **-74.8%** | **-75.0%** | **-62.7%** |
44
+ | Cross-col `OR` → disjoint `UNION ALL` w/ `IS NULL` (`A6`) | `0.0%` | **-75.6%** | `+16.5%` *(auto-blocked on Snowflake!)* | `+1.9%` |
45
+
46
+ ---
47
+
48
+ ## Audit a dbt Project (`target/manifest.json`)
49
+
50
+ ```bash
51
+ dbt compile
52
+
53
+ # Audit compiled models + automatically unfold upstream logical views (`view`/`ephemeral`)
54
+ sqlprove audit . --target snowflake --format github-pr
55
+ sqlprove audit . --target bigquery-ondemand --table-gb 500 --runs-per-month 30 --format github-pr
56
+ sqlprove audit . --target bigquery-editions --show-all
57
+ ```
58
+
59
+ ### Drop-in GitHub Action (PR Comments with Proof Badges & Collapsible Diffs)
60
+
61
+ Save as `.github/workflows/sqlprove.yml` in your dbt repo:
62
+
63
+ ```yaml
64
+ name: sqlprove SQL Cost Audit
65
+ on:
66
+ pull_request:
67
+ paths: ["models/**/*.sql", "models/**/*.yml"]
68
+
69
+ permissions:
70
+ pull-requests: write
71
+
72
+ jobs:
73
+ sqlprove:
74
+ runs-on: ubuntu-latest
75
+ steps:
76
+ - uses: actions/checkout@v4
77
+ - uses: actions/setup-python@v5
78
+ with:
79
+ python-version: "3.12"
80
+ - run: pip install sqlprove
81
+ # Run your existing `dbt compile` step (or point sqlprove at a cached target/manifest.json)
82
+ - name: Run sqlprove audit
83
+ run: |
84
+ sqlprove audit . \
85
+ --target bigquery-ondemand \
86
+ --format github-pr > sqlprove-report.md
87
+ - name: Comment on PR
88
+ env:
89
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
90
+ run: gh pr comment "${{ github.event.pull_request.number }}" --body-file sqlprove-report.md
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Verification Tiers (Fail-Closed)
96
+
97
+ - **`ALGEBRAICALLY_PROVEN`** — Unbounded equivalence established by a sound schema-aware rule (`A0`–`A9`).
98
+ - **`BOUNDED_VERIFIED`** — Z3 proved `UNSAT` for every symbolic database up to `bound` rows per table (including arbitrary `NULL`s and duplicates).
99
+ - **`COUNTEREXAMPLE_FOUND`** — Z3 synthesized concrete input tables where the queries return different multisets, independently confirmed in DuckDB.
100
+ - **`UNSUPPORTED` / `UNKNOWN`** — Fails closed; never emitted as a proven rewrite.
101
+ - **0 false positives across 35,900 randomized `NULL`/duplicate/FK DuckDB fuzz trials.**
102
+
103
+ ## Zero-PII Top-20 Warehouse Spend Audit (Pilot)
104
+
105
+ Spending **$10k+/mo on BigQuery or Snowflake**? Send your `target/manifest.json` + a 30-day query cost rollup (`model_name, bytes_billed/credits, runs_per_month` — zero customer rows or PII) to **`marklar@marklar.systems`** for a free audit returning formally verified PR diffs ranked by real monthly spend.
106
+
107
+ ## Layout
108
+
109
+ ```text
110
+ sqlprove/
111
+ src/sqlprove/
112
+ cli.py # CLI: demo, check, audit, rewrite, prove, scan
113
+ audit.py # Compiled dbt manifest audit & github-pr / markdown / json / text formatters
114
+ dbt_manifest.py # target/manifest.json loader, constraint extractor & sound view unfolder
115
+ targets.py # Live-benchmarked warehouse cost gating & parameterized $/mo estimator
116
+ algebra.py # Unbounded sound algebraic equivalence rules (A0-A9)
117
+ prover.py # Z3 SMT 3-valued NULL + bag-semantics equivalence checker
118
+ rewrites.py # Dialect-native candidate rewrites + CTE congruence verification
119
+ schema.py # Schema constraints, conservative inference & dbt schema.yml parser
120
+ fuzzer.py # DuckDB counterexample confirmer & randomized differential fuzzer
121
+ corpus.py # Raw dbt/SQL repository pattern scanner
122
+ cost.py # DuckDB EXPLAIN (ANALYZE, FORMAT JSON) profiler
123
+ benchmarks/ # Corpus audit, blind LLM bug-catch, 1M-row scale, and $0 live BQ/SF scripts & results
124
+ tests/ # Unit, soundness, manifest, view-unfolding, PR formatter & fuzz tests
125
+ ```
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sqlprove"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  description = "Proof-carrying SQL cost optimizer for BigQuery, Snowflake, and dbt using Z3 SMT and DuckDB verification"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -3,14 +3,24 @@
3
3
  from sqlprove.audit import ManifestAuditReport, audit_dbt_manifest
4
4
  from sqlprove.dbt_manifest import DbtManifest, load_dbt_manifest, unfold_upstream_views
5
5
  from sqlprove.prover import ProofStatus, VerificationResult, prove_equivalence
6
- from sqlprove.schema import ColumnSpec, Schema, TableSpec
7
- from sqlprove.targets import TargetDecision, TargetRuleAdvice, WarehouseTarget, evaluate_rule_for_target
6
+ from sqlprove.schema import ColumnSpec, Schema, TableSpec, infer_conservative_schema
7
+ from sqlprove.targets import (
8
+ CostEstimate,
9
+ CostParams,
10
+ TargetDecision,
11
+ TargetRuleAdvice,
12
+ WarehouseTarget,
13
+ estimate_monthly_savings,
14
+ evaluate_rule_for_target,
15
+ )
8
16
 
9
- __version__ = "0.1.0"
17
+ __version__ = "0.2.0"
10
18
 
11
19
  __all__ = [
12
20
  "__version__",
13
21
  "ColumnSpec",
22
+ "CostEstimate",
23
+ "CostParams",
14
24
  "DbtManifest",
15
25
  "ManifestAuditReport",
16
26
  "ProofStatus",
@@ -21,7 +31,9 @@ __all__ = [
21
31
  "VerificationResult",
22
32
  "WarehouseTarget",
23
33
  "audit_dbt_manifest",
34
+ "estimate_monthly_savings",
24
35
  "evaluate_rule_for_target",
36
+ "infer_conservative_schema",
25
37
  "load_dbt_manifest",
26
38
  "prove_equivalence",
27
39
  "unfold_upstream_views",
@@ -20,7 +20,7 @@ from sqlprove.rewrites import (
20
20
  verify_rewrites_with_ctes,
21
21
  )
22
22
  from sqlprove.schema import DbtModelConstraints, load_dbt_schema_constraints
23
- from sqlprove.targets import TargetDecision, WarehouseTarget
23
+ from sqlprove.targets import CostParams, TargetDecision, WarehouseTarget, estimate_monthly_savings
24
24
 
25
25
 
26
26
  @dataclass(frozen=True)
@@ -28,6 +28,7 @@ class ModelAuditFinding:
28
28
  model_name: str
29
29
  file_path: str
30
30
  materialized: str
31
+ original_sql: str
31
32
  unfolded_views: tuple[str, ...]
32
33
  skipped_views: tuple[str, ...]
33
34
  recommended: tuple[RewriteCandidate, ...]
@@ -37,8 +38,9 @@ class ModelAuditFinding:
37
38
  unsupported: int
38
39
  error: str | None = None
39
40
 
40
- def to_dict(self) -> dict[str, Any]:
41
+ def to_dict(self, cost_params: CostParams | None = None) -> dict[str, Any]:
41
42
  def _ser(c: RewriteCandidate) -> dict[str, Any]:
43
+ est = estimate_monthly_savings(c.target_advice, cost_params) if c.target_advice else None
42
44
  return {
43
45
  "rule": c.rule,
44
46
  "proof_status": c.verification.status.value,
@@ -47,6 +49,8 @@ class ModelAuditFinding:
47
49
  "target_decision": c.target_advice.decision.value if c.target_advice else None,
48
50
  "expected_impact": c.target_advice.expected_impact if c.target_advice else None,
49
51
  "target_rationale": c.target_advice.rationale if c.target_advice else None,
52
+ "estimated_monthly_usd": est.monthly_usd_saved if est else None,
53
+ "estimate_basis": est.basis if est else None,
50
54
  "rewritten_sql": c.rewritten_sql,
51
55
  }
52
56
 
@@ -81,7 +85,16 @@ class ManifestAuditReport:
81
85
  total_unsupported: int
82
86
  findings: tuple[ModelAuditFinding, ...]
83
87
 
84
- def to_dict(self) -> dict[str, Any]:
88
+ def to_dict(self, cost_params: CostParams | None = None) -> dict[str, Any]:
89
+ est_total = 0.0
90
+ has_est = False
91
+ for f in self.findings:
92
+ for c in f.recommended:
93
+ if c.target_advice is not None:
94
+ est = estimate_monthly_savings(c.target_advice, cost_params)
95
+ if est is not None:
96
+ est_total += est.monthly_usd_saved
97
+ has_est = True
85
98
  return {
86
99
  "manifest_path": self.manifest_path,
87
100
  "target": self.target.value,
@@ -96,11 +109,12 @@ class ManifestAuditReport:
96
109
  "total_blocked_by_target": self.total_blocked_by_target,
97
110
  "total_unsafe_counterexamples": self.total_unsafe_counterexamples,
98
111
  "total_unsupported": self.total_unsupported,
112
+ "estimated_monthly_usd_total": round(est_total, 2) if has_est else None,
99
113
  },
100
- "findings": [f.to_dict() for f in self.findings],
114
+ "findings": [f.to_dict(cost_params=cost_params) for f in self.findings],
101
115
  }
102
116
 
103
- def to_text(self, *, show_all: bool = False) -> str:
117
+ def to_text(self, *, show_all: bool = False, cost_params: CostParams | None = None) -> str:
104
118
  lines = [
105
119
  f"sqlprove audit — target={self.target.value} dialect={self.dialect}",
106
120
  f"Manifest: {self.manifest_path}",
@@ -126,11 +140,14 @@ class ManifestAuditReport:
126
140
  for c in cands:
127
141
  dec = c.target_advice.decision.value if c.target_advice else "VERIFIED"
128
142
  imp = c.target_advice.expected_impact if c.target_advice else ""
143
+ est = estimate_monthly_savings(c.target_advice, cost_params) if c.target_advice else None
129
144
  lines.append(
130
145
  f" [{dec:11s}] [{c.verification.status.value}] {c.rule}"
131
146
  )
132
147
  if imp:
133
148
  lines.append(f" Impact : {imp}")
149
+ if est is not None:
150
+ lines.append(f" Est. $ : {est.format_short()}")
134
151
  lines.append(f" Proof : {c.verification.reason}")
135
152
  lines.append(f" SQL : {c.rewritten_sql}")
136
153
  lines.append("")
@@ -138,7 +155,7 @@ class ManifestAuditReport:
138
155
  lines.append("No target-recommended verified rewrites found (use --show-all to inspect neutral/blocked verified rewrites).")
139
156
  return "\n".join(lines).rstrip()
140
157
 
141
- def to_markdown(self, *, show_all: bool = False) -> str:
158
+ def to_markdown(self, *, show_all: bool = False, cost_params: CostParams | None = None) -> str:
142
159
  lines = [
143
160
  f"## `sqlprove` Audit Report (`target={self.target.value}`, `dialect={self.dialect}`)",
144
161
  "",
@@ -154,6 +171,9 @@ class ManifestAuditReport:
154
171
  for c in cands:
155
172
  dec = c.target_advice.decision.value if c.target_advice else "VERIFIED"
156
173
  imp = c.target_advice.expected_impact if c.target_advice else ""
174
+ est = estimate_monthly_savings(c.target_advice, cost_params) if c.target_advice else None
175
+ if est is not None:
176
+ imp = f"{est.format_short()} — {imp}"
157
177
  rows.append(
158
178
  f"| `{f.model_name}` | `{dec}` | `{c.verification.status.value}` | `{c.rule}` | {imp} |"
159
179
  )
@@ -169,6 +189,93 @@ class ManifestAuditReport:
169
189
  lines.append("_No target-recommended verified rewrites found._")
170
190
  return "\n".join(lines)
171
191
 
192
+ def to_github_pr(self, *, show_all: bool = False, cost_params: CostParams | None = None) -> str:
193
+ """Render a rich GitHub PR comment with proof badges, optional parameterized $/mo estimates, and collapsible SQL diffs."""
194
+ est_total = 0.0
195
+ has_est = False
196
+ for f in self.findings:
197
+ for c in f.recommended:
198
+ if c.target_advice is not None:
199
+ est = estimate_monthly_savings(c.target_advice, cost_params)
200
+ if est is not None:
201
+ est_total += est.monthly_usd_saved
202
+ has_est = True
203
+
204
+ lines = [
205
+ f"## 🛡️ `sqlprove` Verified SQL Cost Audit (`target={self.target.value}`)",
206
+ "",
207
+ "| Metric | Count |",
208
+ "|---|---:|",
209
+ f"| Models audited (`dbt compile`) | {self.models_audited} / {self.models_total} |",
210
+ f"| **Verified & Recommended rewrites** | **{self.total_recommended}** (across {self.models_with_recommended} model(s)) |",
211
+ f"| Blocked regressions on `{self.target.value}` | {self.total_blocked_by_target} |",
212
+ f"| Unsafe rewrites auto-blocked (`COUNTEREXAMPLE_FOUND`) | {self.total_unsafe_counterexamples} |",
213
+ ]
214
+ if has_est:
215
+ lines.append(f"| **Parameterized Est. Savings** | **~${est_total:,.2f}/mo** *(illustrative)* |")
216
+ lines.append("")
217
+
218
+ shown = 0
219
+ for f in self.findings:
220
+ cands = list(f.recommended) + (list(f.neutral) + list(f.blocked) if show_all else [])
221
+ if not cands:
222
+ continue
223
+ shown += 1
224
+ unfold_str = f" · unfolded views: `{', '.join(f.unfolded_views)}`" if f.unfolded_views else ""
225
+ lines.append(f"### `{f.model_name}` (`{f.file_path}`{unfold_str})")
226
+ lines.append("")
227
+ for c in cands:
228
+ dec = c.target_advice.decision if c.target_advice else TargetDecision.RECOMMENDED
229
+ dec_badge = {
230
+ TargetDecision.RECOMMENDED: "✅ **RECOMMENDED**",
231
+ TargetDecision.NEUTRAL: "ℹ️ **NEUTRAL**",
232
+ TargetDecision.BLOCKED: "⛔ **BLOCKED (regression on target)**",
233
+ }[dec]
234
+ proof_badge = f"`{c.verification.status.value}`"
235
+ if c.verification.rule_name:
236
+ proof_badge += f" (`{c.verification.rule_name}`)"
237
+ est = estimate_monthly_savings(c.target_advice, cost_params) if c.target_advice else None
238
+ lines.append(f"- {dec_badge} · **Verified Safe:** {proof_badge} · Rule: `{c.rule}`")
239
+ if c.target_advice:
240
+ lines.append(f" - **Warehouse Impact (`{self.target.value}`):** {c.target_advice.expected_impact}")
241
+ if est is not None:
242
+ lines.append(f" - **Estimated Savings:** **{est.format_short()}**")
243
+ lines.append(f" - **Formal Proof:** {c.verification.reason}")
244
+ lines.append("")
245
+ lines.append(f"<details><summary>View verified SQL diff for <code>{f.model_name}</code> (<code>{c.rule}</code>)</summary>")
246
+ lines.append("")
247
+ lines.append("**Before (Original compiled SQL):**")
248
+ lines.append("```sql")
249
+ lines.append(f.original_sql.strip())
250
+ lines.append("```")
251
+ lines.append("")
252
+ lines.append("**After (Formally verified rewrite):**")
253
+ lines.append("```sql")
254
+ lines.append(c.rewritten_sql.strip())
255
+ lines.append("```")
256
+ lines.append("</details>")
257
+ lines.append("")
258
+
259
+ if shown == 0:
260
+ lines.append("_✅ No target-recommended verified rewrites found for the audited models._")
261
+ lines.append("")
262
+
263
+ lines.append("---")
264
+ if not has_est:
265
+ if self.target == WarehouseTarget.BIGQUERY_ONDEMAND:
266
+ tip = "Pass `--table-gb 500 --runs-per-month 30 --cost-per-tb 6.25` for parameterized $/mo estimates."
267
+ elif self.target == WarehouseTarget.SNOWFLAKE:
268
+ tip = "Pass `--avg-runtime-sec 60 --warehouse-size M --runs-per-month 30 --credit-price 3.0` for parameterized $/mo estimates."
269
+ else:
270
+ tip = "Specify `--target bigquery-ondemand` (with `--table-gb`) or `--target snowflake` (with `--avg-runtime-sec`) for parameterized $/mo estimates."
271
+ lines.append(f"<sub>Verified 100% locally by `sqlprove` (Z3 SMT + DuckDB, zero warehouse data accessed). {tip}</sub>")
272
+ else:
273
+ lines.append(
274
+ "<sub>Verified 100% locally by `sqlprove` (Z3 SMT + DuckDB, zero warehouse data accessed). "
275
+ "Dollar amounts are parameterized estimates combining your supplied table/runtime inputs with live cloud benchmark percentages.</sub>"
276
+ )
277
+ return "\n".join(lines)
278
+
172
279
 
173
280
  def _infer_dialect(target: WarehouseTarget, manifest: DbtManifest, explicit_dialect: str | None) -> str:
174
281
  if explicit_dialect:
@@ -232,6 +339,7 @@ def audit_dbt_manifest(
232
339
  model_name=model.name,
233
340
  file_path=model.original_file_path,
234
341
  materialized=model.materialized,
342
+ original_sql="",
235
343
  unfolded_views=(),
236
344
  skipped_views=(),
237
345
  recommended=(),
@@ -319,6 +427,7 @@ def audit_dbt_manifest(
319
427
  model_name=model.name,
320
428
  file_path=model.original_file_path,
321
429
  materialized=model.materialized,
430
+ original_sql=model.compiled_sql,
322
431
  unfolded_views=unfolded_views,
323
432
  skipped_views=skipped_views,
324
433
  recommended=rec,