Skip to content

perf(backend): reduce duplicate and surplus Firestore reads - #23686

Merged
Git-on-my-level merged 4 commits into
mainfrom
lane/solreads
Oct 26, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
lane/solreads

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Small memory pages overfetch raw canonical rows, each replica independently reloads the same cohort memberships, and overlapping external API cache misses duplicate source reads. Refill canonical batches to page demand, share encrypted cohort observations within their original 60-second lease, and coalesce simultaneous identical authorized external-list misses.

All three changes ship on with independent false kill switches. Memory candidate/visibility policies and indexed batching stay unchanged; raw scans return to their original 50-row batch after encountering filtered candidates, avoiding tiny-RPC amplification on sparse prefixes. External callers retain the same authorization, rates, queries, response models, pagination headers and cache freshness. At most eight followers globally wait up to one second on sync workers; excess callers bypass immediately. Followers recheck task writer versions and fall back to their original source path on failure. Shared cohort hits carry their original deadline into the process cache; errors and malformed documents are never shared.

Task-control caching is excluded per lead ruling 06ff36 because account generation is revocation authority. Migration-helper reads have no measured service caller or route series over seven days, so this PR makes no migration change or savings claim.

Validation

  • BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/solreads/tests.txt /Users/dazheng/workspace/omi/bin/omi-heavy run -- nice -n 19 bash backend/test.sh: 149 passed across six files.
  • Additional focused shard: 95 passed, including real ASGI concurrent miss reuse (two auth checks, one source read, identical final responses), index-path behavior, mixed-memory cursor/offset equivalence and expiry/refill/error cases.
  • Final safeguard shard: 56 passed across canonical cursor/offset, indexed paths, real ASGI coalescing and encrypted cohort cache tests, including sparse-prefix backoff and emulator-plane bypass.
  • Review correction shard: 83 passed, including multi-flight waiter saturation/immediate bypass, returned capacity, cohort policies, encrypted cache behavior and existing external-list response parity.
  • OMI_PR_BODY_FILE=/Volumes/Ephemeral/scratch/solreads/pr-body.md /Users/dazheng/workspace/omi/bin/omi-heavy run -- nice -n 19 make preflight: 38 checks passed. Normal bounded pre-push gates run again before publication; GitHub CI remains separate.

Operations

Lead owns merge and deployment to backend, backend-integration, desktop-backend, sync/backfill and notifications as applicable. No new workflow, index, data mutation, rate-limit change or runtime-env literal edit. See backend/docs/runbooks/bundled-reader-reuse.md for kill switches and readback metrics. Cohort source reads move to _read_memberships; sum old and new caller labels across rollout rather than counting the label change as savings. Book savings only after serving-revision and source-read verification.

Product invariants affected

  • INV-MEM-1: tier/device/archive policies and historical authority are unchanged; only raw canonical batch sizes change.
  • INV-MEM-3: canonical identity, suppression and authorization remain authoritative and fail closed; no cached memory payload is introduced.
  • INV-MEM-4: lineage suppression, expiry disposition and promotion authority remain unchanged; filtered candidates refill the existing scan.

Line-Count-Exception: backend/utils/memory/memory_service.py | 4692 -> 4698 | One helper import and a request-local filtered-prefix bit wire demand sizing without changing indexed policy; sparse raw scans retain their original batch size.

Size raw canonical batches to page demand, share encrypted cohort observations
without renewing their sixty-second lease, and coalesce simultaneous authorized
external-list cache misses. Independent switches ship on unless set false.

Preserve source policies, page contracts, writer versions and error behavior.
Exclude task-control caching per lead ruling 06ff36 because its generation is
revocation authority. No migration bound is introduced without measured traffic.
Demand sizing saves surplus rows on dense small pages. Once policy filtering
is observed, keep the original raw batch size so long hidden prefixes cannot
multiply tiny RPCs and consume the request deadline. Indexed batching is unchanged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T07:24:15.235647Z b76ab20 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cc409c99d7

ℹ️ 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".

Comment thread backend/database/rollout_cohorts.py Resolved
…dule scope

Limit waiting followers globally to eight, bypass excess callers immediately,
and release admission on every wait exit. Cover saturation across separate
flights and returned capacity with a controlled concurrent regression.

Move the lazy membership-cache helper import to module scope as required by the
backend guide. Neither change alters source authority or cache freshness.
@Git-on-my-level
Git-on-my-level merged commit ee8cf4f into main Oct 26, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/solreads branch October 26, 2026 09:50
Git-on-my-level added a commit that referenced this pull request Oct 27, 2026
)

## Summary

During the 10-22/25 Firestore surges, maintenance scans multiplied
across replicas; the 10-25 spike followed a lever rollback. The 10-22
exact revision trigger remains unproven. Day-aligned counters attribute
576M and 510M extra reads to the queue sampler and three finalization
sweeps, rather than sync-job redrive processing. Keep the existing
maintenance admission lease on by default in production independently of
the `singleton_loops` cohort, with
`FSR_MAINTENANCE_COORDINATION_ENABLED=false` as the explicit
coordination kill switch.

Redis keys/Lua, scan cadence, takeover bounds, local recovery on Redis
failure, transactional job claims and designated queue publisher are
unchanged. Non-production, including stage-prod staging, retains legacy
cohort qualification unless explicitly overridden. Other Firestore
levers retain their current behavior. No runtime-env/config literal,
index, workflow, account-data or retention changes.

This is a recurrence guard: current singleton100 already coordinates
production, so steady-state new realized savings are **$0**. Comparable
observed scanner regrowth is about $219–271 per incident at
$0.43–0.47/M; recurrence frequency and monthly avoided spend are
unknown. WQ21 privacy memo and WQ24 funded aggregate shortcuts are
excluded because their correctness gates did not pass; WQ22 is already
in #23686. No partial authorization/quota cache ships.

## Validation

-
`BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/fsown/scan-tests.txt
BACKEND_PYTEST_WORKERS=4 nice -n 10 bash backend/test.sh`, through
workspace `bin/omi-heavy`: 68 passed across the scan-storm guard,
existing singleton/recovery and Redis Lua suites.
- Real queue sampler with five replicas and ten ticks: 1000 document
reads with coordination explicitly off, 200 with it on, with the same
empty legacy lever literal. Fixed-loop tick, fail-open, publisher
eligibility and takeover tests pass.
- Feature flag registry check passed; Full `make preflight`: 36 checks
passed (366.85s). Exact-head CI is verified separately before MERGE
READY.
- Independent Luna full-diff review through agentctl found staging uses
stage prod; corrected production detection and added staging/preview
regression profiles. Existing-session Luna delta **SHIP**, no new
actionable findings (`exec-yard-device-motion-guard-episode-voyage`,
continuation key `fsown-luna-delta-1027a`).

## Ship and rollback (lead only)

No merge/deploy/apply by this lane. No apply request during the batch
entry/soak through ~11:30Z. Lead deploys source in its allowed train,
first verifying healthy designated `FSR_QUEUE_AGE_PUBLISHER=1` and fresh
queue-age samples. Compare lease outcomes, finalization recovery/queue
freshness, errors and live p95 before/after; verify the runtime-reported
release SHA for each serving artifact. Setting
`FSR_MAINTENANCE_COORDINATION_ENABLED=false` via the regular lead-owned
runtime procedure restores prior per-replica execution and can raise
spend. See `backend/docs/runbooks/firestore-spend-guard.md`.

#23797 remains owned by the lead and untouched. Finjob5→100 requires a
separate complete-literal lead config change after soak; READY index
metadata alone is not a production apply.

## Product invariants affected

none

## Failure class

Failure-Class: none


## CR train #2 integration (2026-10-27)

Merged `origin/main` at `8da0ca9e1b7867cb9719a33225c3d9371713356a` into
`lane/fsown` with merge commit
`eb963fcfca4106bdc8c718f7c308624116c3034a`; no rebase or force-push. The
two conflicts were documentation/registry additions: retain fleet
coordination and main's server-batch documentation, new batch flags and
newer default-off Soniox idle-reselect declaration; regenerate the
registry. No production-code conflict. #23797's scoped literals and
#23803's metrics collector remain identical to main.

Affected tests through `backend/test.sh`, explicit nine-file
`BACKEND_UNIT_TEST_FILE_LIST`, `BACKEND_PYTEST_WORKERS=4`, under `nice`
/ `omi-heavy`: **458 passed**, one slow test deselected by the standard
harness. Final exact-head CI and `mergeable,mergeStateStatus,headRefOid`
are recorded in `reports/fsown-owner-1027.md`. Lead retains
merge/deploy/apply authority.
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