Metadata-Version: 2.5
Name: bq-cost-guard
Version: 0.5.0
Summary: Estimate BigQuery query cost and lint FinOps anti-patterns before merge.
Project-URL: Homepage, https://github.com/Mehdi-Leqsiouer/bq-cost-guard
Project-URL: Issues, https://github.com/Mehdi-Leqsiouer/bq-cost-guard/issues
Author: Mehdi Leqsiouer
License-Expression: MIT
License-File: LICENSE
Keywords: bigquery,ci,cost,dbt,finops,sql
Classifier: Environment :: Console
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.12
Requires-Dist: google-cloud-bigquery>=3.20
Requires-Dist: pydantic>=2.6
Requires-Dist: pyyaml>=6
Requires-Dist: rich>=13
Requires-Dist: sqlglot>=25
Requires-Dist: typer>=0.12
Description-Content-Type: text/markdown

# bq-cost-guard

Know what a query will cost **before** it is merged. `bq-cost-guard` runs a BigQuery dry run on your SQL
(raw files or compiled dbt models), flags costly anti-patterns, and comments the result on your pull request.

![bq-cost-guard demo](https://raw.githubusercontent.com/Mehdi-Leqsiouer/bq-cost-guard/main/docs/demo.gif)

The pull request comment looks like this:

```text
## BigQuery cost report

| Status | File | Processed | Est. cost |
|---|---|---|---|
| ❌ | `models/marts/events.sql` | 2.4 TiB | $15.2461 |
| ✅ | `models/marts/users.sql` | 4.9 MiB | $0.0000 |

**Total estimated cost: $15.2461**

### Warnings
- `models/marts/events.sql` **BQ001**: SELECT * scans every column; list only the columns you need.
```

## Install

```bash
pip install bq-cost-guard   # or: uvx bq-cost-guard
```

## Usage

```bash
bq-cost-guard check query.sql --project my-gcp-project
bq-cost-guard check ./dbt_project --git-diff origin/main --format markdown   # run `dbt compile` first
bq-cost-guard check ./sql --skip-estimate                                    # lint only, no GCP call
bq-cost-guard audit --project my-gcp-project --region eu --days 30           # past spend report
```

### `check` options

| Option | Description |
|---|---|
| `--format table\|markdown\|json` | Output format (default `table`) |
| `--git-diff <base>` | Only analyze files changed vs. `<base>` |
| `--project` | GCP project used for the dry run |
| `--config` | Path to `.bqcostguard.yaml` |
| `--skip-estimate` | Lint only |
| `--no-python` | Do not scan `.py` files for embedded SQL |

On a folder, SQL strings inside `.py` files (uppercase `SELECT`/`WITH ... FROM`) are analyzed too and reported as
`file.py:<line>`. f-strings with interpolated values are linted but not dry-run, since the final SQL is unknown.

Exit codes: `0` ok, `1` a query exceeds `fail_cost_usd`, `2` an estimation failed (auth, syntax, no project).
Dry runs are free and scan no data.

### `audit`

Reads `INFORMATION_SCHEMA.JOBS_BY_PROJECT` and reports the top query groups (literals normalized), cost by user
and lint rules triggered by the costliest queries. Options: `--project`, `--region` (default `us`), `--days`
(default 30), `--top` (default 20), `--format`. Requires `roles/bigquery.resourceViewer` (`bigquery.jobs.listAll`);
no table data is read. Costs are on-demand estimates from billed bytes (`price_per_tib`); the audit queries
themselves bill a few MiB.

## GitHub Action

```yaml
name: bq-cost-guard
on: pull_request
permissions:
  contents: read
  id-token: write
  pull-requests: write
jobs:
  cost:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: google-github-actions/auth@v2
        with:
          workload_identity_provider: ${{ vars.WIF_PROVIDER }}
          service_account: ${{ vars.WIF_SERVICE_ACCOUNT }}
      - uses: Mehdi-Leqsiouer/bq-cost-guard@v0.5.0
        with:
          path: .
          base: origin/${{ github.base_ref }}
          project: my-gcp-project
```

The service account needs `roles/bigquery.jobUser` and `roles/bigquery.dataViewer` on the queried datasets.

## Configuration

Copy `.bqcostguard.yaml.example` to `.bqcostguard.yaml`:

```yaml
pricing_model: on_demand   # or `slots` for capacity pricing (Editions)
price_per_tib: 6.25        # USD per TiB (on-demand)
warn_cost_usd: 1.0
fail_cost_usd: 10.0
ignore_rules: []           # e.g. [BQ002]
```

### Capacity (slots) pricing

With `pricing_model: slots` and `price_per_slot_hour` (take it from your Edition's price list):

- `audit` prices every query from its real slot time (`total_slot_ms` in `INFORMATION_SCHEMA.JOBS`).
- `check` shows **bytes only, no dollar figure**: a dry run cannot predict slot time. Gate pull requests with
  `warn_bytes_tib` / `fail_bytes_tib` instead (they also work with on-demand pricing).

## Rules

| Rule | Detects |
|---|---|
| `BQ001` | `SELECT *` |
| `BQ002` | `ORDER BY` without `LIMIT` in a subquery or CTE |
| `BQ003` | `CROSS JOIN`, implicit comma join or `ON 1=1` / `ON TRUE` without a `WHERE` |
| `BQ004` | Wildcard table (`events_*`) without a `_TABLE_SUFFIX` filter |
| `BQ005` | CTE referenced more than once that reads a table |
| `BQ006` | `LIMIT` without `WHERE` (does not reduce bytes billed) |
| `BQ007` | Named parameters (`@x`): a dry run cannot bind them, so the estimate may be too low |
| `BQ008` | `NOT IN (subquery)`: NULL trap, prefer `NOT EXISTS` |
| `BQ009` | Date/time function on a column in `WHERE` (`DATE(ts) = ...`): can prevent partition pruning |
| `BQ010` | `UNION DISTINCT`: use `UNION ALL` if duplicates cannot occur |
| `BQ011` | Window with `ORDER BY` but no `PARTITION BY` (single worker) |
| `BQ012` | Function on a join key (`ON LOWER(a.x) = b.x`) |
| `BQ013` | Correlated subquery in the `SELECT` list |

## Development

```bash
uv sync
uv run pytest
pre-commit install
```

MIT licensed.
