Repository navigation
fix(relay): keep failed rehome polls out of the durable failure budget - #19915
Conversation
The regional rehome worker polls claimRegionalRehome about once a second. Any error thrown before an attempt was claimed - in practice a director pool timeout on the pre-claim control read, 52-74 a day against a pool of 3 - was charged to relay_region_rehome_worker_state.consecutive_failures, which durably disables the control at three. That counter only ever resets on a drain receipt, so while the control is disabled it never resets: production sits at 1068 and still climbing. Enabling the control leaves the stale counter in place, so the next pool timeout latches it straight back off. That is what ended the 2026-08-28 enable after ten minutes. - A poll that never claimed an attempt drained nothing, so it no longer feeds the dispatch-failure budget and logs .._poll_failed instead of .._dispatch_failed. recordRegionalRehomeWorkerFailure had no other caller and is removed. - Enabling the control clears consecutive_failures and paused_until, so a budget spent under a previous enable cannot kill a fresh one. The dispatch interval in next_dispatch_at is deliberately left alone. - The budget's auto-disable now emits orca_relay_regional_rehome_failure_budget_disabled, matching the existing .._safety_disabled precedent. It wrote no event before, which is why this went unnoticed for two weeks. No change to region selection, the candidate query, or host eligibility.
📝 WalkthroughWalkthroughThe regional rehome assignment store now uses a named failure budget, resets worker failure state when control is re-enabled, and returns a durable disable log at the budget transition. The worker records dispatch failures only after claiming an attempt and logs poll failures separately. Tests cover state reset, one-time disable logging, worker state inspection, poll failure handling, and concurrent transaction locking. Merge Risk: 🔵 Low · up to The change correctly separates polling failures from dispatch failures and resets the durable failure state when re-enabling regional rehome. The remaining risk is a potentially flaky PostgreSQL concurrency test due to its short 800 ms wait window. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 621617fa-7a8e-460a-a9e2-d166058e10f8
📒 Files selected for processing (4)
cloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/regional-rehome-store.test.tscloud/apps/relay/src/regional-rehome-worker.test.tscloud/apps/relay/src/regional-rehome-worker.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Pre-claim poll failures escape the durable budget —
regional-rehome-worker.tsnow only records a dispatch failure when a claim actually returned an attempt; a poll that failed before the claim (e.g. a pool timeout on the once-a-second control read) logsorca_relay_regional_rehome_poll_failedand never touches the budget. - Enable clears a stale budget —
applyRegionalRehomeControlresetsconsecutive_failures/paused_untilin the same control-then-worker lock orderclaimRegionalRehomeuses, leavingnext_dispatch_atuntouched so rate limiting survives. - Durable auto-disable emits a structured event —
incrementRegionalRehomeWorkerFailurereturns anorca_relay_regional_rehome_failure_budget_disabledrecord, logged after the transaction commits and only on theenabled=1 → 0transition. - Dead trap removed —
recordRegionalRehomeWorkerFailure, which would have misrecorded pre-claim infrastructure errors, is deleted outright rather than left as a live footgun.
ℹ️ Recency window
I agree the budget does not need a time component. A drain receipt and every enable both reset it, so the counter can only advance on post-claim dispatch failures while claims are flowing; a streak of three dispatch failures spaced across an idle stretch is still a faithful "dispatch is broken now" signal, and the residual "latch off a control that has nothing to drain" case is cleared by the next enable. A last_failure_at column and migration on a hot table is not worth it.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 9528c9da-ea37-4d91-9195-9646ece25ec0
📒 Files selected for processing (2)
cloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/regional-rehome-postgres.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- cloud/apps/relay/src/assignment-store.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| expect(failurePid).not.toBe(0) | ||
| const rows = await primary.query('SELECT pg_blocking_pids(?) AS blockers', [failurePid]) | ||
| expect(rows[0]!.blockers).toContain(enablePid) | ||
| }, { interval: 10, timeout: 800 }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Increase the PostgreSQL lock-observation timeout.
The 800 ms limit includes connection checkout, transaction startup, and CI scheduling. A loaded runner can fail this test before PostgreSQL exposes the expected blocker.
Use a less restrictive timeout, such as 5 seconds.
Proposed fix
- }, { interval: 10, timeout: 800 })
+ }, { interval: 10, timeout: 5_000 })📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| }, { interval: 10, timeout: 800 }) | |
| }, { interval: 10, timeout: 5_000 }) |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Failure accounting now locks the control row first —
recordRegionalRehomeDispatchFailuretakesrelay_region_rehome_controlbefore the worker row, matching the control → worker → attempt order used byclaimRegionalRehomeandapplyRegionalRehomeControl. This removes the AB-BA inversion that could deadlock a budget-exhausting failure against a concurrent enable and force a store-level transaction retry. - Postgres concurrency test proves serialization —
serializes an enable with a budget-exhausting failure without retriesdrives a real enable against a budget-exhausting failure across two connections, asserts the failure blocks on the enable's control lock, and confirms both settle with no deadlock and exactly one transaction per side. Verified it is red without the fix: the old worker → control order deadlocks, and the transaction counter (or an exhausted-retry rejection) trips the assertion.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

