Skip to content

fix(relay): keep failed rehome polls out of the durable failure budget - #19915

Merged
Jinwoo-H merged 2 commits into
mainfrom
relay/rehome-failure-budget
Sep 10, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
relay/rehome-failure-budget

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​204 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​197
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​58 $\color{#cf222e}{\Huge{\mathbf{−}}}$​36 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​22

The bug

The regional rehome worker polls claimRegionalRehome roughly once a second. Its catch routed any error thrown before an attempt was claimed into assignments.recordRegionalRehomeWorkerFailure(), which increments the durable relay_region_rehome_worker_state.consecutive_failures budget 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. claimRegionalRehome is already correct: it throws infrastructure errors and lets the caller decide. The defect is the caller's classification — attemptId ? dispatch : worker treats "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 sqlFailures and pool pressure, and the store's one existing swallow is a deliberately narrow isDatabaseLockUnavailable predicate, not a blanket catch.

A pre-claim failure now logs orca_relay_regional_rehome_poll_failed rather than ..._dispatch_failed — those pool timeouts were being reported as failed drains, which is precisely the misreading that hid this. recordRegionalRehomeWorkerFailure had 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_control and never touched the worker row. It now resets consecutive_failures and paused_until in the same transaction, in the same control-then-worker lock order claimRegionalRehome uses. next_dispatch_at is 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, carrying controlGeneration and consecutiveFailures, following the existing orca_relay_regional_rehome_safety_disabled precedent and logged after the transaction commits so a rollback cannot fabricate it. Only the enabled=1 -> 0 transition 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 (recordRegionalRehomeDispatchFailure requires 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_at column 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:

Test Red on main
keeps a failed poll out of the durable dispatch-failure budget TypeError: assignments.recordRegionalRehomeWorkerFailure is not a function — the worker demonstrably reaches for the durable budget on a pre-claim error
clears a stale failure budget when the control is enabled again consecutiveFailures: 3, pausedUntil: 87700000 survive the enable (expected 0, 0)
reports the durable disable when the failure budget latches the control off expected [] to deeply equal [ObjectContaining{...}] — no event emitted

Gates, all from cloud/:

  • pnpm --filter @orca-cloud/relay test with ORCA_RELAY_TEST_POSTGRES_URL on 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 setRegionalRehomeControl is actually named applyRegionalRehomeControl. Everything else in the description matched the code.

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.
@coderabbitai

coderabbitai Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The 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 401d4

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary fix: failed regional rehome polls no longer consume the durable failure budget. It is concise and related to the main change.
Description check ✅ Passed The description is detailed and covers the bug, implementation, scope, design rationale, tests, and validation results. It does not provide the required linked issue, Visual Proof N/A statement, or co…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 621617fa-7a8e-460a-a9e2-d166058e10f8

📥 Commits

Reviewing files that changed from the base of the PR and between 26f9fd8 and 3c74187.

📒 Files selected for processing (4)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/regional-rehome-store.test.ts
  • cloud/apps/relay/src/regional-rehome-worker.test.ts
  • cloud/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Pre-claim poll failures escape the durable budget — regional-rehome-worker.ts now 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) logs orca_relay_regional_rehome_poll_failed and never touches the budget.
  • Enable clears a stale budget — applyRegionalRehomeControl resets consecutive_failures/paused_until in the same control-then-worker lock order claimRegionalRehome uses, leaving next_dispatch_at untouched so rate limiting survives.
  • Durable auto-disable emits a structured event — incrementRegionalRehomeWorkerFailure returns an orca_relay_regional_rehome_failure_budget_disabled record, logged after the transaction commits and only on the enabled=1 → 0 transition.
  • 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 9528c9da-ea37-4d91-9195-9646ece25ec0

📥 Commits

Reviewing files that changed from the base of the PR and between 3c74187 and 401d45a.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/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 })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

Suggested change
}, { interval: 10, timeout: 800 })
}, { interval: 10, timeout: 5_000 })

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Failure accounting now locks the control row first — recordRegionalRehomeDispatchFailure takes relay_region_rehome_control before the worker row, matching the control → worker → attempt order used by claimRegionalRehome and applyRegionalRehomeControl. 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 retries drives 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit a6e6de9 into main Sep 10, 2026
25 checks passed
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