Repository navigation
fix(backend): atomically assign synced conversation chunks across jobs - #15106
Merged
Git-on-my-level merged 5 commits intoSep 20, 2026
Merged
Git-on-my-level merged 5 commits into
Git-on-my-level merged 5 commits into
Conversation
Continuous offline recordings fragmented into one micro-conversation per ~60s WAL chunk: separate /v1/sync-local-files jobs raced the +/-2min closest-conversation lookup, so every chunk created its own conversation (BasedHardware#6551/BasedHardware#5747 class, observed live: 34 conversations in 72 minutes from one 70-minute session). Nothing gated third-party audio either: the only filter was the speaker-blind discard prompt that auto-keeps >100 words. - utils/sync/assignment.py: assign_in_transaction reads AND writes a per-user recent-interval index inside the Firestore transaction on every intake (including the empty-index case), so concurrent jobs cannot both commit an absent target; conflict/retry supplies cross-process serialization, no expiring lease. Legacy lookups are hints reread in the transaction; deleted candidates cannot absorb content; reverse-order arrivals rebase; sync-owned chunks dedupe by absolute range. - database.assign_sync_conversation + lifecycle.ingest_sync_conversation: single intake seam; encrypted transcript codecs preserved; every assignment bumps sync_content_revision. - sync_content_revision fences stale processors: a processor that read before an append cannot replace the newer transcript or publish a stale summary; fenced refresh updates the search projection instead of deleting the row. - sync_relevance=review demotes only <=12 filler tokens AND <=15s speech: visible, original transcript, deterministic title, no auto-summarization; later meaningful content promotes the merged recording. Speaker labels and is_user are intentionally never consulted; failure modes are keep-or-visibly-demote, never silent discard. - process_segment create/merge branches collapse into the intake; the per-job turnstile is an ordering optimization only. Adjacent fix: segment end timestamp uses max(segment.end) instead of assuming order. Design and limits: backend/utils/sync/ARCHITECTURE.md. Regression coverage: backend/tests/unit/test_sync_cross_job_assignment.py (two-job stale-lookup convergence, 70-chunk single-recording, promotion, adapter round-trip, fencing). Verification: BACKEND_UNIT_TEST_FILE_LIST over the seven affected files through backend/test.sh: 312 passed / 0 failed (exit 0). Failure-Class: FC-split-mutation-authority
Mechanical migration of the three suites that stubbed the old create/merge call sites, preserving every behavioral assertion: - test_sync_silent_failure.py: TestProcessSegmentReal stubs completed for the new pipeline import chain (real pure modules merge_dedupe/ assignment/deterministic_minimum against a minimal real-pydantic Structured; lifecycle stubbed at the local-import seam); behavioral tests moved their patches/asserts to utils.conversations.lifecycle.ingest_sync_conversation; the two static source checks re-pointed to the modules that now own the behavior (lock sections, dedupe/survivor contracts) without dropping coverage. - test_sync_transcription_prefs.py: language / private-cloud / speaker-id-exception assertions migrated to the intake incoming dict; vocabulary/keyword assertions already at the prerecorded seam unchanged. - test_sync_v2.py: both stub loaders completed so routers/sync.py execs (the 43+4 failures were downstream of the pipeline import); merged reprocess assertions strengthened for the new is_new kwarg. No production files touched. Counts match clean-main baselines (45+66+169), so no coverage was lost.
The hermetic sync lifecycle suite faked the retired create seam
(process_conversation with a pinned id). Migrate the fake to
ingest_sync_conversation with production contract shape:
- id derives from target_id (merge) or the deterministic created id
- returns (conversation, created, survivors); sync_relevance=keep +
sync_content_revision=1 so batch-end enrichment engages
- reprocess fake accepts the new is_new kwarg
- created keep rows are enriched at batch-end: the create test now
asserts the enrichment output (title "...Reprocessed") instead of the
intake minimum, and expects the once-per-row reprocess pass
- the intake fake merges existing + incoming segments so the target
merge test sees both transcripts
Verification: the two tests that failed in CI now pass locally via the
hermetic runner (pytest testing/e2e/test_sync_lifecycle.py -k test_sync_v2:
2 passed). The 10 non-sync failures under the local layered venv
("Service temporarily unavailable" in memory/retrieval/bootstrap paths)
pass in CI and are environment gaps, not production behavior.
Created sync rows are persisted by the intake itself, so batch-end enrichment must run through the update path (persist_processed_ conversation), never the idempotent-create path — re-creating would be fenced and strand the row without its summary. Drop the is_new special-case from _reprocess_conversation_after_update; every merged or created keep row enriches through the same fenced update path. Task-mode workers whose every conversation was superseded by a newer ingest must not publish an empty success: when all batch-end enrichments are fenced and nothing durable remains in the result, re-raise so the Cloud Tasks lane terminally ACKs the delivery as superseded (never retried), preserving main's fence-ACK contract. The v1 inline lane keeps the absorb behavior. Harness processors (sync_cloud_tasks_stack, replay_harness_phase0a) preserve the ingest-owned sync_content_revision in their completed payloads, matching the real processor contract the fence enforces; the sync e2e fake ingests through the new seam and asserts enrichment output. Verification: Cloud Tasks gauntlet exit 0 (all scenarios, local Firestore emulator); replay harness GREEN/BOUNDED; 282 unit assertions across the seven suites; sync e2e 2 passed.
…r re-exec Two CI failures on 081301b, both test-surface, zero production code: 1. test_sync_cloud_tasks hand-rolled isolation stubs utils.conversations as a MagicMock parent, but utils/conversations is a namespace package on disk (no __init__.py). The pipeline's new module-level utils.conversations.deterministic_minimum import therefore died with "'utils.conversations' is not a package" during the routers/sync.py file-path re-exec. Fix: give the stub parent the real directory __path__ and register the new submodule stub, matching the existing pattern for utils.sync / utils.stt / utils.observability. 2. The repo trust-boundary tripwire requires every new Conversation field to be classified. sync_relevance and sync_content_revision are server-authored intake metadata (fence revision + deterministic keep/review decision) that carry no client-authored text, so the integration redactor must NOT strip them — same non-projection-family precedent as processing_state. Pin both. Failure-Class: FC-split-mutation-authority
Git-on-my-level
added a commit
that referenced
this pull request
Sep 20, 2026
…ent is order-independent and shares realtime's boundary (#15193) * fix(backend): share the conversation continuity boundary Realtime lifecycle decisions and sync interval coverage use the same gap predicate, including the exact 120-second boundary. Realtime retains its configured timeout and speech-silence input. Validation: BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-policy-tests.txt bash backend/test.sh — 26 passed. Pure policy regression exercises both decision and interval paths. Hermetic only; no live service acceptance. Failure-Class: FC-split-mutation-authority * fix(backend): converge late sync chunks by capture continuity Compute connected components transactionally, retain non-evicting day metadata, and use deterministic chunk anchors with bridge redirects. Keep quiet decoded capture coverage through VAD and both upload routes; preserve explicit capture identity when a server target is missing. Keep enhanced storage the default. Replay bridge effects through the existing merge/delete helpers, retain source audio for late workers, and cascade it on capture deletion. Reject deleted lineage and stale processor revisions. Shared, photo-bearing, live and user-curated rows are not automatic donors. Device/lock/capture partitions are not speaker-gated. Regression source: the measured 2026-09-19 45-WAL call; #15106 serialized intake but could not bridge fragments. Empty-STT tests now assert durable quiet coverage while retaining their no-error/no-billing checks. No wire schema changed. Verification (Python 3.11.15, uv and pylock.macos.toml; hermetic service leaves): BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-final-tests.txt bash backend/test.sh 748 passed, 0 failed, 10 deselected by the normal runner markers. BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-last-tests.txt bash backend/test.sh 59 passed after the final deterministic created_at guard (capture continuity, bridge lifecycle, capture pipeline, cross-job assignment files). PATH="$PWD/backend/.venv/bin:$PATH" OMI_PR_BODY_FILE=/tmp/omi-sync-pr-body.md make preflight 32 local checks passed; exact line-count declarations included in that draft. scripts/backend-python-format --write ran on all touched Python files. No Omi service or emulator was contacted. Live device/UI acceptance and real Firestore contention remain unverified. Realtime still measures speech silence and configured timeouts; sync measures decoded capture coverage. No historical backfill, client change, quiescence debounce or independent cleanup scheduler. DESIGN.md intentionally remains uncommitted. No push or PR is authorized. Line-Count-Exception: backend/database/conversations.py | 2530 -> 2533 | Preserve bridge ancestor deletion and tombstone processing fence in the existing persistence owner. Line-Count-Exception: backend/routers/sync.py | 2101 -> 2104 | Forward decoded capture coverage through the already-shipped v1 upload route. Line-Count-Exception: backend/utils/sync/pipeline.py | 2482 -> 2487 | Carry decoded capture coverage without removing run-lease or result fences. Failure-Class: FC-split-mutation-authority Selected test files (contents of /tmp/omi-sync-final-tests.txt): tests/unit/test_sync_cross_job_assignment.py tests/unit/test_transcribe_decisions.py tests/unit/test_sync_geolocation_enrichment.py tests/unit/test_conversation_discard_revival.py tests/unit/test_sync_capture_continuity.py tests/unit/test_sync_bridge_lifecycle.py tests/unit/test_sync_capture_pipeline.py tests/unit/test_sync_ordered_assignment.py tests/unit/test_sync_merge_target_selection.py tests/unit/test_sync_silent_failure.py tests/unit/test_sync_opus_decode.py tests/unit/test_sync_v2.py tests/unit/test_conversation_sync_mutations.py tests/unit/test_conversation_lifecycle_contract.py tests/unit/test_sync_record_usage.py tests/unit/test_sync_transcription_prefs.py tests/unit/test_sync_cloud_tasks.py tests/unit/test_sync_ledger_fence_cutover.py tests/unit/test_merge_conversations_canonical_delete.py tests/unit/test_merge_skips_retraction_without_canonical_memories.py tests/unit/test_merge_deleted_source_race.py tests/unit/test_merge_audio_chunk_copy_failure.py tests/unit/test_delete_conversation_cascade.py tests/unit/test_delete_conversation_cascade_retraction_fence.py tests/unit/test_delete_conversation_cancels_task_reminders.py tests/unit/test_sync_fair_use_gate.py tests/unit/test_sync_two_lane.py tests/unit/test_merge_validation.py * test(backend): cover interleaved newest-first sync jobs Model two overlapping HTTP-202 jobs draining newest-first batches of five while each worker preserves its own oldest-first assignment order. Retain arbitrary permutations and repeated ingestion checks. Validation: BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-permutation-tests.txt bash backend/test.sh — 34 passed, 0 failed. This models successful serial commit schedules; no Firestore service or emulator was contacted. * fix(backend): preserve sync identity when late chunks append Choose an existing matched component by capture start and ID; incoming IDs only create a record when nothing matches. Keep redirects for real bridges. Migrate permutation assertions to partitions and absolute transcript ranges, and exercise a real second bridge during concurrent cleanup. Validation: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-last-tests.txt bash backend/test.sh (59 passed). Failure-Class: FC-split-mutation-authority * fix(backend): exclude live reconnect stubs from sync capture identity Treat missing and empty explicit targets as ordinary temporal sync intake. Client capture IDs no longer partition membership. Preserve real live targets, codec decoding, protected retry anchors and deleted redirect lineage. Replay the September 19 production mechanism: nearest empty live stubs every 35 seconds across 45 sparse-speech WALs, plus nine changing reconnect IDs. Assert unchanged stubs and matching partitions/content over 12 schedules. Update product, architecture and pipeline docs with the corrected mechanism and the separate realtime reconnect reuse/stub reaping follow-up. Validation: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-r1-final-tests.txt bash backend/test.sh (783 passed, 10 deselected, 0 failed; 29 files). Formatting: scripts/backend-python-format --write on all four changed Python files. Failure-Class: FC-split-mutation-authority * fix(backend): restore realtime speech-gap parity for offline sync Remove decoded capture windows and quiet conversation persistence. Restore main's VAD origin, last-word end and no-words expected-silence behavior. Keep deterministic segment identity, closure, stable IDs and stub exclusion. The headline regression replays speech in order through realtime's decision and compares sync partitions, absolute ranges and extents across random and interleaved newest-first schedules with live-flap stubs and reconnect IDs. 119-second gaps join; 120/180-second gaps split. The supplied incident logs supersede the earlier capture-coverage assumption and justify these assertions. Validation: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-r1-final-tests.txt bash backend/test.sh (809 passed, 10 deselected, 0 failed). Failure-Class: FC-split-mutation-authority * fix(backend): checkpoint sync bridge cleanup once per donor revision Run completion only after process_segment audio persistence. Remove external cleanup from lifecycle intake. Persist a revision-fenced receipt on donor tombstones and skip completed retraction on later appends; track copy target separately so later bridges and late donor audio still copy without retraction. Validation: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-r1-focused-tests.txt bash backend/test.sh (125 passed, 0 failed; corrected the new pipeline test's mocked import after an initial 124 passed/1 failed run). Failure-Class: FC-split-mutation-authority * fix(backend): keep retained-source deletion in conversation orchestration Restore database hard delete to a storage-only operation without an extra snapshot read or utils callback. Purge retained sync sources in the existing merge/delete helper used by user deletion and the developer delete endpoint. Keep new-target rollback and stale processing-claim cleanup storage-only. Add the required database package map for its new bridge receipt adapter. Validation: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-r2-final-tests.txt bash backend/test.sh (841 passed, 5 deselected, 0 failed; 31 files). Failure-Class: FC-split-mutation-authority * fix(backend): consume superseded sync intake without inviting WAL retries Use typed assignment outcomes for deleted/protected lineage versus corrupt redirects or provenance mismatches. Quietly consume superseded segments so siblings continue and the coordinator commits ledger completion before the client sees completed, without usage or failure status for deleted audio. Keep conflicts and cleanup failures loud and retryable. Clear an old audio copy receipt before late copying so failure remains pending without a worker hint. Update legacy import stubs for the module-level bridge dependency. Validation: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-r2-final-tests.txt bash backend/test.sh (841 passed, 5 deselected, 0 failed; 31 files). Earlier broad run had 699 passed, 89 failures and 18 import/setup errors from stale test stubs; fixed without bypasses. Intermediate corrected run: 840 passed before the additional late-copy retry regression. Correction: the earlier speech-parity commit recorded 10 deselections by counting both collection and summary output; the actual runner summary was 5 deselected (809 passed). Failure-Class: FC-split-mutation-authority * fix(backend): type sync assignment and expose bridge operations Annotate Firestore references, redirect IDs, retry identity and bridge completion payloads. Expose narrow public operations for retained-source retraction and strict audio copying; keep shared merge internals private and exercise the public seams in behavioral tests. Validation: BACKEND_PYTEST_WORKERS=1 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-r2-final-tests.txt bash backend/test.sh: 841 passed, 0 failed, 0 errors, 5 deselected across 31 files; CPU-duration guard passed. The initial four-worker run passed assertions but exceeded one duration limit (0.32s > 0.30s); no guard or threshold changed. scripts/backend-python-format --write: all six touched Python files unchanged. Failure-Class: FC-split-mutation-authority * fix(backend): honor explicit sync targets before live transcription Restore the fresh-admission capture contract exposed by PR #15193's Sync Cloud Tasks Stack Gauntlet: compatible non-deleted explicit targets keep their ID even when empty. Missing or tombstoned targets use temporal intake; independent retry-lineage deletion fences remain. Legacy timestamp hints never adopt live rows, and sync_live_target prevents later automatic bridging. Migrate the reconnect regressions to distinguish honored existing IDs from missing IDs; scope temporal parity honestly and document the realtime reconnect-reuse limitation. Extend hermetic lifecycle E2E coverage to an empty target with its own recording timestamp. Validation: BACKEND_PYTEST_WORKERS=1 BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-sync-r2-final-tests.txt bash backend/test.sh: 858 passed, 5 deselected across 31 files, duration guard intact. npm run test:sync-cloud-tasks-stack:emulator -- --state-dir /tmp/omi-sync-r4-stack: passed. E2E_PYTEST_TIMEOUT=120s bash backend/testing/e2e/run.sh -q --tb=short: 120 passed, 3 existing skips, 2 existing xfails. Same runner with -k test_sync_v2: 4 passed. Formatter and diff check passed. No Omi service calls. Failure-Class: FC-split-mutation-authority * fix(backend): keep merge deletion off the frame-evidence import graph Resolve delete_conversation_with_sync_sources lazily so stubbed-import tests that load routers.conversations do not need a complete utils.memory.retraction_scope. Failure-Class: none Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-authored-by: Cursor <[email protected]> --------- Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Cursor <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Failure-Class
Failure-Class: FC-split-mutation-authority
Summary
Continuous offline recordings fragmented into one micro-conversation per ~60s
WAL chunk (incident class #6551/#5747, observed live: 34 conversations in
72 minutes, median 9.5s speech each, from a single 70-minute YouTube session
near the wearable), and nothing filtered non-user audio from the timeline.
Two defects, one root boundary:
_OrderedTurnstileserialized segments only within one job; separate/v1/sync-local-filesjobs ran un-ordered, so each chunk'sget_closest_conversation_to_timestampslookup (+/-2min window) missedbefore the previous chunk persisted, and every chunk created its own
conversation.
discard prompt (auto-keeps >100 words), so third-party narration was
transcribed, kept, and summarized per fragment.
Fix
utils/sync/assignment.py(new): production transaction bodyassign_in_transaction— a per-user recent-interval index document is readAND written inside the Firestore transaction on every intake, including the
empty-index case, so concurrent jobs cannot both commit an absent target.
Firestore transaction conflict/retry semantics supply cross-process
serialization; no expiring lease. Legacy closest-conversation lookups are
hints, reread inside the transaction; deleted candidates cannot absorb
content; reverse-order arrivals rebase; sync-owned chunks dedupe by absolute
range.
database/conversations.py::assign_sync_conversation+utils/conversations/lifecycle.py::ingest_sync_conversation: single intakeseam for pipeline create/merge; encrypted-transcript decode/encode
preserved; every assignment bumps
sync_content_revision.sync_content_revisionfencing: a processor that read before another syncappend cannot replace the newer transcript or publish its stale summary;
the fenced refresh updates the search projection instead of deleting the row.
sync_relevance=review: only<=12 filler tokens AND <=15s of speech is demoted (visible, deterministic
title, original transcript, no automatic summarization); any later
meaningful content promotes the merged recording over the full transcript.
is_user/speaker profiles are intentionally never consulted (unreliable perproduct owner); every failure mode is keep-or-visibly-demote, never silent
discard.
process_segmentcreate/merge branches collapse into the intake; theper-job turnstile remains an ordering optimization only. Adjacent bug fixed:
segment end timestamp now uses
max(segment.end)instead of assumingsorted order.
docs/api-reference/app-client-openapi.jsonregenerated withbackend/scripts/export_openapi.py --surface app-client --writefor thetwo additive response fields.
Design/limits:
backend/utils/sync/ARCHITECTURE.md; policy note inPRODUCT.md(Proposed offline fragment policy); guide entry inbackend/AGENTS.md.Invariants
No locked product invariant globs match this diff (diff-scoped
scripts/pr-preflight --suggest). Failure classFC-split-mutation-authorityis the violated contract: conversationassignment had two authorities (per-job lookup-then-create racing across
processes). The reusable guard surface is the single atomic transaction
body (
utils/sync/assignment.py::assign_in_transaction) plus thebehavioral regression tests that execute it
(
test_sync_cross_job_assignment.py), including the two-jobstale-lookup convergence case that reproduces #6551/#5747 through the
production seam.
Line-Count-Exception: backend/database/conversations.py | 2476 -> 2530 | assign_sync_conversation belongs beside the conversation persistence seam it transactionally guards; diff is net-negative repo-wide as the pipeline's scattered create/merge branches collapse into the intake.
Tests
backend/tests/unit/test_sync_cross_job_assignment.py(19 tests):barrier-synchronized two-job stale-lookup convergence through the real
transaction body; 70 consecutive narration chunks -> exactly one
conversation; reverse-order retry; deleted-target replacement; device/gap
isolation; filler demotion + promotion parametrized over
is_user/speaker_idin {False, True, None}; ambiguous-content fail-open table;real
process_segmentwith two independent job responses; Firestoreadapter encode/decode round-trip (standard + enhanced); stale-processor
fencing.
test_sync_silent_failure.py,test_sync_transcription_prefs.py,test_sync_v2.pymigrated to the intakeseam (assertions preserved, re-pointed; no coverage deleted).
BACKEND_UNIT_TEST_FILE_LIST=... bash backend/test.shcountsrecorded before opening; no bare pytest.
Verification
64e779ea529(68 checks, including the desktop Swift compile on Xcode 27 and the
migrated hermetic E2E; log: "Bounded pre-push gate passed; CI remains the
full test authority"). The long-lived
git pushtransport on this machinerepeatedly died (SIGPIPE) during the ~20-minute gate, so the verified-gate
run and the branch transfer were separated and the push used
--no-verify— no failing check was bypassed. Upstream CI is the full test authority.
scripts/failure-class validate --pr-body-file …→ OK(
FC-split-mutation-authority).PYTHON=/tmp/omi-test-venv/bin/python BACKEND_UNIT_TEST_FILE_LIST=… bash backend/test.sh, re-based on currentorigin/main094514cb94):280 assertions passed / 0 failed / 0 errors, exit 0. Counts match
clean-main baselines (169+66+45+…), so no coverage was lost. Note: test
interpreter is pyenv 3.12.1 + anthropic/langchain-anthropic layered venv —
no canonical 3.11 backend venv exists on this machine; CI's pinned 3.11
remains the authority.
stashed under the identical environment, so every migrated failure was
seam-migration, not a latent defect.
scripts/backend-python-format --writeon all changed Pythonfiles;
git diff --checkclean.make preflightresult recorded in the PR comment before opening.contention with two real processes, endpoint end-to-end, and
enrichment-side-effect checks. Cross-process correctness is inferred
from Firestore transaction semantics plus the serialized-commit test.