Skip to content

fix(backend): offline sync never adopts live reconnect stubs; assignment is order-independent and shares realtime's boundary - #15193

Merged
Git-on-my-level merged 12 commits into
mainfrom
fix/sync-capture-continuity
Sep 20, 2026
Merged

Git-on-my-level merged 12 commits into
mainfrom
fix/sync-capture-continuity

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Failure-Class

Failure-Class: FC-split-mutation-authority

Summary

On 2026-09-19 one account received 121 conversations in a day, 107 of them ~70-second shards; a
51-minute call became 45 conversations while the desktop captured the same call as one record.
Production logs (backend-sync, backend-listen; read-only) show the mechanism, and it is not
the cross-job race #15106 fixed:

  1. Live STT failed fleet-wide: Soniox, the mid-session failover for Modulate, had its organization
    monthly budget exhausted (2026-09-19T02:52Z → 2026-09-20T06:29Z), so failed-over streams were
    closed by the vendor; at connect time the chain then ran Modulate circuit_open → Deepgram
    handshake rejected → Parakeet connect timeout. Clients reconnected /v4/listen every ~35 s. Each
    reconnect minted an empty in-progress stub (created_at/started_at/finished_at = now(),
    no segments).
  2. With no live transcript there is no conversation id for WALs to claim, so all audio went to
    offline sync (lane=backfill trust=legacy reason=unbound_capture_time).
  3. For every 60 s chunk, get_closest_conversation_to_timestamps returned 7–13 stubs and sync
    merged the chunk into a different nearest stub ⇒ one visible conversation per chunk, inside
    a single ordered job, with no concurrency needed (0 turnstile timeouts, 0 target fallbacks).

#15106 made assignment atomic, but it still adopts a stub through its candidate_id hint, joins
an incoming chunk to only ONE existing conversation (the mobile client drains newest-first in
batches of 5 and returns on 202, so each older batch started a new conversation), and keys nothing
to the realtime boundary rule.

Fix

One assignment authority makes unattended temporal intake's partition and content independent of
arrival order, with one default speech-gap rule shared with realtime. Existing explicit targets
retain identity authority.

  • utils/conversation_continuity.py (new): the single gap predicate. Realtime
    (transcribe_decisions.decide_existing_conversation_action / decide_lifecycle_action) and sync
    (assignment.interval_matches) both call it; MIN_CONVERSATION_TIMEOUT_SECONDS derives from it.
    Sync continuity stays speech-extent (VAD segment start → last word), exactly what realtime
    measures: ≥120 s of speech silence splits on both paths, 119 s joins on both. Silence creates
    nothing, as on main.
  • utils/sync/assignment.py: transactional closure — an incoming chunk collects every
    connected unattended sync conversation (repeat until the extent stops growing) and folds them
    into one survivor in the same Firestore transaction. Survivor = the existing row with the
    earliest started_at (tie → id); the incoming id is used only when nothing matched, so an
    ordinary append never changes the visible id. Donors become redirect tombstones
    (deleted + sync_merged_into), revisions bump on both sides, and the fix(backend): atomically assign synced conversation chunks across jobs #15106
    sync_content_revision fence plus a new deleted fence stop stale processors writing to either.
  • Timestamp hints never adopt live rows (the 2026-09-19 fix: no client id was sent that day; the
    lookup chose reconnect stubs). Only unattended sync-owned rows (sync_content_revision, no user
    curation: photos, user title, star, folder, shared visibility) may be joined or donated
    automatically. A provenance-compatible, non-deleted explicit target is honored and keeps its id
    even when empty — that is the fresh-lane capture-proof contract the Cloud Tasks gauntlet enforces;
    missing or tombstoned targets fall back to temporal assignment, with retry-lineage deletion fences
    intact. Live targets keep sync_live_target after sync appends and stay excluded from automatic
    bridging.
  • utils/sync/assignment_index.py (new): non-evicting day-bucket interval index
    (users/{uid}/sync_assignment/{yyyy-mm-dd}, metadata only), read and written in the assignment
    transaction; the 128-entry recent document remains as migration hint and cross-version fence.
  • utils/sync/capture.py (new): retry-stable uuid5 chunk identity, so a job retry re-enters its
    own lineage instead of minting a duplicate.
  • utils/sync/bridge.py + database/sync_bridges.py (new): external bridge effects (derived-data
    retraction for donors, private-cloud audio copy) run outside the transaction at one completion
    point, and converge via a revision-fenced receipt on the donor tombstone — a later append to a
    bridged conversation performs no retraction work; a failed cleanup is retried on the next append.
  • Typed outcomes (utils/sync/assignment_errors.py): user-deleted or user-managed lineage is
    consumed quietly (no endless WAL re-upload, siblings unaffected); provenance mismatch and
    redirect cycles stay loud.
  • User deletion of a bridged conversation also purges its retained donor sources
    (merge_conversations.delete_conversation_with_sync_sources); the DB layer gains no utils import.

