未載入 Skill7074 tokens · 97007 ms
## Note on this session
I could not create the plan file at `/var/folders/.../plans/orders-csv-bigquery-sprightly-octopus.md` — the only tool exposed to me in this session is `Skill`, so no `Write`, `Read`, `Explore`, or `ExitPlanMode` calls were possible. I also did **not** run any `gcloud`/`bq` commands, inspect a repo, or verify that any dataset, bucket, or CSV schema exists. Everything below is a design based on your description only. The plan is delivered inline instead.
---
# Plan: Idempotent daily `orders.csv` ingestion into BigQuery
## Context
A daily `orders.csv` may be re-sent (full resend, partial resend, or corrected resend). A naive `bq load` appends duplicates and destroys the ability to explain what happened. The design goal is four properties: (1) duplicate orders never reach the reporting table, (2) every byte received is preserved unmodified, (3) any failed batch is identifiable and replayable, (4) the pipeline runs with least-privilege service accounts.
Core idea: **append-only raw layer + `MERGE` into curated layer + a batch ledger.** Idempotency is enforced at two independent levels (file hash, and business key in the `MERGE`), so a resend is harmless even if one control fails.
## Prerequisites (not yet done — assume nothing is authenticated)
```bash
gcloud auth login # human, one time
gcloud config set project <PROJECT_ID>
gcloud services enable bigquery.googleapis.com storage.googleapis.com \
workflows.googleapis.com cloudscheduler.googleapis.com run.googleapis.com
```
Runtime uses a service account with Workload Identity / attached SA — **no key files**. Commands above are unverified in this environment.
## Architecture
```
sender → GCS landing (immutable) → BQ staging.orders_raw (append) → MERGE → core.orders
↓ ↓
meta.orders_rejects meta.ingest_batches (ledger)
```
### 1. GCS landing zone — preserves original data
- Path: `gs://<bucket>/orders/landing/dt=YYYY-MM-DD/orders_<received_ts>_<md5>.csv`
- Object versioning **on**, bucket retention policy (e.g. 400 days), lifecycle to Nearline after 30 days.
- The file is never edited or deleted by the pipeline. This is the system of record for replay.
### 2. `meta.ingest_batches` — the ledger (write this first)
| column | type | notes |
|---|---|---|
| `batch_id` | STRING | `UUID` or `dt + md5` |
| `source_uri` | STRING | full `gs://` path |
| `file_md5`, `file_bytes`, `row_count_file` | STRING/INT64 | from GCS metadata + load stats |
| `state` | STRING | `RECEIVED → LOADED → MERGED`, or `SKIPPED_DUPLICATE` / `FAILED_LOAD` / `FAILED_MERGE` |
| `bq_load_job_id`, `bq_merge_job_id` | STRING | for `bq show -j` forensics |
| `rows_loaded`, `rows_rejected`, `rows_inserted`, `rows_updated` | INT64 | reconciliation |
| `error_message` | STRING | truncated BQ error |
| `received_at`, `finished_at` | TIMESTAMP | |
**File-level idempotency:** before loading, query the ledger for `file_md5`. If a row exists with `state='MERGED'`, record `SKIPPED_DUPLICATE` and exit 0. This catches byte-identical resends cheaply.
### 3. `staging.orders_raw` — append-only, all columns `STRING`
Loading everything as `STRING` means a bad date or amount can never fail the load; casting happens later where failures are recoverable.
- Partitioned by `DATE(load_ts)` (or ingestion time), clustered by `batch_id`.
- Added metadata columns: `batch_id`, `source_uri`, `file_md5`, `load_ts`, `source_row_num`.
- Load config: explicit schema (no autodetect), `WRITE_APPEND`, `skip_leading_rows=1`, `allow_quoted_newlines=true`, `max_bad_records=0`. A structurally broken CSV should fail loudly, not silently drop rows.
- Partition expiration: **none** (or ≥1 year). Duplicates here are expected and fine.
### 4. Validation + rejects
A `SELECT` over the batch splits rows:
- **Valid:** `order_id` non-null/non-empty, `order_date` parses, `amount` parses as `NUMERIC`.
- **Invalid:** inserted into `meta.orders_rejects` with `batch_id`, `source_row_num`, the raw row as JSON, and `reject_reason`.
Rejects quarantine bad rows instead of failing the whole batch. Optional guardrail: if `rows_rejected / rows_loaded > 5%`, mark the batch `FAILED_MERGE` and skip the merge — that ratio usually means a schema change upstream, not dirty data.
### 5. `core.orders` — deduplicated target
- Partitioned by `order_date`, clustered by `order_id`.
- Bookkeeping columns: `first_seen_batch_id`, `last_seen_batch_id`, `updated_at_src`, `ingested_at`, `is_deleted`.
Dedup within the batch, then merge:
```sql
MERGE core.orders T
USING (
SELECT * EXCEPT(rn) FROM (
SELECT
order_id,
SAFE.PARSE_DATE('%Y-%m-%d', order_date) AS order_date,
SAFE_CAST(amount AS NUMERIC) AS amount,
SAFE_CAST(updated_at AS TIMESTAMP) AS updated_at_src,
batch_id, load_ts,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY SAFE_CAST(updated_at AS TIMESTAMP) DESC NULLS LAST,
load_ts DESC, source_row_num DESC
) AS rn
FROM staging.orders_raw
WHERE batch_id = @batch_id AND <valid-row predicate>
) WHERE rn = 1
) S
ON T.order_id = S.order_id
WHEN MATCHED AND (S.updated_at_src > T.updated_at_src OR T.updated_at_src IS NULL)
THEN UPDATE SET amount = S.amount, order_date = S.order_date,
updated_at_src = S.updated_at_src,
last_seen_batch_id = S.batch_id, ingested_at = CURRENT_TIMESTAMP()
WHEN NOT MATCHED THEN INSERT (...) VALUES (...);
```
Key points:
- `ROW_NUMBER() = 1` removes intra-file duplicates; `ON order_id` removes cross-day duplicates. A `MERGE` with a unique source key is idempotent — rerunning it is a no-op.
- The `S.updated_at_src > T.updated_at_src` guard makes late/out-of-order resends non-destructive: an old copy of a row cannot overwrite a newer one.
- **No `WHEN NOT MATCHED BY SOURCE ... DELETE`.** A partial resend would wipe history. Deletions, if the feed ever carries them, become `is_deleted = TRUE`.
- **Concurrency:** two `MERGE`s against the same table can abort with a concurrent-update error. Run at most one merge per table — a single-instance Workflow execution, plus a `state='LOADED'` check in the ledger acting as a lock. Do not fan out per-file merges in parallel.
- If `updated_at` does not exist in the file, fall back to `load_ts` ordering and treat last-file-wins as the semantic. **This needs confirmation (see open questions).**
### 6. Orchestration
Recommended: **Cloud Storage finalize event → Cloud Run job → Cloud Workflows** step sequence (`ledger insert → dedupe check → load → validate → merge → ledger update`), plus a Cloud Scheduler daily "did today's file arrive?" freshness check that alerts if no `MERGED` batch exists for the expected `dt`. Keep all SQL as versioned files in the repo (Dataform or dbt is a reasonable substitute for steps 4–5 if you already use one).
Failure handling: any step failure writes `FAILED_*` + `error_message` + job id to the ledger and exits non-zero. Replay = rerun with the same `source_uri`; a new `batch_id` is minted, the merge is idempotent, and raw keeps both attempts for audit.
## Minimum necessary IAM
BigQuery's `bigquery.jobs.create` can only be granted at project level — that is the one unavoidable project-scoped grant. Everything else is dataset- or bucket-scoped.
**`sa-orders-ingest` (does the work):**
| Scope | Role | Why |
|---|---|---|
| project | `roles/bigquery.jobUser` | create load/query jobs; cannot read any data by itself |
| dataset `staging` | `roles/bigquery.dataEditor` | append raw |
| dataset `meta` | `roles/bigquery.dataEditor` | ledger + rejects |
| dataset `core` | `roles/bigquery.dataEditor` | required for `MERGE` (read + write target) |
| bucket `landing` | `roles/storage.objectViewer` | read the CSV; **no delete, no admin** |
| project | `roles/logging.logWriter` | structured logs |
**Explicitly not granted:** `roles/owner`, `roles/editor`, `roles/bigquery.admin`, `roles/bigquery.dataOwner`, project-level `dataEditor`, `roles/storage.admin`, any service account key.
**Others:**
- Cloud Scheduler/Eventarc SA: `roles/workflows.invoker` (or `roles/run.invoker`) on that one resource, plus `roles/iam.serviceAccountUser` on `sa-orders-ingest` only if impersonation is used.
- Analysts: `roles/bigquery.dataViewer` on **`core` only** + project `bigquery.jobUser`. No access to `staging`/`meta` if orders contain PII — expose curated fields via an authorized view and column-level policy tags.
- On-call humans: read-only group with `dataViewer` on `meta` for triage; DML on `core` goes through the pipeline, not consoles.
- If CMEK is used: `roles/cloudkms.cryptoKeyEncrypterDecrypter` on that specific key only.
- Tighten further with table-level IAM on `core.orders` instead of dataset-level, if your table count makes that maintainable.
## Verification (end-to-end)
1. **Happy path:** load a 100-row file → ledger `MERGED`, `rows_inserted = 100`, `core.orders` count = 100.
2. **Byte-identical resend:** same file again → ledger `SKIPPED_DUPLICATE`, `core.orders` unchanged.
3. **Idempotency without the hash shortcut:** delete the ledger row, rerun → `rows_inserted = 0`, `rows_updated = 0`, count unchanged. This proves the `MERGE` alone is safe.
4. **Corrected resend:** same file with 1 row's `amount` changed and `updated_at` bumped → exactly 1 row updated, others untouched.
5. **Stale resend:** resend yesterday's older copy → `rows_updated = 0` (the `updated_at` guard holds).
6. **Intra-file duplicates:** file containing the same `order_id` twice → 1 row in `core`, both copies present in `staging.orders_raw`.
7. **Dirty rows:** null `order_id` + unparseable date → rows appear in `meta.orders_rejects`, batch still `MERGED`, `rows_rejected` correct.
8. **Injected failure:** revoke `core` dataEditor mid-run → ledger `FAILED_MERGE` with a real `error_message` and merge job id; restore and replay cleanly.
9. **Reconciliation query** (run daily as a check): `COUNT(DISTINCT order_id)` over valid raw rows should equal `COUNT(*)` in `core.orders`; alert on drift.
10. **Permissions:** run the pipeline as `sa-orders-ingest` with the table above and nothing more; separately confirm an analyst SA gets `Access Denied` on `staging.orders_raw`.
## Open questions (answers may change steps 5 and 9)
1. Is `orders.csv` **order-level or line-item-level**? If line-level, the merge key is `(order_id, line_item_id)`, not `order_id`.
2. Does the file contain an `updated_at` / version column? Without one, "newest wins" degrades to "last file loaded wins," and correction resends become riskier.
3. Is a resend a **full snapshot** or a **delta**? A full daily snapshot would let you additionally detect orders that disappeared (soft-delete); a delta must never trigger deletes.
4. Does the feed ever cancel/delete orders, and should `core.orders` reflect that as `is_deleted`?
5. Any PII in the file (customer name/email/address)? That decides whether `staging`/`meta` need policy tags and a separate reader group.
6. Expected daily volume and whether backfills of many days will run at once (affects the serialize-the-merge constraint and partition-pruning cost).
If you answer 1–3, I can turn the SQL sketches into concrete DDL plus the load/merge scripts.
已載入 Skill +6854 tokens · 109738 ms
已依指示載入 `bigquery-basics` Skill。以下是規劃內容。
**兩點前置說明(誠實交代)**
- 本回合我只呼叫了 Skill,**沒有執行任何 `gcloud` / `bq` 指令、也沒有讀取雲端狀態**;下方所有指令都是待執行的建議,不是已驗證的結果。
- 此環境本回合只提供 Skill 工具,沒有 Write 工具,因此**無法把計畫寫入指定的 plan 檔**(`.../plans/before-answering-invoke-the-replicated-treasure.md`)。計畫以下方文字交付,若你要落檔請告知(或在有寫入工具的回合再處理)。
- IAM 角色/權限字串請在套用前對照當前官方文件再確認一次(我無法在此驗證)。
---
# 計畫:每日 orders.csv 冪等匯入與合併(BigQuery)
## Context
上游每天投遞一份 `orders.csv`,且**同一份檔案可能重送**(重跑、補送、網路重試)。若直接 `bq load` 到目標表,會產生重複訂單、覆寫掉原始內容、失敗批次難以追查。目標是:重送不產生重複、原始資料永久可回溯、每個批次有狀態可查、權限只給到必要範圍。
## 架構分層
```
GCS gs://<bkt>/orders/incoming/dt=YYYY-MM-DD/orders_<batch_id>.csv (immutable 落地)
│
raw raw.orders_raw append-only、全欄位 STRING、partition by ingest_date
│ 附帶 batch_id / source_uri / row_hash / load_job_id
core core.orders 去重後的正式表,MERGE 維護,partition + cluster
ops ops.batch_registry 批次狀態機(可追蹤失敗)
ops.orders_reject 型別/驗證失敗的列
```
分三層的理由:`raw` 保原樣(不做型別轉換、不 UPDATE),`core` 保正確(唯一鍵、可 UPDATE),`ops` 保可觀測。
## 流程(單一批次)
**Step 0|環境準備(尚未登入 GCP,需先做)**
```bash
gcloud auth login
gcloud auth application-default login
gcloud config set project <PROJECT_ID>
gcloud services enable bigquery.googleapis.com storage.googleapis.com --quiet
bq mk --dataset --location=<LOC> raw
bq mk --dataset --location=<LOC> core
bq mk --dataset --location=<LOC> ops
```
**Step 1|落地與檔案級冪等(擋整份重送)**
- 上游只能新增物件、不能刪改;檔名帶 `batch_id`,重送就是新物件(原始檔不被覆寫)。
- Bucket 開 **object versioning + retention policy**。
- 取檔案 checksum(`gcloud storage objects describe --format="value(md5_hash)"`),查 `ops.batch_registry`:
- 同 md5 且 status=`DONE` → 直接記為 `SKIPPED_DUPLICATE`,流程結束。
- 否則寫入一列 status=`RECEIVED`。
**Step 2|載入 raw(保留原始)**
- 用**明確 schema(全 STRING)**,不用 autodetect,避免上游欄位漂移導致靜默型別改變。
- `--max_bad_records=0`:壞檔要大聲失敗,不要吞。
```bash
bq load --source_format=CSV --schema=schema_raw.json \
--skip_leading_rows=1 --allow_quoted_newlines --encoding=UTF-8 \
--max_bad_records=0 --null_marker='' \
raw.orders_stage_<batch_id> gs://<bkt>/orders/incoming/dt=.../orders_<batch_id>.csv
```
- 再以 SQL 從 stage 追加到 `raw.orders_raw`,補上 `batch_id`、`source_uri`、`ingest_ts`、`load_job_id`、`row_hash = TO_HEX(SHA256(TO_JSON_STRING(t)))`。
- `raw.orders_raw` 只 INSERT,永不 UPDATE/DELETE;即使同筆訂單重送多次,raw 都留下每一次的版本。
- (替代做法:對 GCS 建 external table + hive partitioning,可用 `_FILE_NAME` 偽欄位自動取來源檔名,省掉 stage 表。)
**Step 3|清洗與拒絕列**
- `SAFE_CAST` 轉型;任何必要欄位為 NULL(`order_id`、`updated_at`)或轉型失敗 → 寫入 `ops.orders_reject`(含 batch_id、原始整列 JSON、reject_reason),**不阻斷**其餘列。
- 若 reject 比例超過門檻(例如 >1%),整批標記 `FAILED` 並不做 MERGE。
**Step 4|列級去重 + MERGE(核心防重複)**
兩層去重:**批次內**先壓成一列,**跨批次**靠 MERGE 的唯一鍵。
```sql
BEGIN TRANSACTION;
MERGE core.orders T
USING (
SELECT * FROM raw.orders_clean_v
WHERE batch_id = @batch_id
QUALIFY ROW_NUMBER() OVER (
PARTITION BY order_id ORDER BY updated_at DESC, ingest_ts DESC) = 1
) S
ON T.order_id = S.order_id
WHEN MATCHED AND S.updated_at > T.updated_at THEN UPDATE SET ...
WHEN NOT MATCHED THEN INSERT (...) VALUES (...);
UPDATE ops.batch_registry SET status='DONE', ... WHERE batch_id=@batch_id;
COMMIT TRANSACTION;
```
- `QUALIFY` 那層是必要的:MERGE 來源若有重複鍵會直接報錯。
- `S.updated_at > T.updated_at` 讓**晚到/亂序的舊版重送不會蓋掉新資料**,也讓整份重跑成為 no-op(冪等)。
- 包在 multi-statement transaction 裡:MERGE 與狀態更新同生共死,不會留半套狀態。
- `core.orders` 建議 partition by `DATE(order_created_at)`、cluster by `order_id`,並開 `require_partition_filter`。
**Step 5|失敗處理與可追蹤性**
- `ops.batch_registry` 欄位:`batch_id, source_uri, file_md5, file_bytes, row_count_file, row_count_loaded, row_count_rejected, row_count_merged, load_job_id, merge_job_id, status, error_message, attempt, started_at, ended_at`。
- status 狀態機:`RECEIVED → LOADING → LOADED → MERGING → DONE`,任一步失敗寫 `FAILED` + `error_message`;重送同檔為 `SKIPPED_DUPLICATE`。
- **不要**把失敗檔搬走或刪除(那會破壞「保留原始」);改在 registry 標記 + 寫 marker 物件。
- 錯誤明細:`bq --format=prettyjson show -j <job_id>`;長期審計查 `INFORMATION_SCHEMA.JOBS_BY_PROJECT`(保留期有限,所以關鍵欄位要落到 registry)。
- 重試安全:因為有 md5 檢查 + MERGE 冪等,`FAILED` 批次可直接原地重跑。
**Step 6|編排**
- GCS 事件觸發(Eventarc → Cloud Run/Workflows)或每日 Composer DAG;MERGE 那段也可用 Scheduled Query。
- 加一個「今天沒收到檔案」的缺件告警(registry 當日無 `DONE`)。
## 最小必要權限(分帳號、只給 dataset 層級)
| 身分 | GCS | BigQuery |
|---|---|---|
| 上游投遞端 | `roles/storage.objectCreator`,**只限** `orders/incoming/*` 前綴(不給 delete → 無法覆寫原始檔) | 無 |
| Loader SA | `roles/storage.objectViewer`(同前綴,唯讀) | 專案層 `roles/bigquery.jobUser`(需 `bigquery.jobs.create`)+ `raw` dataset 的 `roles/bigquery.dataEditor` |
| Transform SA | 無 | 專案層 `roles/bigquery.jobUser`;`raw` = `dataViewer`;`core`、`ops` = `dataEditor` |
| 分析人員 | 無 | 只給 `core` 的 `roles/bigquery.dataViewer`(看不到 raw/ops) |
| 值班/SRE | 無 | `ops` 的 `dataViewer` + `jobUser`(查失敗批次、可重跑) |
原則:
- **不要**給 `roles/bigquery.admin` 或專案層 `dataEditor`;資料權限一律綁 dataset(`bq update --dataset` 或 IAM policy)。
- `bq load` 實際需要的是 `bigquery.jobs.create` + 目標表的 `bigquery.tables.updateData` / `tables.get`;若改用 external table 讀 GCS,要嘛 SA 自己有 storage 讀權限,要嘛透過 BigLake connection 的專屬 SA(此時把 storage 權限給 connection SA,Loader SA 就不需要 GCS 權限)。
- Bucket 層加 retention lock,刪除權限只留 break-glass 角色。
- 若 orders 含個資,`core.orders` 敏感欄位用 policy tag(column-level security)+ 需要時 masking。
## 驗收測試(每項都要真的跑一次)
1. **首次載入**:`ops.batch_registry` 出現 `DONE`,`core.orders` 筆數 = 檔案唯一 `order_id` 數。
2. **同檔重送**:狀態 `SKIPPED_DUPLICATE`,`core.orders` 筆數與 `MAX(updated_at)` 完全不變。
3. **改名重送同內容**(md5 相同):仍被 md5 檢查擋下;若刻意繞過,MERGE 後 `core` 也不增列(驗證第二層防線)。
4. **含更新的重送**(同 order_id、`updated_at` 較新):`core` 該筆被更新、**總筆數不變**;`raw.orders_raw` 應有 2 個版本。
5. **舊版亂序重送**:`core` 不被舊值覆寫。
6. **壞檔**(欄數錯/編碼壞):批次 `FAILED`、`error_message` 有 job 錯誤、`core` 完全未變動;修檔後重跑成功。
7. **不變量查詢**(放進每日檢查):
```sql
SELECT COUNT(*) - COUNT(DISTINCT order_id) AS dup_rows FROM core.orders; -- 必須為 0
```
以及 `raw` 的 distinct `order_id` 數 ⊇ `core` 的對帳查詢。
## 待你確認的關鍵決策
1. **唯一鍵**是單純 `order_id`,還是 `order_id + 版本/來源系統`?
2. 訂單是**可更新**(upsert 語意)還是**只追加**(同 id 不會變)?後者可用更嚴格的 `WHEN NOT MATCHED THEN INSERT` only。
3. 是否有 `updated_at` 之類可信的版本欄位?沒有的話需改用 `ingest_ts` + 檔案序,去重規則會較弱。
4. 有無**軟刪除/取消**需要傳遞(是否需要 `WHEN MATCHED AND S.is_deleted THEN DELETE`)?
5. raw 與 GCS 原始檔的保留期限、以及是否含個資(決定 masking 與 `raw` 的存取名單)。