Skip to content

fix(dream): bound and isolate discovery so one Firestore timeout cannot fail the sweep - #23302

Merged
Git-on-my-level merged 3 commits into
mainfrom
lane/dream-discover-resilient
Oct 22, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
lane/dream-discover-resilient

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Dream's hourly sweep died at 100% eligibility. On 2026-10-22 at 12:00Z, POST /v2/dream-agent/sweep returned 500 after 10.4 s. The cause was DeadlineExceeded: 504 in dream_scheduler.discover → initialize, a single transaction over a whole 499-row page: two transactional get_alls of about 1,000 refs, plus up to 500 writes. Discovery ran inline in candidates(), so one failed page failed the whole sweep, and zero Dream passes ran that hour. Prod was rolled back to 25% (#23295).

This PR makes discovery bounded, isolated and cheaper:

  • Chunked transactions. Each transaction covers DISCOVERY_TRANSACTION_ROWS = 100 rows: ≤100 refs per get_all and ≤101 writes per commit, about 5× headroom over the incident. The cursor advances only in a page's final chunk, so a failed or stopped page re-scans next sweep. Chunk replay is idempotent, because of the transactional dream_due read.
  • Wall budget. DISCOVERY_BUDGET_SECONDS = 120 is checked per page and per chunk, so discovery can't eat the 1,680 s drain budget. Stops log one WARNING plus record_fallback.
  • Failure isolation. candidates() catches any discovery exception, logs one payload-free dream_discovery_failed stage=discover class=<type> (no uids) plus record_fallback (queue_only), and still drains the already-due dream_due rows. The sweep can no longer 500 on discovery.
  • Fewer reads. dream_users state is read only for rows that are eligible and not yet queued (the only input to due_time()), and the read is skipped entirely when there are none. That's about 30k → about 20–22k reads per sweep once the queue converges. The dream_due read stays: it's the no-clobber guard against concurrent mark_dirty/finish for eligible rows, and the stale-row signal for ineligible ones.
  • BODY_DIGEST for database.dream_scheduler.discover is re-pinned in both registry maps. The runbook's discovery paragraph is updated.

A later PR will replace the full-user scan (which reads free users to find paid ones) with a paid-only query or event-driven enqueue. That's the larger read reduction.

Verification

  • 8 new tests in tests/unit/test_dream_scheduler.py:
    • isolation, logged once;
    • chunk bounds [100,100,50];
    • cursor retained on chunk failure;
    • budget stops at page and chunk;
    • the states read covers only eligible-unqueued ids;
    • zero states reads when all rows are ineligible or all queued.
  • backend/test.sh with BACKEND_UNIT_TEST_FILE_LIST over 19 files (the dream suites, the Firestore guard set, reason-label enums and query shapes): 1,343 passed, 0 failed, under nice -n 19 taskpolicy -b.

These are unit-level tests only. Prod verification after deploy: hourly sweeps log candidates= summaries with no sweep 500s, and no dream_discovery_failed storms. Re-ramp to 100% only after this serves and two sweeps are clean.

Product invariants affected

none

Failure class

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

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

Git-on-my-level and others added 2 commits October 22, 2026 20:19
The 2026-10-22 incident: right after DREAM_AGENT_PAID_PERCENT went to 100,
each discovery page transaction held two 499-ref transactional get_alls plus
up to 499 dream_due sets and the cursor write (exactly Firestore's 500-write
ceiling); the dream_users bulk get blew its 3 s deadline and the whole hourly
sweep 500'd, so zero Dream passes ran.

- candidates() now catches any discovery exception, logs one payload-free
  WARNING (stage + class, no uids) and records a record_fallback degrade
  (firestore_read/dream_discovery -> queue_only), then still returns the
  already-due dream_due rows; the sweep never 500s on discovery again.
- Each page commits in DISCOVERY_TRANSACTION_ROWS=100 chunks, so every
  transactional get_all, commit write count and allowlist bulk read is
  bounded to the 100-ref bulk-get size with ~5x headroom on the old page
  transaction at full eligibility. The cursor advances only with a page's
  final chunk, so failed or budget-stopped pages re-scan from their start;
  replay is idempotent because the transactional dream_due read skips
  owners a concurrent dirty write already enqueued and dirty writes
  overwrite due_at afterwards (mark_dirty/finish are last-writer-wins).
- Discovery wall time is bounded to DISCOVERY_BUDGET_SECONDS=120 (checks
  before each page and each chunk, one warning + fallback on stop), so it
  cannot eat the drain's 1680 s pass budget under the route's 1710 s
  middleware ceiling.
- Re-pinned database.dream_scheduler.discover BODY_DIGEST (both registry
  maps) per the Firestore query checklist; runbook updated.

Co-Authored-By: GLM-5.3 <[email protected]>
…nqueues

Round 2 of the discovery read diet (on 626d978). Each 100-row chunk still
reads every owner's dream_due row inside the transaction - that read is the
no-clobber guard for eligible owners (a blind set would last-writer-wins a
concurrent mark_dirty/finish due_at) and the stale-row signal for ineligible
owners - but the dream_users get_all now covers only rows that are eligible
and not already queued, the only rows whose state due_time() consumes. When
no row qualifies the bulk read is skipped entirely, so a steady-state page
that mostly re-finds already-queued owners costs two reads per scanned owner
instead of three (~30k -> ~21k reads per hourly sweep at 90% queued).

Per 499-row page, reads before -> after: 1,497 -> 1,497 at 100% eligibility
with nobody queued (bootstrap corner, unchanged), 1,497 -> ~1,048 at 100%
with 90% queued, 1,497 -> ~1,123 at 25% eligibility with nobody queued,
1,497 -> ~1,010 at 25% with 90% queued. Writes unchanged (round 1 already
gated sets/deletes on the same predicates). Both get_alls stay inside the
transaction before any write and remain at most the 100-ref bulk-get cap.

