Repository navigation
fix(relay): a lost database reply ends its connection within statement timeout + 10 s - #26829
Conversation
2fb154b to
27adc6b
Compare
a23d623 to
4951d7f
Compare
…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.
4951d7f to
38c80be
Compare
📝 WalkthroughWalkthroughThe 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 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 |
|
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:
65a48d65-86eb-47b3-8199-47a19d1a4342
📒 Files selected for processing (11)
cloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/cell-admission-startup.tscloud/apps/relay/src/database-postgres-timeout.test.tscloud/apps/relay/src/database-transient-error.test.tscloud/apps/relay/src/database.tscloud/apps/relay/src/postgres-lost-reply-postgres.test.tscloud/apps/relay/src/postgres-lost-reply.test.tscloud/apps/relay/src/postgres-pool-pressure.tscloud/apps/relay/src/postgres-query-failure.test.tscloud/apps/relay/src/relay-database-rejection-fence.tscloud/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()), |
There was a problem hiding this comment.
🩺 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,
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
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.query_timeout = statement timeout + marginon 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 byORCA_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.queryLocked'sSET LOCAL lock_timeoutrestore never queues behind the dead statement), andtransaction()throws beforeCOMMITeven if the operation caught the error and returned normally. NoROLLBACKis 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 onBEGINorCOMMITtakes the same path (a lostCOMMITreply is an unknown outcome, as08006already is). Never retried.idle_session_timeout = 30 sin the request pool's startupoptionsbounds a backend orphaned outside a transaction. pg-pool closes healthy idle clients at 10 s, so it never fires on them. Because anoptions=in the database URL would silently replace this, the first session logsorca_relay_postgres_session_settings {idleSessionTimeout}; the director soak should read30sthere.isRelayDatabaseTransientError), so routes answer 503 + Retry-After as for08006, and the R1 fence survives it if unawaited./v1/assignanswering 500 29 times while backends were killed withpg_terminate_backend). New codes:57P01/57P02(session terminated or the server shutting down) and08000/08003, alongside08001/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'sConnection terminated unexpectedly, andECONNRESET. As with08006,transaction()never retries any of these, because the commit outcome is unknown.EPIPEmid-statement is treated likeECONNRESET.write EPIPEfrom the transaction's pool acquire during a Cloud SQL restart, answered 500). When the acquire fails withEPIPE,ECONNRESET,ECONNREFUSED,ETIMEDOUTorEHOSTUNREACH, 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.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: aROLLBACKor a lock-timeout restore on the same client waits its own full timeout behind the dead statement.idle_session_timeoutin the session options is image-only and touches no other service on the shared instance, unlike an instance flag orALTER 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 boundedqueryLockedthat times out sends exactlyBEGIN,SET LOCAL lock_timeout, the statement, then nothing (no restore,ROLLBACK,COMMITor retry) and releases with the error; an operation that catches the timeout and returns still never reachesCOMMIT, and later statements fail unsent; a lostCOMMITreply 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 againstpostgres: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 reportidle_session_timeout = 30s.database-postgres-timeout.test.ts: pool config pinsquery_timeout15 000 (12 500 with a 2 500 statement override) and theoptions, 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,08000and08003are transient. AConnection terminated unexpectedlyorECONNRESETcoming out ofPostgresDatabase.queryis transient, and the same error built outside the database layer is not.An acquire failing with each of
EPIPE,ECONNRESET,ECONNREFUSED,ETIMEDOUTandEHOSTUNREACHis transient and the bare errno is not;PostgresDatabase.transactionover a pool whose connect throwswrite EPIPErejects with a transient error (the staging stack).Mutation check: reverting the poison and the no-
ROLLBACKrule fails 4 of these tests, including the real-server one.Fix level:
RELAY_FIX_LEVEL1 → 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 runincloud/apps/relaywith Postgres: all pass except three Postgres timing/load suites that fail the same way onorigin/mainin 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
Notes
Runs on directors and cells. Canary abort signals (step-2 table): read timeouts while that cell's
sqlLatencyMsMaxis normal; relay backends > baseline + 10 (19 free on the shared instance);eventLoopDelayMsP99> 1 s. Do not merge without the owner's go.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)