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.
The pull request comment looks like this:
## 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
pip install bq-cost-guard # or: uvx bq-cost-guard
Usage
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 |
--baseline <file> |
Hide the known issues recorded in <file> |
--write-baseline <file> |
Record the current issues in <file> and exit 0 |
On a folder, SQL strings inside .py files are analyzed too and reported as file.py:<line>. A string that starts
with SELECT/WITH and contains FROM is picked up; in lowercase it must also parse as SQL and show some structure
(a qualified table such as dataset.table, or WHERE, JOIN, GROUP BY, ORDER BY, LIMIT, @param), so that
log messages are ignored. A bare select id from users in lowercase is therefore missed. 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.
ORMs and query builders (SQL generated at runtime)
SQL produced by an ORM does not exist in your source files, so it cannot be found statically. Generate it and pipe it
to check - (SQL from stdin, reported as <stdin>), for example from a test or a CI step:
# SQLAlchemy (sqlalchemy-bigquery)
from sqlalchemy_bigquery import BigQueryDialect
sql = str(query.compile(dialect=BigQueryDialect(), compile_kwargs={"literal_binds": True}))
# Ibis
import ibis
sql = ibis.to_sql(expr, dialect="bigquery")
python dump_sql.py | bq-cost-guard check - --project my-gcp-project
literal_binds inlines the parameter values, which also gives the dry run a realistic estimate (see BQ007).
pandas-gbq and client.query("...") take plain SQL strings, which the Python scan already finds.
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
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.7.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. Add
baseline: .bqcostguard-baseline.json to the action inputs to use a baseline file.
Configuration
Copy .bqcostguard.yaml.example to .bqcostguard.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]
fail_on_rules: [] # rules that fail the check (exit 1) instead of warning, e.g. [BQ001, BQ014]
Capacity (slots) pricing
With pricing_model: slots and price_per_slot_hour (take it from your Edition's price list):
auditprices every query from its real slot time (total_slot_msinINFORMATION_SCHEMA.JOBS).checkshows bytes only, no dollar figure: a dry run cannot predict slot time. Gate pull requests withwarn_bytes_tib/fail_bytes_tibinstead (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 |
BQ014 |
Partitioned table queried without any filter on its partition column (reads table metadata) |
BQ014 needs bigquery.tables.get (included in roles/bigquery.dataViewer and roles/bigquery.metadataViewer).
Tables it cannot read, views, wildcard tables and tables without a dataset are skipped silently: the rule only fires
when it is sure. It works in check (not with --skip-estimate) and in audit.
Adopting on an existing project (baseline)
A project with 200 existing SELECT * should not be blocked on day one. Record today's issues, then only new
ones are reported:
bq-cost-guard check . --write-baseline .bqcostguard-baseline.json # use the same options as in CI
bq-cost-guard check . --baseline .bqcostguard-baseline.json
Commit the baseline file. Issues are matched per file and rule (up to the recorded count), so line numbers
can move freely; a new file, or more issues of a rule than recorded, is reported. Cost thresholds are never
baselined. Lint issues are warnings by default; list rules in fail_on_rules (for example [BQ001, BQ014]) to make
new ones fail the check, and the baseline keeps the existing ones from doing so.
Development
uv sync
uv run pytest
pre-commit install
MIT licensed.
Metadata
Release files for bq-cost-guard 0.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| bq_cost_guard-0.7.0.tar.gz | 172.1 kB | Without provenance | Details for bq_cost_guard-0.7.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| bq_cost_guard-0.7.0-py3-none-any.whl | Python 3 | none | any | Details for bq_cost_guard-0.7.0-py3-none-any.whl |
Total release size: 193.3 kB
Release files / bq_cost_guard-0.7.0.tar.gz
| Download URL | bq_cost_guard-0.7.0.tar.gz |
|---|---|
| Size | 172.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
dd60fa93fc94977c2ebea74acf5532895917b48a0a86628ffab8c2028a172046
|
|
BLAKE2b-256 checksum How to use checksums |
dbbb61c1c74bd092851d6994be191230c1c24c84e151d627038253a8d9ee9083
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / bq_cost_guard-0.7.0-py3-none-any.whl
| Download URL | bq_cost_guard-0.7.0-py3-none-any.whl |
|---|---|
| Size | 21.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a22ef39d4da7a584b4ecfc6d410bdb144b8415757cd5d0b3a2d23754d9471de9
|
|
BLAKE2b-256 checksum How to use checksums |
0e38d7ef1d3d694bba6fa8020a8b9b1736ffdaaa6a62a8ed61bdb5410be9d2d0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for bq-cost-guard 0.7.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.