Skip to content

fix(windows): stop full action-item hydrate on every local read - #11760

Merged
Git-on-my-level merged 2 commits into
BasedHardware:mainfrom
Git-on-my-level:agent/m1-studio-omp-glm-5-3/77be4903
Aug 17, 2026
Merged

Git-on-my-level merged 2 commits into
BasedHardware:mainfrom
Git-on-my-level:agent/m1-studio-omp-glm-5-3/77be4903

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

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

Review in cubic

Git-on-my-level and others added 2 commits August 17, 2026 17:21
Billing RCA (2026-08-17): omi-windows fired `GET /v1/action-items?limit=500`
on ~61-73 RPS (99% omi-windows, 99% limit=500) because 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 that pushed Firestore Read Ops from $3.3k to $9.9k/mo.

The fix (mirrors macOS TasksStore's 5-min reconcile bound + ID census):

- Reads are SQLite-only. Freshness funnels through ONE throttled
  scheduleBackgroundSync (≤1 per 5 min + in-flight dedup); a 30s retry
  floor heals offline→online without restoring the storm on 429s.
- The background sync reconciles via `GET /v1/action-items/ids?completed=`
  (both buckets) and fetches per-id documents ONLY for ids that are new or
  moved buckets (remote toggles); steady state costs 2 census requests and
  0 document transfers. Failed census = fail-closed round (no delete-by-
  absence off a partial picture). Bucket-moved rows are flipped BEFORE the
  sweeps so a moved row is never delete-by-absence'd by its old bucket.
- Full paged listings survive only in the one-time versioned populate
  (v1→v2 bump: every existing install re-populates once, repairing drift
  the census cannot see) and the explicit user reconcile (tasks:reconcile)
  — the one path that picks up in-place remote edits.
- 5-min interval + window-focus trigger wired in main (both capped by the
  shared throttle); epoch/tombstone/empty-set guards unchanged.

Measured with an identical scripted 5-min UI session (mount + browse +
toggle/create/rename with renderer-faithful re-reads) against an
origin/main worktree and this branch:
  before: 25 requests = 22 full listings / 500 listing docs / 3 writes
  after:   5 requests =  0 full listings /   0 listing docs / 2 census + 3 writes
Firestore-read cut on this path: 100% of listing-scan volume (500→0 docs);
strictest all-QUERY accounting 500→40 census ids (-92%) in the single-user
window, and ~3 orders of magnitude in production where reads fired at
61-73 RPS aggregate. Census cost disclosed: /ids is a select-projection
stream = 1 Firestore Read Op per doc per call (projection trims payload,
not Read Ops) — the cut comes from the 5-min throttle, not per-call magic.

Tests: throttle/dedup, census diff (new/moved/404/unreadable/cap+converge),
fail-closed census, empty-census never wipes, no broadcast on no-op sync,
timer + sign-out idle, explicit reconcile strong path, v2 re-populate,
storage reader contract vs real SQLite (completed coerced from 0/1).
Verified: `vitest run src/main` + Tasks/home/voice renderer suites (3057
passed); tsc node+web clean; eslint clean.

Refs BasedHardware#9889 (not closed — backend QUERY residual remains).
Failure-Class: new

Swarm-review fixes (independent reviewer lanes, pre-PR):
- Census sweeps keep-set is now the UNION of both buckets: a bucket-moved
  row whose per-id GET failed or was cut by MAX_CENSUS_LOOKUPS is KEPT
  (its other-bucket census presence proves it live) instead of being
  hard-deleted by its old bucket's sweep.
- Full-sync sweeps (one-time populate + explicit reconcile) also take the
  census keep-set: the backend hard-caps listings at 2000 docs and reports
  has_more=false AT the cap, so listing ids must never drive forced
  delete-by-absence on large accounts (mass-delete/re-add flap).
- A 402 (locked item, paid plan) per-id GET is negative-cached for 1h so
  locked ids cannot zombie-rebill every round or starve the lookup cap.
- The 30s failure-retry floor applies only when the round served NO
  backend read response (a served census/listing is already billed; a
  partially-failing backend must not be re-scanned every 30s), and never
  after a sign-out (epoch-guarded — the next account syncs immediately).

Co-authored-by: multica-agent <[email protected]>
Definition for the class the windows task-hydrate fix instantiates: a
local-first cached read that re-derives its full backing dataset per read
turns UI read frequency into backend scan frequency, and a store-change
broadcast that triggers UI re-reads makes the loop self-feeding.

Failure-Class: FC-unthrottled-read-revalidation
Co-authored-by: multica-agent <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit a7ff90a into BasedHardware:main Aug 17, 2026
33 checks passed
Git-on-my-level added a commit that referenced this pull request Aug 18, 2026
…#11768)

## Problem

The dev desktop-backend deploy refuses to route traffic whenever
`origin/main` advances during the build:

```
ERROR: candidate is stale because origin/main advanced to
0151724; traffic remains unchanged.
```

A desktop-backend deploy takes ~5 minutes. When commits land faster than
that, every run is pre-empted at the last step — *after* Cloud Build and
the acceptance probes have already run. The check cannot prevent a
build; by the time it fires, the build is finished. All it can do is
discard it.

Three consecutive runs failed this way on 2026-08-17:

| Run | main@ | Outcome |
| --- | --- | --- |
|
[32059345833](https://github.com/BasedHardware/omi/actions/runs/32059345833)
| `4f8da45f` | failed (project/URL resolution — different cause) |
|
[32074024600](https://github.com/BasedHardware/omi/actions/runs/32074024600)
| `fc458ef3` | stale: main advanced to `a7ff90a4` |
|
[32074869094](https://github.com/BasedHardware/omi/actions/runs/32074869094)
| `03f50eb1` | stale: main advanced to `01517240` |

The failure mode is worse than a stuck pipeline. Prod promotes the last
**dev-accepted** candidate, so with dev unable to accept anything since
19:06, the prod run at 22:11 reported **success** while re-shipping the
`34bd15da` image. #11764 is merged, built, and sitting in an unrouted
revision — while the dashboard reads green.

It is also self-reinforcing: the more the team merges, the less likely
any deploy ever lands.

## Why the check was redundant

The two protections it appeared to provide are both already in place
elsewhere, and they fight each other:

- **Ordering** is guaranteed by the `desktop-backend-auto-dev`
concurrency group with `cancel-in-progress: false`. A newer run cannot
route while an older one holds the lock. But holding that lock for the
full build is *exactly* what guarantees `main` has moved by the time the
older run reaches the traffic step — a queued run behind it has its
commit on `main` by definition.
- **Debounce against stacked Cloud Builds** is the entry guard in
`Resolve immutable candidate identity`
([:68](https://github.com/BasedHardware/omi/blob/main/.github/workflows/desktop_backend_auto_dev.yml#L68)),
which exits before Google Auth and before any build is spent. **This PR
does not touch it.** Superseded commits still bail out early; a burst of
three merges still builds only the newest.

Re-asking the same question after the build could only throw away
finished work.

## Change

Gate the promotion on **lineage** rather than recency: refuse only when
the candidate does not descend from the release SHA recorded on the
revision currently serving 100% traffic. That preserves the real safety
property — never move desktop-backend backwards — without requiring that
nobody merged during the build.

Unknown lineage (a legacy revision with no recorded SHA, or a commit
unreachable in the checkout) warns and admits. Dev is currently serving
`desktop-backend-00461-qiy`, a pre-SHA revision, so refusing on unknown
lineage would deadlock the pipeline on the very next run.

Scoped to the dev workflow. `desktop_backend_prod.yml` admits via
`admitted-source` and never carried this guard.

## Verification

```
python3 -m pytest .github/scripts/test_check_desktop_backend_traffic_regression.py -q   # 11 passed
python3 .github/scripts/check-desktop-backend-release-policy.py                          # OK
python3 .github/scripts/check-deployment-concurrency.py                                  # OK
python3 -m pytest .github/scripts/test_check_desktop_backend_release_policy.py -q         # 27 passed
make preflight
```

**Replayed the three real failures** against the SHA prod actually
serves (`34bd15da`):

| Candidate | Old guard | New guard |
| --- | --- | --- |
| `03f50eb1` (#11764) | refused | **admitted** — descends from serving |
| `fc458ef3` | refused | **admitted** |
| `a7ff90a4` (#11760) | refused | **admitted** |
| `34bd15da` vs serving `03f50eb1` | admitted | **refused** — would move
backwards |
| serving SHA empty (dev today) | n/a | **admitted** with `::warning` |

**Exercised the live discovery path** against the prod service:
`extract_single_cloud_run_traffic_revision.py` resolved
`desktop-backend-34bd15da499c-32074856543-1`, and the `jq` expression
read
`OMI_DESKTOP_BACKEND_RELEASE_SHA=34bd15da499cbfe314f1b5d9014b79611f91736c`
off it. The dev project was not reachable from the read-only bot
(`run.services.get` denied), so that half runs first in CI.

The unit tests cover the decision function through an injected ancestry
oracle, and the `git` seam itself against a real temporary repository —
including the unreachable-commit path — rather than stubbing it.

## Risk

Traffic shifts become more frequent, because builds that pass acceptance
now actually ship instead of being discarded. That is the intent. If
churn needs bounding, the correct lever is the entry-side debounce, not
discarding completed work at the exit.

Failure-Class: new

Adds `FC-promotion-gate-admits-on-recency-not-lineage` — a gate between
an accepted candidate and its traffic promotion may refuse only
backwards promotions, never merely because the branch advanced during
the build. Guard artifact is the checked-in decision function and its
fixtures.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11768?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