Repository navigation
perf: reduce Firestore read amplification - #9891
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1b624a4a10
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| _migrateCategoryOrderFromPrefs(); | ||
| /// Shares the eager Home preload with the Tasks page's first visible load. | ||
| Future<void> ensureLoaded({bool showShimmer = false}) { | ||
| if (_initialLoadCompleted) return Future.value(); |
There was a problem hiding this comment.
Reset the initial-load gate when clearing tasks
When logout/user-switch calls clearAllUserState() it invokes ActionItemsProvider.clearUserData() but this new _initialLoadCompleted flag remains true after the previous account's successful preload. The next account then opens the Tasks page with actionItems empty, ensureLoaded() returns immediately here, and no initial request is made until some unrelated manual refresh/foreground sync happens, leaving the new user's tasks blank. Reset _initialLoadCompleted (and any in-flight _initialLoad) as part of clearUserData() so a cleared provider can load for the next session.
Useful? React with 👍 / 👎.
fix(windows): stop full action-item hydrate on every local read ## Why Billing RCA (2026-08-17, coordinator-verified): Windows Desktop fired `GET /v1/action-items?limit=500` on **~61–73 RPS** (Cloud Logging 30s sample: 1,825 requests, 99% `omi-windows`, 99% `limit=500`, ~2:1 completed:true/false). Every local Tasks read (`listIncomplete` / `listCompleted` / `dashboardSlices`) kicked an **unthrottled** paged `fetchAll`, and every `tasks:changed` broadcast made the renderer re-read (Tasks page + Hub stats + Quick Task widget) — a self-feeding listing storm. Firestore Read Ops SKU: **$3,285.95 → $9,862.43/mo** (10.42B → 21.39B ops), live QUERY ~10.5–12k reads/s. Related: #9889 (open; not closed by this PR), #9891 (merged, did not drop cash). ## What changed (Windows client only; backend untouched) `desktop/windows/src/main/tasks/taskSyncEngine.ts` + storage reader + main wiring: - **Reads are SQLite-only.** `listIncomplete` / `listCompleted` / `dashboardSlices` never talk to the backend. - **One throttled background sync** (`scheduleBackgroundSync`): ≤1 per 5 min + in-flight dedup; reads, a 5-min interval (`startTaskBackgroundSync`, wired at startup), and window focus all funnel through the same gate, so no trigger can restore the storm. A 30s failure-retry floor heals offline→online, and only when the failed round served **no** backend read response (a served response is already billed — no 30s re-scans of a partially-failing backend), never after sign-out (epoch-guarded). - **ID-census reconcile**: `GET /v1/action-items/ids?completed=false|true` (existing endpoint), diffed against local synced ids (`getSyncedActionItemIds`, new minimal storage reader); per-id document GETs only for ids that are **new or moved buckets** (remote toggles), capped at 200/sync with convergence on later ticks. Steady state with no remote changes = **2 census requests, 0 document transfers**. - **Delete-by-absence safety**: keep-set for both sweeps is the **union of both census buckets** — an id present in either bucket is proven live remotely, so a bucket-moved row whose flip didn't land is kept and retried, never deleted by its old bucket's sweep. Failed census = fail-closed round (no sweep at all). Empty censuses no-op in storage. Epoch + tombstone guards unchanged; offline/401 never wipes the local store. - **Full paged listings only** in the one-time versioned populate (flag `v1 → v2`: every existing install re-populates once, repairing drift the census can't see) and the explicit reconcile (`tasks:reconcile` — the Tasks-page refresh button). Both take their sweep keep-sets from the **uncapped census**, because the backend hard-caps listings at 2,000 docs and reports `has_more=false` at the cap — listing ids must never drive forced delete-by-absence on large accounts. - **Locked items (402)**: per-id GETs that return 402 (paid-plan lock; the doc is listed truncated but never readable by id) are negative-cached for 1h so they can't re-bill every round or starve the lookup cap; they appear via the explicit reconcile's listing, matching pre-fix behavior. - No-op syncs stay silent (no `tasks:changed`), so the read → sync → broadcast → re-read loop cannot self-feed. ## Cost evidence (deterministic, same script on both trees) Identical scripted 5-min UI session (mount reads; browse; toggle/create/rename; renderer-faithful re-reads after every broadcast), run against an `origin/main` worktree and this branch (temporary harness, not committed; the committed `steady-state cost guard` test pins the after-side): | | requests | full listings | listing docs | census | per-id | writes | |---|---|---|---|---|---|---| | origin/main | 25 | **22** | **500** | 0 | 0 | 3 | | this branch | 5 | **0** | **0** | 2 | 0 | 3 | - **Listing-scan volume (the acceptance metric): −100%** (22→0 requests, 500→0 docs). Deterministically pinned by `taskSyncEngine.test.ts › steady-state cost guard`. - **Honest strictest accounting**: each census call is a select-projection stream over the whole collection = **1 Firestore Read Op per doc per call** (projection trims payload, not Read Ops; verified in `backend/database/action_items.py get_visible_action_item_ids`), so a round costs 2N read-ops where N = total tasks. In the single-user test window that is 80 vs 500 (**−84%**); in production the old path billed R×N per window at 61–73 RPS aggregate (≥3 orders of magnitude above 2N/5min). The cut comes from the 5-min throttle + per-id fetching, **not** per-call read magic. A per-call read-ops cut needs a backend `updated_at` watermark/index — deliberately out of scope here. - New steady-state floor per signed-in client: 2N read-ops per 5 min (the ≤5-min remote-visibility bound). Cadence is the only client-side lever; a slower bound would cut it linearly. ## UX - Lists paint **instantly from SQLite** on every read (unchanged local-first contract; create/complete/edit/delete stay optimistic write-through with revert-on-failure semantics). - **Remote adds / deletes / completion toggles appear within ≤5 minutes** (census cadence) or immediately on the explicit refresh. - **In-place remote edits (rename, due-date) appear on explicit refresh** (`tasks:reconcile`, full listing) or the one-time v2 re-populate — the census is ids-only and cannot see content edits. This is the stated bound; a watermark endpoint would tighten it. - Locked (paid-plan) items: background sync skips their docs for 1h at a time; the explicit refresh still shows them (truncated), as before. ## Swarm review (before `gh pr create`) Two independent reviewer lanes ran on the unpushed branch (data-loss/correctness + cost-refuter): - **DataLossReviewer — must-fix (fixed)**: per-bucket sweep keep-sets hard-deleted a bucket-moved row whose per-id GET failed (429/5xx) or was cut by the 200-lookup cap — destroying local-only fields (score/tags/priority) on re-insert; deterministic repro via 300 remote bulk-completes. **Fix**: union keep-set for both sweeps + regression tests (failed-flip keeper, cap keeper). - **DataLossReviewer — note (fixed)**: sign-out mid-failed-sync re-stamped the throttle window, deferring the next account's first sync ≤30s. **Fix**: epoch-guarded re-stamp + regression test. - **CostRefuter — should-fix (fixed)**: 402 locked-item ids became permanent per-round re-fetch zombies starving the lookup cap → negative-cached (1h TTL, cleared on sign-out); 30s retry floor re-billed served census scans on partially-failing backends → relax now gated on "no backend read response served" (also bounds degraded-mode v2-populate retries to the 5-min cadence); forced full-sync sweeps used the 2,000-capped listing ids (mass-delete/re-add flap on refresh for >2k-task accounts) → census keep-set. - **CostRefuter — disclosure (addressed in this body)**: census costs 2 full-collection scans per round (2N read-ops) and introduces an idle-polling cost class the old read-driven code didn't have; numbers above state it plainly. - Confirmed by both lanes: no steady-state full-listing path with the v2 flag set, no hydrate-broadcast loop, epoch/tombstone/empty-set invariants hold, fail-closed on failed/partial census. **Verification round**: both lanes re-reviewed the fixed tree — DataLossReviewer: *"correct, no remaining findings from my lane"* (all previously-traced invariants re-checked); CostRefuter: *"all three should-fix findings are fixed as claimed"* with one P3 residual (locked skips occupying lookup slots before the slice) — also fixed: the lookup queue filters locked skips **before** the `MAX_CENSUS_LOOKUPS` slice. Residual trade-offs both lanes accepted: an intermittent-5xx backend retries freshness at the 5-min window instead of 30s (fail-closed, no data risk); the explicit reconcile costs 2 listings + 2 censuses per click (user-action rate); a 401 response counts as "served" and blocks that round's 30s retry (over-conservative, harmless). ## Tests Focused suites in `desktop/windows` (vitest): throttle/dedup, census diff (new/moved/404/402/500-skip/cap+converge), union keep-set keepers, fail-closed census, empty-census no-wipe, no-op silence, timer + signed-out idle, explicit reconcile strong path, v2 re-populate + capped-tail survival, sign-out stamp hygiene, storage reader contract vs real SQLite (`dbTasks.test.ts`). Verified locally: `vitest run src/main` (2,551 passed) + Tasks/home/voice renderer suites (3,057 passed across the task-adjacent surface), `tsc` node+web clean, eslint clean. Full-suite runs on this machine show unrelated renderer flakes under parallel load that pass in isolation on both clean and patched trees. Refs #9889 (not closed — backend QUERY residual remains). Failure-Class: new <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11760?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. -->
Summary
Verification
cd backend && PYTHON=.venv/bin/python bash test-preflight.shcd backend && bash test.sh20 passedflutter testfull suite:858 passedbefore rebase (run through the local Flutter Tools source fallback because the bundled Dart VM did not start)cd app && bash scripts/analyze_ratchet.shmake preflightLocal-path note
The offline backend harness could not start because this machine does not have
redis-server. The rebased Flutter-suite rerun could not start because the local engine compiler snapshot is incompatible with the available Dart SDK; the original full suite and hermetic regression tests cover the changed load behavior. The Flutter UI could not be dogfooded because no debug Flutter VM Service was running foragent-flutter.