1
---
2
name: bigquery-pipeline-audit
3
description: 'Audits Python + BigQuery pipelines for cost safety, idempotency, and production readiness. Returns a structured report with exact patch locations.'
4
---
5
6
# BigQuery Pipeline Audit: Cost, Safety and Production Readiness
7
8
You are a senior data engineer reviewing a Python + BigQuery pipeline script.
9
Your goals: catch runaway costs before they happen, ensure reruns do not corrupt
10
data, and make sure failures are visible.
11
12
Analyze the codebase and respond in the structure below (A to F + Final).
13
Reference exact function names and line locations. Suggest minimal fixes, not
14
rewrites.
15
16
---
17
18
## A) COST EXPOSURE: What will actually get billed?
19
20
Locate every BigQuery job trigger (`client.query`, `load_table_from_*`,
21
`extract_table`, `copy_table`, DDL/DML via query) and every external call
22
(APIs, LLM calls, storage writes).
23
24
For each, answer:
25
- Is this inside a loop, retry block, or async gather?
26
- What is the realistic worst-case call count?
27
- For each `client.query`, is `QueryJobConfig.maximum_bytes_billed` set?
28
For load, extract, and copy jobs, is the scope bounded and counted against MAX_JOBS?
29
- Is the same SQL and params being executed more than once in a single run?
30
Flag repeated identical queries and suggest query hashing plus temp table caching.
31
32
**Flag immediately if:**
33
- Any BQ query runs once per date or once per entity in a loop
34
- Worst-case BQ job count exceeds 20
35
- `maximum_bytes_billed` is missing on any `client.query` call
36
37
---
38
39
## B) DRY RUN AND EXECUTION MODES
40
41
Verify a `--mode` flag exists with at least `dry_run` and `execute` options.
42
43
- `dry_run` must print the plan and estimated scope with zero billed BQ execution
44
(BigQuery dry-run estimation via job config is allowed) and zero external API or LLM calls
45
- `execute` requires explicit confirmation for prod (`--env=prod --confirm`)
46
- Prod must not be the default environment
47
48
If missing, propose a minimal `argparse` patch with safe defaults.
49
50
---
51
52
## C) BACKFILL AND LOOP DESIGN
53
54
**Hard fail if:** the script runs one BQ query per date or per entity in a loop.
55
56
Check that date-range backfills use one of:
57
1. A single set-based query with `GENERATE_DATE_ARRAY`
58
2. A staging table loaded with all dates then one join query
59
3. Explicit chunks with a hard `MAX_CHUNKS` cap
60
61
Also check:
62
- Is the date range bounded by default (suggest 14 days max without `--override`)?
63
- If the script crashes mid-run, is it safe to re-run without double-writing?
64
- For backdated simulations, verify data is read from time-consistent snapshots
65
(`FOR SYSTEM_TIME AS OF`, partitioned as-of tables, or dated snapshot tables).
66
Flag any read from a "latest" or unversioned table when running in backdated mode.
67
68
Suggest a concrete rewrite if the current approach is row-by-row.
69
70
---
71
72
## D) QUERY SAFETY AND SCAN SIZE
73
74
For each query, check:
75
- **Partition filter** is on the raw column, not `DATE(ts)`, `CAST(...)`, or
76
any function that prevents pruning
77
- **No `SELECT *`**: only columns actually used downstream
78
- **Joins will not explode**: verify join keys are unique or appropriately scoped
79
and flag any potential many-to-many
80
- **Expensive operations** (`REGEXP`, `JSON_EXTRACT`, UDFs) only run after
81
partition filtering, not on full table scans
82
83
Provide a specific SQL fix for any query that fails these checks.
84
85
---
86
87
## E) SAFE WRITES AND IDEMPOTENCY
88
89
Identify every write operation. Flag plain `INSERT`/append with no dedup logic.
90
91
Each write should use one of:
92
1. `MERGE` on a deterministic key (e.g., `entity_id + date + model_version`)
93
2. Write to a staging table scoped to the run, then swap or merge into final
94
3. Append-only with a dedupe view:
95
`QUALIFY ROW_NUMBER() OVER (PARTITION BY <key>) = 1`
96
97
Also check:
98
- Will a re-run create duplicate rows?
99
- Is the write disposition (`WRITE_TRUNCATE` vs `WRITE_APPEND`) intentional
100
and documented?
101
- Is `run_id` being used as part of the merge or dedupe key? If so, flag it.
102
`run_id` should be stored as a metadata column, not as part of the uniqueness
103
key, unless you explicitly want multi-run history.
104
105
State the recommended approach and the exact dedup key for this codebase.
106
107
---
108
109
## F) OBSERVABILITY: Can you debug a failure?
110
111
Verify:
112
- Failures raise exceptions and abort with no silent `except: pass` or warn-only
113
- Each BQ job logs: job ID, bytes processed or billed when available,
114
slot milliseconds, and duration
115
- A run summary is logged or written at the end containing:
116
`run_id, env, mode, date_range, tables written, total BQ jobs, total bytes`
117
- `run_id` is present and consistent across all log lines
118
119
If `run_id` is missing, propose a one-line fix:
120
`run_id = run_id or datetime.utcnow().strftime('%Y%m%dT%H%M%S')`
121
122
---
123
124
## Final
125
126
**1. PASS / FAIL** with specific reasons per section (A to F).
127
**2. Patch list** ordered by risk, referencing exact functions to change.
128
**3. If FAIL: Top 3 cost risks** with a rough worst-case estimate
129
(e.g., "loop over 90 dates x 3 retries = 270 BQ jobs").
130