Repository navigation
fix(relay): serve readiness from last-known-good during auth or SQL blips - #21161
Conversation
…lips The load balancer health check hits /ready, which re-probed the auth JWKS endpoint and Postgres on every poll and reported not-ready on the first failure. On 2026-09-16 an auth outage therefore took every cell out of the load balancer within ~30s and dropped every connected host, even though the token verifier caches keys in process and kept verifying tokens. /ready now remembers when each dependency last answered and keeps reporting ready while the failed one stays inside a grace window (ORCA_RELAY_READINESS_GRACE_MS, default 15 minutes, 0 disables). A process that has never succeeded still gates on the real dependencies, so cold boot is unchanged. Grace answers carry degraded plus the failure reason on the existing readiness observation, and entering or leaving grace logs once. MIG autohealing still uses the dependency-free /health endpoint.
… poll
Review follow-ups on the last-known-good readiness window.
An unset environment variable arrives as an empty string, which z.coerce
reads as 0, so the single ORCA_RELAY_READINESS_GRACE_MS would have switched
the window off instead of falling back to its default. The two replacement
variables preprocess '' to undefined.
JWKS and SQL now get separate windows and separate clocks:
ORCA_RELAY_READINESS_JWKS_GRACE_MS defaults to 15 minutes, and
ORCA_RELAY_READINESS_SQL_GRACE_MS to 3 minutes. Each cell is its own load
balancer backend, so failing readiness never re-routes a host, it only makes
that hostname unreachable, and a host that lands on a SQL-dead cell gets
WRONG_CELL and is re-placed by the director. Three minutes rides a Cloud SQL
failover without hiding a per-cell fault for a quarter of an hour.
Both dependencies are probed on every poll. A JWKS failure used to
short-circuit the SQL probe, which let the SQL clock age with no evidence
behind it. Grace transitions are emitted per dependency, so JWKS recovering
while SQL fails logs both sides instead of nothing.
/ready keeps its 200 and its {ok:true} body when healthy, and adds
degraded plus the dependency list when the answer comes from a window.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor semantic inconsistency in the readiness observation, plus an operational note.
Reviewed changes
- Per-dependency last-known-good clocks —
relay-readiness.tsreplaces the fail-on-first-error probe with aRelayReadinessProbethat tracks a separate success timestamp per dependency and keeps the cell ready while a failed dependency sits inside its own window (jwks15 min,sql3 min, both0-disablable). - Both dependencies probed every poll —
check()runsprobeJwksandprobeSqlconcurrently throughPromise.all, so a SQL clock can no longer age with no evidence behind it, andfailuresreports both when they fail together. - Grace events — entering, recovering, and expiring each emit exactly one
orca_relay_readiness_grace_entered/_leftevent viarecordReadinessGrace, carryingdependency,failure,lastSuccessAgeMs, andgraceMs. /readybody — still 503 when not ready and still{ok:true}when healthy, but a windowed answer is{ok:true, degraded:true, dependency:[...]}; a degraded answer logs at WARNING.- Config plumbing —
ORCA_RELAY_READINESS_{JWKS,SQL}_GRACE_MSare bounded0..3_600_000, with''preprocessed back to undefined so an unset Cloud Run variable means the default, never "window off". - Tests — new
relay readiness last-known-good gracesuite (window boundaries, restart-from-last-success, per-dependency isolation, both sides of an overlap, SQL probed during JWKS failure, cache-vs-grace interaction), a new/readyendpoint suite, the two new observability records, and the config default/unset cases.
ℹ️ The new degraded state is visible only in logs, while the existing ops detectors still read /ready as a hard dependency check
/ready can now return 200 for up to 15 minutes while the auth JWKS endpoint is unreachable, and up to 3 minutes while Postgres is. relay-ops' incident-monitor.ts:415 (cell.<id>.ready equal 1) and the Terraform/ops docs (cloud/infra/terraform/README.md:313, cloud/docs/orca-relay-operations.md:103) describe /ready as the SQL/JWKS-backed gate, and nothing is updated to consume the new orca_relay_readiness_grace_entered event or the body's degraded flag. The PR body calls this out and says the grace logs are where the state is visible, but as it stands no monitor rule or alert keys off them, so the only automated cell-level detector reads green through a real auth outage.
Technical details
# New readiness state has no detector
## Affected sites
- `cloud/apps/relay-ops/src/incident-monitor.ts:415` — emits `cell.<id>.ready` from the HTTP status; stays 1 through a window.
- `cloud/infra/terraform/README.md:313` — "SQL/JWKS-backed `/ready` controls LB admission".
- `cloud/docs/orca-relay-operations.md:103` — "dependency-backed `/ready`" in the preflight description.
## Required outcome
- Decide whether a dependency outage should continue to surface as a cell-level fault while inside
the grace window. If yes, add a signal that reads the new state (e.g. a rule on
`orca_relay_readiness_grace_entered`, or have `/ready` consumers treat
`degraded: true` as a distinct health state), and note the window in the ops doc that calls
`/ready` dependency-backed.
## Open questions for the human
- Is the silence during the window intended to also suppress paging for an auth outage, or is the
grace meant only to keep the cell in LB rotation while a separate signal still fires?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| jwksLatencyMs: Math.max(0, jwksCompletedAt - startedAt), | ||
| sqlLatencyMs: failure?.startsWith('jwks_') ? 0 : Math.max(0, completedAt - sqlStartedAt), | ||
| ...(failures.length > 1 ? { failures } : {}), | ||
| ...(degraded.length > 0 ? { degraded: true, degradedDependencies: [...degraded] } : {}), |
There was a problem hiding this comment.
When one dependency's window has expired while the other is still inside its window (e.g. JWKS failed 1 min ago, SQL failed 4 min ago), degraded is populated even though cached is false. The observation then reads ready: false with degraded: true, degradedDependencies: ['jwks'], which contradicts both the field's meaning (the answer is served from last-known-good) and what /ready exposes — the endpoint only emits degraded when ready() is true.
Technical details
# `degraded` is not gated on the overall ready answer
## Affected sites
- `cloud/apps/relay/src/relay-readiness.ts:165-175` — `degraded` is built from the per-dependency settlements only; `cached` is not consulted.
## Required outcome
- A record with `ready: false` must not claim it is being served from last-known-good, so the `degraded`/`degradedDependencies` fields should only appear when the combined answer is ready.
## Suggested approach
- Gate the spread on `cached && degraded.length > 0`. The per-dependency diagnosis is still available through `failure`/`failures` in the not-ready case.| ...(degraded.length > 0 ? { degraded: true, degradedDependencies: [...degraded] } : {}), | |
| ...(cached && degraded.length > 0 ? { degraded: true, degradedDependencies: [...degraded] } : {}), |
📝 WalkthroughWalkthroughRelay readiness now probes JWKS and SQL concurrently with independent grace periods. It reports degraded dependencies while prior successful checks remain within grace. It emits grace transition events and exposes a probe object with Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to A dependency can remain readiness-covered longer than its configured grace period after it fails, potentially keeping the relay ready while that dependency is unavailable. Correct the per-probe timestamping before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the change, rationale, testing, visual proof, risks, and checklist. However, the required Linked Issue section contains “N/A,” while the template requires an issue link.
✨ 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: 8f67c0e5-8a1b-4944-9e95-c0818fed7350
📒 Files selected for processing (9)
cloud/apps/relay/src/app.tscloud/apps/relay/src/config.test.tscloud/apps/relay/src/config.tscloud/apps/relay/src/relay-observability.test.tscloud/apps/relay/src/relay-observability.tscloud/apps/relay/src/relay-readiness.test.tscloud/apps/relay/src/relay-readiness.tscloud/apps/relay/src/relay-ready-endpoint.test.tscloud/apps/relay/src/relay-server.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| return { value, latencyMs: Math.max(0, now() - startedAt) } | ||
| } | ||
|
|
||
| export function createRelayReadiness( | ||
| database: RelayDatabase, | ||
| jwksUrl: string, | ||
| options: RelayReadinessOptions = {} | ||
| ): () => Promise<boolean> { | ||
| ): RelayReadinessProbe { | ||
| const fetchImpl = options.fetch ?? fetch | ||
| const timeoutMs = options.timeoutMs ?? 2_000 | ||
| const cacheMs = options.cacheMs ?? 10_000 | ||
| const now = options.now ?? Date.now | ||
| const settleJwks = createDependencyGrace( | ||
| 'jwks', | ||
| options.jwksGraceMs ?? RELAY_READINESS_JWKS_GRACE_MS | ||
| ) | ||
| const settleSql = createDependencyGrace('sql', options.sqlGraceMs ?? RELAY_READINESS_SQL_GRACE_MS) | ||
| let cachedAt = Number.NEGATIVE_INFINITY | ||
| let cached = false | ||
| let lastObservedReady: boolean | undefined | ||
| let degraded: RelayReadinessDependency[] = [] | ||
|
|
||
| return async () => { | ||
| if (now() - cachedAt < cacheMs) return cached | ||
| const startedAt = now() | ||
| let jwksCompletedAt = startedAt | ||
| let sqlStartedAt = startedAt | ||
| let failure: RelayReadinessFailure | undefined | ||
| const probeJwks = async (): Promise<RelayReadinessFailure | undefined> => { | ||
| try { | ||
| let response: Response | ||
| try { | ||
| response = await fetchImpl(jwksUrl, { signal: AbortSignal.timeout(timeoutMs) }) | ||
| } catch (error) { | ||
| failure = fetchFailure(error) | ||
| throw error | ||
| } finally { | ||
| jwksCompletedAt = now() | ||
| } | ||
| if (!response.ok) { | ||
| failure = 'jwks_http_failed' | ||
| throw new Error(failure) | ||
| } | ||
| sqlStartedAt = now() | ||
| try { | ||
| await database.query('SELECT 1 AS ready') | ||
| } catch (error) { | ||
| failure = 'sql_failed' | ||
| throw error | ||
| } | ||
| const response = await fetchImpl(jwksUrl, { signal: AbortSignal.timeout(timeoutMs) }) | ||
| return response.ok ? undefined : 'jwks_http_failed' | ||
| } catch (error) { | ||
| return fetchFailure(error) | ||
| } | ||
| } | ||
|
|
||
| const probeSql = async (): Promise<RelayReadinessFailure | undefined> => { | ||
| try { | ||
| await database.query('SELECT 1 AS ready') | ||
| return undefined | ||
| } catch { | ||
| // The load balancer only needs the boolean; the safe reason is emitted below. | ||
| // The load balancer only needs the boolean; the safe reason is all that is emitted. | ||
| return 'sql_failed' | ||
| } | ||
| } | ||
|
|
||
| const check = async (): Promise<boolean> => { | ||
| if (now() - cachedAt < cacheMs) return cached | ||
| const startedAt = now() | ||
| const [jwks, sql] = await Promise.all([timed(now, probeJwks), timed(now, probeSql)]) | ||
| const completedAt = now() | ||
| cached = failure === undefined | ||
| const jwksSettlement = settleJwks(completedAt, jwks.value) | ||
| const sqlSettlement = settleSql(completedAt, sql.value) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '60,200p' cloud/apps/relay/src/relay-readiness.ts
rg -n 'completedAt|lastSuccess|graceMs|timed\\(' cloud/apps/relay/src/relay-readiness.ts cloud/apps/relay/src/relay-readiness.test.tsRepository: stablyai/orca
Length of output: 4771
🏁 Script executed:
#!/bin/bash
sed -n '1,260p' cloud/apps/relay/src/relay-readiness.test.ts
printf '\n--- related references ---\n'
rg -n -C 3 'cacheMs|jwksGraceMs|sqlGraceMs|createDependencyGrace|lastSuccessAt|completedAt' cloud/apps/relay/src cloud/apps/relayRepository: stablyai/orca
Length of output: 41022
Use each dependency's completion time for its grace clock.
completedAt is recorded only after both probes finish. If JWKS succeeds quickly and SQL finishes much later, the JWKS success is recorded at the SQL completion time. A subsequent JWKS failure can therefore remain grace-covered longer than jwksGraceMs after the actual successful JWKS probe.
Return a completion timestamp from timed, then pass each dependency's timestamp to its settlement function.
Proposed fix
async function timed<T>(
now: () => number,
run: () => Promise<T>
-): Promise<{ value: T; latencyMs: number }> {
+): Promise<{ value: T; latencyMs: number; completedAt: number }> {
const startedAt = now()
const value = await run()
- return { value, latencyMs: Math.max(0, now() - startedAt) }
+ const completedAt = now()
+ return {
+ value,
+ latencyMs: Math.max(0, completedAt - startedAt),
+ completedAt
+ }
}- const jwksSettlement = settleJwks(completedAt, jwks.value)
- const sqlSettlement = settleSql(completedAt, sql.value)
+ const jwksSettlement = settleJwks(jwks.completedAt, jwks.value)
+ const sqlSettlement = settleSql(sql.completedAt, sql.value)…lips (stablyai#21161) * fix(relay): serve readiness from last-known-good during auth or SQL blips The load balancer health check hits /ready, which re-probed the auth JWKS endpoint and Postgres on every poll and reported not-ready on the first failure. On 2026-09-16 an auth outage therefore took every cell out of the load balancer within ~30s and dropped every connected host, even though the token verifier caches keys in process and kept verifying tokens. /ready now remembers when each dependency last answered and keeps reporting ready while the failed one stays inside a grace window (ORCA_RELAY_READINESS_GRACE_MS, default 15 minutes, 0 disables). A process that has never succeeded still gates on the real dependencies, so cold boot is unchanged. Grace answers carry degraded plus the failure reason on the existing readiness observation, and entering or leaving grace logs once. MIG autohealing still uses the dependency-free /health endpoint. * fix(relay): split readiness grace per dependency and probe both every poll Review follow-ups on the last-known-good readiness window. An unset environment variable arrives as an empty string, which z.coerce reads as 0, so the single ORCA_RELAY_READINESS_GRACE_MS would have switched the window off instead of falling back to its default. The two replacement variables preprocess '' to undefined. JWKS and SQL now get separate windows and separate clocks: ORCA_RELAY_READINESS_JWKS_GRACE_MS defaults to 15 minutes, and ORCA_RELAY_READINESS_SQL_GRACE_MS to 3 minutes. Each cell is its own load balancer backend, so failing readiness never re-routes a host, it only makes that hostname unreachable, and a host that lands on a SQL-dead cell gets WRONG_CELL and is re-placed by the director. Three minutes rides a Cloud SQL failover without hiding a per-cell fault for a quarter of an hour. Both dependencies are probed on every poll. A JWKS failure used to short-circuit the SQL probe, which let the SQL clock age with no evidence behind it. Grace transitions are emitted per dependency, so JWKS recovering while SQL fails logs both sides instead of nothing. /ready keeps its 200 and its {ok:true} body when healthy, and adds degraded plus the dependency list when the answer comes from a window.

ELI5
Every relay machine answers a "are you ready for traffic?" question that the load balancer asks every 10 seconds. It used to answer "no" the instant the login service or the database hiccuped, even though it was still happily carrying thousands of live connections. The load balancer took it out of rotation, and everyone connected to it got dropped. Now a machine that answered "yes" a moment ago keeps answering "yes" for a while longer while that dependency is down, and it says so out loud in the logs and in its own answer.
What Changed
Before:
/readyfetched the auth JWKS document (uncached, 2 second timeout) and then ranSELECT 1, and returned 503 on the first failure of either. The load balancer health check has an unhealthy threshold of 2 at a 10 second interval, so a shared dependency failure marked every cell unhealthy in about 30 seconds and every connected host was dropped. That is what happened on 2026-09-16: auth returned 5xx for roughly 40 minutes, all 23 cells went unhealthy, and about 15k connections were cut. The cells themselves were fine, and the real token verifier caches JWKS keys in process, so it kept verifying tokens the whole time.After:
/readyremembers when each dependency last answered successfully and keeps reporting ready while the failed one is inside its own window. Past the window it reports not ready exactly as before. A process that has never had a successful probe stays not ready, so a cold boot still gates on real dependencies.Mechanism details:
ORCA_RELAY_READINESS_JWKS_GRACE_MSdefaults to 15 minutes,ORCA_RELAY_READINESS_SQL_GRACE_MSto 3 minutes. Both are bounded to 0 through 3,600,000 ms, and0disables that window and restores the old fail-on-first-error answer. Each dependency tracks its own last success, so a healthy JWKS poll cannot hold a dead Postgres inside its window.orca_relay_readiness_grace_enteredandorca_relay_readiness_grace_left, carryingdependency, whether leaving wasrecoveredorexpired, the age of the last success, and the window in force. JWKS recovering at the same moment SQL fails logs both sides rather than nothing.degraded: true,degradedDependencies, andfailures(when both dependencies failed in the same poll) join the existing payload. The event name cells publish,orca_relay_readiness_check, is unchanged, so existing log queries and dashboards keep working. A degraded answer now logs at WARNING rather than INFO./readysays so in its body. Status code and the healthy body are unchanged: 200 with{"ok":true}. When the answer comes from a window it is 200 with{"ok":true,"degraded":true,"dependency":["sql"]}.cacheMs) and theobservecallback are untouched./healthendpoint. That split is deliberate and is not changed here.Why
The load balancer check turned an auth outage into a relay outage. A cell that cannot reach the JWKS host or Postgres cannot accept new hosts, but the connections it already carries keep working, so removing it from rotation destroys far more than it protects.
The two windows are different lengths because the two failures mean different things. Auth key rotation is rare and the token verifier caches keys in process, so a cell rides out a JWKS outage with no loss of function at all. A cell that cannot reach Postgres is more compromised, but still not usefully removed: each cell is its own load balancer backend, so failing readiness never re-routes a host, it only makes that hostname unreachable. A host that reaches a SQL-dead cell for a new session gets
WRONG_CELLand is re-placed by the director, and existing control sockets survive a generic Postgres error. Three minutes rides a Cloud SQL failover; per-cell SQL faults are real, so the window stops well short of hiding one for a quarter of an hour.Alternatives considered:
/ready. Rejected: it is the check that keeps a genuinely broken cell out of rotation at boot, and dropping it means a cell that can never verify a token still advertises itself as ready.Linked Issue
N/A. This came out of the 2026-09-16 auth incident review rather than a tracked issue.
Visual Proof
N/A. This is a backend health-check endpoint with no user interface.
Testing
Unit tests only. This is server-side logic with no platform-specific code, no path handling, and no client-facing wire change.
Relay suite:
Test Files 63 passed | 20 skipped (83),Tests 645 passed | 104 skipped (749).Relay-ops suite:
Test Files 12 passed (12),Tests 96 passed (96).New tests in
cloud/apps/relay/src/relay-readiness.test.ts, suiterelay readiness last-known-good grace:New file
cloud/apps/relay/src/relay-ready-endpoint.test.ts:New tests in
cloud/apps/relay/src/relay-observability.test.ts:New tests in
cloud/apps/relay/src/config.test.ts:defaults readiness grace to fifteen minutes for JWKS and three for SQL
reads an unset readiness grace variable as the default, never as zero
I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
cloud/infra, so production runs on the defaults. Turning a window off, which is the kill switch for this change, needs a Terraform change to reach production. No Terraform edit is included here.z.coerce.number()reads that as 0. Both variables preprocess''back to undefined so an unset value means the default and never means "window off". Covered by a test./ready, never its body, so the added fields change nothing for them. The consequence worth knowing is thatcell.<id>.readystays 1 while a cell is serving from a window, which is the intended behaviour; the grace log events are where that state is visible.relay-token-verifier.ts) and is unchanged; this only affects whether the load balancer keeps sending traffic to a cell. The observation payload still carries only the fixed failure reason strings, never error text, so nothing sensitive reaches the logs.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)