sqlprove 0.2.0__tar.gz → 0.3.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 (30) hide show
  1. {sqlprove-0.2.0/src/sqlprove.egg-info → sqlprove-0.3.0}/PKG-INFO +38 -6
  2. {sqlprove-0.2.0 → sqlprove-0.3.0}/README.md +37 -5
  3. {sqlprove-0.2.0 → sqlprove-0.3.0}/pyproject.toml +1 -1
  4. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/__init__.py +7 -1
  5. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/audit.py +47 -7
  6. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/cli.py +17 -1
  7. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/dbt_manifest.py +7 -0
  8. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/targets.py +150 -0
  9. {sqlprove-0.2.0 → sqlprove-0.3.0/src/sqlprove.egg-info}/PKG-INFO +38 -6
  10. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove.egg-info/SOURCES.txt +2 -1
  11. sqlprove-0.3.0/tests/test_v03_stats_and_pr_polish.py +189 -0
  12. {sqlprove-0.2.0 → sqlprove-0.3.0}/LICENSE +0 -0
  13. {sqlprove-0.2.0 → sqlprove-0.3.0}/MANIFEST.in +0 -0
  14. {sqlprove-0.2.0 → sqlprove-0.3.0}/setup.cfg +0 -0
  15. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/algebra.py +0 -0
  16. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/corpus.py +0 -0
  17. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/cost.py +0 -0
  18. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/fuzzer.py +0 -0
  19. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/prover.py +0 -0
  20. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/rewrites.py +0 -0
  21. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove/schema.py +0 -0
  22. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove.egg-info/dependency_links.txt +0 -0
  23. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove.egg-info/entry_points.txt +0 -0
  24. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove.egg-info/requires.txt +0 -0
  25. {sqlprove-0.2.0 → sqlprove-0.3.0}/src/sqlprove.egg-info/top_level.txt +0 -0
  26. {sqlprove-0.2.0 → sqlprove-0.3.0}/tests/test_corpus.py +0 -0
  27. {sqlprove-0.2.0 → sqlprove-0.3.0}/tests/test_prover.py +0 -0
  28. {sqlprove-0.2.0 → sqlprove-0.3.0}/tests/test_rewrites_and_schema.py +0 -0
  29. {sqlprove-0.2.0 → sqlprove-0.3.0}/tests/test_targets_and_manifest.py +0 -0
  30. {sqlprove-0.2.0 → sqlprove-0.3.0}/tests/test_v02_check_and_pr.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlprove
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Proof-carrying SQL cost optimizer for BigQuery, Snowflake, and dbt using Z3 SMT and DuckDB verification
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/MarklarSystems/sqlprove
@@ -78,11 +78,36 @@ dbt compile
78
78
 
79
79
  # Audit compiled models + automatically unfold upstream logical views (`view`/`ephemeral`)
80
80
  sqlprove audit . --target snowflake --format github-pr
81
- sqlprove audit . --target bigquery-ondemand --table-gb 500 --runs-per-month 30 --format github-pr
81
+ sqlprove audit . --target bigquery-ondemand --table-stats table_stats.json --format github-pr
82
82
  sqlprove audit . --target bigquery-editions --show-all
83
83
  ```
84
84
 
85
- ### Drop-in GitHub Action (PR Comments with Proof Badges & Collapsible Diffs)
85
+ ### Per-Model Cost Calibration (`table_stats.json` or dbt `meta:`)
86
+
87
+ Instead of applying one uniform `--table-gb` across every model, you can calibrate monthly `$/mo` estimates per model via either dbt `meta:` tags in `schema.yml` / `config(meta=...)`:
88
+
89
+ ```yaml
90
+ models:
91
+ - name: fct_events
92
+ meta:
93
+ table_gb: 1200
94
+ runs_per_month: 60
95
+ ```
96
+
97
+ or a lightweight `--table-stats table_stats.json`:
98
+
99
+ ```json
100
+ {
101
+ "cost_per_tb": 6.25,
102
+ "credit_price": 3.0,
103
+ "models": {
104
+ "fct_events": { "table_gb": 1200, "runs_per_month": 60 },
105
+ "tides_publication_organizations": { "avg_runtime_sec": 95, "warehouse_size": "L", "runs_per_month": 30 }
106
+ }
107
+ }
108
+ ```
109
+
110
+ ### Drop-in GitHub Action (Sticky PR Comment, Zero Spam on Clean PRs)
86
111
 
87
112
  Save as `.github/workflows/sqlprove.yml` in your dbt repo:
88
113
 
@@ -109,11 +134,18 @@ jobs:
109
134
  run: |
110
135
  sqlprove audit . \
111
136
  --target bigquery-ondemand \
112
- --format github-pr > sqlprove-report.md
113
- - name: Comment on PR
137
+ --format github-pr \
138
+ --skip-if-clean > sqlprove-report.md
139
+ - name: Post or update sticky PR comment
140
+ if: always()
114
141
  env:
115
142
  GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
116
- run: gh pr comment "${{ github.event.pull_request.number }}" --body-file sqlprove-report.md
143
+ run: |
144
+ if [ -s sqlprove-report.md ]; then
145
+ gh pr comment "${{ github.event.pull_request.number }}" \
146
+ --body-file sqlprove-report.md \
147
+ --edit-last --create-if-none
148
+ fi
117
149
  ```