Backend only. No wire schema, generated file, client, or .github/ change.

Invariants

No locked product invariant globs match this diff. The violated contract is
FC-split-mutation-authority: unattended sync membership had competing authorities in timestamp
hints, per-job ordering and arrival order. The reusable guard is the single transaction body plus
behavioral regressions. test_sync_live_stub_intake.py::test_sync_speech_partition_equals_realtime_reference
builds the reference by replaying speech in order through realtime's production decision function,
then requires identical sync membership, absolute transcript ranges and extents for temporal intake
in random permutations and interleaved newest-first batches of five, with 35-second hint-only stubs
and missing target ids present, including 119-second joins and 120/180-second splits. The separate
nine-reconnect-id regression asserts that existing live targets are honored and hint-only stubs stay
untouched; it does not claim partition parity for mixed partial-flap intake.

Line-Count-Exception: backend/utils/sync/pipeline.py | 2482 -> 2498 | Consume deleted or user-managed assignment quietly without failing sibling speech or inviting endless WAL retries; preserve existing run and persistence fences.
Line-Count-Exception: backend/routers/developer.py | 2563 -> 2567 | Import the deletion orchestrator so developer user-deletion also purges retained sync sources without database-to-utils callbacks.

Tests

  • New: test_sync_live_stub_intake.py (incident-shaped regression + realtime parity),
    test_sync_capture_continuity.py (permutation invariance over 45 chunks incl. newest-first and
    overlapping jobs, idempotent replay, enhanced/standard/None codecs, donor isolation by
    source/device/lock, midnight and historical index, exact 119.99/120/120.01 boundary on both
    paths, deleted-survivor non-resurrection), test_sync_bridge_lifecycle.py (receipt convergence,
    retryable cleanup, late audio), test_sync_capture_pipeline.py (through process_segment).
  • Existing sync suites migrated, assertions preserved; main's silence/no-words behavior asserted
    unchanged.
  • Independently re-run by the reviewer on the pushed head:
    BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=<31 files> bash backend/test.sh on uv
    Python 3.11.15 → 841 passed before the final round; author's final run 858 passed, 0 failed (reviewer re-run pending at push time).