Re-pinned database.dream_scheduler.discover BODY_DIGEST (both registry maps)
per the Firestore query checklist; runbook updated. New tests: the states
get_all covers only eligible unqueued rows, and no states read happens when
none qualify.

Co-Authored-By: GLM-5.3 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T15:36:04.957485Z 7c7b057 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.

Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
…3308)

## Summary

The `apt-native-audio-replay-timeout` flake persisted after #23266
because that fix left three exposure paths on the hot step of
`backend-unit-tests.yml` shards, all observed on 2026-10-22:

1. **Runner image rollout empties the cache.** The cache key pins
`ImageVersion`; image `20261021.345.10` rolled out on 10-21/22, and with
no `restore-keys` every shard of the first runs on the new image went
cold into a 62.8 MB download. On throttled `azure.archive.ubuntu.com`
runners that cannot finish inside the 5m step budget (observed 10–60s
per small package).
2. **The 6-shard save race leaves no entry.** All shards save the same
primary key concurrently; the cache service reserves per key, so losing
shards log `Unable to reserve cache ... another job may be creating this
cache` (run 39790722827 shard 1, 13:53:38Z) and shards whose install
timed out never reach the save step at all — main-push run 39791659773
had 5/6 shards fail this way, so nothing repopulated the cache for
anyone.
3. **Even a cache hit is not network-free.** Run 39782487842 shard 3
restored the cached `.deb`s at 12:57:16Z and still timed out at
13:02:29Z inside `apt-get update -qq`, which downloads package indexes
from the mirror regardless of cached archives.

Confirmed occurrences of the 5-minute `Install native audio replay
dependencies` timeout: runs 39790722827 (PR #23302, shards 2+3),
39791659773 (main push, shards 1/2/4/5/6), 39782487842 (shards 3/4/5,
one of them with a warm cache). The same code passed with a warm
old-image cache at 12:15Z (run 39776810910), so this is CI
infrastructure flakiness, not a regression.

## Changes (all inside this flake's own step in
`.github/workflows/backend-unit-tests.yml`)

- `restore-keys` fallback across `ImageVersion` bumps within the same
runner OS: the `.deb` set tracks the ubuntu24 distro repos, not the
image patch version, so the newest saved image keeps every run warm
through rollouts.
- Warm installs replay the cached dependency closure with `sudo dpkg -i`
— zero network on the hot path. `apt-get` (update + `install -f`,
bounded by the existing Acquire retries/timeouts) runs only as repair if
the replay fails; the cold path is unchanged and keeps its 5m bounded
allowance.
- Single-writer cache save (shard 1 only), removing the concurrent
same-key save race. A `restore-keys` fallback hit reports `cache-hit:
'false'`, so shard 1 also backfills the exact key for new image
versions.

`.github` is edited only for this flake's own step and no workflow is
added, per the 10-22 CI flake-fix and caching direction.

## Verification

- `actionlint` clean on the modified workflow; YAML parse and `bash -n`
on the changed run block pass.
- `scripts/pr-preflight --suggest`: ci lane, no product-invariant
citations, no failure-class declaration required.
- The restored-cache-but-still-timed-out shard (39782487842 shard 3)
demonstrates the warm path must skip `apt-get update`; `dpkg -i` of the
cached 87-`.deb` closure needs no indexes and no mirror.

## Risk

- `dpkg -i` replays exactly the saved closure; if a future image bump
ever made that replay fail, the apt repair path resolves and downloads
only the delta before failing loudly — no silent skips.
- Old-image cache entries are reused across image bumps; they come from
the same ubuntu24 noble/noble-updates pools the images are built from,
and a stale set degrades to the apt repair path, not a hang.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/23308?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="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/23308?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23308&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@Git-on-my-level
Git-on-my-level merged commit afba33f into main Oct 22, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/dream-discover-resilient branch October 22, 2026 15:44
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Oct 22, 2026
The 2026-10-22 runner image rollout (20261021.345.10) emptied the
native-audio .deb cache for every shard because the cache key pins
ImageVersion and no restore-keys fallback exists; the six shards also
race one another saving the same key ('Unable to reserve cache ...'),
so no entry was written back. Cold 62.8 MB downloads then hit the 5m
step ceiling on throttled mirrors (runs 39790722827 PR BasedHardware#23302 shards
2/3, main-push 39791659773 shards 1/2/4/5/6, 39782487842 shards 3-5).

Even a cache hit stayed exposed: run 39782487842 shard 3 restored the
.debs at 12:57:16Z and still timed out at 13:02:29Z inside
apt-get update -qq, which downloads package indexes from the mirror
regardless of cached archives.

- restore-keys fall back across ImageVersion bumps within the same
  runner OS; the .deb set tracks the ubuntu24 distro repos, not the
  image patch version.
- warm installs replay the cached closure with dpkg -i (no network);
  apt repairs only if that replay fails.
- save runs on shard 1 only, removing the concurrent same-key save
  race; a restore-keys hit reports cache-hit 'false', so shard 1 also
  backfills the exact key for new image versions.
Git-on-my-level added a commit that referenced this pull request Oct 23, 2026
…sed gate) (#23374)

Discovery is bounded (#23302) and quiet-hour admission self-heals (#23331;
proven 05:00Z 10-23). David approved the revised gate 10-23: self-heal plus two
clean sweeps, then this env-only apply and a 6h soak.

Co-authored-by: Claude Opus 5.5 <[email protected]>
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