The bug
The regional rehome worker polls
claimRegionalRehomeroughly once a second. Itscatchrouted any error thrown before an attempt was claimed intoassignments.recordRegionalRehomeWorkerFailure(), which increments the durablerelay_region_rehome_worker_state.consecutive_failuresbudget and disables the control at three.In practice the thing throwing there is not a rehome failure at all: it is a node-postgres pool timeout on the pre-claim control read (
RELAY_DIRECTOR_DATABASE_POOL_MAX = 3,POSTGRES_CONNECTION_TIMEOUT_MS = 2_000), 52-74 a day out of ~86,400 polls.That counter resets in exactly one place —
recordRegionalRehomeDrainReceipt, when a source cell answers a drain. While the control is disabled no drains happen, so it never resets. Production has been sitting at 1068 and still climbing since 2026-08-28. Enabling the control did not clear it, so the next pool timeout took it to 1069, saw>= 3, and silently disabled the control again. That is the ten-minute lifetime of the 2026-08-28 21:06 UTC enable.The auto-disable also wrote no log event, which is why nobody noticed for two weeks.
The fix
1. A poll that never claimed an attempt no longer spends the budget (
regional-rehome-worker.ts).The boundary is the worker, not the store.
claimRegionalRehomeis already correct: it throws infrastructure errors and lets the caller decide. The defect is the caller's classification —attemptId ? dispatch : workertreats "we never dispatched" as a dispatch-budget event. The budget's own reset condition ("the source cell answered") proves it measures the drain-dispatch path, so only post-claim errors belong in it.Making the store swallow connection errors instead would be wrong twice over: it would hide infrastructure failure from the safety telemetry that already tracks
sqlFailuresand pool pressure, and the store's one existing swallow is a deliberately narrowisDatabaseLockUnavailablepredicate, not a blanket catch.A pre-claim failure now logs
orca_relay_regional_rehome_poll_failedrather than..._dispatch_failed— those pool timeouts were being reported as failed drains, which is precisely the misreading that hid this.recordRegionalRehomeWorkerFailurehad no other caller and is removed rather than left as a live trap.2. Enabling the control clears the stale budget (
applyRegionalRehomeControl).A budget spent under a previous enable is not evidence about this one. The enable path updated only
relay_region_rehome_controland never touched the worker row. It now resetsconsecutive_failuresandpaused_untilin the same transaction, in the same control-then-worker lock orderclaimRegionalRehomeuses.next_dispatch_atis deliberately left alone so rate limiting survives the enable.3. The durable auto-disable now emits a structured event.
orca_relay_regional_rehome_failure_budget_disabled, carryingcontrolGenerationandconsecutiveFailures, following the existingorca_relay_regional_rehome_safety_disabledprecedent and logged after the transaction commits so a rollback cannot fabricate it. Only theenabled=1 -> 0transition logs; later failures find the control already off.On the recency window (deliberately not done)
The brief asked whether the budget needs a time component. I argue no, and want the reviewer to push back if they disagree.
After fix 1 the only writers to the budget are post-claim dispatch failures and safety pauses, both of which can only happen while the control is enabled and claims are flowing. The staleness hazard needs increments to stop without either a reset or an enable. While the rehome is idle the counter cannot advance at all (
recordRegionalRehomeDispatchFailurerequires an attempt row, so a claim must have happened); while it is dispatching, receipts reset it. Fix 2 zeroes it at every enable.The one residual case — two failures, then candidates run out permanently, then one more failure days later — latches off a control that has nothing left to do, and the next enable clears it. Buying that costs a
last_failure_atcolumn and a schema migration on a hot table. Not worth it. If ops wants a rolling window later it is an additive follow-up, not a prerequisite for re-enabling.Scope
No change to region selection, the candidate query, or which hosts are eligible. Failure accounting and the enable path only.
Testing
Each behaviour change has a test that fails on
origin/main:keeps a failed poll out of the durable dispatch-failure budgetTypeError: assignments.recordRegionalRehomeWorkerFailure is not a function— the worker demonstrably reaches for the durable budget on a pre-claim errorclears a stale failure budget when the control is enabled againconsecutiveFailures: 3, pausedUntil: 87700000survive the enable (expected0, 0)reports the durable disable when the failure budget latches the control offexpected [] to deeply equal [ObjectContaining{...}]— no event emittedGates, all from
cloud/:pnpm --filter @orca-cloud/relay testwithORCA_RELAY_TEST_POSTGRES_URLon port 55440 — 72 files, 635 tests passed. Postgres-backed suites confirmed executing, not skipped (regional-rehome-postgres.test.ts: 20 passed against a real PostgreSQL 16).pnpm typecheck— clean across all 4 projects.pnpm lint— clean across all 4 projects.Note on the brief
The method described as
setRegionalRehomeControlis actually namedapplyRegionalRehomeControl. Everything else in the description matched the code.