Skip to content

fix(backend): stop the action-item scan once the page is filled - #15202

Merged
aryanorastar merged 1 commit into
BasedHardware:mainfrom
singhharsh1708:fix/backend-action-items-bounded-scan
Sep 22, 2026
Merged

aryanorastar merged 1 commit into
BasedHardware:mainfrom
singhharsh1708:fix/backend-action-items-bounded-scan

Conversation

@singhharsh1708

@singhharsh1708 singhharsh1708 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified both changed files at the current head.

backend/database/conversations.py — The early break is exact, not heuristic, and I traced why: the stream is ordered created_at DESC, every flattened item inherits its conversation's created_at, and the final sort uses that same key, so the prefix collected before the break is precisely the slice the old full scan returned. _page_eligible_action_item_count mirrors the flattening's deleted/completed filters (and keeps non-dict items, as the flattening does), so filtered items don't shorten the page. The needed > 0 guard also preserves the limit<=0 behavior of the old code. Nice fix — fewer conversations decrypted per request is a real cost and privacy win on a path the MCP/tools routers hit repeatedly.

backend/tests/unit/test_action_items_bounded_scan.py — Good isolation: the query double counts documents pulled and the monkeypatch auto-reverts; the three behaviour-pinning cases (page contents unchanged, filtered items excluded, short-history users get everything) are the right guard against an over-eager break. All 5 tests passed in CI (shard 3).

Heads-up so you don't chase it: the red Backend unit suite is pre-existing base breakage — the same enable_app_endpoint TypeError (test_setup_completed_url_uid_query.py, test_app_enable_install_count.py) and test_app_client_schema_inventory.py assertion fail identically on the base commit's own run. Nothing in this diff touches those areas.

🤖 Automated review on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 20, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fixes #15201: get_action_items scanned every completed conversation in Firestore regardless of limit/offset, decrypting all of them; costly for MCP/tools paths called repeatedly per session. Now stops the scan once offset+limit eligible items are collected, exact (not approximate) given the created_at-ordered stream. New bounded-scan tests plus 3 pinning tests pass. Approving only, not merging: Backend unit shard 1/4, 2/4, 3/4 and the suite check are currently failing on this PR's CI.

@aryanorastar

Copy link
Copy Markdown
Collaborator

get_action_items on main still streams every matching conversation. This head stops once the page is filled, and the tests pin that bound. Backend unit shards are red on 6fa1b3fbf760, so this stays open and unapproved.

— Astar, on behalf of @aryanorastar

