[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CAQPP22YKREVCWJRV9RJJ3":3,"skill-same:01M6CAQPP22YKREVCWJRV9RJJ3":122},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":17,"categories":18,"keywords":29,"publishedAt":60,"linkOnly":61,"markdownContent":62,"markdownBody":63,"frontMatter":64,"refName":67,"commitSha":68,"skillDirectory":69,"forksCount":70,"repositoryHtmlUrl":71,"repositoryHomepageUrl":13,"ownerHtmlUrl":72,"ownerBlogUrl":13,"ownerDescription":13,"updatedAt":73,"install":74,"resources":87},"01M6CAQPP22YKREVCWJRV9RJJ3","module-global-flag-race","模块全局标志竞态修复","Diagnose and fix module-global boolean\u002Fscalar flags used as schema or feature gates that race across concurrent writers — specifically the pattern where a single in-process bool gates \"have we confirmed the target table has these columns \u002F feature is initialized?\" and silently drops writes on cold replicas or transient init failures. Fires when a flag like `_payloads_schema_migrated`, `_feature_initialized`, `_schema_ready` (or any module-level \"we've finished first-time setup\" boolean) is the gate between the writer and a column set \u002F capability, when transient BQ \u002F DB \u002F feature-store failures leave the flag stuck False, and when sibling PRs (PR","诊断并修复被用作 schema 或功能开关、在并发写入方之间产生竞态的模块级布尔\u002F标量标志——特指这种场景：单个进程内布尔值充当“是否已确认目标表包含这些列 \u002F 功能是否已初始化？”的闸门，在冷副本或瞬时初始化失败时静默丢弃写入。当出现以下情况时触发：诸如 `_payloads_schema_migrated`、`_feature_initialized`、`_schema_ready` 之类的标志（或任何模块级“我们已完成首次初始化设置”的布尔值）充当写入方与某组列 \u002F 能力之间的闸门；BQ \u002F DB \u002F 特征存储的瞬时故障使标志卡在 False；以及当同级 PR（PR","jleechanorg\u002Fjleechan-skills","jleechanorg","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F221404966?v=4","01M6C1VJ99XG950X1DWPEBCBGX",null,"01M6C1VJDK5YVDNT3362RT5WSB",6,"MIT","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fsoftware-development\u002Fmodule-global-flag-race\u002FSKILL.md",[19,24],{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":25,"categoryName":26,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BRSRYQ3M8N5063NNQPF2B1","调试与故障排查","SCENARIO","使用场景",[30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],"module","module global flag race","global","bq","capability","cold","condition","db","time","writer","durable-fix","root-cause-fix","silent-drop","cold-start","schema-migration","bug-class","init","bug","ready","schema","payloads","fix","first","race-condition","cloud-run","SET","start","run","pr","diagnose","2026-11-10 10:12:30",false,"---\nname: module-global-flag-race\nversion: 1.3.0\ndescription: Diagnose and fix module-global boolean\u002Fscalar flags used as schema or feature gates that race across concurrent writers — specifically the pattern where a single in-process bool gates \"have we confirmed the target table has these columns \u002F feature is initialized?\" and silently drops writes on cold replicas or transient init failures. Fires when a flag like `_payloads_schema_migrated`, `_feature_initialized`, `_schema_ready` (or any module-level \"we've finished first-time setup\" boolean) is the gate between the writer and a column set \u002F capability, when transient BQ \u002F DB \u002F feature-store failures leave the flag stuck False, and when sibling PRs (PR #8070 \u002F #8351 family) keep trying to add retries + serialization without removing the underlying race. v1.3.0 adds Pitfall 11 (test-budget-vs-lock-hold regression — when a v1.1.0\u002Fv1.2.0 production-budget change (e.g. `_PAYLOADS_SCHEMA_RETRY_BUDGET_S = 0.5s`) breaks an existing test that holds a shared lock for longer than the new budget, the fix is to monkeypatch the budget wider in the TEST only, not loosen production; verified live 2026-07-24 against PR #8462 in $GITHUB_REPOSITORY where `test_startup_schema_migration_uses_shared_migration_lock` started failing 3\u002F3 on the PR head but passed 3\u002F3 on `origin\u002Fmain` HEAD — same file, same assertion, different conclusion driven by the new 0.5s production budget vs the test's 5s lock hold). v1.2.0 adds Pitfall 10 (the v1.1.0 cache fix STILL drops gated columns on cold replicas between deployments — `_payloads_schema_set is None` AND `_ensure_payloads_schema_cached()` returns False on first-call → `live_columns = frozenset()` → all gated columns silently dropped for that replica's lifetime; verified live 2026-07-19 against PR #8418 with 186 NULL is_test rows in last 24h after the cache-shape fix merged) AND the diagnostic recipe to prove cold-replica persistence from BQ alone (per-hour + per-minute buckets + no revision_id column = inferred cold-start) AND the recommended structural fix shape (boot-warmup fallback flag + retry-with-backoff; treat in-process `_payloads_schema()` as the cache when `ensure_dataset_and_tables` succeeded, since that means the table HAS those columns even if the cache is stale). v1.1.0 adds Step 4.1 (cooldown re-check inside the lock — third gate, CodeRabbit-flagged), Pitfall 8 (CI stub `GOOGLE_APPLICATION_CREDENTIALS=\u002Fdev\u002Fnull` failure mode requires mocking `_get_token_and_project` too, not just `_refresh_payloads_schema_set`), and Pitfall 9 (validate `tables.get` response shape before caching, or a malformed response silently drops ALL gated columns). Anti-trigger: cross-process \u002F distributed locks (those need different machinery — leader election, fencing tokens, etc.), per-call state (no race), or scalar config flags that are immutable for process lifetime (no race). Triggers on phrases like \"is_test IS NULL\", \"gated column dropped on cold replica\", \"global flag stuck False\", \"schema migration flag\", \"_payloads_schema_migrated\", \"boolean gate silently skips gated columns\", \"Cloud Run cold start drops writes\", \"two PRs tried to fix this\", or when verify-telemetry-alert \u002F systematic-debugging identifies the silent-drop class with a module-level boolean as the named suspect.\ntags: [bug-class, race-condition, schema-migration, cloud-run, cold-start, silent-drop, root-cause-fix, durable-fix]\n---\n\n# Module-Global Flag Race (the \"_payloads_schema_migrated pattern\")\n\nWhen a single **module-level boolean** in a Python service is used as a \"first-time setup complete\" gate on the hot write path, three things are simultaneously true and structurally broken:\n\n1. **Transient failure during init leaves the flag stuck False.** On a fresh Cloud Run replica (or any cold process start), the first caller's setup attempt fails with a transient BQ \u002F DB \u002F Redis error. The retry-after-N-seconds logic kicks in, but every writer in the meantime sees `flag == False` and silently drops the gated fields.\n2. **The flag is process-global, so cross-call race wins are inevitable.** Thread A finishes migration and sets the flag True. Thread B was mid-write, saw False, dropped gated fields. Thread C is now racing the flag flip. There is no \"make gated writes wait for first successful migration\" guarantee because the flag is non-atomic with the column-existence check.\n3. **Sibling PRs mitigate but never fix.** Each subsequent PR adds more code: a `_migration_started` companion flag, a `_migration_next_retry_at` backoff, a lock to serialize writers. None of these remove the boolean flag structurally — they only gate WHEN the flag flips. The first cold-start writer still silently drops fields.\n\nThe right fix is not \"add another flag\" or \"add another lock layer.\" The right fix is **replace the boolean with a per-process state cache keyed on the actual state** (column-name frozenset, capability list, etc.), populated by a single source-of-truth fetch (`tables.get`, `DESCRIBE`, capability probe) and guarded by a **double-check pattern under the same lock used to write the state**. Each gated field then independently guards on its presence in the cached state, not on a single global \"all-or-nothing\" flag.\n\n## When to use this skill\n\n- The bug surface is **silently dropped writes on a cold start** (co-NULL signature across multiple gated columns, full payload populated, no error logged).\n- A single module-level boolean (`_feature_ready`, `_schema_migrated`, `_cache_warmed`, etc.) is the named gate.\n- Two or more previous PRs attempted to fix it by adding serialization \u002F backoff \u002F retry-on-failure but kept the boolean flag in place.\n- The bug is reproducing live (per-day BQ rows, per-minute metrics, etc.) — not historic backlog.\n- A targeted BQ \u002F metric query proves the bug is live (co-NULL signature, arrival-time micro-bursts with no populated rows between them = producing process never saw a successful setup).\n\n## When NOT to use this skill\n\n- **Distributed locks \u002F cross-process coordination.** If you need a single global truth across replicas, the answer is leader election, fencing tokens, or an external coordinator (etcd, ZooKeeper, Cloud Run revision pinning). The fix shape here is intra-process only.\n- **Per-call state.** If the race only spans one request and the flag is set within that request, there is no flag race — just a missing initialization order.\n- **Immutable config flags.** If the flag is set from env \u002F config and never flips during process lifetime, there is no race. (You might still have a \"stuck on old value\" bug, but that's a different class.)\n- **Concurrency bugs unrelated to a boolean gate.** Deadlocks, data corruption, ordering violations — different classes.\n\n## The diagnostic recipe\n\nBefore fixing, prove the bug is this class, not something else:\n\n```bash\n# 1. Confirm co-NULL signature across multiple gated columns on the same row.\n#    A real race produces rows that ARE NULL on the gated set and POPULATED elsewhere.\n#    (A real bug elsewhere produces uniform NULL or uniform POPULATED rows.)\n\nbq query --use_legacy_sql=false \"\nSELECT\n  COUNTIF(\u003Ccol_a> IS NULL) AS null_a,\n  COUNTIF(\u003Ccol_b> IS NULL) AS null_b,\n  COUNTIF(\u003Ccol_a> IS NULL AND \u003Ccol_b> IS NULL) AS both_null\nFROM \\`\u003Cproject>.\u003Cdataset>.\u003Ctable>\\`\nWHERE \u003Ctime_window>\n\"\n\n# 2. Confirm arrival-time micro-bursts — rows arriving close together with NO\n#    populated rows between them. This is the fingerprint of \"one cold replica\n#    silently dropped writes for its lifetime\".\n\nbq query --use_legacy_sql=false \"\nSELECT\n  FORMAT_TIMESTAMP('%H:%M:%S', \u003Cts_col>) AS ts,\n  COUNTIF(\u003Cgated_col> IS NULL) AS nulls,\n  COUNTIF(\u003Cgated_col> IS NOT NULL) AS populated\nFROM \\`\u003Cproject>.\u003Cdataset>.\u003Ctable>\\`\nWHERE \u003Ctime_window>\nGROUP BY ts\nORDER BY ts\n\"\n\n# 3. Confirm the named gate is a single boolean in the source.\n\ngrep -nE '_(migrated|initialized|ready|warmed|initialized)\\s*[:=]\\s*(True|False)' \\\n  \u003Cmodule_under_test>\n```\n\nIf all three check out: this is the module-global flag race class. Apply the fix shape below.\n\n## The fix shape\n\n### Step 1: Replace the boolean with a state-cache.\n\n```python\n# BEFORE (the race):\n_payloads_schema_migrated: bool = False  # global flag\n\n# AFTER (per-process state cache keyed on actual state):\n_payloads_schema_set: frozenset[str] | None = None  # actual column names\n_payloads_schema_cached_at: float = 0.0\n_payloads_schema_refresh_attempted_at: float = 0.0\n_payloads_schema_ttl_seconds: float = 3600.0   # one BQ GET per hour per process\n_payloads_schema_refresh_cooldown: float = 60.0  # 60s backoff after a failed refresh\n```\n\n### Step 2: Replace migration-completion side effect with cache population.\n\n```python\n# BEFORE: side effect that flips the boolean.\nwith _migration_lock:\n    _migrate_table_schema(token, project, PAYLOADS_TABLE, _payloads_schema())\n    _payloads_schema_migrated = True  # RACE: other threads can see False, skip gated writes\n\n# AFTER: populate the cache from the source-of-truth fetch (tables.get \u002F DESCRIBE \u002F capability probe).\nwith _migration_lock:\n    _migrate_table_schema(token, project, PAYLOADS_TABLE, _payloads_schema())\n    try:\n        _payloads_schema_set = _refresh_payloads_schema_set(token, project)\n        _payloads_schema_cached_at = time.monotonic()\n    except (RequestException, AuthError, RuntimeError) as exc:\n        logging.warning(f\"boot-time schema cache prime failed: {exc}\")  # fail-soft\n```\n\n### Step 3: Per-field guarded writes with double-check under lock.\n\n```python\n# BEFORE: all-or-nothing flag gates a block of gated writes.\nif _payloads_schema_migrated:\n    row[\"is_test\"] = test_flag\n    row[\"user_id\"] = uid\n    row[\"cached_tokens\"] = cached_tokens\n    # ... 6 gated columns ...\n\n# AFTER: per-column guard, with double-check under the same lock used to populate the cache.\nif (\n    _payloads_schema_set is None\n    or (time.monotonic() - _payloads_schema_cached_at) >= _payloads_schema_ttl_seconds\n):\n    cache_ok = _ensure_payloads_schema_cached()  # double-check pattern under _migration_lock\nelse:\n    cache_ok = True\nlive_columns: frozenset[str] = _payloads_schema_set if cache_ok else frozenset()\nfor column_name, value in gated_columns.items():\n    if column_name in live_columns:\n        row[column_name] = value\n    # missing columns are OMITTED — BigQuery rejects unknown fields.\n\n> **Pin declaration separately from values.** The pre-fix inline `gated = {...}` dict at the call site had to be kept in sync with `_GATED_COLUMNS` (the tuple that downstream consumers, audit logs, and migration tests iterate). Decoupling them by hoisting `_GATED_COLUMNS` to the authoritative declaration point and writing `for column_name in _GATED_COLUMNS: if column_name in live_columns: row[column_name] = gated_values[column_name]` means adding\u002Fremoving a gated column is a single-line declaration change that cannot drift from the iteration. CodeRabbit review will catch any remaining inline-dict pattern — treat it as a regression.\n\n### Step 4.1: Add the THIRD gate — cooldown re-check inside the lock.\n\nStep 4 has the TTL double-check under the lock. It is **also** missing a cooldown re-check. A thread that races past the first cooldown gate (because the cooldown timestamp was 0.0 at evaluation time, or because another thread just released the lock and stamped the cooldown in the gap) still queues on `_migration_lock`. Without a third check inside the lock, the thread enters the `try` block and hammers BQ even though a sibling already stamped the cooldown during the wait. The fix:\n\n```python\ndef _ensure_payloads_schema_cached() -> bool:\n    global _payloads_schema_set, _payloads_schema_cached_at\n    global _payloads_schema_refresh_attempted_at\n    now = time.monotonic()\n    cached_set = _payloads_schema_set\n    if (\n        cached_set is not None\n        and (now - _payloads_schema_cached_at) \u003C _payloads_schema_ttl_seconds\n    ):\n        return True\n    if (now - _payloads_schema_refresh_attempted_at) \u003C _payloads_schema_refresh_cooldown:\n        # Cooldown active — don't hammer BQ with refresh attempts.\n        return False\n    with _migration_lock:\n        # Re-check #1: TTL — another thread may have populated while we waited.\n        cached_set = _payloads_schema_set\n        if (\n            cached_set is not None\n            and (time.monotonic() - _payloads_schema_cached_at) \u003C _payloads_schema_ttl_seconds\n        ):\n            return True\n        # Re-check #2: cooldown — sibling thread may have failed-and-stamped\n        # during the wait. Without this gate, the thread that acquired the\n        # lock last still re-hammers BQ despite the cooldown.\n        if (time.monotonic() - _payloads_schema_refresh_attempted_at) \u003C _payloads_schema_refresh_cooldown:\n            return False\n        try:\n            token, project = _get_token_and_project()\n            new_set = _refresh_payloads_schema_set(token, project)\n            _payloads_schema_set = new_set\n            _payloads_schema_cached_at = time.monotonic()\n            return True\n        except (RequestException, AuthError, RuntimeError) as exc:\n            _payloads_schema_refresh_attempted_at = time.monotonic()\n            logging.warning(f\"state cache refresh failed: {exc}\")\n            return False\n```\n\nPin the third gate with a dedicated test (`test_schema_refresh_cooldown_holds_under_lock_acquire`) — pre-arm `_payloads_schema_refresh_attempted_at` to a recent value, two threads barrier-sync, the second thread to acquire the lock must observe the freshly-stamped cooldown and abort WITHOUT calling the mock refresh.\n```\n\n### Step 4: The double-check helper.\n\n```python\ndef _ensure_payloads_schema_cached() -> bool:\n    \"\"\"Refresh the cached state if stale, missing, or recently failed.\n\n    Returns True when cache is populated; False on failure (caller logs a\n    warning and skips the gated columns rather than throwing). The\n    double-check under ``_migration_lock`` means concurrent callers see\n    the SAME populated cache, not N parallel refreshes.\n    \"\"\"\n    global _payloads_schema_set, _payloads_schema_cached_at\n    global _payloads_schema_refresh_attempted_at\n    now = time.monotonic()\n    cached_set = _payloads_schema_set\n    if (\n        cached_set is not None\n        and (now - _payloads_schema_cached_at) \u003C _payloads_schema_ttl_seconds\n    ):\n        return True\n    if (now - _payloads_schema_refresh_attempted_at) \u003C _payloads_schema_refresh_cooldown:\n        # Cooldown active — don't hammer BQ with refresh attempts.\n        return False\n    with _migration_lock:\n        # Re-check under the lock: another thread may have populated while we waited.\n        cached_set = _payloads_schema_set\n        if (\n            cached_set is not None\n            and (time.monotonic() - _payloads_schema_cached_at)\n            \u003C _payloads_schema_ttl_seconds\n        ):\n            return True\n        try:\n            token, project = _get_token_and_project()\n            new_set = _refresh_payloads_schema_set(token, project)\n            _payloads_schema_set = new_set\n            _payloads_schema_cached_at = time.monotonic()\n            return True\n        except (RequestException, AuthError, RuntimeError) as exc:\n            _payloads_schema_refresh_attempted_at = time.monotonic()\n            logging.warning(f\"state cache refresh failed: {exc}\")\n            return False\n```\n\n### Step 5: Test the fix shape, not just the bug.\n\nThree new tests pin the new architecture:\n\n1. **Race test** — two threads with `threading.Barrier`, slow refresh, assert BOTH writers' rows have gated columns populated. This deterministically reproduces the pre-fix bug.\n2. **Cooldown test** — after a failed refresh, a second immediate call within the cooldown window does NOT re-hit BQ.\n3. **TTL test** — `time.sleep(TTL_seconds)` between two calls triggers a refresh on the second.\n\nExisting tests that monkey-patched the old boolean flag must be rewritten to seed the new frozenset cache. Use `raising=False` on the legacy-attr setattrs so old shims don't crash, and seed the cache shape (frozenset of column names) for tests that simulate \"post-startup, all gated columns present.\"\n\n## Pitfalls\n\n### Pitfall 1: Replacing the boolean with ANOTHER boolean (\"_migration_started\", \"_migration_in_progress\", etc.)\n\nSibling PRs almost always do this. Each new flag adds a state machine but doesn't remove the race — it just gates WHEN the original flag flips. Stop. The fix is removing the boolean entirely and replacing it with a per-process state cache.\n\n### Pitfall 2: Reading the schema on EVERY write\n\nThe right shape is one BQ GET per process per TTL window (1h default), not per-row. If your helper does a `tables.get` per insert, you'll hit BigQuery rate limits and your `bq_logging_enabled` flag check becomes load-bearing. Keep the TTL high enough that steady state is one fetch per hour.\n\n### Pitfall 3: Forgetting to refresh from tables.get (only refreshing from the local migration side effect)\n\nThe fix shape MUST include a `tables.get` \u002F `DESCRIBE` \u002F capability-probe round-trip to confirm the columns actually exist in the live table. The migration PATCH may have succeeded locally but BQ may have rejected it, or a sibling process may have modified the schema. The cache is invalidated by TTL (1h) AND by failed PATCHes. Don't skip the fetch — the whole point is to read ground truth.\n\n### Pitfall 4: Cache miss path that throws on transient BQ hiccup\n\nIf the writer throws when the cache is unpopulated, a transient BQ outage breaks the gameplay path. The fix must be fail-soft: on refresh failure, log a warning, set `live_columns = frozenset()`, skip the gated columns, let the row insert. The downstream backfill job (the one that already exists for this exact case) fills the gaps.\n\n### Pitfall 5: Not updating the existing test fixtures\n\nAfter the rename, every test that monkey-patched `_payloads_schema_migrated = True` (or `False`) must be updated to seed `_payloads_schema_set = frozenset({...})`. This is mechanical but spans multiple test files (3+ in the bq_logging case). Use `raising=False` on the legacy-attr setattrs so a stale test attribute on legacy shims doesn't blow up the test run.\n\n### Pitfall 6: \"Just add a try\u002Fexcept around the flag flip\" anti-fix\n\nA common mitigation PR wraps the migration in try\u002Fexcept so the flag stays False on failure (with backoff). This doesn't fix the race — it just makes the race longer-lived on bad days. The race is structural (one boolean, many writers). It cannot be fixed by exception handling.\n\n### Pitfall 7: Confusing this skill with \"I need a distributed lock\"\n\nIf two REPLICAS (not two in-process threads) are racing, the answer is not the fix shape above — the answer is leader election \u002F fencing tokens. The intra-process cache fix assumes one process's writers all share the same in-memory state. For cross-process consistency, BQ \u002F Postgres \u002F etc. IS the source of truth; you must read it on every write (which is expensive) or accept eventual consistency.\n\n### Pitfall 8: Skipping `_get_token_and_project` mock in tests — CI stub failure mode\n\nCI runners (and most hermes-agent self-hosted runners) use `GOOGLE_APPLICATION_CREDENTIALS=\u002Fdev\u002Fnull` as a deliberate safety stub. `_get_token_and_project()` reads this env var via `google.auth.default()` and raises `DefaultCredentialsError` BEFORE `_refresh_payloads_schema_set(token, project)` is ever called. The exception is then caught by `_ensure_payloads_schema_cached`'s `except (GoogleAuthError, ...)` block, which sets `_payloads_schema_refresh_attempted_at` to `time.monotonic()` and logs the warning — making the test look like \"refresh failed, no mock called\" when in reality the mock was bypassed entirely. Every test that exercises the cache-refresh path must patch BOTH `_refresh_payloads_schema_set` AND `_get_token_and_project`:\n\n```python\nmonkeypatch.setattr(bq_logging, \"_refresh_payloads_schema_set\", mock_refresh)\nmonkeypatch.setattr(bq_logging, \"_get_token_and_project\", lambda: (\"mock-token\", \"mock-project\"))\n# Now mock_refresh WILL be called, and the test is deterministic regardless\n# of GOOGLE_APPLICATION_CREDENTIALS.\n```\n\nThe diagnostic signature is: `_payloads_schema_refresh_attempted_at` is non-zero AFTER the test, mock call count is 0, and the warning log mentions `File \u002Fdev\u002Fnull is not a valid json file` (google-auth's stub-load failure message). Local repro: set `GOOGLE_APPLICATION_CREDENTIALS=\u002Fdev\u002Fnull` and run the test — if it passes locally but fails on CI, this is your bug.\n\n### Pitfall 9: Caching an unvalidated `tables.get` response\n\n`_refresh_payloads_schema_set` reads BQ's `tables.get` response and iterates `fields`. If the response is malformed (HTTP 200 but body is an HTML error page, an empty dict, a list, or a dict missing the `schema` key), the comprehension silently returns `frozenset()` — the same shape as \"table exists but has no columns.\" A row inserted with `live_columns=frozenset()` will then drop ALL gated columns because none of them are in the empty set. Pin the response shape before caching:\n\n```python\ndef _refresh_payloads_schema_set(token, project) -> frozenset[str]:\n    resp = requests.get(url, headers=_auth_headers(token), timeout=_HTTP_TIMEOUT_S)\n    if resp.status_code != 200:\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE} [{resp.status_code}]: {resp.text}\")\n    body = resp.json()\n    if not isinstance(body, dict):\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE}: body is not a JSON object ({type(body).__name__})\")\n    schema = body.get(\"schema\")\n    if not isinstance(schema, dict):\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE}: missing or non-dict 'schema'\")\n    fields = schema.get(\"fields\")\n    if not isinstance(fields, list):\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE}: 'schema.fields' is not a list\")\n    return frozenset(f[\"name\"] for f in fields if isinstance(f, dict) and f.get(\"name\"))\n```\n\nThe exception gets caught at the `_ensure_payloads_schema_cached` `except (RequestException, RuntimeError, ...)` block, stamps the cooldown, and lets the row insert without gated columns — fail-soft as designed, but now you've at least logged the malformed response and won't poison the cache for the TTL window with an `frozenset()` that looks identical to \"table has zero columns.\"\n\n### Pitfall 10: The v1.1.0 cache fix STILL silently drops on cold replicas between deployments\n\nThe v1.1.0 fix replaces the boolean with a per-process `frozenset[str]` cache + `tables.get` + double-check under lock. It is correct for the **steady-state** race (two writers in the same process seeing a stale boolean). It is **not** sufficient for the **cold-replica** race, because:\n\n```python\n# In log_llm_payload (the write path):\nif (\n    _payloads_schema_set is None\n    or (time.monotonic() - _payloads_schema_cached_at) >= _payloads_schema_ttl_seconds\n):\n    cache_ok = _ensure_payloads_schema_cached()\nelse:\n    cache_ok = True\nlive_columns: frozenset[str] = (\n    _payloads_schema_set\n    if cache_ok and _payloads_schema_set is not None\n    else frozenset()  # ← THE LEAK: drops ALL gated cols on cold cache + transient refresh-fail\n)\n```\n\nWhen a Cloud Run replica is cold (just spun up between deployments) AND `_ensure_payloads_schema_cached()` fails on the first call (transient BQ hiccup, IAM token not yet primed, network cold-start delay), `cache_ok=False` AND `_payloads_schema_set is None`. The writer proceeds with `live_columns = frozenset()` and omits every gated column (`is_test`, `user_id`, `cached_tokens`, `thoughts_tokens`, `tool_use_tokens`, `rag_mode`, + 6 more). The cooldown logic in `_ensure_payloads_schema_cached` then keeps the cache cold for the next `_payloads_schema_refresh_cooldown` seconds (60s default), during which every insert on this replica silently drops all gated columns.\n\n**Verified live 2026-07-19 against PR [#8418](https:\u002F\u002Fgithub.com\u002F$GITHUB_REPOSITORY\u002Fpull\u002F8418)** (which DID land the v1.1.0 fix at `90238d16b8`):\n- Last 24h: 186 NULL `is_test` rows \u002F 2014 total = **90.76% populated** (target ≥95%) — fails the watcher.\n- Schema-gate signature: **100.0%** of NULL rows are 5-col co-NULL (the exact silent-drop shape).\n- Per-hour pattern 2026-07-19: hour 18:00 UTC = 100% populated, hour 19:00 = 72.62%, hour 20:00 = 54.0% — fresh replicas spinning up between steady-state hours and hitting the cold-cache race.\n- 7d rolling: 85.68% populated (1237 NULL rows) — the cumulative window trips every watcher run.\n\n**The diagnostic recipe to prove cold-replica persistence from BQ alone** (no Cloud Run logs needed):\n\n```sql\n-- 1. Per-hour buckets last 96h — shows the alternating OK \u002F NOT-OK pattern\nSELECT\n  FORMAT_TIMESTAMP('%Y-%m-%d %H:00', ingested_at) AS hour,\n  COUNTIF(is_test IS NULL) AS n_is_test_null,\n  COUNT(*) AS n_total,\n  ROUND(100.0 * COUNTIF(is_test IS NOT NULL) \u002F COUNT(*), 2) AS pct_populated\nFROM `\u003Cproject>.llm_forensics.llm_payloads`\nWHERE ingested_at > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 96 HOUR)\n  AND model LIKE '%gemini%'\nGROUP BY hour ORDER BY hour DESC;\n\n-- 2. Per-minute buckets for the bad hours — shows the micro-bursts that\n--    are the fingerprint of \"one cold replica silently dropped writes for\n--    its lifetime then died\" (5-8 NULLs every few minutes, no populated\n--    rows between).\nSELECT\n  FORMAT_TIMESTAMP('%Y-%m-%d %H:%M', ingested_at) AS minute_bucket,\n  COUNT(*) AS n_null\nFROM `\u003Cproject>.llm_forensics.llm_payloads`\nWHERE ingested_at >= TIMESTAMP('\u003Cbad-hour-start> UTC')\n  AND ingested_at \u003C TIMESTAMP('\u003Cbad-hour-end> UTC')\n  AND model LIKE '%gemini%'\n  AND is_test IS NULL\nGROUP BY minute_bucket ORDER BY minute_bucket;\n\n-- 3. Schema-gate signature — 5-col co-NULL on EVERY NULL row is the\n--    smoking gun for \"all gated cols dropped by the cache fail-soft path\".\nSELECT\n  COUNTIF(is_test IS NULL AND cached_tokens IS NULL AND thoughts_tokens IS NULL\n          AND tool_use_tokens IS NULL AND rag_mode IS NULL) AS n_co_null_5cols,\n  COUNTIF(is_test IS NULL) AS n_is_test_null_total,\n  ROUND(100.0 * COUNTIF(is_test IS NULL AND cached_tokens IS NULL AND thoughts_tokens IS NULL\n                        AND tool_use_tokens IS NULL AND rag_mode IS NULL)\n        \u002F GREATEST(1, COUNTIF(is_test IS NULL)), 2) AS co_null_pct\nFROM `\u003Cproject>.llm_forensics.llm_payloads`\nWHERE ingested_at > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 24 HOUR)\n  AND model LIKE '%gemini%';\n```\n\nIf `co_null_pct == 100.0`, the bug is the cold-cache silent-drop. Per-replica attribution requires a `revision_id` column (reading `K_REVISION` env var on Cloud Run) — **add it now** as part of the fix, not as a follow-up. Without it, you can't tell which replica is dropping.\n\n**The structural fix shape (belt + suspenders — do both):**\n\n1. **Boot-warmup fallback flag.** Add `_boot_warmup_succeeded: bool = False` to the module state. Set it True at the end of `ensure_dataset_and_tables` after the cache prime attempt (regardless of success\u002Ffailure of the cache fetch itself, since the table exists and has the schema we just declared). In the write path, when `cache_ok=False` AND `_payloads_schema_set is None`, consult `_boot_warmup_succeeded` — if True, the table HAS the columns (we just created or migrated it during boot), so fall back to the in-process `_payloads_schema()` (the authoritative declaration) instead of `frozenset()`. If False (replica never finished boot warmup), log a structured warning with replica_id + retry attempt count, and skip the insert (better to lose a row than silently pollute BQ with NULLs — change from fail-soft to fail-loud only for the truly-no-cache case).\n\n2. **Retry-with-backoff on first call.** Before falling through to `frozenset()`, retry `_ensure_payloads_schema_cached()` up to N=3 times within a short budget (e.g., 500ms total with 100\u002F200\u002F200ms delays). Transient BQ hiccups on cold replicas typically clear within 200ms. Combined with #1, this means: transient hiccup → retry succeeds → cache populated normally; transient hiccup past retry budget + boot warmup succeeded → fall back to `_payloads_schema()` declaration; transient hiccup past retry budget + boot warmup failed → log structured warning + skip insert.\n\n3. **`revision_id` column.** Read `os.environ.get('K_REVISION', 'local-dev')` (Cloud Run sets this; local dev falls back to a sentinel). Add to `_payloads_schema()` as a NON-gated column (it's always present after the schema bump). Make the watcher alert report the `revision_id` distribution of NULL rows so future cold-replica incidents are diagnosable from BQ alone without reading Cloud Run logs.\n\n```python\n# Module state additions:\n_boot_warmup_succeeded: bool = False\n_boot_warmup_lock = threading.Lock()\n\n# In ensure_dataset_and_tables, at the end:\nwith _boot_warmup_lock:\n    _boot_warmup_succeeded = True  # table was created\u002Fmigrated even if cache fetch failed\n\n# In log_llm_payload write path, replacing the live_columns line:\nif cache_ok and _payloads_schema_set is not None:\n    live_columns = _payloads_schema_set\nelif _boot_warmup_succeeded:\n    # Cold cache, but the boot-time migrate created the table with the\n    # authoritative schema. Fall back to the in-process declaration so\n    # gated columns aren't silently dropped.\n    live_columns = frozenset(_payloads_schema())  # use the declared schema\n    logging.warning(\n        f\"BQ logging: schema cache cold, falling back to declared schema; \"\n        f\"revision_id={K_REVISION}\"\n    )\nelse:\n    # Cold cache AND boot warmup never completed — log loud, skip the row.\n    logging.error(\n        f\"BQ logging: schema cache cold AND boot warmup not complete; \"\n        f\"skipping insert to avoid silent NULL pollution. revision_id={K_REVISION}\"\n    )\n    return None  # do NOT silently drop; refuse the insert instead\n\nfor column_name in _GATED_COLUMNS:\n    if column_name in live_columns:\n        row[column_name] = gated_values[column_name]\n```\n\n**Tests to pin the new architecture** (add to `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py`):\n\n```python\ndef test_cold_cache_transient_refresh_failure_includes_gated_columns(monkeypatch):\n    \"\"\"Cold cache + transient refresh failure + boot warmup succeeded\n    → fall back to declared schema; gated cols ARE in the row.\"\"\"\n    monkeypatch.setattr(bq_logging, \"_payloads_schema_set\", None)\n    monkeypatch.setattr(bq_logging, \"_boot_warmup_succeeded\", True)\n    monkeypatch.setattr(bq_logging, \"_ensure_payloads_schema_cached\", lambda: False)\n    # ... call log_llm_payload with a mocked _insert_rows, capture the row arg ...\n    assert \"is_test\" in captured_row\n    assert \"user_id\" in captured_row\n\ndef test_cold_cache_no_boot_warmup_refuses_insert(monkeypatch):\n    \"\"\"Cold cache + boot warmup never completed → refuse the insert,\n    do NOT silently drop.\"\"\"\n    monkeypatch.setattr(bq_logging, \"_payloads_schema_set\", None)\n    monkeypatch.setattr(bq_logging, \"_boot_warmup_succeeded\", False)\n    monkeypatch.setattr(bq_logging, \"_ensure_payloads_schema_cached\", lambda: False)\n    # ... call log_llm_payload ...\n    assert captured_insert_id is None  # refused, not silently dropped\n\ndef test_log_llm_payload_includes_revision_id(monkeypatch, tmp_path):\n    \"\"\"revision_id column reads K_REVISION env var and is included in every row.\"\"\"\n    monkeypatch.setenv(\"K_REVISION\", \"wa-mvp-00042-abc\")\n    # ... call log_llm_payload ...\n    assert captured_row.get(\"revision_id\") == \"wa-mvp-00042-abc\"\n```\n\n**Anti-pattern (do NOT do this):** \"Just push another `_migration_started: bool` companion flag to handle cold-replica case.\" Each new boolean re-introduces the v1.0.0 race in a new shape. The fix is the `_boot_warmup_succeeded` flag PLUS the boot-warmup fallback to the declared schema — not another boolean. The `_boot_warmup_succeeded` flag is set ONCE during boot and never flipped, so it has no race; the `frozenset[str]` cache is keyed on actual state, not a binary \"ready\" signal.\n\n### Pitfall 11: A v1.1.0\u002Fv1.2.0 production-budget change silently breaks existing tests that hold a shared resource longer than the new budget\n\n**Verified live 2026-07-24 against PR [#8462](https:\u002F\u002Fgithub.com\u002F$GITHUB_REPOSITORY\u002Fpull\u002F8462) in $GITHUB_REPOSITORY** (the Pitfall 10 follow-up). The v1.1.0 fix introduced `_PAYLOADS_SCHEMA_RETRY_BUDGET_S: float = 0.5s` — a production wall-clock budget for the cold-replica retry loop. The v1.1.0 fix also added `test_startup_schema_migration_uses_shared_migration_lock`, a regression test that holds `_migration_lock` for **5 seconds** to verify the request path *truly* blocks on the lock (the slow `_migrate_table_schema` mock waits on `release_migration.wait(timeout=5.0)`).\n\nAfter merge, CI core-mvp-3 reports the new test as FAILED with `assert []` on `inserted_rows`. Root cause: the request-path writer's `_lock_before_deadline(_migration_lock, retry_deadline)` times out at 0.5s, logs \"wall-clock budget exceeded\", and falls back to di[REDACTED_OPENAI_KEY] (no BQ insert). The test then asserts `inserted_rows` and fails. The test was passing on the PR branch before the budget change, and it passes on `origin\u002Fmain` HEAD on a clean worktree (`git checkout origin\u002Fmain -- \u003Ctest files>`) — same file, same assertion, same test name, but the production budget change makes it fail on the PR.\n\n**The same-test-name-rule four-check confirms a real PR regression, not a flake:**\n\n1. **Same test name** — `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py::test_startup_schema_migration_uses_shared_migration_lock` is unchanged on both branches.\n2. **Same assertion** — `assert inserted_rows` is unchanged.\n3. **Same file at the same commit** — exists on both `origin\u002Fmain` and PR head (this test was added in PR #8462 itself).\n4. **Explicit same-SHA reproduction on `origin\u002Fmain` HEAD** — `python3 -m pytest $PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py::test_startup_schema_migration_uses_shared_migration_lock` on a `git checkout origin\u002Fmain -- \u003Cfiles>` worktree → **3\u002F3 PASS in 0.34-0.42s** (fast because the lock acquire is fast in isolation). On the PR head (clean worktree, before any fix) → **3\u002F3 FAIL in 2.92-3.54s** (slow because the test actually waits for the 5s lock hold, then times out the 0.5s budget).\n\n**Fix (verified on PR #8462 commit `e2253af7e1`):** monkeypatch the budget wider **in the test only**. Production code keeps the 0.5s invariant; the test widens the budget to a value that comfortably exceeds the 5s lock hold:\n\n```python\ndef test_startup_schema_migration_uses_shared_migration_lock(  # noqa: PLR0915\n    monkeypatch,\n):\n    real_lock = threading.Lock()\n    monkeypatch.setattr(bq_logging, \"_migration_lock\", real_lock)\n    # ... other monkeypatches ...\n    # The shared retry budget defaults to 0.5s so a degraded replica cannot\n    # hold a request-path insert for longer; this test deliberately holds the\n    # migration lock for up to 5s to verify the request path *truly* blocks\n    # on it, so we widen the budget to comfortably exceed that 5s wait.\n    monkeypatch.setattr(bq_logging, \"_PAYLOADS_SCHEMA_RETRY_BUDGET_S\", 10.0)\n    # ... test body unchanged ...\n    assert release_migration.wait(timeout=5.0), \"migration release timed out\"\n```\n\nAfter the fix: `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py` 19\u002F19 PASS; `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging.py` + `_integration.py` + `_schema_migration.py` 83\u002F83 PASS. PR #8462 went from failing 1 self-hosted MVP shard (core-mvp-3) to 7-green.\n\n**Why this is the right fix, not a budget relaxation.** The 0.5s production budget is a real correctness invariant (a degraded replica cannot hold a request-path insert for >0.5s). Relaxing it to 5s to satisfy one test would silently weaken production behavior. Widening the budget in the test preserves the invariant AND lets the test verify the lock semantics the test was written to verify. The pattern generalizes to any timeout\u002Fbudget + lock-hold test combination: any test that holds a shared resource longer than a new production timeout\u002Fbudget needs the budget widened in the test, not loosened in production.\n\n**Generalization recipe (any timeout\u002Fbudget + lock-hold test combination):**\n\n1. Identify the new production budget\u002Ftimeout\u002Fdeadline value introduced by the PR (grep for `_TIMEOUT = \\|_BUDGET = \\|_LIMIT = \\|_DEADLINE = ` in the diff).\n2. Identify any test in the diff (or any existing test that the new budget would break) that holds a shared resource for longer than that budget.\n3. Add `monkeypatch.setattr(\u003Cmodule>, \"\u003CCONSTANT>\", \u003Cvalue comfortably above test's resource hold>)` to the test setup. Document the value choice in a comment (\"this test deliberately holds X for N seconds to verify Y; production budget is 0.5s but the test needs at least N+1s\").\n4. Local verification: `python3 -m pytest \u003Ctest>` 3 times in a row → all pass on the PR head.\n5. Same-test-name-rule check on `origin\u002Fmain`: `git checkout origin\u002Fmain -- \u003Ctest file> && python3 -m pytest \u003Ctest>` → 3\u002F3 pass (proving the test was always passing before the budget regression).\n\n**Don't fall into:** \"The test is flaky, just re-run\" — this dismisses a real PR regression. The test is deterministic; the failure is reproducible. The PR introduced the budget that broke the test.\n\n**Don't fall into:** \"Loosen the production budget to make the test pass\" — this silently weakens production. The budget is a real invariant; the test should widen the budget, not production.\n\n**Don't fall into:** \"Skip the test, mark it as known-failure\" — the test is the only one that proves the lock serialization invariant the v1.1.0 fix established. Skipping it would silently lose regression coverage on the most important fix-shape property.\n\n**Cross-skill reference:** This pattern is a sibling to the same-test-name-rule dismissal gate (the `qa-test-failure-dismissal-anti-pattern` skill) — that gate decides whether a CI failure is a real PR regression or an infra flake. Pitfall 11 is the \"yes, it's a real PR regression, here's how to fix the test while keeping production tight\" companion.\n\n**PR-topology reminder:** when the v1.1.0 fix is already merged (e.g., PR #8418) and you discover the cold-replica persistence, do NOT push a follow-up commit onto the v1.1.0 branch — open a NEW branch from `origin\u002Fmain` with `git worktree add -b fix\u002F\u003Ctopic> origin\u002Fmain`, cherry-pick only the load-bearing change (the `_boot_warmup_succeeded` + revision_id + retry logic), and open a fresh PR. Per `pr-clean-branch-from-main-no-history-bloat` and `never-push-onto-someone-elses-pr-head`, pushing onto a non-owned PR head is the #1 PR-pollution failure mode. The follow-up PR (fix\u002Fbq-payloads-schema-cold-replica-fix, bead `rev-zurdo`) was opened on 2026-07-19 with this exact pattern.\n\n## Reference\n\n- `references\u002F2026-07-16-bq-is-test-null-pr-8418.md` — worked example: the `_payloads_schema_migrated: bool` race in `$PROJECT_ROOT\u002Fbq_logging.py`, PR [#8418](https:\u002F\u002Fgithub.com\u002F$GITHUB_REPOSITORY\u002Fpull\u002F8418) (commit `51242edb2`). Reproduces the live bug (5\u002F1069 NULL rows in last 24h, co-NULL on 6 columns, two micro-bursts at 10:03 and 10:05 UTC). Previous sibling PRs #8070 (preserve additive schema migration + serialize writers) and #8351 (preserve live schema columns) attempted the same fix but kept the boolean flag in place.\n- `references\u002F2026-07-17-pr-8418-driven-to-green.md` — v1.1.0 addendum: three CodeRabbit-flagged corrections (cooldown re-check inside lock, `_GATED_COLUMNS` authoritative declaration, `_get_token_and_project` CI mock requirement), the `tables.get` response-shape validation pattern, AND the 8-section PR description gate choreography used to drive PR #8418 to green on 2026-07-17.\n- `references\u002F2026-07-19-cold-replica-persistence.md` — v1.2.0 evidence: PR #8418's v1.1.0 cache fix did NOT hold across new Cloud Run replicas between deployments. Live BQ probe on 2026-07-19 21:00 UTC shows 186 NULL is_test rows in last 24h (90.76% populated, fails ≥95% target), 100% co-NULL on 5 gated cols, per-hour pattern of alternating OK \u002F NOT-OK as fresh replicas spin up. Follow-up PR `fix\u002Fbq-payloads-schema-cold-replica-fix` (bead `rev-zurdo`, worker `worldarchitect-64`) implements Pitfall 10's fix shape. Includes the `env -i PYTHONPATH=` workaround for the broken `bq` CLI on this Mac, and the `gh api` GraphQL rate-limit fallback to REST.\n\n## Cross-references\n\n- `~\u002F.hermes\u002Fskills\u002Fsoftware-development\u002Fsystematic-debugging\u002FSKILL.md` — the 4-phase protocol for finding root cause before fixing. Use this skill after systematic-debugging identifies the silent-drop class with a module-level boolean as the named suspect.\n- `~\u002F.hermes\u002Fskills\u002Fsoftware-development\u002Fconvergent-bug-triage\u002FSKILL.md` — when 3+ sibling bug investigations on the same surface point to the same root class. The is_test NULL family (PR #8070 + #8351 + #8418) is exactly this pattern.\n- `~\u002F.hermes\u002Fskills\u002Fdevops\u002Fverify-telemetry-alert\u002FSKILL.md` — how to verify the BQ \u002F metric alert that surfaces this class before assuming the alert is accurate.\n- `~\u002F.hermes\u002Fskills\u002Fworldarchitect\u002Fwa-cloud-run-deploy-failure-debug\u002FSKILL.md` — sibling skill for Cloud Run deploy failure debugging (different class: deployment, not race).","# Module-Global Flag Race (the \"_payloads_schema_migrated pattern\")\n\nWhen a single **module-level boolean** in a Python service is used as a \"first-time setup complete\" gate on the hot write path, three things are simultaneously true and structurally broken:\n\n1. **Transient failure during init leaves the flag stuck False.** On a fresh Cloud Run replica (or any cold process start), the first caller's setup attempt fails with a transient BQ \u002F DB \u002F Redis error. The retry-after-N-seconds logic kicks in, but every writer in the meantime sees `flag == False` and silently drops the gated fields.\n2. **The flag is process-global, so cross-call race wins are inevitable.** Thread A finishes migration and sets the flag True. Thread B was mid-write, saw False, dropped gated fields. Thread C is now racing the flag flip. There is no \"make gated writes wait for first successful migration\" guarantee because the flag is non-atomic with the column-existence check.\n3. **Sibling PRs mitigate but never fix.** Each subsequent PR adds more code: a `_migration_started` companion flag, a `_migration_next_retry_at` backoff, a lock to serialize writers. None of these remove the boolean flag structurally — they only gate WHEN the flag flips. The first cold-start writer still silently drops fields.\n\nThe right fix is not \"add another flag\" or \"add another lock layer.\" The right fix is **replace the boolean with a per-process state cache keyed on the actual state** (column-name frozenset, capability list, etc.), populated by a single source-of-truth fetch (`tables.get`, `DESCRIBE`, capability probe) and guarded by a **double-check pattern under the same lock used to write the state**. Each gated field then independently guards on its presence in the cached state, not on a single global \"all-or-nothing\" flag.\n\n## When to use this skill\n\n- The bug surface is **silently dropped writes on a cold start** (co-NULL signature across multiple gated columns, full payload populated, no error logged).\n- A single module-level boolean (`_feature_ready`, `_schema_migrated`, `_cache_warmed`, etc.) is the named gate.\n- Two or more previous PRs attempted to fix it by adding serialization \u002F backoff \u002F retry-on-failure but kept the boolean flag in place.\n- The bug is reproducing live (per-day BQ rows, per-minute metrics, etc.) — not historic backlog.\n- A targeted BQ \u002F metric query proves the bug is live (co-NULL signature, arrival-time micro-bursts with no populated rows between them = producing process never saw a successful setup).\n\n## When NOT to use this skill\n\n- **Distributed locks \u002F cross-process coordination.** If you need a single global truth across replicas, the answer is leader election, fencing tokens, or an external coordinator (etcd, ZooKeeper, Cloud Run revision pinning). The fix shape here is intra-process only.\n- **Per-call state.** If the race only spans one request and the flag is set within that request, there is no flag race — just a missing initialization order.\n- **Immutable config flags.** If the flag is set from env \u002F config and never flips during process lifetime, there is no race. (You might still have a \"stuck on old value\" bug, but that's a different class.)\n- **Concurrency bugs unrelated to a boolean gate.** Deadlocks, data corruption, ordering violations — different classes.\n\n## The diagnostic recipe\n\nBefore fixing, prove the bug is this class, not something else:\n\n```bash\n# 1. Confirm co-NULL signature across multiple gated columns on the same row.\n#    A real race produces rows that ARE NULL on the gated set and POPULATED elsewhere.\n#    (A real bug elsewhere produces uniform NULL or uniform POPULATED rows.)\n\nbq query --use_legacy_sql=false \"\nSELECT\n  COUNTIF(\u003Ccol_a> IS NULL) AS null_a,\n  COUNTIF(\u003Ccol_b> IS NULL) AS null_b,\n  COUNTIF(\u003Ccol_a> IS NULL AND \u003Ccol_b> IS NULL) AS both_null\nFROM \\`\u003Cproject>.\u003Cdataset>.\u003Ctable>\\`\nWHERE \u003Ctime_window>\n\"\n\n# 2. Confirm arrival-time micro-bursts — rows arriving close together with NO\n#    populated rows between them. This is the fingerprint of \"one cold replica\n#    silently dropped writes for its lifetime\".\n\nbq query --use_legacy_sql=false \"\nSELECT\n  FORMAT_TIMESTAMP('%H:%M:%S', \u003Cts_col>) AS ts,\n  COUNTIF(\u003Cgated_col> IS NULL) AS nulls,\n  COUNTIF(\u003Cgated_col> IS NOT NULL) AS populated\nFROM \\`\u003Cproject>.\u003Cdataset>.\u003Ctable>\\`\nWHERE \u003Ctime_window>\nGROUP BY ts\nORDER BY ts\n\"\n\n# 3. Confirm the named gate is a single boolean in the source.\n\ngrep -nE '_(migrated|initialized|ready|warmed|initialized)\\s*[:=]\\s*(True|False)' \\\n  \u003Cmodule_under_test>\n```\n\nIf all three check out: this is the module-global flag race class. Apply the fix shape below.\n\n## The fix shape\n\n### Step 1: Replace the boolean with a state-cache.\n\n```python\n# BEFORE (the race):\n_payloads_schema_migrated: bool = False  # global flag\n\n# AFTER (per-process state cache keyed on actual state):\n_payloads_schema_set: frozenset[str] | None = None  # actual column names\n_payloads_schema_cached_at: float = 0.0\n_payloads_schema_refresh_attempted_at: float = 0.0\n_payloads_schema_ttl_seconds: float = 3600.0   # one BQ GET per hour per process\n_payloads_schema_refresh_cooldown: float = 60.0  # 60s backoff after a failed refresh\n```\n\n### Step 2: Replace migration-completion side effect with cache population.\n\n```python\n# BEFORE: side effect that flips the boolean.\nwith _migration_lock:\n    _migrate_table_schema(token, project, PAYLOADS_TABLE, _payloads_schema())\n    _payloads_schema_migrated = True  # RACE: other threads can see False, skip gated writes\n\n# AFTER: populate the cache from the source-of-truth fetch (tables.get \u002F DESCRIBE \u002F capability probe).\nwith _migration_lock:\n    _migrate_table_schema(token, project, PAYLOADS_TABLE, _payloads_schema())\n    try:\n        _payloads_schema_set = _refresh_payloads_schema_set(token, project)\n        _payloads_schema_cached_at = time.monotonic()\n    except (RequestException, AuthError, RuntimeError) as exc:\n        logging.warning(f\"boot-time schema cache prime failed: {exc}\")  # fail-soft\n```\n\n### Step 3: Per-field guarded writes with double-check under lock.\n\n```python\n# BEFORE: all-or-nothing flag gates a block of gated writes.\nif _payloads_schema_migrated:\n    row[\"is_test\"] = test_flag\n    row[\"user_id\"] = uid\n    row[\"cached_tokens\"] = cached_tokens\n    # ... 6 gated columns ...\n\n# AFTER: per-column guard, with double-check under the same lock used to populate the cache.\nif (\n    _payloads_schema_set is None\n    or (time.monotonic() - _payloads_schema_cached_at) >= _payloads_schema_ttl_seconds\n):\n    cache_ok = _ensure_payloads_schema_cached()  # double-check pattern under _migration_lock\nelse:\n    cache_ok = True\nlive_columns: frozenset[str] = _payloads_schema_set if cache_ok else frozenset()\nfor column_name, value in gated_columns.items():\n    if column_name in live_columns:\n        row[column_name] = value\n    # missing columns are OMITTED — BigQuery rejects unknown fields.\n\n> **Pin declaration separately from values.** The pre-fix inline `gated = {...}` dict at the call site had to be kept in sync with `_GATED_COLUMNS` (the tuple that downstream consumers, audit logs, and migration tests iterate). Decoupling them by hoisting `_GATED_COLUMNS` to the authoritative declaration point and writing `for column_name in _GATED_COLUMNS: if column_name in live_columns: row[column_name] = gated_values[column_name]` means adding\u002Fremoving a gated column is a single-line declaration change that cannot drift from the iteration. CodeRabbit review will catch any remaining inline-dict pattern — treat it as a regression.\n\n### Step 4.1: Add the THIRD gate — cooldown re-check inside the lock.\n\nStep 4 has the TTL double-check under the lock. It is **also** missing a cooldown re-check. A thread that races past the first cooldown gate (because the cooldown timestamp was 0.0 at evaluation time, or because another thread just released the lock and stamped the cooldown in the gap) still queues on `_migration_lock`. Without a third check inside the lock, the thread enters the `try` block and hammers BQ even though a sibling already stamped the cooldown during the wait. The fix:\n\n```python\ndef _ensure_payloads_schema_cached() -> bool:\n    global _payloads_schema_set, _payloads_schema_cached_at\n    global _payloads_schema_refresh_attempted_at\n    now = time.monotonic()\n    cached_set = _payloads_schema_set\n    if (\n        cached_set is not None\n        and (now - _payloads_schema_cached_at) \u003C _payloads_schema_ttl_seconds\n    ):\n        return True\n    if (now - _payloads_schema_refresh_attempted_at) \u003C _payloads_schema_refresh_cooldown:\n        # Cooldown active — don't hammer BQ with refresh attempts.\n        return False\n    with _migration_lock:\n        # Re-check #1: TTL — another thread may have populated while we waited.\n        cached_set = _payloads_schema_set\n        if (\n            cached_set is not None\n            and (time.monotonic() - _payloads_schema_cached_at) \u003C _payloads_schema_ttl_seconds\n        ):\n            return True\n        # Re-check #2: cooldown — sibling thread may have failed-and-stamped\n        # during the wait. Without this gate, the thread that acquired the\n        # lock last still re-hammers BQ despite the cooldown.\n        if (time.monotonic() - _payloads_schema_refresh_attempted_at) \u003C _payloads_schema_refresh_cooldown:\n            return False\n        try:\n            token, project = _get_token_and_project()\n            new_set = _refresh_payloads_schema_set(token, project)\n            _payloads_schema_set = new_set\n            _payloads_schema_cached_at = time.monotonic()\n            return True\n        except (RequestException, AuthError, RuntimeError) as exc:\n            _payloads_schema_refresh_attempted_at = time.monotonic()\n            logging.warning(f\"state cache refresh failed: {exc}\")\n            return False\n```\n\nPin the third gate with a dedicated test (`test_schema_refresh_cooldown_holds_under_lock_acquire`) — pre-arm `_payloads_schema_refresh_attempted_at` to a recent value, two threads barrier-sync, the second thread to acquire the lock must observe the freshly-stamped cooldown and abort WITHOUT calling the mock refresh.\n```\n\n### Step 4: The double-check helper.\n\n```python\ndef _ensure_payloads_schema_cached() -> bool:\n    \"\"\"Refresh the cached state if stale, missing, or recently failed.\n\n    Returns True when cache is populated; False on failure (caller logs a\n    warning and skips the gated columns rather than throwing). The\n    double-check under ``_migration_lock`` means concurrent callers see\n    the SAME populated cache, not N parallel refreshes.\n    \"\"\"\n    global _payloads_schema_set, _payloads_schema_cached_at\n    global _payloads_schema_refresh_attempted_at\n    now = time.monotonic()\n    cached_set = _payloads_schema_set\n    if (\n        cached_set is not None\n        and (now - _payloads_schema_cached_at) \u003C _payloads_schema_ttl_seconds\n    ):\n        return True\n    if (now - _payloads_schema_refresh_attempted_at) \u003C _payloads_schema_refresh_cooldown:\n        # Cooldown active — don't hammer BQ with refresh attempts.\n        return False\n    with _migration_lock:\n        # Re-check under the lock: another thread may have populated while we waited.\n        cached_set = _payloads_schema_set\n        if (\n            cached_set is not None\n            and (time.monotonic() - _payloads_schema_cached_at)\n            \u003C _payloads_schema_ttl_seconds\n        ):\n            return True\n        try:\n            token, project = _get_token_and_project()\n            new_set = _refresh_payloads_schema_set(token, project)\n            _payloads_schema_set = new_set\n            _payloads_schema_cached_at = time.monotonic()\n            return True\n        except (RequestException, AuthError, RuntimeError) as exc:\n            _payloads_schema_refresh_attempted_at = time.monotonic()\n            logging.warning(f\"state cache refresh failed: {exc}\")\n            return False\n```\n\n### Step 5: Test the fix shape, not just the bug.\n\nThree new tests pin the new architecture:\n\n1. **Race test** — two threads with `threading.Barrier`, slow refresh, assert BOTH writers' rows have gated columns populated. This deterministically reproduces the pre-fix bug.\n2. **Cooldown test** — after a failed refresh, a second immediate call within the cooldown window does NOT re-hit BQ.\n3. **TTL test** — `time.sleep(TTL_seconds)` between two calls triggers a refresh on the second.\n\nExisting tests that monkey-patched the old boolean flag must be rewritten to seed the new frozenset cache. Use `raising=False` on the legacy-attr setattrs so old shims don't crash, and seed the cache shape (frozenset of column names) for tests that simulate \"post-startup, all gated columns present.\"\n\n## Pitfalls\n\n### Pitfall 1: Replacing the boolean with ANOTHER boolean (\"_migration_started\", \"_migration_in_progress\", etc.)\n\nSibling PRs almost always do this. Each new flag adds a state machine but doesn't remove the race — it just gates WHEN the original flag flips. Stop. The fix is removing the boolean entirely and replacing it with a per-process state cache.\n\n### Pitfall 2: Reading the schema on EVERY write\n\nThe right shape is one BQ GET per process per TTL window (1h default), not per-row. If your helper does a `tables.get` per insert, you'll hit BigQuery rate limits and your `bq_logging_enabled` flag check becomes load-bearing. Keep the TTL high enough that steady state is one fetch per hour.\n\n### Pitfall 3: Forgetting to refresh from tables.get (only refreshing from the local migration side effect)\n\nThe fix shape MUST include a `tables.get` \u002F `DESCRIBE` \u002F capability-probe round-trip to confirm the columns actually exist in the live table. The migration PATCH may have succeeded locally but BQ may have rejected it, or a sibling process may have modified the schema. The cache is invalidated by TTL (1h) AND by failed PATCHes. Don't skip the fetch — the whole point is to read ground truth.\n\n### Pitfall 4: Cache miss path that throws on transient BQ hiccup\n\nIf the writer throws when the cache is unpopulated, a transient BQ outage breaks the gameplay path. The fix must be fail-soft: on refresh failure, log a warning, set `live_columns = frozenset()`, skip the gated columns, let the row insert. The downstream backfill job (the one that already exists for this exact case) fills the gaps.\n\n### Pitfall 5: Not updating the existing test fixtures\n\nAfter the rename, every test that monkey-patched `_payloads_schema_migrated = True` (or `False`) must be updated to seed `_payloads_schema_set = frozenset({...})`. This is mechanical but spans multiple test files (3+ in the bq_logging case). Use `raising=False` on the legacy-attr setattrs so a stale test attribute on legacy shims doesn't blow up the test run.\n\n### Pitfall 6: \"Just add a try\u002Fexcept around the flag flip\" anti-fix\n\nA common mitigation PR wraps the migration in try\u002Fexcept so the flag stays False on failure (with backoff). This doesn't fix the race — it just makes the race longer-lived on bad days. The race is structural (one boolean, many writers). It cannot be fixed by exception handling.\n\n### Pitfall 7: Confusing this skill with \"I need a distributed lock\"\n\nIf two REPLICAS (not two in-process threads) are racing, the answer is not the fix shape above — the answer is leader election \u002F fencing tokens. The intra-process cache fix assumes one process's writers all share the same in-memory state. For cross-process consistency, BQ \u002F Postgres \u002F etc. IS the source of truth; you must read it on every write (which is expensive) or accept eventual consistency.\n\n### Pitfall 8: Skipping `_get_token_and_project` mock in tests — CI stub failure mode\n\nCI runners (and most hermes-agent self-hosted runners) use `GOOGLE_APPLICATION_CREDENTIALS=\u002Fdev\u002Fnull` as a deliberate safety stub. `_get_token_and_project()` reads this env var via `google.auth.default()` and raises `DefaultCredentialsError` BEFORE `_refresh_payloads_schema_set(token, project)` is ever called. The exception is then caught by `_ensure_payloads_schema_cached`'s `except (GoogleAuthError, ...)` block, which sets `_payloads_schema_refresh_attempted_at` to `time.monotonic()` and logs the warning — making the test look like \"refresh failed, no mock called\" when in reality the mock was bypassed entirely. Every test that exercises the cache-refresh path must patch BOTH `_refresh_payloads_schema_set` AND `_get_token_and_project`:\n\n```python\nmonkeypatch.setattr(bq_logging, \"_refresh_payloads_schema_set\", mock_refresh)\nmonkeypatch.setattr(bq_logging, \"_get_token_and_project\", lambda: (\"mock-token\", \"mock-project\"))\n# Now mock_refresh WILL be called, and the test is deterministic regardless\n# of GOOGLE_APPLICATION_CREDENTIALS.\n```\n\nThe diagnostic signature is: `_payloads_schema_refresh_attempted_at` is non-zero AFTER the test, mock call count is 0, and the warning log mentions `File \u002Fdev\u002Fnull is not a valid json file` (google-auth's stub-load failure message). Local repro: set `GOOGLE_APPLICATION_CREDENTIALS=\u002Fdev\u002Fnull` and run the test — if it passes locally but fails on CI, this is your bug.\n\n### Pitfall 9: Caching an unvalidated `tables.get` response\n\n`_refresh_payloads_schema_set` reads BQ's `tables.get` response and iterates `fields`. If the response is malformed (HTTP 200 but body is an HTML error page, an empty dict, a list, or a dict missing the `schema` key), the comprehension silently returns `frozenset()` — the same shape as \"table exists but has no columns.\" A row inserted with `live_columns=frozenset()` will then drop ALL gated columns because none of them are in the empty set. Pin the response shape before caching:\n\n```python\ndef _refresh_payloads_schema_set(token, project) -> frozenset[str]:\n    resp = requests.get(url, headers=_auth_headers(token), timeout=_HTTP_TIMEOUT_S)\n    if resp.status_code != 200:\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE} [{resp.status_code}]: {resp.text}\")\n    body = resp.json()\n    if not isinstance(body, dict):\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE}: body is not a JSON object ({type(body).__name__})\")\n    schema = body.get(\"schema\")\n    if not isinstance(schema, dict):\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE}: missing or non-dict 'schema'\")\n    fields = schema.get(\"fields\")\n    if not isinstance(fields, list):\n        raise RuntimeError(f\"tables.get {PAYLOADS_TABLE}: 'schema.fields' is not a list\")\n    return frozenset(f[\"name\"] for f in fields if isinstance(f, dict) and f.get(\"name\"))\n```\n\nThe exception gets caught at the `_ensure_payloads_schema_cached` `except (RequestException, RuntimeError, ...)` block, stamps the cooldown, and lets the row insert without gated columns — fail-soft as designed, but now you've at least logged the malformed response and won't poison the cache for the TTL window with an `frozenset()` that looks identical to \"table has zero columns.\"\n\n### Pitfall 10: The v1.1.0 cache fix STILL silently drops on cold replicas between deployments\n\nThe v1.1.0 fix replaces the boolean with a per-process `frozenset[str]` cache + `tables.get` + double-check under lock. It is correct for the **steady-state** race (two writers in the same process seeing a stale boolean). It is **not** sufficient for the **cold-replica** race, because:\n\n```python\n# In log_llm_payload (the write path):\nif (\n    _payloads_schema_set is None\n    or (time.monotonic() - _payloads_schema_cached_at) >= _payloads_schema_ttl_seconds\n):\n    cache_ok = _ensure_payloads_schema_cached()\nelse:\n    cache_ok = True\nlive_columns: frozenset[str] = (\n    _payloads_schema_set\n    if cache_ok and _payloads_schema_set is not None\n    else frozenset()  # ← THE LEAK: drops ALL gated cols on cold cache + transient refresh-fail\n)\n```\n\nWhen a Cloud Run replica is cold (just spun up between deployments) AND `_ensure_payloads_schema_cached()` fails on the first call (transient BQ hiccup, IAM token not yet primed, network cold-start delay), `cache_ok=False` AND `_payloads_schema_set is None`. The writer proceeds with `live_columns = frozenset()` and omits every gated column (`is_test`, `user_id`, `cached_tokens`, `thoughts_tokens`, `tool_use_tokens`, `rag_mode`, + 6 more). The cooldown logic in `_ensure_payloads_schema_cached` then keeps the cache cold for the next `_payloads_schema_refresh_cooldown` seconds (60s default), during which every insert on this replica silently drops all gated columns.\n\n**Verified live 2026-07-19 against PR [#8418](https:\u002F\u002Fgithub.com\u002F$GITHUB_REPOSITORY\u002Fpull\u002F8418)** (which DID land the v1.1.0 fix at `90238d16b8`):\n- Last 24h: 186 NULL `is_test` rows \u002F 2014 total = **90.76% populated** (target ≥95%) — fails the watcher.\n- Schema-gate signature: **100.0%** of NULL rows are 5-col co-NULL (the exact silent-drop shape).\n- Per-hour pattern 2026-07-19: hour 18:00 UTC = 100% populated, hour 19:00 = 72.62%, hour 20:00 = 54.0% — fresh replicas spinning up between steady-state hours and hitting the cold-cache race.\n- 7d rolling: 85.68% populated (1237 NULL rows) — the cumulative window trips every watcher run.\n\n**The diagnostic recipe to prove cold-replica persistence from BQ alone** (no Cloud Run logs needed):\n\n```sql\n-- 1. Per-hour buckets last 96h — shows the alternating OK \u002F NOT-OK pattern\nSELECT\n  FORMAT_TIMESTAMP('%Y-%m-%d %H:00', ingested_at) AS hour,\n  COUNTIF(is_test IS NULL) AS n_is_test_null,\n  COUNT(*) AS n_total,\n  ROUND(100.0 * COUNTIF(is_test IS NOT NULL) \u002F COUNT(*), 2) AS pct_populated\nFROM `\u003Cproject>.llm_forensics.llm_payloads`\nWHERE ingested_at > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 96 HOUR)\n  AND model LIKE '%gemini%'\nGROUP BY hour ORDER BY hour DESC;\n\n-- 2. Per-minute buckets for the bad hours — shows the micro-bursts that\n--    are the fingerprint of \"one cold replica silently dropped writes for\n--    its lifetime then died\" (5-8 NULLs every few minutes, no populated\n--    rows between).\nSELECT\n  FORMAT_TIMESTAMP('%Y-%m-%d %H:%M', ingested_at) AS minute_bucket,\n  COUNT(*) AS n_null\nFROM `\u003Cproject>.llm_forensics.llm_payloads`\nWHERE ingested_at >= TIMESTAMP('\u003Cbad-hour-start> UTC')\n  AND ingested_at \u003C TIMESTAMP('\u003Cbad-hour-end> UTC')\n  AND model LIKE '%gemini%'\n  AND is_test IS NULL\nGROUP BY minute_bucket ORDER BY minute_bucket;\n\n-- 3. Schema-gate signature — 5-col co-NULL on EVERY NULL row is the\n--    smoking gun for \"all gated cols dropped by the cache fail-soft path\".\nSELECT\n  COUNTIF(is_test IS NULL AND cached_tokens IS NULL AND thoughts_tokens IS NULL\n          AND tool_use_tokens IS NULL AND rag_mode IS NULL) AS n_co_null_5cols,\n  COUNTIF(is_test IS NULL) AS n_is_test_null_total,\n  ROUND(100.0 * COUNTIF(is_test IS NULL AND cached_tokens IS NULL AND thoughts_tokens IS NULL\n                        AND tool_use_tokens IS NULL AND rag_mode IS NULL)\n        \u002F GREATEST(1, COUNTIF(is_test IS NULL)), 2) AS co_null_pct\nFROM `\u003Cproject>.llm_forensics.llm_payloads`\nWHERE ingested_at > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 24 HOUR)\n  AND model LIKE '%gemini%';\n```\n\nIf `co_null_pct == 100.0`, the bug is the cold-cache silent-drop. Per-replica attribution requires a `revision_id` column (reading `K_REVISION` env var on Cloud Run) — **add it now** as part of the fix, not as a follow-up. Without it, you can't tell which replica is dropping.\n\n**The structural fix shape (belt + suspenders — do both):**\n\n1. **Boot-warmup fallback flag.** Add `_boot_warmup_succeeded: bool = False` to the module state. Set it True at the end of `ensure_dataset_and_tables` after the cache prime attempt (regardless of success\u002Ffailure of the cache fetch itself, since the table exists and has the schema we just declared). In the write path, when `cache_ok=False` AND `_payloads_schema_set is None`, consult `_boot_warmup_succeeded` — if True, the table HAS the columns (we just created or migrated it during boot), so fall back to the in-process `_payloads_schema()` (the authoritative declaration) instead of `frozenset()`. If False (replica never finished boot warmup), log a structured warning with replica_id + retry attempt count, and skip the insert (better to lose a row than silently pollute BQ with NULLs — change from fail-soft to fail-loud only for the truly-no-cache case).\n\n2. **Retry-with-backoff on first call.** Before falling through to `frozenset()`, retry `_ensure_payloads_schema_cached()` up to N=3 times within a short budget (e.g., 500ms total with 100\u002F200\u002F200ms delays). Transient BQ hiccups on cold replicas typically clear within 200ms. Combined with #1, this means: transient hiccup → retry succeeds → cache populated normally; transient hiccup past retry budget + boot warmup succeeded → fall back to `_payloads_schema()` declaration; transient hiccup past retry budget + boot warmup failed → log structured warning + skip insert.\n\n3. **`revision_id` column.** Read `os.environ.get('K_REVISION', 'local-dev')` (Cloud Run sets this; local dev falls back to a sentinel). Add to `_payloads_schema()` as a NON-gated column (it's always present after the schema bump). Make the watcher alert report the `revision_id` distribution of NULL rows so future cold-replica incidents are diagnosable from BQ alone without reading Cloud Run logs.\n\n```python\n# Module state additions:\n_boot_warmup_succeeded: bool = False\n_boot_warmup_lock = threading.Lock()\n\n# In ensure_dataset_and_tables, at the end:\nwith _boot_warmup_lock:\n    _boot_warmup_succeeded = True  # table was created\u002Fmigrated even if cache fetch failed\n\n# In log_llm_payload write path, replacing the live_columns line:\nif cache_ok and _payloads_schema_set is not None:\n    live_columns = _payloads_schema_set\nelif _boot_warmup_succeeded:\n    # Cold cache, but the boot-time migrate created the table with the\n    # authoritative schema. Fall back to the in-process declaration so\n    # gated columns aren't silently dropped.\n    live_columns = frozenset(_payloads_schema())  # use the declared schema\n    logging.warning(\n        f\"BQ logging: schema cache cold, falling back to declared schema; \"\n        f\"revision_id={K_REVISION}\"\n    )\nelse:\n    # Cold cache AND boot warmup never completed — log loud, skip the row.\n    logging.error(\n        f\"BQ logging: schema cache cold AND boot warmup not complete; \"\n        f\"skipping insert to avoid silent NULL pollution. revision_id={K_REVISION}\"\n    )\n    return None  # do NOT silently drop; refuse the insert instead\n\nfor column_name in _GATED_COLUMNS:\n    if column_name in live_columns:\n        row[column_name] = gated_values[column_name]\n```\n\n**Tests to pin the new architecture** (add to `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py`):\n\n```python\ndef test_cold_cache_transient_refresh_failure_includes_gated_columns(monkeypatch):\n    \"\"\"Cold cache + transient refresh failure + boot warmup succeeded\n    → fall back to declared schema; gated cols ARE in the row.\"\"\"\n    monkeypatch.setattr(bq_logging, \"_payloads_schema_set\", None)\n    monkeypatch.setattr(bq_logging, \"_boot_warmup_succeeded\", True)\n    monkeypatch.setattr(bq_logging, \"_ensure_payloads_schema_cached\", lambda: False)\n    # ... call log_llm_payload with a mocked _insert_rows, capture the row arg ...\n    assert \"is_test\" in captured_row\n    assert \"user_id\" in captured_row\n\ndef test_cold_cache_no_boot_warmup_refuses_insert(monkeypatch):\n    \"\"\"Cold cache + boot warmup never completed → refuse the insert,\n    do NOT silently drop.\"\"\"\n    monkeypatch.setattr(bq_logging, \"_payloads_schema_set\", None)\n    monkeypatch.setattr(bq_logging, \"_boot_warmup_succeeded\", False)\n    monkeypatch.setattr(bq_logging, \"_ensure_payloads_schema_cached\", lambda: False)\n    # ... call log_llm_payload ...\n    assert captured_insert_id is None  # refused, not silently dropped\n\ndef test_log_llm_payload_includes_revision_id(monkeypatch, tmp_path):\n    \"\"\"revision_id column reads K_REVISION env var and is included in every row.\"\"\"\n    monkeypatch.setenv(\"K_REVISION\", \"wa-mvp-00042-abc\")\n    # ... call log_llm_payload ...\n    assert captured_row.get(\"revision_id\") == \"wa-mvp-00042-abc\"\n```\n\n**Anti-pattern (do NOT do this):** \"Just push another `_migration_started: bool` companion flag to handle cold-replica case.\" Each new boolean re-introduces the v1.0.0 race in a new shape. The fix is the `_boot_warmup_succeeded` flag PLUS the boot-warmup fallback to the declared schema — not another boolean. The `_boot_warmup_succeeded` flag is set ONCE during boot and never flipped, so it has no race; the `frozenset[str]` cache is keyed on actual state, not a binary \"ready\" signal.\n\n### Pitfall 11: A v1.1.0\u002Fv1.2.0 production-budget change silently breaks existing tests that hold a shared resource longer than the new budget\n\n**Verified live 2026-07-24 against PR [#8462](https:\u002F\u002Fgithub.com\u002F$GITHUB_REPOSITORY\u002Fpull\u002F8462) in $GITHUB_REPOSITORY** (the Pitfall 10 follow-up). The v1.1.0 fix introduced `_PAYLOADS_SCHEMA_RETRY_BUDGET_S: float = 0.5s` — a production wall-clock budget for the cold-replica retry loop. The v1.1.0 fix also added `test_startup_schema_migration_uses_shared_migration_lock`, a regression test that holds `_migration_lock` for **5 seconds** to verify the request path *truly* blocks on the lock (the slow `_migrate_table_schema` mock waits on `release_migration.wait(timeout=5.0)`).\n\nAfter merge, CI core-mvp-3 reports the new test as FAILED with `assert []` on `inserted_rows`. Root cause: the request-path writer's `_lock_before_deadline(_migration_lock, retry_deadline)` times out at 0.5s, logs \"wall-clock budget exceeded\", and falls back to di[REDACTED_OPENAI_KEY] (no BQ insert). The test then asserts `inserted_rows` and fails. The test was passing on the PR branch before the budget change, and it passes on `origin\u002Fmain` HEAD on a clean worktree (`git checkout origin\u002Fmain -- \u003Ctest files>`) — same file, same assertion, same test name, but the production budget change makes it fail on the PR.\n\n**The same-test-name-rule four-check confirms a real PR regression, not a flake:**\n\n1. **Same test name** — `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py::test_startup_schema_migration_uses_shared_migration_lock` is unchanged on both branches.\n2. **Same assertion** — `assert inserted_rows` is unchanged.\n3. **Same file at the same commit** — exists on both `origin\u002Fmain` and PR head (this test was added in PR #8462 itself).\n4. **Explicit same-SHA reproduction on `origin\u002Fmain` HEAD** — `python3 -m pytest $PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py::test_startup_schema_migration_uses_shared_migration_lock` on a `git checkout origin\u002Fmain -- \u003Cfiles>` worktree → **3\u002F3 PASS in 0.34-0.42s** (fast because the lock acquire is fast in isolation). On the PR head (clean worktree, before any fix) → **3\u002F3 FAIL in 2.92-3.54s** (slow because the test actually waits for the 5s lock hold, then times out the 0.5s budget).\n\n**Fix (verified on PR #8462 commit `e2253af7e1`):** monkeypatch the budget wider **in the test only**. Production code keeps the 0.5s invariant; the test widens the budget to a value that comfortably exceeds the 5s lock hold:\n\n```python\ndef test_startup_schema_migration_uses_shared_migration_lock(  # noqa: PLR0915\n    monkeypatch,\n):\n    real_lock = threading.Lock()\n    monkeypatch.setattr(bq_logging, \"_migration_lock\", real_lock)\n    # ... other monkeypatches ...\n    # The shared retry budget defaults to 0.5s so a degraded replica cannot\n    # hold a request-path insert for longer; this test deliberately holds the\n    # migration lock for up to 5s to verify the request path *truly* blocks\n    # on it, so we widen the budget to comfortably exceed that 5s wait.\n    monkeypatch.setattr(bq_logging, \"_PAYLOADS_SCHEMA_RETRY_BUDGET_S\", 10.0)\n    # ... test body unchanged ...\n    assert release_migration.wait(timeout=5.0), \"migration release timed out\"\n```\n\nAfter the fix: `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging_schema_migration.py` 19\u002F19 PASS; `$PROJECT_ROOT\u002Ftests\u002Ftest_bq_logging.py` + `_integration.py` + `_schema_migration.py` 83\u002F83 PASS. PR #8462 went from failing 1 self-hosted MVP shard (core-mvp-3) to 7-green.\n\n**Why this is the right fix, not a budget relaxation.** The 0.5s production budget is a real correctness invariant (a degraded replica cannot hold a request-path insert for >0.5s). Relaxing it to 5s to satisfy one test would silently weaken production behavior. Widening the budget in the test preserves the invariant AND lets the test verify the lock semantics the test was written to verify. The pattern generalizes to any timeout\u002Fbudget + lock-hold test combination: any test that holds a shared resource longer than a new production timeout\u002Fbudget needs the budget widened in the test, not loosened in production.\n\n**Generalization recipe (any timeout\u002Fbudget + lock-hold test combination):**\n\n1. Identify the new production budget\u002Ftimeout\u002Fdeadline value introduced by the PR (grep for `_TIMEOUT = \\|_BUDGET = \\|_LIMIT = \\|_DEADLINE = ` in the diff).\n2. Identify any test in the diff (or any existing test that the new budget would break) that holds a shared resource for longer than that budget.\n3. Add `monkeypatch.setattr(\u003Cmodule>, \"\u003CCONSTANT>\", \u003Cvalue comfortably above test's resource hold>)` to the test setup. Document the value choice in a comment (\"this test deliberately holds X for N seconds to verify Y; production budget is 0.5s but the test needs at least N+1s\").\n4. Local verification: `python3 -m pytest \u003Ctest>` 3 times in a row → all pass on the PR head.\n5. Same-test-name-rule check on `origin\u002Fmain`: `git checkout origin\u002Fmain -- \u003Ctest file> && python3 -m pytest \u003Ctest>` → 3\u002F3 pass (proving the test was always passing before the budget regression).\n\n**Don't fall into:** \"The test is flaky, just re-run\" — this dismisses a real PR regression. The test is deterministic; the failure is reproducible. The PR introduced the budget that broke the test.\n\n**Don't fall into:** \"Loosen the production budget to make the test pass\" — this silently weakens production. The budget is a real invariant; the test should widen the budget, not production.\n\n**Don't fall into:** \"Skip the test, mark it as known-failure\" — the test is the only one that proves the lock serialization invariant the v1.1.0 fix established. Skipping it would silently lose regression coverage on the most important fix-shape property.\n\n**Cross-skill reference:** This pattern is a sibling to the same-test-name-rule dismissal gate (the `qa-test-failure-dismissal-anti-pattern` skill) — that gate decides whether a CI failure is a real PR regression or an infra flake. Pitfall 11 is the \"yes, it's a real PR regression, here's how to fix the test while keeping production tight\" companion.\n\n**PR-topology reminder:** when the v1.1.0 fix is already merged (e.g., PR #8418) and you discover the cold-replica persistence, do NOT push a follow-up commit onto the v1.1.0 branch — open a NEW branch from `origin\u002Fmain` with `git worktree add -b fix\u002F\u003Ctopic> origin\u002Fmain`, cherry-pick only the load-bearing change (the `_boot_warmup_succeeded` + revision_id + retry logic), and open a fresh PR. Per `pr-clean-branch-from-main-no-history-bloat` and `never-push-onto-someone-elses-pr-head`, pushing onto a non-owned PR head is the #1 PR-pollution failure mode. The follow-up PR (fix\u002Fbq-payloads-schema-cold-replica-fix, bead `rev-zurdo`) was opened on 2026-07-19 with this exact pattern.\n\n## Reference\n\n- `references\u002F2026-07-16-bq-is-test-null-pr-8418.md` — worked example: the `_payloads_schema_migrated: bool` race in `$PROJECT_ROOT\u002Fbq_logging.py`, PR [#8418](https:\u002F\u002Fgithub.com\u002F$GITHUB_REPOSITORY\u002Fpull\u002F8418) (commit `51242edb2`). Reproduces the live bug (5\u002F1069 NULL rows in last 24h, co-NULL on 6 columns, two micro-bursts at 10:03 and 10:05 UTC). Previous sibling PRs #8070 (preserve additive schema migration + serialize writers) and #8351 (preserve live schema columns) attempted the same fix but kept the boolean flag in place.\n- `references\u002F2026-07-17-pr-8418-driven-to-green.md` — v1.1.0 addendum: three CodeRabbit-flagged corrections (cooldown re-check inside lock, `_GATED_COLUMNS` authoritative declaration, `_get_token_and_project` CI mock requirement), the `tables.get` response-shape validation pattern, AND the 8-section PR description gate choreography used to drive PR #8418 to green on 2026-07-17.\n- `references\u002F2026-07-19-cold-replica-persistence.md` — v1.2.0 evidence: PR #8418's v1.1.0 cache fix did NOT hold across new Cloud Run replicas between deployments. Live BQ probe on 2026-07-19 21:00 UTC shows 186 NULL is_test rows in last 24h (90.76% populated, fails ≥95% target), 100% co-NULL on 5 gated cols, per-hour pattern of alternating OK \u002F NOT-OK as fresh replicas spin up. Follow-up PR `fix\u002Fbq-payloads-schema-cold-replica-fix` (bead `rev-zurdo`, worker `worldarchitect-64`) implements Pitfall 10's fix shape. Includes the `env -i PYTHONPATH=` workaround for the broken `bq` CLI on this Mac, and the `gh api` GraphQL rate-limit fallback to REST.\n\n## Cross-references\n\n- `~\u002F.hermes\u002Fskills\u002Fsoftware-development\u002Fsystematic-debugging\u002FSKILL.md` — the 4-phase protocol for finding root cause before fixing. Use this skill after systematic-debugging identifies the silent-drop class with a module-level boolean as the named suspect.\n- `~\u002F.hermes\u002Fskills\u002Fsoftware-development\u002Fconvergent-bug-triage\u002FSKILL.md` — when 3+ sibling bug investigations on the same surface point to the same root class. The is_test NULL family (PR #8070 + #8351 + #8418) is exactly this pattern.\n- `~\u002F.hermes\u002Fskills\u002Fdevops\u002Fverify-telemetry-alert\u002FSKILL.md` — how to verify the BQ \u002F metric alert that surfaces this class before assuming the alert is accurate.\n- `~\u002F.hermes\u002Fskills\u002Fworldarchitect\u002Fwa-cloud-run-deploy-failure-debug\u002FSKILL.md` — sibling skill for Cloud Run deploy failure debugging (different class: deployment, not race).",{"name":5,"tags":65,"version":66,"description":7},[45,53,44,54,43,42,41,40],"1.3.0","main","05df7380981a2c4af868ce0fa57962ae0eea62a9","hermes\u002Fskills\u002Fsoftware-development\u002Fmodule-global-flag-race",0,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills","https:\u002F\u002Fgithub.com\u002Fjleechanorg","2026-11-14 14:55:35",{"source":9,"skillName":5,"commands":75,"prompt":85,"zipAvailable":86},[76,79,82],{"tool":77,"command":78},"npx","npx skills add jleechanorg\u002Fjleechan-skills --skill module-global-flag-race",{"tool":80,"command":81},"bunx","bunx skills add jleechanorg\u002Fjleechan-skills --skill module-global-flag-race",{"tool":83,"command":84},"pnpm","pnpm dlx skills add jleechanorg\u002Fjleechan-skills --skill module-global-flag-race","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fsoftware-development\u002Fmodule-global-flag-race\u002FSKILL.md",true,[88,94,98,102,106,110,114,118],{"path":89,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":92,"sourceHtmlUrl":93},"reference\u002Fchart-types.md","REFERENCE","参考文档",8763,"https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fscientific\u002Fplotly\u002Freference\u002Fchart-types.md",{"path":95,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":96,"sourceHtmlUrl":97},"reference\u002Fexport-interactivity.md",9204,"https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fscientific\u002Fplotly\u002Freference\u002Fexport-interactivity.md",{"path":99,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":100,"sourceHtmlUrl":101},"reference\u002Fgraph-objects.md",5986,"https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fscientific\u002Fplotly\u002Freference\u002Fgraph-objects.md",{"path":103,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":104,"sourceHtmlUrl":105},"reference\u002Flayouts-styling.md",9128,"https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fscientific\u002Fplotly\u002Freference\u002Flayouts-styling.md",{"path":107,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":108,"sourceHtmlUrl":109},"reference\u002Fplotly-express.md",4893,"https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fscientific\u002Fplotly\u002Freference\u002Fplotly-express.md",{"path":111,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":112,"sourceHtmlUrl":113},"references\u002F2026-07-16-bq-is-test-null-pr-8418.md",11192,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fsoftware-development\u002Fmodule-global-flag-race\u002Freferences\u002F2026-07-16-bq-is-test-null-pr-8418.md",{"path":115,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":116,"sourceHtmlUrl":117},"references\u002F2026-07-17-pr-8418-driven-to-green.md",8091,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fsoftware-development\u002Fmodule-global-flag-race\u002Freferences\u002F2026-07-17-pr-8418-driven-to-green.md",{"path":119,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":120,"sourceHtmlUrl":121},"references\u002F2026-07-19-cold-replica-persistence.md",11818,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002Fhermes\u002Fskills\u002Fsoftware-development\u002Fmodule-global-flag-race\u002Freferences\u002F2026-07-19-cold-replica-persistence.md",[123,131,138,145,153,162],{"skillNo":124,"name":125,"nameZh":13,"description":126,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":130},"01M7DRVZXXMGY4G81K5GVF4V20","disk-reclaim-playbook","Use Disk Magician to diagnose disk growth or qualify cleanup on macOS or Linux.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fdisk-reclaim-playbook\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":132,"name":133,"nameZh":13,"description":134,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":130},"01M7B63PNTT2TY78RFKHD8SP3X","claudea-bench","Compare `claudea` and normal `claude` on a fair split of comparable work by default; use `--strict` for duplicate runs of the exact same task.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fclaudea-bench\u002FSKILL.md",[],[],{"skillNo":139,"name":58,"nameZh":13,"description":140,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":141,"categories":142,"keywords":143,"publishedAt":144},"01M7622KQJ32AV4K5BXEMVSSEB","Alias for the canonical pr-lifecycle PR workflow skill (\u002Fpr-workflow, \u002Fprw).","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr\u002FSKILL.md",[],[],"2026-11-12 13:55:43",{"skillNo":146,"name":147,"nameZh":13,"description":148,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":149,"categories":150,"keywords":151,"publishedAt":152},"01M7432W92AKC4D1TKJ00VCMMT","whisper","OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fwhisper\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":154,"name":155,"nameZh":13,"description":156,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":157,"licenseFileUrl":158,"sourceHtmlUrl":159,"categories":160,"keywords":161,"publishedAt":152},"01M7432T6BN1A9SHB8RBQR5EMP","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":163,"name":164,"nameZh":13,"description":165,"descriptionZh":13,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":13,"sourceHtmlUrl":166,"categories":167,"keywords":168,"publishedAt":152},"01M7432NDC7S6C6MX7M6RW8CTT","pr-report","This skill should be used when the user asks for a PR report, PR audit, PR delta analysis, \u002Fpr-report, or wants per-PR summary with delta files\u002Flines. Generates a structured report for one or more open PRs covering purpose, files changed, +\u002F− line counts, \u002Fcode-standards + \u002Fthermo review findings, \u002Fponytail simplification opportunities, file-overlap combination candidates, and \u002Fgreen status per pr-green-definition. Output: machine-readable JSONL + human-readable markdown. Read-only by default; can apply simplifications if user opts in.","https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills_archive\u002F2026-11-09-no-usage-evidence\u002Fpr-report\u002FSKILL.md",[],[]]