Repository navigation
feat(smart-merge): content-free audit sibling and survivor-deleted counter (split from #19978) - #20314
Conversation
…unter Split from #19978: only the part needed to measure false merges. The absorb transaction now stages users/{uid}/smart_merge_audit/{donor_id} (ids, decision numbers, model/question version, ledger position, expire_at with no TTL policy) behind the account destructive-operation gate, read in the same transaction and only on the absorbing path. A live/malformed gate or an invalid projection commits the merge without the sibling; the merge decision never depends on the audit. CONVERSATION_SMART_MERGE_AUDIT_ENABLED (unset = on, anything but an on-value = off) removes the read and write. Survivors record last_merged_at in their ledger; purging a survivor counts omi_conversation_smart_merge_survivor_deleted_total by age bucket from the row the purge already read. Audit outcomes are counted in omi_conversation_smart_merge_audit_total. No unmerge tool, cascade, executor, legal-hold, storage or paywall-disposition change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
Restart optional audit I/O failures on a fresh transaction, validate server enums and document IDs, and fence audit creation with the durable account-deletion marker. Exercise the real SDK transaction decorator with mocked RPCs for rollback, buffer cleanup and commit retry. Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
Retain the pre-commit audit failure at the callback boundary because the Firestore SDK can replace it with a rollback error. Verify recovery with failing read and rollback RPCs using the real SDK decorator. Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
3 issues found across 15 files
Confidence score: 3/5
smart_merge_audit.pyemits 16 fields for a 17-field audit schema, so accepted-absorb records won’t match the published projection. Add and validate the missingmergedoutcome.smart_merge_audit.pycan still block a merge: Firestore buffers writes, so audit failures may surface at commit and abort the transaction. Handle commit-time audit failures if audit must never block merges.feature-flags.yamldoesn’t identify which services need the kill switch, and no deploy file declares the environment variable. Record the service coverage so ops can disable the audit reliably.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/database/smart_merge_audit.py">
<violation number="1" location="backend/database/smart_merge_audit.py:142">
P2: This projection emits 16 fields instead of the declared 17-field audit schema. Add and validate the missing accepted-absorb outcome (for example, `decision: 'merged'`) so records conform to the published projection.</violation>
<violation number="2" location="backend/database/smart_merge_audit.py:182">
P2: The 'audit never blocks the merge' guarantee only holds until commit: the Python Firestore SDK buffers writes, so most audit write failures surface when the transaction commits, and any commit-time failure aborts the survivor update and donor tombstone too (the docstring documents this atomicity). That makes a misconfigured or over-limit `smart_merge_audit` subcollection a permanent hard failure for every enabled absorb, not a skipped sibling. Worth an ops note: verify collection permissions/size and monitor `absorbed` failure rates after enabling.</violation>
</file>
<file name="config/feature-flags.yaml">
<violation number="1" location="config/feature-flags.yaml:31">
P3: This kill-switch note never records which services must set the value off, and no deploy file declares the env var, so disabling the audit requires ops to know unrecorded service coverage. Repo precedent enumertes the exact service set for kill switches (e.g. `SYNC_LINEAGE_RESOLVE_ENABLED`, `ACTION_ITEM_IDENTITY_PRESERVE_ENABLED`); the PR itself says the setting must stay consistent on the GKE pusher and Cloud Run backend-sync. Add the service list to `notes` so a partial disable on one service is not mistaken for a full one.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| if decision.get(name) != expected: | ||
| raise ValueError('audit decision enum is unsupported') | ||
| record: dict[str, Any] = { | ||
| 'version': AUDIT_VERSION, |
There was a problem hiding this comment.
P2: This projection emits 16 fields instead of the declared 17-field audit schema. Add and validate the missing accepted-absorb outcome (for example, decision: 'merged') so records conform to the published projection.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/smart_merge_audit.py, line 142:
<comment>This projection emits 16 fields instead of the declared 17-field audit schema. Add and validate the missing accepted-absorb outcome (for example, `decision: 'merged'`) so records conform to the published projection.</comment>
<file context>
@@ -0,0 +1,183 @@
+ if decision.get(name) != expected:
+ raise ValueError('audit decision enum is unsupported')
+ record: dict[str, Any] = {
+ 'version': AUDIT_VERSION,
+ 'donor_id': _token(donor_id),
+ 'survivor_id': _token(survivor_id),
</file context>
| try: | ||
| transaction.set(audit_ref(client, uid, donor_id), record) | ||
| except Exception as error: | ||
| raise AuditUnavailable('audit staging failed') from error |
There was a problem hiding this comment.
P2: The 'audit never blocks the merge' guarantee only holds until commit: the Python Firestore SDK buffers writes, so most audit write failures surface when the transaction commits, and any commit-time failure aborts the survivor update and donor tombstone too (the docstring documents this atomicity). That makes a misconfigured or over-limit smart_merge_audit subcollection a permanent hard failure for every enabled absorb, not a skipped sibling. Worth an ops note: verify collection permissions/size and monitor absorbed failure rates after enabling.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/smart_merge_audit.py, line 182:
<comment>The 'audit never blocks the merge' guarantee only holds until commit: the Python Firestore SDK buffers writes, so most audit write failures surface when the transaction commits, and any commit-time failure aborts the survivor update and donor tombstone too (the docstring documents this atomicity). That makes a misconfigured or over-limit `smart_merge_audit` subcollection a permanent hard failure for every enabled absorb, not a skipped sibling. Worth an ops note: verify collection permissions/size and monitor `absorbed` failure rates after enabling.</comment>
<file context>
@@ -0,0 +1,183 @@
+ try:
+ transaction.set(audit_ref(client, uid, donor_id), record)
+ except Exception as error:
+ raise AuditUnavailable('audit staging failed') from error
+ return WRITTEN
</file context>
| - {"key":"ACTION_ITEM_IDENTITY_ANCHOR_SHADOW_ENABLED","aliases":[],"kind":"env","lifecycle":"rollout","surfaces":["backend"],"summary":"Measure, in the action_item_identity log line only, how many reprocess-unmatched prior tasks pair one-to-one with a new task by stored transcript segment ids; never changes what is written or delivered (default on)","fail":"open","owner":"dazheng","created":"2026-10-01","review_by":"2026-10-31","decision":"pending","notes":"Measurement-only shadow for the task-identity follow-up. Kill switch: set false/off on the services that run process_conversation (Cloud Run backend, backend-sync, backend-sync-backfill, backend-integration; GKE backend-listen and pusher); an unrecognized value also means off. Off drops the extra provenance field from the prior-task read and logs shadow=disabled; writes are identical either way. Remove after the follow-up decision"} | ||
| - {"key":"SYNC_LINEAGE_RESOLVE_UID_ALLOWLIST","aliases":[],"kind":"env","lifecycle":"rollout","surfaces":["backend"],"summary":"Limit sync lineage binding and its live-row fences to listed UIDs; empty admits every user","fail":"open","owner":"dazheng","created":"2026-09-30","review_by":"2026-10-30","decision":"pending","notes":"Staged rollout 2026-09-30: prod lists David's uid on Cloud Run backend, backend-sync, backend-sync-backfill, backend-integration and GKE backend-listen (keep identical); dev unset (everyone). Widen after the 48 h log gates in utils/sync/ARCHITECTURE.md by clearing the value on all five together. The origin stamp ignores it"} | ||
| - {"key":"CONVERSATION_SMART_MERGE_UID_ALLOWLIST","aliases":[],"kind":"env","lifecycle":"rollout","surfaces":["backend"],"summary":"Limit smart merge to listed UIDs; empty admits every user","fail":"closed","owner":"dazheng","created":"2026-09-29","review_by":"2026-10-29","decision":"pending"} | ||
| - {"key":"CONVERSATION_SMART_MERGE_AUDIT_ENABLED","aliases":[],"kind":"env","lifecycle":"ops_kill","surfaces":["backend"],"summary":"Write the content-free smart-merge audit sibling inside the absorb transaction (unset = on; off or any unrecognized value = no gate read, no audit write)","fail":"open","owner":"dazheng","created":"2026-10-02","decision":"keep","notes":"Never changes a merge decision; kill switch for the extra read+write on the absorb transaction"} |
There was a problem hiding this comment.
P3: This kill-switch note never records which services must set the value off, and no deploy file declares the env var, so disabling the audit requires ops to know unrecorded service coverage. Repo precedent enumertes the exact service set for kill switches (e.g. SYNC_LINEAGE_RESOLVE_ENABLED, ACTION_ITEM_IDENTITY_PRESERVE_ENABLED); the PR itself says the setting must stay consistent on the GKE pusher and Cloud Run backend-sync. Add the service list to notes so a partial disable on one service is not mistaken for a full one.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At config/feature-flags.yaml, line 31:
<comment>This kill-switch note never records which services must set the value off, and no deploy file declares the env var, so disabling the audit requires ops to know unrecorded service coverage. Repo precedent enumertes the exact service set for kill switches (e.g. `SYNC_LINEAGE_RESOLVE_ENABLED`, `ACTION_ITEM_IDENTITY_PRESERVE_ENABLED`); the PR itself says the setting must stay consistent on the GKE pusher and Cloud Run backend-sync. Add the service list to `notes` so a partial disable on one service is not mistaken for a full one.</comment>
<file context>
@@ -28,6 +28,7 @@ flags:
- {"key":"ACTION_ITEM_IDENTITY_ANCHOR_SHADOW_ENABLED","aliases":[],"kind":"env","lifecycle":"rollout","surfaces":["backend"],"summary":"Measure, in the action_item_identity log line only, how many reprocess-unmatched prior tasks pair one-to-one with a new task by stored transcript segment ids; never changes what is written or delivered (default on)","fail":"open","owner":"dazheng","created":"2026-10-01","review_by":"2026-10-31","decision":"pending","notes":"Measurement-only shadow for the task-identity follow-up. Kill switch: set false/off on the services that run process_conversation (Cloud Run backend, backend-sync, backend-sync-backfill, backend-integration; GKE backend-listen and pusher); an unrecognized value also means off. Off drops the extra provenance field from the prior-task read and logs shadow=disabled; writes are identical either way. Remove after the follow-up decision"}
- {"key":"SYNC_LINEAGE_RESOLVE_UID_ALLOWLIST","aliases":[],"kind":"env","lifecycle":"rollout","surfaces":["backend"],"summary":"Limit sync lineage binding and its live-row fences to listed UIDs; empty admits every user","fail":"open","owner":"dazheng","created":"2026-09-30","review_by":"2026-10-30","decision":"pending","notes":"Staged rollout 2026-09-30: prod lists David's uid on Cloud Run backend, backend-sync, backend-sync-backfill, backend-integration and GKE backend-listen (keep identical); dev unset (everyone). Widen after the 48 h log gates in utils/sync/ARCHITECTURE.md by clearing the value on all five together. The origin stamp ignores it"}
- {"key":"CONVERSATION_SMART_MERGE_UID_ALLOWLIST","aliases":[],"kind":"env","lifecycle":"rollout","surfaces":["backend"],"summary":"Limit smart merge to listed UIDs; empty admits every user","fail":"closed","owner":"dazheng","created":"2026-09-29","review_by":"2026-10-29","decision":"pending"}
+ - {"key":"CONVERSATION_SMART_MERGE_AUDIT_ENABLED","aliases":[],"kind":"env","lifecycle":"ops_kill","surfaces":["backend"],"summary":"Write the content-free smart-merge audit sibling inside the absorb transaction (unset = on; off or any unrecognized value = no gate read, no audit write)","fail":"open","owner":"dazheng","created":"2026-10-02","decision":"keep","notes":"Never changes a merge decision; kill switch for the extra read+write on the absorb transaction"}
- {"key":"CONVERSATION_RELEVANCE_KEEP_ALL_PERCENT","aliases":[],"kind":"env","lifecycle":"experiment","surfaces":["backend"],"summary":"Conversation percentage kept at the ambiguous model tier without a decision call","fail":"closed","owner":"dazheng","created":"2026-09-30","review_by":"2026-10-21","decision":"pending","prereg":"backend/docs/experiments/EXP-004-jev-relevance-owner-ramp.md"}
- {"key":"CONVERSATION_RELEVANCE_JEV_PERCENT","aliases":[],"kind":"env","lifecycle":"experiment","surfaces":["backend"],"summary":"Jev conversation percentage after keep-all; production stage 1 is 1% (2026-10-02); ramp 1 -> 10 -> 50 -> 100 with 24h soaks; unset is 100 when enabled","fail":"closed","owner":"dazheng","created":"2026-09-30","review_by":"2026-10-21","decision":"pending","prereg":"backend/docs/experiments/EXP-004-jev-relevance-owner-ramp.md"}
</file context>
| - {"key":"CONVERSATION_SMART_MERGE_AUDIT_ENABLED","aliases":[],"kind":"env","lifecycle":"ops_kill","surfaces":["backend"],"summary":"Write the content-free smart-merge audit sibling inside the absorb transaction (unset = on; off or any unrecognized value = no gate read, no audit write)","fail":"open","owner":"dazheng","created":"2026-10-02","decision":"keep","notes":"Never changes a merge decision; kill switch for the extra read+write on the absorb transaction"} | |
| "notes":"Never changes a merge decision; kill switch for the extra read+write on the absorb transaction (set off on both services that run the absorb: GKE pusher and Cloud Run backend-sync)"} |
Problem and behavior
Smart-merge redirects disappear when their survivor is purged, so they cannot support later measurement. This slice of #19978 writes a bounded audit sibling atomically with each accepted absorb and counts survivor purges. The undo tool, audio/executor changes, merge policy and mode default are outside this PR.
Implementation
users/{uid}/smart_merge_audit/{donor_id}is a closed projection of 17 flat fields: version, donor/survivor IDs, revision, ledger position, source, merge/expiry timestamps, stretch count, four decision numbers, model, question version and mode. No transcript, title, overview, ledger summary, prompt hash or UID field is copied. IDs are bounded slash-free tokens validated with fullmatch; source must be an eligible source and decision enums must match server-known values. IDs are user-scoped metadata, not anonymized data. A regex is not a proof that arbitrary strings contain no content.account_deletions/{uid}marker and the existinglegal_hold_deletion_gates/{uid}document before any writes. Pending/running/failed/completed or malformed deletion authority suppresses the audit. Cancelled/billing_failed markers permit it. The durable marker closes the sibling-enumeration window even if a wipe runs past the six-hour gate staleness bound. Live/malformed destructive gates also suppress the audit.smart_merge.last_merged_atadds a timestamp inside the existing survivor write. Only the new age-bucket helper reads it; existing pair checks and Jev state builders ignore it. Older survivors use their newest fragment end as an approximate age.Cost and contention
At roughly 700 merges/day: about 1,400 additional reads and 700 writes/day before retries. Gate/marker reads can delay a concurrent authority writer under pessimistic locking or cause retries under contention. Mocked SDK tests prove callback rollback and commit replay; server lock scheduling and deployment latency are not measured.
Flag, services and observability
CONVERSATION_SMART_MERGE_AUDIT_ENABLED: unset/blank means on; true/on/1/yes enable it; any other value, including a typo, disables audit I/O. Kill it on both GKE pusher and Cloud Run backend-sync, the production finalization hosts. The same main image can execute the finalization endpoint wherever deployed; keep the flag consistent if that routing changes. Flag off leaves the timestamp and purge counter active.omi_conversation_smart_merge_audit_total{outcome=written|disabled|skipped_gate|skipped_invalid|skipped_error|unknown}counts committed absorb audit outcomes.event=smart_merge_audit outcome=...logs those outcomes even where counters are not scraped.event=smart_merge_audit_restart reason=io_failedlogs attempted recovery; the shared fallback helper records degraded audit recovery after a committed merge.omi_conversation_smart_merge_survivor_deleted_total{age_bucket=lt_1h|lt_24h|lt_7d|gte_7d|unknown}andevent=smart_merge outcome=survivor_deletedcount purges after successful deletion. Manual-merge source deletion is included. Account wipes/raw database deletes bypass it. This is an approximate purge signal, not user-confirmed false-merge ground truth; concurrent deletes/retries can overcount.expire_atis 60 days after merge, but no TTL policy is activated, so records otherwise accumulate.Verification
Synthetic data, hermetic network guard, fake Jev and processing seams only. No production/dev/real Firestore or real Jev calls.
BACKEND_UNIT_TEST_FILE_LIST=sol-focused-tests.txt bash backend/test.sh: 149 tests passed (53 audit, 26 SDK RPC-mock, 70 smart merge), including failed read plus failed rollback recovery.backend/scripts/typecheck.sh: 0 errors (warnings remain). Pinned formatter: all 11 changed Python files clean.scripts/pr-preflight --pr-body-file <body>andmake preflight: each passed all 36 selected checks. Managed pre-push passed onbb46fc6a102c93b8188abea8b111047b782bd004, including repeated Pyright (0 errors), selected backend tests, runtime-image source closure and all shared PR checks. CI remains the full test authority.Not verified: real Firestore contention, emulator, deployment acceptance, TTL activation or Cloud Run scraping. Watch audit skips/restarts, finalization failures and latency after deployment. Only the audit/absorb account-deletion thread from #19978 applies to this slice; undo/audio/executor threads remain outside it.
Product invariants affected
none
Failure-Class: none
Review hardening of a new measurement feature; no existing registered failure class precisely covers optional transaction read recovery plus audit projection validation.