The conversations query had no limit, so every call streamed and decrypted the user's whole completed history before slicing to the requested page. The stream order and the sort key are the same created_at, so stopping at offset+limit eligible items returns the identical page for bounded work.
@singhharsh1708
singhharsh1708 force-pushed the fix/backend-action-items-bounded-scan branch from 6fa1b3f to 9f50733 Compare September 22, 2026 15:04
@aryanorastar
aryanorastar merged commit d13136b into BasedHardware:main Sep 22, 2026
43 checks passed
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. -->
Wizard815 pushed a commit to Wizard815/omi-local that referenced this pull request Nov 25, 2026
Brings the fork from the 2026-09-14 merge base (6075928) to upstream
8a1de0d (2026-10-21). 122 conflicts. Upstream's code is the baseline; the
fork's self-hosting changes are re-applied on top, ported into upstream's new
structure where it moved code. Fork commits that were cherry-picks of
upstream PRs (BasedHardware#15202, BasedHardware#15289, BasedHardware#15304, BasedHardware#15317, BasedHardware#15462, BasedHardware#15649) take upstream's
newer version.

Resolution decisions
- Chat: upstream moved the send-message turn into utils/chat_turn.py. That
  call now forwards model_shortcut, so the sticky /adult toggle still works.
  graph.execute_chat_stream keeps the shortcut-routing wrapper around
  upstream's body. upstream already has the async quota release.
- Local LLM: upstream routes every managed get_llm() through the Omi LLM
  gateway (OMI_LLM_GATEWAY_FEATURE_MODE no longer opts out). In local mode
  (is_local_mode()) clients.py now keeps generation on the direct client at
  OPENAI_BASE_URL. model_config keeps the fork's Redis/env model resolution,
  the per-turn shortcut override and local_base_chat_model.
- Conversation notes: upstream serves them only through the shaped notes
  agent and fails closed unless OMI_SHAPED_AGENT_MODE is on, so
  omi-host/entrypoint.sh now exports OMI_SHAPED_AGENT_MODE=on (default).
- Auth: upstream added POST /v1/auth/local-dev/custom-token, gated only on
  FIREBASE_AUTH_EMULATOR_HOST. omi-host always sets that (the emulator is its
  real auth store), so the route would mint a token for any uid.
  OMI_DISABLE_LOCAL_DEV_TOKEN_ROUTE (set by the entrypoint) switches it off.
  The fork's /v1/auth/local-login and remote-login sessions are kept.
- Time zone: upstream added the same PUT /v1/users/time-zone. Keep upstream's
  handler and database.notifications.set_user_time_zone, and drop the fork's
  duplicate setter (it shadowed upstream's) and SaveTimeZoneRequest. The
  app calls upstream's syncUserTimeZoneServer.
- Folders: upstream has no hierarchy, so the fork's folder tree is kept.
  folder_tabs.dart was deleted upstream (folder browsing moved into global
  search), so the subfolder bar, breadcrumb and tree entry were ported into
  global_search.dart and folder_options_sheet.dart.
- Static map: rebuilt on upstream's themed renderer. The no-key
  OpenStreetMap fallback dispatches to _render_osm_png.
- TTS: upstream's provider switch, plus the fork's local Piper path
  (TTS_LOCAL_BASE_URL).
- Subscription/billing: the PROVIDER_MODE=offline early return sits ahead of
  upstream's new funded-compute and budget gates.
- belief_model.py: deleted upstream (BasedHardware#22209) with nothing left importing it,
  so it stays deleted, as do its fork-only tests.
- Vector DB: the fork's LOCAL_VECTOR_DB=chroma path is kept on top of
  upstream's upsert_vector2 metrics and legal-hold gates.
- App:
  - The "/" popup, the sticky shortcut chip and modelShortcut are ported
    onto upstream's composer.
  - The day-review banner stays on Home.
  - The day-review list moves into the Daily Recaps app bar (its Home header
    button went away upstream).
  - LED dim on mute is re-applied after upstream's dispatch-based
    pause/resume.
- Session snapshots: AuthService snapshots recognize a valid remote-login
  session. Upstream's snapshots read it as signed out, which silently
  disabled data export, on-demand recaps and onboarding sync.
- SaaS removals stay removed: referral page and its Settings destination,
  Creator Payouts destination, Crashlytics, the FCM token, and the Google
  sign-in button.
- route_policy_manifest.yaml: upstream's entries plus the fork's 25 routes.
- Generated files:
  - regenerated from the merged sources: app-client OpenAPI spec and its
    Dart/Swift/TS types, flutter gen-l10n;
  - regenerated from requirements.txt by update-python-lock.sh: all
    pylocks, which also restores the e2e packages main's pylock had lost.

Verification (details in the PR):
- flutter analyze: 0 errors; app/scripts/analyze_ratchet.sh passes.
- Backend suites for every touched area pass, among them
  test_local_model_routing (including the new gateway-bypass tests),
  test_chat_model_shortcuts through upstream's run_chat_turn,
  test_nested_folders, test_local_scheduler, test_local_dev_auth plus the
  new self-host opt-out test, test_static_map, and the
  LLM/retrieval/vector suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148HLrpWR8Mimn43rkNvGKg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bounty proposal] fix(backend): get_action_items reads every conversation a user has, whatever the limit ($100 proposed)

4 participants