Metadata-Version: 2.1
Name: sqlprove
Version: 0.2.0
Summary: Proof-carrying SQL cost optimizer for BigQuery, Snowflake, and dbt using Z3 SMT and DuckDB verification
License: MIT
Project-URL: Homepage, https://github.com/MarklarSystems/sqlprove
Project-URL: Repository, https://github.com/MarklarSystems/sqlprove
Project-URL: Issues, https://github.com/MarklarSystems/sqlprove/issues
Keywords: sql,dbt,bigquery,snowflake,duckdb,z3,smt,formal-verification,query-optimization,finops
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: duckdb >=1.1.0
Requires-Dist: sqlglot >=25.0.0
Requires-Dist: z3-solver >=4.13.0
Provides-Extra: dev
Requires-Dist: build >=1.0.0 ; extra == 'dev'
Requires-Dist: pytest >=8.0.0 ; extra == 'dev'
Requires-Dist: twine >=5.0.0 ; extra == 'dev'

# sqlprove

**Formally verified SQL cost optimizer for BigQuery, Snowflake, and dbt — 100% local, zero PII.**

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).

`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.

---

## Try in 10 Seconds (Zero Config, No dbt Needed)

```bash
pip install sqlprove

# 1. Watch Z3 + DuckDB catch subtle NULL & join-multiplication bugs live
sqlprove demo

# 2. Check any raw query on the spot (conservative inferred schema)
sqlprove check "SELECT event_id, amount FROM events WHERE EXTRACT(YEAR FROM created_at) = 2025 AND EXTRACT(MONTH FROM created_at) = 12" \
  --target bigquery-ondemand --table-gb 500 --runs-per-month 30

# 3. Watch Z3 refuse an unsafe dead-join drop with a concrete DuckDB counterexample,
#    then unlock an unbounded proof once you declare --unique customers.id:
sqlprove check "SELECT o.id, o.amount FROM orders o LEFT JOIN customers c ON o.customer_id = c.id" --target snowflake
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
```

---

## Live Cloud Benchmark Summary (Cold Runs, Zero Cache)

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).

| Formally Proven Rewrite Pattern | BigQuery On-Demand (`$/TB`) | BigQuery Editions (`slot_ms`) | Snowflake Scan (`MB`) | Snowflake Compute (`ms`) |
|---|---:|---:|---:|---:|
| Cross-view dead `LEFT JOIN` + nested `DISTINCT` (`A4`) | `-20.0%` | `-5.8%` | `-13.1%` | **-95.9%** (24.4×) |
| Redundant `DISTINCT` via dbt `unique`+`not_null` (`A3b`) | `-10.3%` | **-79.7%** | `0.0%` | **-60.7%** |
| Dead `INNER JOIN` via dbt `relationships` FK (`A2`) | `-4.3%` | **-65.6%** | `-13.1%` | **-31.6%** |
| `COALESCE(bool, FALSE)` / `NOT COALESCE` / `<> sentinel` (`A5`) | **-76.9% to -87.1%** | **-21% to -37.5%** | `0%` / `+4.1%` | **-10% to -31.3%** |
| `EXTRACT(YEAR/MONTH)` → `[lo, hi)` range (`A7`) | **-91.3%** | **-92.5%** | `-3.1%` | `-12.3%` |
| 2× repeated CTE `UNION ALL` → single pass (`A8`) | `0.0%` | **-61.2%** | `0.0%` | **-70.4%** (3.4×) |
| 4× disjoint `UNION ALL` `GROUP BY` → 1 scan (`A9`) | `0.0%` | **-74.8%** | **-75.0%** | **-62.7%** |
| Cross-col `OR` → disjoint `UNION ALL` w/ `IS NULL` (`A6`) | `0.0%` | **-75.6%** | `+16.5%` *(auto-blocked on Snowflake!)* | `+1.9%` |

---

## Audit a dbt Project (`target/manifest.json`)

```bash
dbt compile

# Audit compiled models + automatically unfold upstream logical views (`view`/`ephemeral`)
sqlprove audit . --target snowflake --format github-pr
sqlprove audit . --target bigquery-ondemand --table-gb 500 --runs-per-month 30 --format github-pr
sqlprove audit . --target bigquery-editions --show-all
```

### Drop-in GitHub Action (PR Comments with Proof Badges & Collapsible Diffs)

Save as `.github/workflows/sqlprove.yml` in your dbt repo:

```yaml
name: sqlprove SQL Cost Audit
on:
  pull_request:
    paths: ["models/**/*.sql", "models/**/*.yml"]

permissions:
  pull-requests: write

jobs:
  sqlprove:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install sqlprove
      # Run your existing `dbt compile` step (or point sqlprove at a cached target/manifest.json)
      - name: Run sqlprove audit
        run: |
          sqlprove audit . \
            --target bigquery-ondemand \
            --format github-pr > sqlprove-report.md
      - name: Comment on PR
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh pr comment "${{ github.event.pull_request.number }}" --body-file sqlprove-report.md
```

---

## Verification Tiers (Fail-Closed)

- **`ALGEBRAICALLY_PROVEN`** — Unbounded equivalence established by a sound schema-aware rule (`A0`–`A9`).
- **`BOUNDED_VERIFIED`** — Z3 proved `UNSAT` for every symbolic database up to `bound` rows per table (including arbitrary `NULL`s and duplicates).
- **`COUNTEREXAMPLE_FOUND`** — Z3 synthesized concrete input tables where the queries return different multisets, independently confirmed in DuckDB.
- **`UNSUPPORTED` / `UNKNOWN`** — Fails closed; never emitted as a proven rewrite.
- **0 false positives across 35,900 randomized `NULL`/duplicate/FK DuckDB fuzz trials.**

## Zero-PII Top-20 Warehouse Spend Audit (Pilot)

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.

## Layout

```text
sqlprove/
  src/sqlprove/
    cli.py            # CLI: demo, check, audit, rewrite, prove, scan
    audit.py          # Compiled dbt manifest audit & github-pr / markdown / json / text formatters
    dbt_manifest.py   # target/manifest.json loader, constraint extractor & sound view unfolder
    targets.py        # Live-benchmarked warehouse cost gating & parameterized $/mo estimator
    algebra.py        # Unbounded sound algebraic equivalence rules (A0-A9)
    prover.py         # Z3 SMT 3-valued NULL + bag-semantics equivalence checker
    rewrites.py       # Dialect-native candidate rewrites + CTE congruence verification
    schema.py         # Schema constraints, conservative inference & dbt schema.yml parser
    fuzzer.py         # DuckDB counterexample confirmer & randomized differential fuzzer
    corpus.py         # Raw dbt/SQL repository pattern scanner
    cost.py           # DuckDB EXPLAIN (ANALYZE, FORMAT JSON) profiler
  benchmarks/         # Corpus audit, blind LLM bug-catch, 1M-row scale, and $0 live BQ/SF scripts & results
  tests/              # Unit, soundness, manifest, view-unfolding, PR formatter & fuzz tests
```