118
150
 
119
151
  ---
@@ -52,11 +52,36 @@ dbt compile
52
52
 
53
53
  # Audit compiled models + automatically unfold upstream logical views (`view`/`ephemeral`)
54
54
  sqlprove audit . --target snowflake --format github-pr
55
- sqlprove audit . --target bigquery-ondemand --table-gb 500 --runs-per-month 30 --format github-pr
55
+ sqlprove audit . --target bigquery-ondemand --table-stats table_stats.json --format github-pr
56
56
  sqlprove audit . --target bigquery-editions --show-all
57
57
  ```
58
58
 
59
- ### Drop-in GitHub Action (PR Comments with Proof Badges & Collapsible Diffs)
59
+ ### Per-Model Cost Calibration (`table_stats.json` or dbt `meta:`)
60
+
61
+ Instead of applying one uniform `--table-gb` across every model, you can calibrate monthly `$/mo` estimates per model via either dbt `meta:` tags in `schema.yml` / `config(meta=...)`:
62
+
63
+ ```yaml
64
+ models:
65
+ - name: fct_events
66
+ meta:
67
+ table_gb: 1200
68
+ runs_per_month: 60
69
+ ```
70
+
71
+ or a lightweight `--table-stats table_stats.json`:
72
+
73
+ ```json
74
+ {
75
+ "cost_per_tb": 6.25,
76
+ "credit_price": 3.0,
77
+ "models": {
78
+ "fct_events": { "table_gb": 1200, "runs_per_month": 60 },
79
+ "tides_publication_organizations": { "avg_runtime_sec": 95, "warehouse_size": "L", "runs_per_month": 30 }
80
+ }
81
+ }
82
+ ```
83
+
84
+ ### Drop-in GitHub Action (Sticky PR Comment, Zero Spam on Clean PRs)
60
85
 
61
86
  Save as `.github/workflows/sqlprove.yml` in your dbt repo:
62
87
 
@@ -83,11 +108,18 @@ jobs:
83
108
  run: |
84
109
  sqlprove audit . \
85
110
  --target bigquery-ondemand \
86
- --format github-pr > sqlprove-report.md
87
- - name: Comment on PR
111
+ --format github-pr \
112
+ --skip-if-clean > sqlprove-report.md
113
+ - name: Post or update sticky PR comment
114
+ if: always()
88
115
  env:
89
116
  GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
90
- run: gh pr comment "${{ github.event.pull_request.number }}" --body-file sqlprove-report.md
117
+ run: |
118
+ if [ -s sqlprove-report.md ]; then
119
+ gh pr comment "${{ github.event.pull_request.number }}" \
120
+ --body-file sqlprove-report.md \
121
+ --edit-last --create-if-none
122
+ fi
91
123
  ```
92
124
 
93
125
  ---
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sqlprove"
7
- version = "0.2.0"
7
+ version = "0.3.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"}
@@ -7,14 +7,17 @@ from sqlprove.schema import ColumnSpec, Schema, TableSpec, infer_conservative_sc
7
7
  from sqlprove.targets import (
8
8
  CostEstimate,
9
9
  CostParams,
10
+ TableStatsCatalog,
10
11
  TargetDecision,
11
12
  TargetRuleAdvice,
12
13
  WarehouseTarget,
13
14
  estimate_monthly_savings,
14
15
  evaluate_rule_for_target,
16
+ load_table_stats,
17
+ resolve_model_cost_params,
15
18
  )
16
19
 
17
- __version__ = "0.2.0"
20
+ __version__ = "0.3.0"
18
21
 
19
22
  __all__ = [
20
23
  "__version__",
@@ -26,6 +29,7 @@ __all__ = [
26
29
  "ProofStatus",
27
30
  "Schema",
28
31
  "TableSpec",
32
+ "TableStatsCatalog",
29
33
  "TargetDecision",
30
34
  "TargetRuleAdvice",
31
35
  "VerificationResult",
@@ -35,6 +39,8 @@ __all__ = [
35
39
  "evaluate_rule_for_target",
36
40
  "infer_conservative_schema",
37
41
  "load_dbt_manifest",
42
+ "load_table_stats",
38
43
  "prove_equivalence",
44
+ "resolve_model_cost_params",
39
45
  "unfold_upstream_views",
40
46
  ]
@@ -20,7 +20,15 @@ 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 CostParams, TargetDecision, WarehouseTarget, estimate_monthly_savings
23
+ from sqlprove.targets import (
24
+ CostParams,
25
+ TableStatsCatalog,
26
+ TargetDecision,
27
+ WarehouseTarget,
28
+ estimate_monthly_savings,
29
+ load_table_stats,
30
+ resolve_model_cost_params,
31
+ )
24
32
 
25
33
 
26
34
  @dataclass(frozen=True)
@@ -36,11 +44,17 @@ class ModelAuditFinding:
36
44
  blocked: tuple[RewriteCandidate, ...]
37
45
  unsafe_counterexamples: int
38
46
  unsupported: int
47
+ model_cost_params: CostParams | None = None
39
48
  error: str | None = None
40
49
 
50
+ def effective_cost_params(self, fallback: CostParams | None = None) -> CostParams | None:
51
+ return self.model_cost_params if self.model_cost_params is not None else fallback
52
+
41
53
  def to_dict(self, cost_params: CostParams | None = None) -> dict[str, Any]:
54
+ eff_cp = self.effective_cost_params(cost_params)
55
+
42
56
  def _ser(c: RewriteCandidate) -> dict[str, Any]:
43
- est = estimate_monthly_savings(c.target_advice, cost_params) if c.target_advice else None
57
+ est = estimate_monthly_savings(c.target_advice, eff_cp) if c.target_advice else None
44
58
  return {
45
59
  "rule": c.rule,
46
60
  "proof_status": c.verification.status.value,
@@ -85,13 +99,21 @@ class ManifestAuditReport:
85
99
  total_unsupported: int
86
100
  findings: tuple[ModelAuditFinding, ...]
87
101
 
102
+ def has_reportable_findings(self, *, show_all: bool = False) -> bool:
103
+ if self.total_recommended > 0:
104
+ return True
105
+ if show_all and (self.total_neutral > 0 or self.total_blocked_by_target > 0):
106
+ return True
107
+ return False
108
+
88
109
  def to_dict(self, cost_params: CostParams | None = None) -> dict[str, Any]:
89
110
  est_total = 0.0
90
111
  has_est = False
91
112
  for f in self.findings:
113
+ eff_cp = f.effective_cost_params(cost_params)
92
114
  for c in f.recommended:
93
115
  if c.target_advice is not None:
94
- est = estimate_monthly_savings(c.target_advice, cost_params)
116
+ est = estimate_monthly_savings(c.target_advice, eff_cp)
95
117
  if est is not None:
96
118
  est_total += est.monthly_usd_saved
97
119
  has_est = True
@@ -137,10 +159,11 @@ class ManifestAuditReport:
137
159
  shown += 1
138
160
  unfold_note = f" [unfolded views: {', '.join(f.unfolded_views)}]" if f.unfolded_views else ""
139
161
  lines.append(f"Model: {f.model_name} ({f.file_path}, {f.materialized}){unfold_note}")
162
+ eff_cp = f.effective_cost_params(cost_params)
140
163
  for c in cands:
141
164
  dec = c.target_advice.decision.value if c.target_advice else "VERIFIED"
142
165
  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
166
+ est = estimate_monthly_savings(c.target_advice, eff_cp) if c.target_advice else None
144
167
  lines.append(
145
168
  f" [{dec:11s}] [{c.verification.status.value}] {c.rule}"
146
169
  )
@@ -168,10 +191,11 @@ class ManifestAuditReport:
168
191
  rows: list[str] = []
169
192
  for f in self.findings:
170
193
  cands = list(f.recommended) + (list(f.neutral) + list(f.blocked) if show_all else [])
194
+ eff_cp = f.effective_cost_params(cost_params)
171
195
  for c in cands:
172
196
  dec = c.target_advice.decision.value if c.target_advice else "VERIFIED"
173
197
  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
198
+ est = estimate_monthly_savings(c.target_advice, eff_cp) if c.target_advice else None
175
199
  if est is not None:
176
200
  imp = f"{est.format_short()} — {imp}"
177
201
  rows.append(
@@ -194,9 +218,10 @@ class ManifestAuditReport:
194
218
  est_total = 0.0
195
219
  has_est = False
196
220
  for f in self.findings:
221
+ eff_cp = f.effective_cost_params(cost_params)
197
222
  for c in f.recommended:
198
223
  if c.target_advice is not None:
199
- est = estimate_monthly_savings(c.target_advice, cost_params)
224
+ est = estimate_monthly_savings(c.target_advice, eff_cp)
200
225
  if est is not None:
201
226
  est_total += est.monthly_usd_saved
202
227
  has_est = True
@@ -224,6 +249,7 @@ class ManifestAuditReport:
224
249
  unfold_str = f" · unfolded views: `{', '.join(f.unfolded_views)}`" if f.unfolded_views else ""
225
250
  lines.append(f"### `{f.model_name}` (`{f.file_path}`{unfold_str})")
226
251
  lines.append("")
252
+ eff_cp = f.effective_cost_params(cost_params)
227
253
  for c in cands:
228
254
  dec = c.target_advice.decision if c.target_advice else TargetDecision.RECOMMENDED
229
255
  dec_badge = {
@@ -234,7 +260,7 @@ class ManifestAuditReport:
234
260
  proof_badge = f"`{c.verification.status.value}`"
235
261
  if c.verification.rule_name:
236
262
  proof_badge += f" (`{c.verification.rule_name}`)"
237
- est = estimate_monthly_savings(c.target_advice, cost_params) if c.target_advice else None
263
+ est = estimate_monthly_savings(c.target_advice, eff_cp) if c.target_advice else None
238
264
  lines.append(f"- {dec_badge} · **Verified Safe:** {proof_badge} · Rule: `{c.rule}`")
239
265
  if c.target_advice:
240
266
  lines.append(f" - **Warehouse Impact (`{self.target.value}`):** {c.target_advice.expected_impact}")
@@ -309,6 +335,8 @@ def audit_dbt_manifest(
309
335
  models: set[str] | None = None,
310
336
  unfold_views: bool = True,
311
337
  extra_dbt_schema: str | Path | None = None,
338
+ table_stats_path: str | Path | None = None,
339
+ cost_params: CostParams | None = None,
312
340
  bound: int = 2,
313
341
  timeout_ms: int = 5_000,
314
342
  confirm_in_duckdb: bool = True,
@@ -323,6 +351,10 @@ def audit_dbt_manifest(
323
351
  if extra_dbt_schema is not None:
324
352
  extra_constraints = load_dbt_schema_constraints(extra_dbt_schema)
325
353
 
354
+ stats_catalog: TableStatsCatalog | None = None
355
+ if table_stats_path is not None:
356
+ stats_catalog = load_table_stats(table_stats_path)
357
+
326
358
  selected = sorted(manifest.models.values(), key=lambda m: (m.original_file_path, m.name))
327
359
  if models:
328
360
  wanted = {m.strip().lower() for m in models if m.strip()}
@@ -422,6 +454,13 @@ def audit_dbt_manifest(
422
454
  ce_cnt = sum(1 for c in all_cands if c.verification.status == ProofStatus.COUNTEREXAMPLE_FOUND)
423
455
  unsup_cnt = sum(1 for c in all_cands if c.verification.status == ProofStatus.UNSUPPORTED)
424
456
 
457
+ model_cp = resolve_model_cost_params(
458
+ model.name,
459
+ model.alias,
460
+ model.meta,
461
+ table_stats=stats_catalog,
462
+ fallback=cost_params,
463
+ )
425
464
  findings.append(
426
465
  ModelAuditFinding(
427
466
  model_name=model.name,
@@ -435,6 +474,7 @@ def audit_dbt_manifest(
435
474
  blocked=blk,
436
475
  unsafe_counterexamples=ce_cnt,
437
476
  unsupported=unsup_cnt,
477
+ model_cost_params=model_cp,
438
478
  error=parse_err,
439
479
  )
440
480
  )
@@ -260,9 +260,20 @@ def main(argv: list[str] | None = None) -> int:
260
260
  )
261
261
  audit_p.add_argument("--dialect", default=None, help="Override SQL dialect (defaults from --target or manifest)")
262
262
  audit_p.add_argument("--dbt-schema", type=Path, default=None, help="Optional extra dbt schema.yml file/dir overlay")
263
+ audit_p.add_argument(
264
+ "--table-stats",
265
+ type=Path,
266
+ default=None,
267
+ help="Optional per-model table_stats.json for calibrated $/mo estimates (overrides dbt meta: and CLI fallbacks)",
268
+ )
263
269
  audit_p.add_argument("--models", default=None, help="Comma-separated list of model names to audit")
264
270
  audit_p.add_argument("--no-unfold-views", action="store_true", help="Disable cross-model upstream view unfolding")
265
271
  audit_p.add_argument("--show-all", action="store_true", help="Include NEUTRAL and target-BLOCKED verified rewrites")
272
+ audit_p.add_argument(
273
+ "--skip-if-clean",
274
+ action="store_true",
275
+ help="Emit empty output (exit 0) when no reportable findings exist — prevents noisy PR comments on clean PRs",
276
+ )
266
277
  audit_p.add_argument(
267
278
  "--format",
268
279
  choices=("text", "markdown", "github-pr", "json"),
@@ -467,12 +478,17 @@ def main(argv: list[str] | None = None) -> int:
467
478
  models=model_filter,
468
479
  unfold_views=not args.no_unfold_views,
469
480
  extra_dbt_schema=args.dbt_schema,
481
+ table_stats_path=args.table_stats,
482
+ cost_params=cost_params,
470
483
  bound=args.bound,
471
484
  )
472
- except FileNotFoundError as exc:
485
+ except (FileNotFoundError, ValueError) as exc:
473
486
  print(f"Error: {exc}", file=sys.stderr)
474
487
  return 2
475
488
 
489
+ if args.skip_if_clean and not report.has_reportable_findings(show_all=args.show_all):
490
+ return 0
491
+
476
492
  if args.format == "json":
477
493
  print(json.dumps(report.to_dict(cost_params=cost_params), indent=2))
478
494
  elif args.format == "github-pr":
@@ -80,6 +80,7 @@ class DbtManifestModel:
80
80
  raw_sql: str | None
81
81
  depends_on: tuple[str, ...] = ()
82
82
  columns: dict[str, str] = field(default_factory=dict) # col_name -> canonical dtype
83
+ meta: dict[str, Any] = field(default_factory=dict)
83
84
 
84
85
 
85
86
  @dataclass(frozen=True)
@@ -263,6 +264,11 @@ def load_dbt_manifest(path: str | Path) -> DbtManifest:
263
264
  for cname, cinfo in (node.get("columns") or {}).items():
264
265
  dt_raw = cinfo.get("data_type")
265
266
  cols[cname] = normalize_dtype(dt_raw) if isinstance(dt_raw, str) and dt_raw.strip() else "INT"
267
+ node_meta: dict[str, Any] = {}
268
+ if isinstance(cfg.get("meta"), dict):
269
+ node_meta.update(cfg["meta"])
270
+ if isinstance(node.get("meta"), dict):
271
+ node_meta.update(node["meta"])
266
272
  m = DbtManifestModel(
267
273
  unique_id=uid,
268
274
  name=name,
@@ -275,6 +281,7 @@ def load_dbt_manifest(path: str | Path) -> DbtManifest:
275
281
  raw_sql=node.get("raw_code") or node.get("raw_sql"),
276
282
  depends_on=tuple((node.get("depends_on") or {}).get("nodes") or ()),
277
283
  columns=cols,
284
+ meta=node_meta,
278
285
  )
279
286
  relations[uid] = m
280
287
  if rtype == "model":
@@ -14,6 +14,9 @@ from __future__ import annotations
14
14
 
15
15
  from dataclasses import dataclass
16
16
  from enum import Enum
17
+ import json
18
+ from pathlib import Path
19
+ from typing import Any
17
20
 
18
21
 
19
22
  class WarehouseTarget(str, Enum):
@@ -212,6 +215,153 @@ def estimate_monthly_savings(advice: TargetRuleAdvice, params: CostParams | None
212
215
  return None
213
216
 
214
217
 
218
+ @dataclass(frozen=True)
219
+ class TableStatsCatalog:
220
+ """Per-model calibrated cost statistics loaded from a lightweight `table_stats.json` file."""
221
+
222
+ models: dict[str, dict[str, Any]] # lowercased model/alias -> stats dict
223
+ default_cost_per_tb: float | None = None
224
+ default_credit_price: float | None = None
225
+
226
+
227
+ def load_table_stats(path: str | Path) -> TableStatsCatalog:
228
+ """Load optional per-model cost statistics from `table_stats.json`.
229
+
230
+ Accepts either:
231
+ {"cost_per_tb": 6.25, "credit_price": 3.0, "models": {"my_model": {"table_gb": 1200, "runs_per_month": 60}}}
232
+ or flat:
233
+ {"my_model": {"table_gb": 1200, "runs_per_month": 60}}
234
+ """
235
+ raw = json.loads(Path(path).read_text(encoding="utf-8"))
236
+ if not isinstance(raw, dict):
237
+ raise ValueError("table_stats.json must contain a JSON object")
238
+
239
+ def _opt_float(v: Any) -> float | None:
240
+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None
241
+
242
+ default_cpt = _opt_float(raw.get("cost_per_tb"))
243
+ default_cp = _opt_float(raw.get("credit_price"))
244
+ raw_models = raw.get("models") if isinstance(raw.get("models"), dict) else raw
245
+
246
+ models: dict[str, dict[str, Any]] = {}
247
+ for k, v in raw_models.items():
248
+ if isinstance(v, dict):
249
+ models[str(k).strip().lower()] = dict(v)
250
+ return TableStatsCatalog(
251
+ models=models,
252
+ default_cost_per_tb=default_cpt,
253
+ default_credit_price=default_cp,
254
+ )
255
+
256
+
257
+ def _pick_float(d: dict[str, Any], *keys: str) -> float | None:
258
+ for k in keys:
259
+ v = d.get(k)
260
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
261
+ return float(v)
262
+ return None
263
+
264
+
265
+ def _pick_int(d: dict[str, Any], *keys: str) -> int | None:
266
+ for k in keys:
267
+ v = d.get(k)
268
+ if isinstance(v, int) and not isinstance(v, bool):
269
+ return v
270
+ return None
271
+
272
+
273
+ def _pick_str(d: dict[str, Any], *keys: str) -> str | None:
274
+ for k in keys:
275
+ v = d.get(k)
276
+ if isinstance(v, str) and v.strip():
277
+ return v.strip()
278
+ return None
279
+
280
+
281
+ def resolve_model_cost_params(
282
+ model_name: str,
283
+ model_alias: str,
284
+ model_meta: dict[str, Any] | None,
285
+ *,
286
+ table_stats: TableStatsCatalog | None = None,
287
+ fallback: CostParams | None = None,
288
+ ) -> CostParams | None:
289
+ """Resolve effective CostParams for a single dbt model.
290
+
291
+ Precedence (highest -> lowest):
292
+ 1. `table_stats.json` entry matching model name or alias
293
+ 2. dbt model `meta:` keys (e.g., `table_gb` / `sqlprove_table_gb`, `avg_runtime_sec`, `runs_per_month`)
294
+ 3. CLI fallback `CostParams` (when explicitly passed via `--table-gb` / `--avg-runtime-sec`)
295
+
296
+ Returns None if no scale input (`table_gb` or `avg_runtime_sec`) is present at any layer.
297
+ """
298
+ stat_entry: dict[str, Any] = {}
299
+ if table_stats is not None:
300
+ stat_entry = (
301
+ table_stats.models.get(model_name.lower())
302
+ or table_stats.models.get(model_alias.lower())
303
+ or {}
304
+ )
305
+ meta = model_meta or {}
306
+ # Also support nested `meta: { sqlprove: { table_gb: ... } }`
307
+ nested_meta = meta.get("sqlprove") if isinstance(meta.get("sqlprove"), dict) else {}
308
+ merged_meta = {**meta, **nested_meta}
309
+
310
+ table_gb = (
311
+ _pick_float(stat_entry, "table_gb", "sqlprove_table_gb")
312
+ if _pick_float(stat_entry, "table_gb", "sqlprove_table_gb") is not None
313
+ else _pick_float(merged_meta, "sqlprove_table_gb", "table_gb")
314
+ )
315
+ if table_gb is None and fallback is not None:
316
+ table_gb = fallback.table_gb
317
+
318
+ avg_runtime_sec = (
319
+ _pick_float(stat_entry, "avg_runtime_sec", "sqlprove_avg_runtime_sec")
320
+ if _pick_float(stat_entry, "avg_runtime_sec", "sqlprove_avg_runtime_sec") is not None
321
+ else _pick_float(merged_meta, "sqlprove_avg_runtime_sec", "avg_runtime_sec")
322
+ )
323
+ if avg_runtime_sec is None and fallback is not None:
324
+ avg_runtime_sec = fallback.avg_runtime_sec
325
+
326
+ if table_gb is None and avg_runtime_sec is None:
327
+ return None
328
+
329
+ runs_per_month = (
330
+ _pick_int(stat_entry, "runs_per_month", "sqlprove_runs_per_month")
331
+ or _pick_int(merged_meta, "sqlprove_runs_per_month", "runs_per_month")
332
+ or (fallback.runs_per_month if fallback is not None else 30)
333
+ )
334
+ warehouse_size = (
335
+ _pick_str(stat_entry, "warehouse_size", "sqlprove_warehouse_size")
336
+ or _pick_str(merged_meta, "sqlprove_warehouse_size", "warehouse_size")
337
+ or (fallback.warehouse_size if fallback is not None else "XS")
338
+ )
339
+ cost_per_tb = _pick_float(stat_entry, "cost_per_tb", "sqlprove_cost_per_tb")
340
+ if cost_per_tb is None:
341
+ cost_per_tb = _pick_float(merged_meta, "sqlprove_cost_per_tb", "cost_per_tb")
342
+ if cost_per_tb is None and table_stats is not None and table_stats.default_cost_per_tb is not None:
343
+ cost_per_tb = table_stats.default_cost_per_tb
344
+ if cost_per_tb is None:
345
+ cost_per_tb = fallback.cost_per_tb if fallback is not None else 6.25
346
+
347
+ credit_price = _pick_float(stat_entry, "credit_price", "sqlprove_credit_price")
348
+ if credit_price is None:
349
+ credit_price = _pick_float(merged_meta, "sqlprove_credit_price", "credit_price")
350
+ if credit_price is None and table_stats is not None and table_stats.default_credit_price is not None:
351
+ credit_price = table_stats.default_credit_price
352
+ if credit_price is None:
353
+ credit_price = fallback.credit_price if fallback is not None else 3.00
354
+
355
+ return CostParams(
356
+ cost_per_tb=cost_per_tb,
357
+ credit_price=credit_price,
358
+ table_gb=table_gb,
359
+ avg_runtime_sec=avg_runtime_sec,
360
+ warehouse_size=warehouse_size,
361
+ runs_per_month=runs_per_month,
362
+ )
363
+
364
+
215
365
  def normalize_rule_family(rule: str) -> str:
216
366
  """Strip CTE prefixes (`cte[name]:...`) and dynamic suffixes (`:alias`) from a rule label."""
217
367
  r = rule.strip()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlprove
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Proof-carrying SQL cost optimizer for BigQuery, Snowflake, and dbt using Z3 SMT and DuckDB verification
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/MarklarSystems/sqlprove
@@ -78,11 +78,36 @@ dbt compile
78
78
 
79
79
  # Audit compiled models + automatically unfold upstream logical views (`view`/`ephemeral`)
80
80
  sqlprove audit . --target snowflake --format github-pr
81
- sqlprove audit . --target bigquery-ondemand --table-gb 500 --runs-per-month 30 --format github-pr
81
+ sqlprove audit . --target bigquery-ondemand --table-stats table_stats.json --format github-pr
82
82
  sqlprove audit . --target bigquery-editions --show-all
83
83
  ```
84
84
 
85
- ### Drop-in GitHub Action (PR Comments with Proof Badges & Collapsible Diffs)
85
+ ### Per-Model Cost Calibration (`table_stats.json` or dbt `meta:`)
86
+
87
+ Instead of applying one uniform `--table-gb` across every model, you can calibrate monthly `$/mo` estimates per model via either dbt `meta:` tags in `schema.yml` / `config(meta=...)`:
88
+
89
+ ```yaml
90
+ models:
91
+ - name: fct_events
92
+ meta:
93
+ table_gb: 1200
94
+ runs_per_month: 60
95
+ ```
96
+
97
+ or a lightweight `--table-stats table_stats.json`:
98
+
99
+ ```json
100
+ {
101
+ "cost_per_tb": 6.25,
102
+ "credit_price": 3.0,
103
+ "models": {
104
+ "fct_events": { "table_gb": 1200, "runs_per_month": 60 },
105
+ "tides_publication_organizations": { "avg_runtime_sec": 95, "warehouse_size": "L", "runs_per_month": 30 }
106
+ }
107
+ }
108
+ ```
109
+
110
+ ### Drop-in GitHub Action (Sticky PR Comment, Zero Spam on Clean PRs)
86
111
 
87
112
  Save as `.github/workflows/sqlprove.yml` in your dbt repo:
88
113
 
@@ -109,11 +134,18 @@ jobs:
109
134
  run: |
110
135
  sqlprove audit . \
111
136
  --target bigquery-ondemand \
112
- --format github-pr > sqlprove-report.md
113
- - name: Comment on PR
137
+ --format github-pr \
138
+ --skip-if-clean > sqlprove-report.md
139
+ - name: Post or update sticky PR comment
140
+ if: always()
114
141
  env:
115
142
  GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
116
- run: gh pr comment "${{ github.event.pull_request.number }}" --body-file sqlprove-report.md
143
+ run: |
144
+ if [ -s sqlprove-report.md ]; then
145
+ gh pr comment "${{ github.event.pull_request.number }}" \
146
+ --body-file sqlprove-report.md \
147
+ --edit-last --create-if-none
148
+ fi
117
149
  ```
118
150
 
119
151
  ---
@@ -24,4 +24,5 @@ tests/test_corpus.py
24
24
  tests/test_prover.py
25
25
  tests/test_rewrites_and_schema.py
26
26
  tests/test_targets_and_manifest.py
27
- tests/test_v02_check_and_pr.py
27
+ tests/test_v02_check_and_pr.py
28
+ tests/test_v03_stats_and_pr_polish.py
@@ -0,0 +1,189 @@
1
+ """Tests for v0.3.0: per-model table_stats.json / dbt meta: cost calibration and --skip-if-clean PR anti-spam."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from sqlprove.audit import audit_dbt_manifest
9
+ from sqlprove.cli import main as cli_main
10
+ from sqlprove.targets import WarehouseTarget
11
+
12
+
13
+ def _manifest_with_meta() -> dict:
14
+ return {
15
+ "metadata": {"adapter_type": "bigquery"},
16
+ "sources": {
17
+ "source.p.raw.events": {
18
+ "resource_type": "source",
19
+ "name": "events",
20
+ "identifier": "events",
21
+ "relation_name": "proj.raw.events",
22
+ "original_file_path": "models/sources.yml",
23
+ "columns": {
24
+ "event_id": {"data_type": "INT"},
25
+ "created_at": {"data_type": "TIMESTAMP"},
26
+ "is_default": {"data_type": "BOOL"},
27
+ "amount": {"data_type": "INT"},
28
+ },
29
+ }
30
+ },
31
+ "nodes": {
32
+ "model.p.fct_dec_events": {
33
+ "resource_type": "model",
34
+ "name": "fct_dec_events",
35
+ "alias": "fct_dec_events",
36
+ "relation_name": "proj.mart.fct_dec_events",
37
+ "original_file_path": "models/mart/fct_dec_events.sql",
38
+ "config": {"materialized": "table"},
39
+ "meta": {"table_gb": 1024, "runs_per_month": 30},
40
+ "compiled_code": (
41
+ "SELECT event_id, amount FROM proj.raw.events "
42
+ "WHERE EXTRACT(YEAR FROM created_at) = 2025 AND EXTRACT(MONTH FROM created_at) = 12"
43
+ ),
44
+ "depends_on": {"nodes": ["source.p.raw.events"]},
45
+ "columns": {},
46
+ },
47
+ "model.p.fct_default_events": {
48
+ "resource_type": "model",
49
+ "name": "fct_default_events",
50
+ "alias": "fct_default_events",
51
+ "relation_name": "proj.mart.fct_default_events",
52
+ "original_file_path": "models/mart/fct_default_events.sql",
53
+ "config": {"materialized": "table"},
54
+ "meta": {},
55
+ "compiled_code": (
56
+ "SELECT event_id, amount FROM proj.raw.events WHERE COALESCE(is_default, FALSE)"
57
+ ),
58
+ "depends_on": {"nodes": ["source.p.raw.events"]},
59
+ "columns": {},
60
+ },
61
+ "model.p.clean_model": {
62
+ "resource_type": "model",
63
+ "name": "clean_model",
64
+ "alias": "clean_model",
65
+ "relation_name": "proj.mart.clean_model",
66
+ "original_file_path": "models/mart/clean_model.sql",
67
+ "config": {"materialized": "table"},
68
+ "compiled_code": "SELECT event_id, amount FROM proj.raw.events WHERE amount > 10",
69
+ "depends_on": {"nodes": ["source.p.raw.events"]},
70
+ "columns": {},
71
+ },
72
+ },
73
+ }
74
+
75
+
76
+ def test_per_model_dbt_meta_and_table_stats_precedence(tmp_path: Path) -> None:
77
+ mpath = tmp_path / "target" / "manifest.json"
78
+ mpath.parent.mkdir(parents=True)
79
+ mpath.write_text(json.dumps(_manifest_with_meta()), encoding="utf-8")
80
+
81
+ # 1. dbt meta: calibrates fct_dec_events ONLY; fct_default_events has no meta -> None (never fabricated!)
82
+ rep_meta = audit_dbt_manifest(tmp_path, target=WarehouseTarget.BIGQUERY_ONDEMAND, bound=2)
83
+ d_meta = rep_meta.to_dict()
84
+ by_name = {f["model_name"]: f for f in d_meta["findings"]}
85
+ # 1024 GB x 30 runs x 91.3% x $6.25/TB = $171.19
86
+ assert by_name["fct_dec_events"]["recommended"][0]["estimated_monthly_usd"] == 171.19
87
+ assert by_name["fct_default_events"]["recommended"][0]["estimated_monthly_usd"] is None
88
+ assert d_meta["summary"]["estimated_monthly_usd_total"] == 171.19
89
+
90
+ # 2. table_stats.json overrides dbt meta: on fct_dec_events AND supplies stats for fct_default_events
91
+ stats_file = tmp_path / "table_stats.json"
92
+ stats_file.write_text(
93
+ json.dumps(
94
+ {
95
+ "cost_per_tb": 5.0,
96
+ "models": {
97
+ "fct_dec_events": {"table_gb": 2048, "runs_per_month": 30},
98
+ "fct_default_events": {"table_gb": 512, "runs_per_month": 60},
99
+ },
100
+ }
101
+ ),
102
+ encoding="utf-8",
103
+ )
104
+ rep_stats = audit_dbt_manifest(
105
+ tmp_path,
106
+ target=WarehouseTarget.BIGQUERY_ONDEMAND,
107
+ table_stats_path=stats_file,
108
+ bound=2,
109
+ )
110
+ d_stats = rep_stats.to_dict()
111
+ by_name_s = {f["model_name"]: f for f in d_stats["findings"]}
112
+ # fct_dec_events: 2 TB x 30 x 91.3% x $5.00 = $273.90
113
+ assert by_name_s["fct_dec_events"]["recommended"][0]["estimated_monthly_usd"] == 273.90
114
+ # fct_default_events: 0.5 TB x 60 x 87.1% x $5.00 = $130.65
115
+ assert by_name_s["fct_default_events"]["recommended"][0]["estimated_monthly_usd"] == 130.65
116
+ assert d_stats["summary"]["estimated_monthly_usd_total"] == 404.55
117
+
118
+
119
+ def test_cli_skip_if_clean_prevents_pr_comment_spam(tmp_path: Path, capsys) -> None:
120
+ mpath = tmp_path / "target" / "manifest.json"
121
+ mpath.parent.mkdir(parents=True)
122
+ mpath.write_text(json.dumps(_manifest_with_meta()), encoding="utf-8")
123
+
124
+ # Auditing ONLY clean_model with --skip-if-clean must produce ZERO stdout (so GH Action posts no comment)
125
+ rc = cli_main(
126
+ [
127
+ "audit",
128
+ str(tmp_path),
129
+ "--models",
130
+ "clean_model",
131
+ "--target",
132
+ "bigquery-ondemand",
133
+ "--format",
134
+ "github-pr",
135
+ "--skip-if-clean",
136
+ ]
137
+ )
138
+ assert rc == 0
139
+ assert capsys.readouterr().out == ""
140
+
141
+ # Auditing fct_dec_events with --skip-if-clean emits the full PR comment with dbt meta: $/mo estimate
142
+ rc = cli_main(
143
+ [
144
+ "audit",
145
+ str(tmp_path),
146
+ "--models",
147
+ "fct_dec_events",
148
+ "--target",
149
+ "bigquery-ondemand",
150
+ "--format",
151
+ "github-pr",
152
+ "--skip-if-clean",
153
+ ]
154
+ )
155
+ assert rc == 0
156
+ out = capsys.readouterr().out
157
+ assert "fct_dec_events" in out
158
+ assert "$171.19/mo" in out
159
+ assert "<details>" in out
160
+
161
+
162
+ def test_flat_table_stats_json_format_via_cli(tmp_path: Path, capsys) -> None:
163
+ mpath = tmp_path / "target" / "manifest.json"
164
+ mpath.parent.mkdir(parents=True)
165
+ mpath.write_text(json.dumps(_manifest_with_meta()), encoding="utf-8")
166
+
167
+ flat_stats = tmp_path / "flat_stats.json"
168
+ flat_stats.write_text(
169
+ json.dumps({"fct_default_events": {"table_gb": 1024, "runs_per_month": 30}}),
170
+ encoding="utf-8",
171
+ )
172
+ rc = cli_main(
173
+ [
174
+ "audit",
175
+ str(tmp_path),
176
+ "--models",
177
+ "fct_default_events",
178
+ "--target",
179
+ "bigquery-ondemand",
180
+ "--table-stats",
181
+ str(flat_stats),
182
+ "--format",
183
+ "json",
184
+ ]
185
+ )
186
+ assert rc == 0
187
+ payload = json.loads(capsys.readouterr().out)
188
+ # 1 TB x 30 x 87.1% x $6.25 = $163.31
189
+ assert payload["summary"]["estimated_monthly_usd_total"] == 163.31
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes