Skip to content

fix(relay): a database fault reaching unhandledRejection no longer kills the process - #26817

Merged
Jinwoo-H merged 5 commits into
mainfrom
relay-db-fault-no-crash
Oct 9, 2026
Merged

Jinwoo-H merged 5 commits into
mainfrom
relay-db-fault-no-crash

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​174 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​173
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​117 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​111

Merge together with #26829 (stacked R2): both ship in one image, and the fix-level bump is in #26829.

ELI5

If the relay's database hiccups in an unexpected place, a relay process can crash, and every desktop on that cell gets disconnected at once and stampedes back. This PR makes database hiccups that escape their handler get logged and survived instead, while real programming bugs still stop the process as before.

What Changed

  • Before: an unhandled promise rejection ends the process (Node's default), whatever caused it. On 2026-09-28 one Cloud SQL failover crashed 18 cells on older images and dropped ~16k desktops (that crash path, an error event on a checked-out client, was fixed by fix(relay): stop a terminated checked-out PostgreSQL client from killing the cell #21840; this closes the rejection path).
  • After: a process-wide unhandledRejection handler (relay-database-rejection-fence.ts, installed first thing in index.ts) survives a rejection only when both:
    1. Path: the relay's database layer threw or rethrew it. PostgresDatabase.query, PostgresTransaction.query, commitWithFinal (and its ROLLBACK) and transaction() mark what they throw in one WeakSet; pool acquire failures were already recorded at the acquire seam.
    2. Type: any pool acquire failure (no statement ran; includes a 28P01 at connect), pg's Query read timeout, pg's Connection terminated…, a raw ECONNRESET or EPIPE socket error (pg 8.22 hands the active query the socket's own error when the connection drops), or a pg.DatabaseError in SQLSTATE class 08, 40, 53, 55, 57 or 58 (the database is unwell) or 23 (a constraint lost a race with a concurrent writer; the row it guards is intact), plus the single class-25 code 25P03 (the server ended a session left idle in a transaction past 5 s, which a whole-VM stall of 6–7 s does to any backend caught idle mid-transaction). The rest of class 25 stays fatal. 25P03 is also now transient in isRelayDatabaseTransientError, so a handled request answers 503 instead of 500.
    • Survived: one orca_relay_database_rejection_fenced {code, message} line (message trimmed to 120 printable chars).
    • Everything else stays fatal, after one orca_relay_process_fatal line: schema errors (42, e.g. 42P01/42703), data errors (22), pg TypeErrors, the relay's own database_lock_unavailable, and every bare EPIPE/ECONNRESET from ws, fetch or any other socket. Fatal rejections are rethrown, so the process ends exactly as Node's default would.
  • Every pooled client also gets a permanent error listener on connect (both pools), so no gap between pg-pool's own listener swaps can turn a client error into a crash. The idle and checked-out listeners keep doing the logging.
  • The fix-level bump (1 → 2) lives in the stacked R2 PR (fix(relay): a lost database reply ends its connection within statement timeout + 10 s #26829), so no image reports level 2 without both fixes; the two ship in the same image. This PR also corrects the relay-fix-level.ts comment: the alert pages below a fixed floor (relay_cell_min_fix_level, production.tfvars, currently 1), raised by hand later.

Why

Design DESIGN-step2-cell-roll.md §2 (R1), cut from step 2 with no PR, carried into step-5 prep (DESIGN-step3-and-step5-prep-2026-10-09.md §2.6, PR 2). It is a prerequisite for the E-dep-3 drill (a cell with its database blocked for 20 min must not exit). Fencing by path and type (review-step2b-correctness B2, verify N5) avoids swallowing socket errnos and programmer errors, which an errno allow-list would. No exit budget: exiting mid-outage is exactly the 09-28 failure. The census test that forbids un-awaited database promises stays; this handler is the backstop for one that slips through.

The companion fix (R2: a lost database reply ends its connection within statement timeout + 2 s) is stacked on this PR.

Linked Issue

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

Visual Proof

N/A: server-only, no UI.

Testing

  • relay-database-rejection-fence.test.ts, through a real PostgresDatabase over a fake pool: a 25P03 from inside transaction() is fenced while a 25P02 stays fatal; fenced — a 23505 from query, Connection terminated unexpectedly, read ECONNRESET and read EPIPE from inside transaction(), a 28P01 at acquire; fatal (handler rethrows and logs orca_relay_process_fatal) — 42P01, a pg TypeError, database_lock_unavailable; fatal because the database layer never saw it — a bare EPIPE, an unmarked 23505, an unmarked "Connection terminated", non-objects. The permanent listener keeps a client error from throwing.

  • database-transient-error.test.ts: 25P03 classifies as transient.

  • Checked by hand that a throw inside an unhandledRejection listener ends a Node 24 process with exit code 1.

  • vitest run in cloud/apps/relay: 90 passed, 32 skipped (Postgres suites); tsc --noEmit clean.

  • 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. Abort signals for the canary (from the step-2 table): any orca_relay_process_fatal; any orca_relay_database_rejection_fenced (a log metric and alert for it is a separate Terraform change). 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)

…lls the process

A rejection is fenced only when the relay's database layer threw or
rethrew it and it is a pool acquire failure, pg's read timeout, a dropped
connection, or a server error in classes 08/23/40/53/55/57/58. Everything
else stays fatal and is named by an orca_relay_process_fatal line first.
Every pooled client also keeps a permanent error listener. Fix level 2.
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 56410044-65a0-478a-bd8a-7384fd092741

📥 Commits

Reviewing files that changed from the base of the PR and between a30d5e4 and 85f7cd3.


📒 Files selected for processing (2)
  • cloud/apps/relay/src/relay-database-rejection-fence.test.ts
  • cloud/apps/relay/src/relay-database-rejection-fence.ts

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



📝 Walkthrough

Walkthrough

The relay marks errors caught during PostgreSQL operations and attaches error listeners to clients from both PostgreSQL pools. It registers an unhandled-rejection handler that classifies and logs fenced database errors, while logging and rethrowing other rejections. New tests cover classification, logging, and client error handling. The relay fix-level comment now describes a fixed minimum-level floor and a six-hour alert condition.


Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 85f7c

This change can expose sensitive connection data in logs and suppress unrelated transaction failures, so both issues should be fixed before merge.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check Passed The title clearly and concisely summarizes the primary change: preventing database-related unhandled rejections from terminating the relay process.
Description check Passed The description is complete and well aligned with the template. It explains the problem, implementation, rationale, linked-issue exception, testing, review considerations, and checklist status.


  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • 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: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8e816c14-5fe8-4473-a82a-2f0cec26b19c
📥 Commits

Reviewing files that changed from the base of the PR and between 39a01f9 and f075bb1.

📒 Files selected for processing (6)
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/index.ts
  • cloud/apps/relay/src/postgres-pool-pressure.ts
  • cloud/apps/relay/src/relay-database-rejection-fence.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; 3 remain after this review.

this.holds.recordLockTimeout(transaction.consumeLockTimeouts())
return result
} catch (error) {
markRelayDatabaseError(error)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not mark errors from the transaction callback as database errors.

If operation rejects with an unrelated Error('Connection terminated unexpectedly'), this catch marks that error. The rejection fence then treats an unhandled callback failure as a dropped database connection and keeps the process alive. Mark failures from BEGIN and COMMIT at those query calls. Preserve the marks already applied by database query methods, but do not mark an arbitrary error from operation.

Comment on lines +43 to +46
const code = 'code' in error ? String(error.code) : ''
const message = 'message' in error ? String(error.message) : String(reason)
// Server messages can quote values; the code and the start of the message identify the fault.
return { code, message: message.replace(/[^\x20-\x7e]/g, '').slice(0, 120) }

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Redact rejection fields before logging them.

If a database or application error contains a token or personal data in its message, rejectionFields writes that text to the fenced or fatal log. Removing non-printable characters and limiting the message to 120 characters does not remove the sensitive text. Log approved fault identifiers instead, or redact sensitive values before serialization. Based on learnings, error text can contain credentials, tokens, and personal data and needs redaction before diagnostic logging.

Source: Learnings

…mp to the read-timeout fix

R1 alone does not close the lost-reply stall, so the level rises with R2.
The fix-level comment now describes the fixed alert floor.
… timeout a VM stall triggers

A whole-VM database stall of 6-7 s outlasts the 5 s idle-in-transaction
limit for a backend caught idle mid-transaction, and the server ends that
session with FATAL 25P03 on resume. The fence now survives that one class-25
code (the rest of class 25 stays fatal), and routes answer it as transient.
…threw

pg 8.22 rejects the active query with the raw socket error ('read
ECONNRESET'), which the message-only check let through to a fatal exit:
the 09-28 crash shape. Match ECONNRESET and EPIPE by code, gated by the
database-layer mark.
@Jinwoo-H
Jinwoo-H merged commit dc69efa into main Oct 9, 2026
23 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