Repository navigation
fix(relay): wait out a cold proxy at boot instead of exiting the cell - #21516
Conversation
A cell container starts its relay process beside a cloud-sql-proxy that is itself still dialling. The first pool acquire therefore competes with a proxy cold start, and the 2s connect timeout that protects the request path fires before the proxy is listening. `openRelayDatabase` rejects out of the region backfill, the top-level await rejects, and the process exits; COS restarts the container and the next boot succeeds 1-3s later. The 2026-09-18 fleet roll saw 0-7 of these per cell, including on cells with zero hosts, so it is a property of the boot sequence rather than of database load. The boot open now retries on transient errors only, inside a 45s wall-clock window with exponential backoff from 250ms to 4s. The classifier is the one the request path already uses, so a rejected credential or a bad URL still exits on the first attempt. Each wait logs `orca_relay_boot_database_retry` and a give-up logs `orca_relay_boot_database_failed`, both with the bounded error category, so a rollout can tell a slow boot from a stuck one without reading container exit codes. The bounded startup retry is lifted out of `reconcileCellAdmissionAtStartup`, which had the same loop; its attempt budget, flat delay, and both log events are unchanged (a flat delay is a cap equal to the base).
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughThe change adds a shared bounded retry helper for transient database startup failures. Cell admission reconciliation uses this helper. Relay boot database opening now retries unreachable database failures with backoff and logs retry, recovery, and failure events. The database open input type is exported. PostgreSQL error-code categorization is centralized. Tests cover recovery, immediate failures, lock-contention failures, and retry exhaustion. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Relay startup can exceed its 45-second retry budget by a full final database-open attempt. Add a post-sleep deadline check before merging. 🚥 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, risks, and checklist. However, the required Linked Issue section is incomplete because it states there is no issue and leaves
✨ 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: 3dbf68e7-48a3-40da-97b8-6a8e1ae232e5
📒 Files selected for processing (7)
cloud/apps/relay/src/boot-database-open.test.tscloud/apps/relay/src/boot-database-open.tscloud/apps/relay/src/cell-admission-startup.tscloud/apps/relay/src/database-startup-retry.tscloud/apps/relay/src/database.tscloud/apps/relay/src/index.tscloud/apps/relay/src/postgres-query-failure.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs) | ||
| observer.onRetry?.({ attempt, delayMs, error }) | ||
| await new Promise((resolve) => setTimeout(resolve, delayMs)) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Check the deadline again before the next operation.
delayMs can consume all remaining time. The loop then starts another operation() after retryDeadline. This final attempt can extend startup by the full database connection timeout.
Check Date.now() after the sleep. If the deadline has expired, call onGaveUp and rethrow the current error.
Proposed fix
const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs)
observer.onRetry?.({ attempt, delayMs, error })
await new Promise((resolve) => setTimeout(resolve, delayMs))
+ if (Date.now() >= retryDeadline) {
+ observer.onGaveUp?.({ attempts: attempt, error, transient })
+ throw error
+ }📝 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.
| const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs) | |
| observer.onRetry?.({ attempt, delayMs, error }) | |
| await new Promise((resolve) => setTimeout(resolve, delayMs)) | |
| const delayMs = Math.min(retryDelayMs(policy, attempt), remainingMs) | |
| observer.onRetry?.({ attempt, delayMs, error }) | |
| await new Promise((resolve) => setTimeout(resolve, delayMs)) | |
| if (Date.now() >= retryDeadline) { | |
| observer.onGaveUp?.({ attempts: attempt, error, transient }) | |
| throw error | |
| } |
The boot open re-runs the schema apply, and applyPostgresSchema refuses to repeat a DDL lock timeout on purpose: relation locks are granted in queue order, so a repeat parks every writer behind the same statement again. Gating the boot retry on the full request-path classifier would have re-queued it up to 16 times in 45s on sustained 55P03 - the mechanism behind the 2026-09-16 outage. The boot call site now has its own predicate: pool connect failures (both connect-timeout messages and an acquire-marked early-ended socket) plus 08001 and 08006. Lock and overload SQLSTATEs - 55P03, 57014, 53300 - exit on the first attempt. The retry predicate moves onto the policy because what a step re-runs, not the request path, decides what it may repeat; the startup reconcile keeps the full classifier, which is what lets it wait out 55P03.
There was a problem hiding this comment.
ℹ️ No critical issues — two defer-able test/observability nits.
Reviewed changes
- Boot database retry —
index.tsnow opens the database throughopenRelayDatabaseAtBoot, which retriesopenRelayDatabaseonly on transient errors within a 20-attempt / 45s window using exponential backoff (250ms → 4s plus jitter). - Shared startup retry — the director reconcile retry loop is lifted into
database-startup-retry.tsand both callers use it; reconcile keeps its exact attempt budget, flat 250ms delay (baseDelayMs === maxDelayMs), and both log events. - Bounded error categories —
postgresErrorCodeCategoryis extracted fromreportPostgresQueryFailureand reused by the new boot logs, which emit only allowlisted codes plus aconnectionTimeoutboolean.
The refactor preserves reconcile semantics exactly, and retrying the whole open is safe: openRelayDatabase closes what it built on throw, the untimed schema pool closes in its finally, and the schema apply is catalog-prechecked and idempotent. The classifier covers the fleet's Connection terminated due to connection timeout via message match, and no raw driver text reaches the logs.
ℹ️ Nitpicks
boot-database-open.test.ts:43asserts onlydelayMs: expect.any(Number), so the exponential 250ms → 4s sequence the PR body documents is not pinned — a regression to a flat delay would still pass. Asserting the first few delays would protect the mechanism.postgres-query-failure.ts:5omits28P01, so a password-auth boot failure logscode: 'unknown'on the neworca_relay_boot_database_failedevent (asserted atboot-database-open.test.ts:60). Since boot diagnostics are the point of the new event, adding that fixed SQLSTATE (no credential risk) would make the most common permanent failure identifiable.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since 3e792fa)
- Narrowed boot retry gate — the boot open now retries only
isBootDatabaseUnreachable: the pool's connect-timeout messages, an acquire-boundaryConnection terminated unexpectedly, and SQLSTATE08001/08006.55P03,57014,53300,40001,40P01, and57P03are now terminal at boot, so the schema apply is never re-queued behind writers. - Per-caller retry predicate —
DatabaseStartupRetryPolicygains an optionalisRetryable; the shared loop defaults toisRelayDatabaseTransientError, so the director reconcile keeps the full classifier, attempt budget, and both log events unchanged. The observer field renametransient→retryableis applied consistently. - Tests — new cases pin
55P03/57014/53300exiting on the first attempt with no retry event, plus08006being retried.
I checked the DDL rationale against apply-postgres-schema.ts: with retryLockTimeout unset it throws 55P03 immediately rather than re-queueing, so excluding it from the boot gate is exactly what avoids the 2026-09-16 re-queue pattern. The observed fleet error (Connection terminated due to connection timeout) is still matched by isPostgresPoolConnectFailure, so the fix still covers the reported crash.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
When a relay cell machine starts up, two programs start at the same time: the relay itself, and a small helper that opens the connection to the database. The relay asked for the database straight away, gave up after two seconds when the helper was not ready yet, and killed itself. The machine then restarted it and everything was fine. This teaches the relay to wait a moment and ask again instead of dying.
What Changed
Before (what an operator sees): during a fleet roll, a freshly started cell logs
Connection terminated due to connection timeoutand the container exits before it ever serves a request. Container-OS restarts it and the next boot succeeds one to three seconds later. On the 2026-09-18 roll (21 cells) every cell did this between zero and seven times — one cell restarted seven times in 23 seconds — including two canary cells carrying no hosts at all. Nothing is lost, but each crash costs a boot cycle and thecontainer dieevents make it hard to tell a healthy roll from a failing one.After: the same cold start logs one or two
orca_relay_boot_database_retrylines and then serves. No container exit, no restart, and the rollout log says plainly what happened.Mechanism: the boot sequence opens the database (
openRelayDatabase) before anything else — schema apply, then a small region backfill. Both use a pool with a 2 second connect timeout, which exists to keep a request from hanging on the pool; the very first acquire of the process runs whilecloud-sql-proxyis still starting, so it can legitimately exceed that. The rejection reaches a top-levelawaitin the entrypoint, which ends the process.That first open now runs through
openRelayDatabaseAtBoot, which retries only when Postgres could not be reached at all, bounded by a 45 second wall-clock window with exponential backoff (250ms, 500ms, 1s, 2s, then 4s).Retried:
timeout exceeded when trying to connect,Connection terminated due to connection timeout),Connection terminated unexpectedlyonly when it was seen at the acquire boundary, so a socket that ended mid-statement is never repeated,08001and08006(client cannot establish / connection failure).Not retried — the process exits on the first attempt, as today:
55P03lock not available,57014statement timeout,53300too many connections,40001/40P01serialization and deadlock,57P03cannot connect now,That exclusion is deliberate and is the one place this differs from the request path's transient classifier. A boot retry re-runs the schema apply, and
applyPostgresSchemarefuses to repeat a DDL lock timeout on purpose: relation locks are granted in queue order, so repeating the statement parks every writer behind it again for another timeout. Retrying a55P03up to sixteen times in a 45 second window is the mechanism behind the 2026-09-16 outage, so the boot loop must not re-queue it. The director's startup reconcile (reconcileCellAdmissionAtStartup) keeps the full classifier — it re-runs one statement, not DDL, and waiting out55P03is exactly what it is for.Each wait emits
orca_relay_boot_database_retry(attempt, delayMs, bounded error code, connectionTimeout), a late success emitsorca_relay_boot_database_recovered, and giving up emitsorca_relay_boot_database_failed(attempts, retryable, code) before the process exits. Error codes are emitted only from the existing recognised-code list, never raw messages, because a driver message can carry a credential.Readiness semantics, schema-apply behaviour, and the runtime pool timeouts are untouched: this only changes what happens between "process starts" and "database handle exists", which is before anything reports ready.
The bounded retry loop itself already existed in
reconcileCellAdmissionAtStartup(director startup reconcile). Rather than write a second copy, it is lifted intodatabase-startup-retry.tsand both callers use it. The reconcile keeps its exact attempt budget, flat 250ms delay, and both of its log events — a flat delay is expressed as a backoff cap equal to the base.Why
The crash is systematic, not load-dependent: it happens on cells with no hosts and is independent of Cloud SQL pressure. It is a race between two processes in the same container, and the relay is the one that can wait.
Alternatives considered:
openRelayDatabasecloses what it built before it throws, and the schema apply is idempotent and catalog-pre-checked — but only because the retry gate excludes lock timeouts, so no DDL is ever re-queued.55P03, which would have had a contended boot re-queue the same DDL sixteen times.Linked Issue
No GitHub issue: this came out of the 2026-09-18 production fleet roll rather than a filed report.
Fixes #
Visual Proof
N/A — server-side boot behaviour with no UI surface. The observable change is in the cell's container log (
orca_relay_boot_database_retryinstead of a process exit).Testing
cd cloud/apps/relay && pnpm test src/boot-database-open.test.ts src/cell-admission-startup.test.ts src/database-transient-error.test.ts src/postgres-query-failure.test.ts— 4 files, 40 tests passed.Full relay unit project (
npx vitest run --project relay): 67 files, 716 passed, 1 skipped.Full relay Postgres project against a throwaway
postgres:16-alpine: 24 files, 130 passed.pnpm typecheckandpnpm buildincloud/apps/relay: clean.New tests cover: a connect timeout retried and then succeeding; an
08006connection failure retried; a rejected credential exiting on the first attempt;55P03,57014and53300each exiting on the first attempt with no retry event, so the schema apply is never re-queued; and the retry budget exhausting within the 45 second window and emitting the final failure event.Platforms: the relay runs on Linux (Container-Optimized OS) only; tested on macOS by unit test, and the change is platform-independent Node.
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
Security: no new logged field can carry a credential — error codes pass through the existing recognised-code allowlist and messages are never logged. Backwards compatibility: no wire, schema, or readiness change; a cell running this code is indistinguishable from the old one once booted. Performance: the retry path only runs before the process serves anything, and a healthy boot takes the exact same path as before.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)