Skip to content

fix(relay): a lost database reply ends its connection within statement timeout + 10 s - #26829

Merged
Jinwoo-H merged 5 commits into
mainfrom
relay-db-lost-reply-bound
Oct 9, 2026
Merged

Jinwoo-H merged 5 commits into
mainfrom
relay-db-lost-reply-bound

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​381 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​366
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​139 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​124

Stacked on #26817 (R1, the rejection fence). This PR's diff is only R2. Merge together with #26817: the fix-level bump to 2 is here.

ELI5

If a reply from the database gets lost on the network, the relay today can wait on that connection indefinitely, and other work queues up behind it. This PR gives every database call a hard deadline a little past the database's own, throws away a connection whose reply went missing, and makes sure nothing is committed after such a loss.

What Changed

  • Before: the request pool has statement_timeout (5 s) but no client-side read deadline. A reply lost in the network leaves the call hanging until TCP gives up (minutes), holding a pooled client, and if the caller later retried on the same client everything queued behind the dead statement.
  • After:
    • query_timeout = statement timeout + margin on the request pool only (the schema pool stays untimed). The margin defaults to 10 s (15 s total at the default 5 s statement timeout) and is set by ORCA_RELAY_POSTGRES_READ_TIMEOUT_MARGIN_MS (positive integer; no env change is needed to ship). It is that wide because whole-VM database stalls of 5–7 s are routine (connect-burst RCA) and delay replies the server already timed: a 2 s margin would fire inside them, destroying healthy clients and turning requests that succeed today into 503s.
    • Inside a transaction, a read timeout poisons it: every later statement rejects at once without being sent (so queryLocked's SET LOCAL lock_timeout restore never queues behind the dead statement), and transaction() throws before COMMIT even if the operation caught the error and returned normally. No ROLLBACK is sent; the client is released with the error, so pg-pool destroys it and the server drops its locks with the session. A read timeout on BEGIN or COMMIT takes the same path (a lost COMMIT reply is an unknown outcome, as 08006 already is). Never retried.
    • Autocommit statements that lose their reply also destroy their client instead of returning it to the pool.
    • idle_session_timeout = 30 s in the request pool's startup options bounds a backend orphaned outside a transaction. pg-pool closes healthy idle clients at 10 s, so it never fires on them. Because an options= in the database URL would silently replace this, the first session logs orca_relay_postgres_session_settings {idleSessionTimeout}; the director soak should read 30s there.
    • A read timeout counts as transient (isRelayDatabaseTransientError), so routes answer 503 + Retry-After as for 08006, and the R1 fence survives it if unawaited.
    • The server ending the session counts as transient too (staging found /v1/assign answering 500 29 times while backends were killed with pg_terminate_backend). New codes: 57P01/57P02 (session terminated or the server shutting down) and 08000/08003, alongside 08001/08006/57P03. Two more failures count only when the database layer threw them, because the same message from another socket means nothing about the database: pg's Connection terminated unexpectedly, and ECONNRESET. As with 08006, transaction() never retries any of these, because the commit outcome is unknown. EPIPE mid-statement is treated like ECONNRESET.
    • A failed connection attempt on a dead socket counts as transient (the staging re-test saw write EPIPE from the transaction's pool acquire during a Cloud SQL restart, answered 500). When the acquire fails with EPIPE, ECONNRESET, ECONNREFUSED, ETIMEDOUT or EHOSTUNREACH, it is now a pool connect failure like a connect timeout, because no statement ran. That also lets the boot open retry it while the database proxy comes up, and makes the control-renewal batch skip its per-host fallback. Acquire failures now count as database-layer errors.
    • A control-renewal batch that loses its reply fails whole, with no per-host fallback that would fan one stall into N statements.
  • Unchanged: ordinary server errors still roll back and retry as before.

Why

Design DESIGN-step2-cell-roll.md §2 (R2; reviews step2b-correctness B1/M2/M3/M4 and step2b-verify N1/N4), cut from step 2 with no PR and carried into step-5 prep (DESIGN-step3-and-step5-prep-2026-10-09.md §2.6). It is a prerequisite for the E-dep-3 drill and for step 4's cutover. Note for E-dep-3: its row "no DB call outlives 7 s" assumed the design's 2 s margin; with the review's 10 s margin the bound is 15 s, so that row should read 15 s. Poisoning the transaction rather than rolling back is what keeps the bound at one timeout: a ROLLBACK or a lock-timeout restore on the same client waits its own full timeout behind the dead statement. idle_session_timeout in the session options is image-only and touches no other service on the shared instance, unlike an instance flag or ALTER ROLE.

Known caller-visible effect (accepted in the design): a write whose reply was lost may have landed, and the caller sees a failure. Renewals and sweeps re-run; a counter committed high is released by lease expiry and reconcile.

Linked Issue

N/A (internal relay redesign; step-2 R2).

Visual Proof

N/A: server-only, no UI.

Testing

  • postgres-lost-reply.test.ts (fake pool): a bounded queryLocked that times out sends exactly BEGIN, SET LOCAL lock_timeout, the statement, then nothing (no restore, ROLLBACK, COMMIT or retry) and releases with the error; an operation that catches the timeout and returns still never reaches COMMIT, and later statements fail unsent; a lost COMMIT reply is not rolled back or retried; an autocommit timeout destroys its client and the next query is served; an ordinary 40P01 still rolls back and retries on a clean client.

  • Stall case (real PostgreSQL): the proxy holds a reply 6.5 s and then delivers it; with the default margin the query succeeds and the next query runs on the same backend (not destroyed). With the old 2 s margin this test fails at 2.5 s.

  • postgres-lost-reply-postgres.test.ts (real PostgreSQL, CI's service container; run locally against postgres:16-alpine): through a TCP proxy that drops the server's replies once the locked statement is sent, the transaction fails in under the read timeout + 1 s, nothing but pg's Terminate goes out after the statement, the next query succeeds on a fresh connection, and the row lock is free again. Request sessions report idle_session_timeout = 30s.

  • database-postgres-timeout.test.ts: pool config pins query_timeout 15 000 (12 500 with a 2 500 statement override) and the options, on the serving pool only; the margin env defaults to 10 s and refuses 0, negatives and non-integers.

  • database-transient-error.test.ts: 57P01, 57P02, 08000 and 08003 are transient. A Connection terminated unexpectedly or ECONNRESET coming out of PostgresDatabase.query is transient, and the same error built outside the database layer is not.

  • An acquire failing with each of EPIPE, ECONNRESET, ECONNREFUSED, ETIMEDOUT and EHOSTUNREACH is transient and the bare errno is not; PostgresDatabase.transaction over a pool whose connect throws write EPIPE rejects with a transient error (the staging stack).

  • Mutation check: reverting the poison and the no-ROLLBACK rule fails 4 of these tests, including the real-server one.

  • Fix level: RELAY_FIX_LEVEL 1 → 2 is in this PR, so it must merge together with fix(relay): a database fault reaching unhandledRejection no longer kills the process #26817 (same image).

  • vitest run in cloud/apps/relay with Postgres: all pass except three Postgres timing/load suites that fail the same way on origin/main in this environment (assignment-connection-headroom-postgres "releases an aborted older epoch…", postgres-transaction-recovery "defers completion…") or pass when run alone (drain-release-cell-row-contention-postgres, a lock-waiting mean under full-suite load). CI is the arbiter.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Runs on directors and cells. Canary abort signals (step-2 table): read timeouts while that cell's sqlLatencyMsMax is normal; relay backends > baseline + 10 (19 free on the shared instance); eventLoopDelayMsP99 > 1 s. Do not merge without the owner's go.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@Jinwoo-H
Jinwoo-H force-pushed the relay-db-lost-reply-bound branch from 2fb154b to 27adc6b Compare October 9, 2026 10:04
@Jinwoo-H Jinwoo-H changed the title fix(relay): a lost database reply ends its connection within statement timeout + 2 s fix(relay): a lost database reply ends its connection within statement timeout + 10 s Oct 9, 2026
@Jinwoo-H
Jinwoo-H force-pushed the relay-db-lost-reply-bound branch 3 times, most recently from a23d623 to 4951d7f Compare October 9, 2026 20:20
@Jinwoo-H
Jinwoo-H changed the base branch from relay-db-fault-no-crash to main October 9, 2026 20:58
…t timeout + 2 s

The request pool sets query_timeout to the statement timeout plus 2 s. A
read timeout poisons its transaction: later statements fail at once,
COMMIT never runs (even when the operation caught the error), no ROLLBACK
queues behind the dead statement, and the client is released with the
error so pg-pool destroys it. Autocommit statements destroy their client
too. The server bounds an orphaned idle backend with idle_session_timeout
30 s. A read timeout is answered 503 and never retried, and a renewal
batch that loses its reply fails whole instead of fanning out.
…database stalls never trip it

A whole-VM stall delays replies the server already timed. With a 2 s
margin the read timeout fired inside routine stalls, destroying healthy
clients and failing requests that succeed today. The margin is now 10 s
(ORCA_RELAY_POSTGRES_READ_TIMEOUT_MARGIN_MS), and a real-server test holds
a reply 6.5 s and requires it delivered on the same connection. The fix
level rises to 2 here, with the lost-reply fix.
…why it is safe

Boot open retries only an unreachable database. The director's startup
cell reconcile does retry a lost reply, which is safe: it re-runs upserts
and limit-change deletes that converge on the same rows.
…equest

Staging B1: pg_terminate_backend during /v1/assign returned 500 29 times.
57P01/57P02 and 08000/08003 join the transient SQLSTATEs; pg's
'Connection terminated' and ECONNRESET count only when the database layer
threw them. transaction() still never retries them.
Staging B1 re-test: a Cloud SQL restart failed PostgresDatabase.transaction's
acquire with 'write EPIPE', answered 500. An acquire failure with EPIPE,
ECONNRESET, ECONNREFUSED, ETIMEDOUT or EHOSTUNREACH is now a pool connect
failure (no statement ran), and acquire failures count as database-layer
errors. EPIPE mid-statement is treated like ECONNRESET.
@Jinwoo-H
Jinwoo-H force-pushed the relay-db-lost-reply-bound branch from 4951d7f to 38c80be Compare October 9, 2026 21:00
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Walkthrough

The PostgreSQL pool now configures a read-timeout margin and a 30-second idle-session timeout. Lost read replies poison transactions, prevent further statements, skip rollback and retry, and destroy affected clients. Failure classification covers additional PostgreSQL states and acquisition socket errors. Relay assignment renewal maps pool failures and read timeouts to database errors. Tests cover unit, integration, timeout, classification, and recovery behavior. The relay fix level increases from 1 to 2.


Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 38c80

An oversized read-timeout setting can cause serving queries to fail almost immediately and discard their connections. Validate the final deadline before merging.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 11 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 main change: ending a lost database connection within the PostgreSQL statement timeout plus a 10-second margin.
Description check Passed The description is detailed and covers the required change summary, rationale, testing, visual proof, checklist, and operational notes. The Linked Issue section says N/A even though the template reque…
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 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: 65a48d65-86eb-47b3-8199-47a19d1a4342
📥 Commits

Reviewing files that changed from the base of the PR and between d358e59 and 38c80be.

📒 Files selected for processing (11)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/cell-admission-startup.ts
  • cloud/apps/relay/src/database-postgres-timeout.test.ts
  • cloud/apps/relay/src/database-transient-error.test.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/postgres-lost-reply-postgres.test.ts
  • cloud/apps/relay/src/postgres-lost-reply.test.ts
  • cloud/apps/relay/src/postgres-pool-pressure.ts
  • cloud/apps/relay/src/postgres-query-failure.test.ts
  • cloud/apps/relay/src/relay-database-rejection-fence.ts
  • cloud/apps/relay/src/relay-fix-level.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

// The server answers every statement within statement_timeout, as 57014 at worst, so
// this fires only on a lost reply, or a database or event-loop stall past the margin.
query_timeout:
statementTimeoutMs + (input.readTimeoutMarginMs ?? relayPostgresReadTimeoutMarginMs()),

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 | 🟠 Major | ⚡ Quick win

Reject read deadlines that exceed the timer limit.

If ORCA_RELAY_POSTGRES_READ_TIMEOUT_MARGIN_MS is 2147483648, the parser accepts it and this sum exceeds 2147483647 ms. Node.js then schedules the timeout for 1 ms, not for the configured duration. Serving queries can fail immediately and discard their clients. Validate the final sum before constructing the pool, including when readTimeoutMarginMs comes from input. (github.com)

Proposed validation
+    const queryTimeoutMs =
+      statementTimeoutMs + (input.readTimeoutMarginMs ?? relayPostgresReadTimeoutMarginMs())
+    if (!Number.isSafeInteger(queryTimeoutMs) || queryTimeoutMs > 2_147_483_647) {
+      throw new Error('invalid_read_timeout')
+    }
     const pool = new pg.Pool({
       ...
-      query_timeout:
-        statementTimeoutMs + (input.readTimeoutMarginMs ?? relayPostgresReadTimeoutMarginMs()),
+      query_timeout: queryTimeoutMs,

@Jinwoo-H
Jinwoo-H merged commit e72044a into main Oct 9, 2026
41 of 55 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