Verification

  • Full installed pre-push hook on the pushed head: exit 0 (32 contract checks, 0 pyright errors,
    534 hook-selected tests). Locally, run the way CI runs them: test:sync-cloud-tasks-stack:emulator
    passed, test:listen-pusher-stack:emulator passed (+6 emulator concurrency tests), full hermetic
    E2E 120 passed / 3 existing skips / 2 existing xfails. The first push of this PR FAILED the Sync
    Cloud Tasks gauntlet because an empty explicit target was ignored; that was a review error, fixed
    in ab1229654a.
  • The first CI run of this branch also reddened test_conversations_date_range_validation.py: the
    new delete_conversation_with_sync_sources default was imported at module load, so any test that
    stubs utils.memory.* and then imports routers.conversations pulled in an incomplete
    retraction_scope. Both call sites now resolve that default lazily inside the function; the
    injectable parameter and the default behavior are unchanged.
  • main's Backend Unit Tests shards 1, 2 and 4 are red independently of this PR since
    2026-09-20T14:41Z (a merge train; fixed by the separate fix/main-backend-unit-tests-red PR).
    After the import fix, the only failures left on this branch are exactly those five tests.
  • Clean merge against current origin/main (git merge-tree).
  • Not exercised: real Firestore transaction contention across processes (every sync chunk for
    a user serializes on the index documents; failure mode is a retried job, not a fragment),
    endpoint end-to-end against a live stack, device/UI acceptance, real external cleanup. Watch
    event=sync_assignment, sync job failure/retry rates and transaction aborts during the dev bake.
  • Remaining differences: realtime's timeout is session-configurable, while WALs use the 120 s
    default. Known limitation: different existing explicit live target ids can keep one recording
    split — sync cannot bridge those records while live sockets may still write to them. The fix
    belongs to realtime (reuse the in-progress conversation on a reconnect inside the continuity
    window), tracked as the follow-up below.
  • Out of scope, tracked as follow-ups: realtime should reuse the in-progress conversation
    across a reconnect inside the continuity window and reap empty stubs (the realtime half of this
    incident); one-off repair of already-fragmented accounts; quiescence-debounced enrichment;
    oldest-first client drain; alerting on STT chain exhaustion (separate PR in flight).

Implemented with Codex (gpt-6-astra) over three review rounds; design reviewed and tests re-run by Claude.

