Skip to content

feat(smart-merge): content-free audit sibling and survivor-deleted counter (split from #19978) - #20314

Merged
Git-on-my-level merged 4 commits into
mainfrom
lane/smart-merge-audit-record
Oct 2, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
lane/smart-merge-audit-record

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

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.
  • Survivor, donor tombstone and audit are written in the same transaction. Rejected and already-absorbed replays write no audit. The donor document ID makes successful commit retries idempotent; skipped audits are never backfilled by a replay.
  • Account wipe fencing reads the durable account_deletions/{uid} marker and the existing legal_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.
  • A failed authority RPC or audit staging operation raises before commit. The SDK attempts rollback, and the storage boundary restarts the absorb once with a fresh transaction and no audit I/O. Callback state preserves recovery even when the rollback RPC masks the original error. No commit RPC was attempted for the failed callback. It re-reads both conversations and rechecks the existing deterministic policy without re-asking Jev. It never continues writing on a transaction with a failed read or partially staged audit.
  • A projection validation error skips only the audit. Commit errors still atomically fail the absorb; ambiguous commits retain the existing donor readback behavior.
  • smart_merge.last_merged_at adds 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

Path Reads Writes
Accepted absorb, audit on 4 (survivor, donor, deletion marker, gate) 3 (survivor, donor, audit)
Accepted absorb, audit off 2 2
Rejected/already-absorbed absorb 2 0
Survivor purge counter +0 +0

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_failed logs 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} and event=smart_merge outcome=survivor_deleted count 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.
  • Records survive conversation cascades and are purged by account deletion. expire_at is 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.

  • Final focused runner: 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.
  • SDK tests cover aborted/deadline/unavailable/invalid authority RPCs, rollback after partially buffering an audit write, successful commit retries, a live gate appearing between commit attempts, replay and untrusted string rejection.
  • Conversation-document equivalence is checked across audit on/off, live gate, durable deletion marker, invalid projection and read failure. Existing smart-merge suites retain eligibility/gap/cutoff/caps/default coverage.
  • Broader 70-file merge, process_conversation, finalization, sync, deletion and stub-isolation runner: 1,827 passed. After the rollback hardening, the focused 149-test runner passed again.
  • backend/scripts/typecheck.sh: 0 errors (warnings remain). Pinned formatter: all 11 changed Python files clean. scripts/pr-preflight --pr-body-file <body> and make preflight: each passed all 36 selected checks. Managed pre-push passed on bb46fc6a102c93b8188abea8b111047b782bd004, 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.

Git-on-my-level and others added 4 commits October 2, 2026 14:29
…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]>
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]>
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 2, 2026 08:19
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 15 files

Confidence score: 3/5

  • smart_merge_audit.py emits 16 fields for a 17-field audit schema, so accepted-absorb records won’t match the published projection. Add and validate the missing merged outcome.
  • smart_merge_audit.py can 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.yaml doesn’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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Comment thread config/feature-flags.yaml
- {"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"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
- {"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)"}

@Git-on-my-level
Git-on-my-level merged commit 3dd44da into main Oct 2, 2026
65 of 67 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/smart-merge-audit-record branch October 2, 2026 08:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant