Skip to content

fix(sync): stop re-encoding stored open_loop_extractions on sync assignment - #23718

Merged
Git-on-my-level merged 1 commit into
mainfrom
lane/openloop-codec-fix
Oct 26, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
lane/openloop-codec-fix

Conversation

@Git-on-my-level

Copy link
Copy Markdown
Member

Problem and fix

The supplied RCA counted 1,271 terminally affected sync jobs: 894 persistence failures and 377 finalize failures. The reproduced storage round-trip defect is a strong explanation for the new persistence failures; these aggregate counts do not prove individual attribution. The existing finalize population is separate and is not attributed to this defect. Disabling extraction stops new blobs but does not unblock existing encoded rows.

Sync assignment now strictly decodes retained open_loop_extractions before the logical write encoder, matching manual speaker receipts. The field round-trips as the same dictionary with compression/encryption at the destination protection level. Assignment, canonical updates and donor redirects remain in the same transaction. An unreadable extraction aborts before writes; it is never converted to empty content. Both extraction fields remain outside client wire models.

Write-path audit

  • Sync: assign_sync_conversation.decode and encode_sync_assignment_plan; canonical append, retry, sync donor merge, mixed protection, and new-row creation.
  • Smart absorb: database.smart_merge.absorb_conversation / absorb_payloads use a partial survivor update. Same-level writes preserve the exact stored blob; upgrades now decode/re-encrypt retained survivor content. Donor redirects are metadata-only and preserve donor blobs.
  • Processing/reprocess: upsert_conversation_with_lifecycle, persist_processing_result_with_lifecycle, create_conversation_if_absent_with_lifecycle, and _reapply_current_manual_assignments. Model-based processing omits retained extractions when no fresh extraction exists, so merge writes preserve them. Fresh output encoded before a concurrent protection migration is now re-protected at the transactional document level.
  • Protection migration: migrate_conversations_level_batch now strictly decodes and re-encodes extractions in the same transaction as its protection-level change. Null stays null; failed decode cannot partially migrate the row.
  • Other codec callers: encode_conversation_for_write, _prepare_conversation_for_write, update_conversation, chat edits, manual speaker assignments, segment updates, translation materialization, final transcript promotion, speaker resolution/voice-profile/evidence writes and transcript imports. These pass logical field-specific patches, not retained raw extraction blobs. Retention/deletion/timestamp writers use metadata patches or delete the owner; they do not re-encode retained extractions. The tolerant daily read helper remains separate from the strict write decoder. The smart-absorb query-body digest was re-reviewed and re-pinned; no query shape or read was added.
  • Existing persistence/finalize diagnostics now emit a closed value_error_reason: open_loop_extractions_not_object, other_value_error, or none. No exception text is emitted in this field.

Verification

  • Real compressed and enhanced-encrypted rows: append/retry, donor merge, new-row creation, corrupt-input write refusal, migration both directions, reprocess preservation, concurrent migration, and client wire exclusion.
  • Smart absorb tests verify byte-identical preservation at the same level and logical equality after protection upgrade, including untouched donor blobs.
  • Pipeline tests exercise both telemetry boundaries and verify unknown exception text never enters the reason token.
  • Required test selection: all test_open_loops_*.py, test_sync_lineage_created.py, and selector-chosen sync/Firestore suites, plus smart merge and speaker receipt/protection suites, through bin/omi-heavy at nice -n 15, with file isolation. After rebase: 219 files passed, 5,380 tests passed, 39 skipped, 35 deselected; zero failures. The 22 focused storage regressions are included.
  • Backend environment preflight: 18 passed, 8 optional warnings, zero failures. Async blocker scan: zero findings.
  • make preflight: all 37 checks passed. PR metadata validation: 4 checks passed. The installed push hook repeated the full preflight on the rebased head and passed typechecking, runtime source closure, 4 changed test files and its remaining bounded checks; push succeeded with hooks enabled.
  • Hermetic tests only. No production reads, API calls, GCP tier, deploy, configuration change, or merge.

Failure-Class: new

Root cause: the write-side round trip was extended for a protected field without updating the read-modify-write decoders and protection migration paths. Durable guard: FC-conversation-write-codec-roundtrip names behavioral tests seeded by the real storage encoder across these write owners, rather than unencoded fixture dictionaries. The fix uses a shared strict decoder instead of another permissive display fallback.

Product invariants affected

none

Line-Count-Exception: backend/database/conversations.py | 4514 -> 4542 | Keep the strict extraction decoder and transaction-owned codec calls beside the existing protected-field owners for this urgent incident fix.
Line-Count-Exception: backend/utils/sync/pipeline.py | 3756 -> 3758 | Add closed ValueError reason tokens at the existing persistence and finalize exception boundaries without moving their ownership.

Rollback: revert (OPEN_LOOPS_ENABLED=false remains the mitigation)

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-26T11:55:23.033777Z 288cd34 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Git-on-my-level
Git-on-my-level merged commit 87083b7 into main Oct 26, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/openloop-codec-fix branch October 26, 2026 12:08
Git-on-my-level added a commit that referenced this pull request Oct 26, 2026
Reverts #23731 (merged c5486dd), restoring the 8 FIRESTORE_READ_LEVERS
it set to 0.

Why: #23731 was a precaution against a backend-sync 5xx guard breach at
the 14Z tick (0.73% vs 0.11% ref). op1 attributed those 5xx: ~256 are
audio-merge manifest-retry 500s that predate the regression (722/h on
10-25), and ~110 align with Firestore expired_transaction storms caused
by #23718's in-transaction decode (fixed by #23738). None are
lever-linked, so the levers are exonerated and their read savings should
stay.

#23731 never deployed (the serving Cloud Run, listen and pusher
revisions predate c5486dd). Merging this before the next CR train keeps
the lever state unchanged in production.

## Product invariants affected

- INV-MEM-4 (path match on backend/deploy/runtime_env.yaml only; this
revert restores Firestore read-lever values and does not change memory
promotion behavior)

Rollback: re-merge #23731.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Oct 26, 2026
…ay path; retry expired transactions under the bounded budget (#23738)

## Problem and fix

Since the 87083b7 roll (#23718), sync assignment strictly decoded
retained `open_loop_extractions` inside the transaction body — and paid
that decrypt/decompress again on every SDK same-chain replay. Longer
bodies plus the chronic contention storms pushed transaction chains past
Firestore's server-side transaction lifetime, so commits began returning
`InvalidArgument … transaction has expired`.

Diagnosis counts (ro-prod, counts only, 12:45–13:45Z window on
2026-10-26):

- Inner expiry restarts: **454/hour** vs ~1.75/hour on 10-25, in
episodic storms (181 in the single minute 12:51), starting ~8 min after
the ~12:43Z roll.
- 11 expired lines across **9 distinct sync jobs** in one hour ended
`partial_failure` via `sync_persistence_exception
firestore_error=expired_transaction`; 0 at finalize.
- Outer `sync_assignment` contention stayed at its chronic baseline (508
events/hour, 13 exhausted): contention is old, the expiry escape is new
in volume.

Fix:

1. **Structural — the decode is off the replay hot path.**
`assign_sync_conversation`'s decode no longer decodes retained
extractions; the encoded blob never enters the decoded row, so it can
never reach the logical write encoder (the #23718 invariant).
`encode_sync_assignment_plan` carries the stored blob and its compressed
marker verbatim when the row's protection level is unchanged (zero
decode calls, byte-identical write), and strictly decodes + re-protects
only when the plan's level differs from the stored row's; an unreadable
blob still aborts before any write there. Processing-persist
(`_reapply_current_manual_assignments`) and smart absorb already decode
only on a level change; both keep that shape. Shorter bodies and replays
are what stop chains outliving the server-side transaction lifetime.
2. **Equal-jitter backoff on the default-path expired restart.**
`run_transactional`'s default path now sleeps the same equal-jitter
delay as the `transient=True` path (at most 0.6 s across the two
restarts, no Firestore lock held during the sleep), so an inner restart
lands outside the spike that retired the previous id instead of inside
it.

**Dropped after review: classifying an expired transaction id as
contention at the outer boundary**
(`firestore_transaction_retry._is_transaction_contention`).
`run_sync_assignment` nests `run_transactional` (3 inner attempts)
inside `run_with_transaction_contention_retry` (5 outer attempts), so
the classification admitted up to 15 fresh transaction chains — each
allowed to run for Firestore's 270 s server-side transaction maximum,
far past the sync handler's 1,380 s budget, the 1,500 s dispatch
deadline, and the 1,800 s run-lock TTL; batch projection holds a 300 s
claim against the same nesting. A safe version needs one layer to own a
deadline-aware budget, which is a redesign, not a classification tweak.
It becomes a separate follow-up so this fix is not delayed by it;
`firestore_transaction_retry.py` and its tests are back at `main`
behaviour unchanged in this PR.

## Tests

- `test_sync_assignment_contention_retry.py`: new integrated replay
regression. The real `assign_sync_conversation` →
`assign_in_transaction` → encode path runs against an SDK-surface fake
whose first commit raises `Aborted` once, so the SDK replays the whole
production body on the same transaction id — `assign_in_transaction` is
not stubbed. Asserts one transaction chain, two body executions of the
stored-row read, **zero** `decode_open_loop_extractions` calls, and that
the committed write carries the stored blob and compressed marker
byte-identical — standard compressed and enhanced encrypted both
covered.
- `test_open_loops_assignment.py`: a same-level assignment on a row
carrying real encoded extractions makes zero decode calls across append
+ retry and writes the blob and marker back byte-identical; a level
change decodes the stored blob exactly once and re-protects it; an
unreadable blob aborts a re-protecting write before any transaction
write and is carried untouched at an unchanged level.
- `test_cap_publication_retry.py`: the default-path expired restart
sleeps equal-jitter delays and uses a fresh transaction per restart;
non-expiry errors still never sleep.
- #23718's tests are kept and extended: donor merge byte-identical at
the same level and logically equal after an upgrade, new-row
encode/absent/null controls, protection migration atomic round-trip,
reprocess preservation, and processor re-protection after a concurrent
migration.

## Verification

Hermetic tests only. No production reads, writes, API calls, or config
changes; the counts above are the read-only diagnosis already on record.
Selection through `bin/omi-heavy` at `nice -n 15`, per-file pytest
isolation, rebased on `origin/main` (de8c741):

- All `test_open_loops_*.py`, `test_sync_*.py`, `test_firestore_*.py`,
plus the changed files' suites
(`test_sync_assignment_contention_retry.py`,
`test_cap_publication_retry.py`,
`test_conversation_persistence_transaction_expiry.py`): 146 files, 4,571
passed, 3 skipped, 0 failed.
- `scripts/select_backend_unit_tests.py` requires the full backend unit
suite for `backend/database/_client.py` changes; CI runs that selection
on this PR. The locally run set above is the prescribed subset.
- `make preflight`: all checks pass with this PR body.

Failure-Class: FC-conversation-persistence-expired-transaction

## Product invariants affected

none

Rollback: revert
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Oct 26, 2026
…ay path; retry expired transactions under the bounded budget

Sync assignment decoded retained open_loop_extractions inside the
transaction body on every SDK same-chain replay since BasedHardware#23718; longer
bodies plus chronic contention pushed chains past Firestore's
server-side lifetime, escaping as expired_transaction (454 inner
restarts/hour vs ~1.75/hour on 10-25; ~9 jobs/hour ending
partial_failure).

- Assignment now carries the stored blob and its marker verbatim when
  the protection level is unchanged (zero decode calls, byte-identical
  write) and strictly decodes/re-protects only on a level change, which
  still aborts on unreadable input before any write.
- An expired transaction id is classified as contention at the outer
  boundary, so the bounded 5-attempt equal-jitter budget governs it
  instead of the error escaping after 3 inner restarts.
- run_transactional's default-path expired restart now backs off with
  the same equal-jitter delay as the transient path.

Failure-Class: FC-conversation-persistence-expired-transaction
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