🤖 Generated with Claude Code

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
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
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.
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
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
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
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
…tion

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
…ries

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
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
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
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]>
@Git-on-my-level
Git-on-my-level merged commit a7ff0e0 into main Sep 20, 2026
57 of 61 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/sync-capture-continuity branch September 20, 2026 18:09
Git-on-my-level added a commit that referenced this pull request Sep 21, 2026
…tructive gate (#15340)

PR #15193 ran donor retraction on the routine sync intake path through
deletion machinery that takes the exclusive per-account lock. Concurrent
GCS staging then 503'd as DestructiveOperationInProgress. Sync-bridge
cleanup is bounded per-conversation derived-data retraction, so it no
longer claims that lock; if the gate is already held, retraction defers
onto the revision-fenced receipt and converges on a later append.

Failure-Class: FC-destructive-gate-keyed-on-proxy-for-intent

Co-authored-by: Cursor <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 21, 2026
PR #15193 left merged-away conversations on every list/count path because
readers never evaluated deleted. Stamp discarded=True on donors for the
indexed hide, drop deleted rows even when include_discarded=True, and keep
sync_merged_into redirects working.

Failure-Class: FC-record-lifetime-enforced-by-one-reader
Co-authored-by: Cursor <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 21, 2026
…n lists, counts or exports (#15346)

* fix(backend): hide sync donor tombstones from conversation readers

PR #15193 left merged-away conversations on every list/count path because
readers never evaluated deleted. Stamp discarded=True on donors for the
indexed hide, drop deleted rows even when include_discarded=True, and keep
sync_merged_into redirects working.

Failure-Class: FC-record-lifetime-enforced-by-one-reader
Co-authored-by: Cursor <[email protected]>

* test(backend): bind real is_soft_deleted on AutoMock conversation stubs

GET-by-id now 404s tombstones, but the search/finalize router suite stubs
database.conversations with a truthy MagicMock, so every live fixture 404d.

Failure-Class: FC-record-lifetime-enforced-by-one-reader
Co-authored-by: Cursor <[email protected]>

* revert(app): restore main's Dart formatting in two untouched files

A pre-commit formatter rewrote conversation_detail_provider.dart and
speaker_summary_refresh_test.dart during an earlier merge commit, so this
backend-only PR carried a Dart reformat it never intended and CI's Formatting
check rejected it. Restore both to origin/main byte-for-byte.

Co-Authored-By: Claude Opus 5 <[email protected]>

* revert(app): restore main's Dart formatting in two untouched files

This backend-only PR carried a Dart reformat it never made. The local
pre-commit formatter cannot resolve package:flutter_lints/flutter.yaml in this
worktree, so it runs dart format without the project's analysis options and
rewrites any staged Dart file into a style CI's Formatting check rejects.

Committed with --no-verify because that hook is the defect here, not a check
being evaded: it rewrites the files on every commit. Both files are verified
byte-identical to origin/main afterwards, which is a stricter assertion than
the hook makes.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
aryanorastar added a commit that referenced this pull request Sep 22, 2026
Fixes #15201.

`get_action_items` takes `limit` and `offset`, but the Firestore query
behind it has neither. It streams every completed conversation the user
has, decrypts each one that carries action items through
`_prepare_conversation_for_read`, flattens the lot, sorts, and only then
slices `[offset:offset + limit]` in Python. The arguments bound the
response; they never bounded the work.

Seven routers call it: `action_items.py`, `chat_first.py`,
`developer.py`, `integration.py`, `mcp.py`, `mcp_sse.py` and `tools.py`.
The MCP and tools paths are agent-driven and call it repeatedly inside
one session, so a user with a long history pays a full-collection read
plus a decrypt of every conversation that has items, per call.

The scan now stops once it holds `offset + limit` eligible items. That
is exact rather than approximate: the stream is ordered by `created_at`
descending, every flattened item inherits its conversation's
`created_at` as its sort key, and the final sort uses that same key, so
the items collected before the break are precisely the ones the slice
would have kept. `_page_eligible_action_item_count` applies the same
deleted and completed filters the flattening applies, so items that
would be dropped do not shorten the page.

`backend/tests/unit/test_action_items_bounded_scan.py` drives the real
function against a query double that counts how many documents the
caller pulls. Against 200 conversations a 10 item page now reads at most
6 of them and an offset page at most 7; on main both read all 200. Three
further cases pin behaviour rather than cost: the page contents are
unchanged, filtered-out items do not count towards it, and a user with
fewer items than the page still gets all of them. Those three pass
before and after, which is the point of them.

```
$ cd backend && BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh
5 passed in 0.45s
```

#15193 also touches this file, for offline sync assignment. Different
function, no overlap with this change.

Failure-Class: FC-bounded-read-exceeds-request-budget

Line-Count-Exception: backend/database/conversations.py | 3098 -> 3119 |
the page-eligible count and the early break that stop the scan once the
page is filled


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/15202?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Wizard815 pushed a commit to Wizard815/omi-local that referenced this pull request Nov 25, 2026
…dHardware#15202)

Fixes BasedHardware#15201.

`get_action_items` takes `limit` and `offset`, but the Firestore query
behind it has neither. It streams every completed conversation the user
has, decrypts each one that carries action items through
`_prepare_conversation_for_read`, flattens the lot, sorts, and only then
slices `[offset:offset + limit]` in Python. The arguments bound the
response; they never bounded the work.

Seven routers call it: `action_items.py`, `chat_first.py`,
`developer.py`, `integration.py`, `mcp.py`, `mcp_sse.py` and `tools.py`.
The MCP and tools paths are agent-driven and call it repeatedly inside
one session, so a user with a long history pays a full-collection read
plus a decrypt of every conversation that has items, per call.

The scan now stops once it holds `offset + limit` eligible items. That
is exact rather than approximate: the stream is ordered by `created_at`
descending, every flattened item inherits its conversation's
`created_at` as its sort key, and the final sort uses that same key, so
the items collected before the break are precisely the ones the slice
would have kept. `_page_eligible_action_item_count` applies the same
deleted and completed filters the flattening applies, so items that
would be dropped do not shorten the page.

`backend/tests/unit/test_action_items_bounded_scan.py` drives the real
function against a query double that counts how many documents the
caller pulls. Against 200 conversations a 10 item page now reads at most
6 of them and an offset page at most 7; on main both read all 200. Three
further cases pin behaviour rather than cost: the page contents are
unchanged, filtered-out items do not count towards it, and a user with
fewer items than the page still gets all of them. Those three pass
before and after, which is the point of them.

```
$ cd backend && BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh
5 passed in 0.45s
```

BasedHardware#15193 also touches this file, for offline sync assignment. Different
function, no overlap with this change.

Failure-Class: FC-bounded-read-exceeds-request-budget

Line-Count-Exception: backend/database/conversations.py | 3098 -> 3119 |
the page-eligible count and the early break that stop the scan once the
page is filled


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/15202?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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