Skip to content

fix(platform): answer a database restart with 503, not a crash or 500 - #3506

Merged
yannickmonney merged 4 commits into
mainfrom
fix/database-unavailability-resilience
Sep 27, 2026
Merged

yannickmonney merged 4 commits into
mainfrom
fix/database-unavailability-resilience

Conversation

@yannickmonney

Copy link
Copy Markdown
Contributor

Summary

A database restart no longer takes the api process down or floods error tracking with events. Managed upgrades recreate db on every release, and on-prem hosts restart. Now requests answer a retryable 503 DATABASE_UNAVAILABLE with Retry-After and are not reported, /events backs off and resumes, and jobs fail quietly for pg-boss to retry. From task TALE-28 (triage T02, P2); there is no GitHub issue.

Problem

  • The api process exited. Better Auth's pg.Pool had no 'error' listener, so an idle client's 57P01 became an uncaught exception. Reproduced on origin/main: the fast stop exited the process and sent a fatal event.
  • /events reported every failed poll, at a fixed 1 s backoff.
  • Every request answered a 500, and each was reported. Better Auth's session read makes this worse: it catches the adapter's error, logs it, and throws a bare INTERNAL_SERVER_ERROR with no cause. So every session-gated route, /events reconnects included, looked like a defect.
  • A working API key answered 401 when the key lookup could not reach the database. A client reads that as "stop using this key".
  • Nothing retried, and failed jobs were reported as defects.

Fix

  • backend/db/unavailable.ts: isDatabaseUnavailable(error, {fromDatabase}). It follows the cause chain and covers:
    • SQLSTATE 57P01/57P02/57P03 and class 08, from either driver;
    • postgres.js CONNECT_TIMEOUT/CONNECTION_CLOSED/CONNECTION_ENDED/CONNECTION_DESTROYED;
    • node-postgres's code-less Connection terminated unexpectedly and …due to connection timeout (its counterparts of the postgres.js codes);
    • ECONNREFUSED/ECONNRESET/EAI_AGAIN/ENOTFOUND/ETIMEDOUT, but only from a database client. postgres.js stamps its query errors, and callers vouch for Better Auth's node-postgres errors. Any other client raises the same errnos, so an object-store or model-provider outage keeps being reported.
  • Other classifiers are unchanged. Rejected credentials (28xxx), a missing database (3D000) and capacity (53xxx) still report: they need an operator. The module says how this differs from isTransientDbError and isConnectionFailure.
  • Better Auth (auth/auth.ts):
    • the pool warns on dropped idle clients (pool.on('error')), and on dropped checked-out clients from acquire until release;
    • its logger.log notes the database error behind the session read's bare 500 in a per-request slot (AsyncLocalStorage, opened in app.ts). The same outage prints one warn line instead of an error stack.
  • appErrorHandler and the REST onError answer 503 {error, code: "DATABASE_UNAVAILABLE", requestId} with Retry-After: 5 and Cache-Control: no-store. They log one warn line and report nothing. Retry-After: 5 matches the edge's UPSTREAM_UNAVAILABLE.
  • The REST key lookup answers the same 503 instead of 401. It does not charge the failed-auth IP bucket.
  • /events:
    • backs off from 1 s, doubling to a 10 s cap;
    • keeps its heartbeat during the outage, so a proxy does not cut an idle lane;
    • reads the outbox tail inside the loop, so a stream opened as the database went away backs off instead of ending;
    • retries the resume check instead of skipping it;
    • reports once per outage, at warning level, after about 60 s. The outage watch is shared by the handler's streams, so the report comes once however many streams wait.
  • Job runner: a job the outage failed logs a warn, is not reported, and returns failed. pg-boss then retries it under the queue's own policy; retryLimit: 0 lanes keep their watchdogs.
  • REST contract 2.2.0:
    • DATABASE_UNAVAILABLE joins the registry;
    • every /api/v1 operation and both webhook doors document the 503, with Retry-After;
    • the preamble names the code, and openapi.json and the fingerprint are regenerated (the hashes are unchanged).
  • Docs (EN/DE/FR): the API reference's 503 row and edge-refusal paragraph, what a restart does to error reporting (observability page), and a troubleshooting row.
  • Manual layer: box PERF-B5 (database restart), a provocation-map row, and a pin.

Proof

Unit tests (new or extended).

  • db/unavailable.test.ts: every code class, both drivers' error classes, and real postgres.js and node-postgres refusals against a closed port. It also covers a fetch failure that stays unclassified, causes, loops, the per-request slot, and isolation between concurrent requests.
  • auth/auth.database-unavailable.test.ts: the pool listeners, and real Better Auth against a closed port. Its getSession throws a cause-less 500 while the ECONNREFUSED is recovered from the slot, so an upgrade that stops logging the swallowed error fails here.
  • error-reporting.test.ts, with the real SDK and a fake ingest: the 503 is not reported; a bare 500 with a noted cause answers 503; the same 500 without one is still reported; level reaches the event.
  • rest/v1.test.ts: a key lookup during an outage gets 503, not 401, and nothing is charged; an escaped outage gets an unreported 503 with requestId.
  • realtime/sse.test.ts:
    • stays open, heartbeats, and delivers the next hint;
    • two streams produce one warning report;
    • a stream opened mid-outage recovers;
    • other faults are still reported.
  • jobs/runner.test.ts: quiet failed for an outage; other failures are still reported.

End to end against a real PostgreSQL 16 fast stop. A fast stop is the SIGINT the db image's STOPSIGNAL gives docker compose restart db. The backend ran with ROLE=all, with SENTRY_DSN pointed at a fake ingest, an open /events stream, and REST and app loops every 250 ms. No Docker daemon is available in the sandbox, so the database is a process, not a container.

origin/main 67e863e this branch
20 s restart the process exited on the idle client's 57P01; one fatal event REST 49×200 / 78×503, app 50×200 / 78×503; stream open, hint delivered after recovery; process up; no event
75 s outage — REST 32×200 / 292×503, app the same; 4 heartbeats; process up; one warning event (events-poll, outageMs 65019)
Requests blocked mid-query at the stop — both answered 503 (57P01 through postgres.js, and through Better Auth's recovered cause); no event

There was no 401 or 500 in any run.

Checks.

  • The affected test files pass (20 files, 303 tests). The docs suite passes (34 files).
  • The full platform server and pii projects: 807 files pass. render_fetch.test.ts (needs a browser) and one openai-compat embeddings case fail the same way on origin/main in this sandbox.
  • lint:manual, check-guide on performance.md, and oxfmt --check pass.
  • Type-aware oxlint and opengrep find nothing on the changed files. knip on the platform shows only the existing oidcOrganizationClaims finding, which origin/main has too.
  • The workspace-wide tsc and type-aware lint were OOM-killed at this sandbox's 4 GB memory cap. tsc passed on a config rooted at the changed files; through app.ts and spec.ts that covers the whole backend import graph. CI runs the full ones.

Checklist

  • bun run check passes (format, lint, typecheck, all tests). Partly. Format, scoped lint and typecheck, and the tests above pass. The workspace-wide typecheck and type-aware lint could not run here (memory cap); CI decides.
  • bun run lint:sast passes (Opengrep), on the changed files: 0 findings.
  • Translations: N/A. No catalog key changed. The 503 sentence is a REST envelope sentence, English like every other.
  • Docs updated in docs/{en,de,fr}/.
  • README.md / README.de.md / README.fr.md: N/A, nothing they describe changed.

Test plan

  • bun run --filter @tale/platform test. The new and changed specs are listed above.
  • Manual PERF-B5:
    1. Open a dashboard tab and loop curl …/api/v1/me, then run docker compose restart db.
    2. Expect 200s, then 503 DATABASE_UNAVAILABLE with Retry-After: 5, never 401 or 500, then 200s again.
    3. Expect the hint stream to stay open and deliver again without a reload.
    4. Expect no backend-api restart and no error-level event.

Follow-up (not in this PR)

  • pg-boss logs every failed worker poll through boss.on('error') as a full console.error dump, about 650 lines in a 20 s outage with ~60 queues. Nothing is reported and the api-only role runs no workers, but the log noise could get the same one-line warn treatment.

A managed upgrade recreates `db` on every release, and an on-prem host
restart does the same. The api process met both badly: Better Auth's
pg.Pool had no 'error' listener, so an idle client's 57P01 was an uncaught
exception that exited the process; every failed /events poll was
reported; every request answered a reported 500, and an API key the
database could not look up answered 401.

- isDatabaseUnavailable (backend/db/unavailable.ts): SQLSTATE 57P01,
  57P02, 57P03 and class 08 from either driver, postgres.js's
  connection-lifecycle codes, node-postgres's code-less termination
  errors, and ECONNREFUSED, ECONNRESET, EAI_AGAIN, ENOTFOUND and ETIMEDOUT
  only from a database client (postgres.js stamps its query errors;
  callers vouch for Better Auth's), so an object-store or model-provider
  outage is still reported.
- Better Auth's pool listens for dropped idle and checked-out clients, and
  its logger notes the database error the session read swallows behind a
  bare 500, so the error handlers can still see it.
- appErrorHandler and the REST onError answer 503 DATABASE_UNAVAILABLE
  with Retry-After: 5 and a requestId, unreported; the REST key lookup
  answers the same instead of 401.
- /events backs off (1 s, doubling to 10 s), keeps its heartbeat, reads
  the outbox tail inside the poll loop, and reports one warning-level
  event per outage that lasts past about 60 s.
- The job runner fails the job for pg-boss to retry, without reporting.
- REST contract 2.2.0: the code joins the registry, and every operation
  documents the 503.

Verified against a real PostgreSQL 16 fast stop (the db image's STOPSIGNAL
SIGINT) with an open /events stream and in-flight /api/v1 and /api/app
calls. They answered 503, the stream resumed, the process stayed up, and
no error-level event arrived (one warning after a 75 s outage).
origin/main exited at the same stop.
PERF-B5 drives the restart the platform now survives: a REST loop and an
open hint stream across `docker compose restart db`, judged on 503
DATABASE_UNAVAILABLE with Retry-After (never 401 or 500), the stream
resuming without a reload, no backend-api restart and no error-level
event. The provocation map gains the code beside the edge's
UPSTREAM_UNAVAILABLE, and pins.md records why the box exists and which
specs hold each half.
The API reference names the platform's own 503 beside the edge's
UPSTREAM_UNAVAILABLE (it carries X-Tale-Api-Version and a requestId, and
a working key is never answered 401 meanwhile). The observability page
says what a database restart does and does not send to error tracking,
and troubleshooting gains the symptom row. EN, DE and FR.
CI's terminal takes colour, so Better Auth wraps its `[Better Auth]:`
prefix in ANSI codes and the one-span regex missed a line that was
printed as intended. The assertion now matches the prefix and the outage
sentence separately; it passes with FORCE_COLOR=1 as well.
@yannickmonney
yannickmonney merged commit d2ec462 into main Sep 27, 2026
57 checks passed
@yannickmonney
yannickmonney deleted the fix/database-unavailability-resilience branch September 27, 2026 13:15
tale-code-bot added a commit that referenced this pull request Oct 30, 2026
A database restart during an MCP tool call was reported to error
tracking at error level, once per failing call, and the agent got
INTERNAL_ERROR. The catch blocks of callTool (#4592) and of the settings
writer loop (#4685) answered every non-refusal as a fault without asking
db/unavailable.ts, which the REST and app doors have used since #3506.

Both now ask databaseUnavailableCause first, through one helper in
domains/mcp/refusals.ts: such a call writes one warning line, reports
nothing and answers DATABASE_UNAVAILABLE with data.retryAfterMs 5000,
the REST door's Retry-After. A settings write answers it beside what
landed; a resource read, the resource list and a prompt answer -32603
with the code and the wait, never "resource not found". It counts as a
refusal, not a failure. Any other failure keeps INTERNAL_ERROR and its
report, a bare socket error no database client stamped included.

The MCP spec gains MCP-R43 (MCP-R8's example used a database outage as
its fault), the manual suite MCP-B3 and the error-code rows, the Tale
skill, the settings reference and the docs the code, and the contract
moves to 3.50.0.

Closes #4771
tale-review-bot pushed a commit that referenced this pull request Oct 30, 2026
A database restart during an MCP tool call was reported to error
tracking at error level, once per failing call, and the agent got
INTERNAL_ERROR. The catch blocks of callTool (#4592) and of the settings
writer loop (#4685) answered every non-refusal as a fault without asking
db/unavailable.ts, which the REST and app doors have used since #3506.

Both now ask databaseUnavailableCause first, through one helper in
domains/mcp/refusals.ts: such a call writes one warning line, reports
nothing and answers DATABASE_UNAVAILABLE with data.retryAfterMs 5000,
the REST door's Retry-After. A settings write answers it beside what
landed; a resource read, the resource list and a prompt answer -32603
with the code and the wait, never "resource not found". It counts as a
refusal, not a failure. Any other failure keeps INTERNAL_ERROR and its
report, a bare socket error no database client stamped included.

The MCP spec gains MCP-R43 (MCP-R8's example used a database outage as
its fault), the manual suite MCP-B3 and the error-code rows, the Tale
skill, the settings reference and the docs the code, and the contract
moves to 3.50.0.

Closes #4771
Task: TALE-149
yannickmonney pushed a commit that referenced this pull request Oct 30, 2026
A database restart during an MCP tool call was reported to error
tracking at error level, once per failing call, and the agent got
INTERNAL_ERROR. The catch blocks of callTool (#4592) and of the settings
writer loop (#4685) answered every non-refusal as a fault without asking
db/unavailable.ts, which the REST and app doors have used since #3506.

Both now ask databaseUnavailableCause first, through one helper in
domains/mcp/refusals.ts: such a call writes one warning line, reports
nothing and answers DATABASE_UNAVAILABLE with data.retryAfterMs 5000,
the REST door's Retry-After. A settings write answers it beside what
landed; a resource read, the resource list and a prompt answer -32603
with the code and the wait, never "resource not found". It counts as a
refusal, not a failure. Any other failure keeps INTERNAL_ERROR and its
report, a bare socket error no database client stamped included.

The MCP spec gains MCP-R43 (MCP-R8's example used a database outage as
its fault), the manual suite MCP-B3 and the error-code rows, the Tale
skill, the settings reference and the docs the code, and the contract
moves to 3.50.0.

Closes #4771
Task: TALE-149
tale-code-bot added a commit that referenced this pull request Oct 30, 2026
A database restart during an MCP tool call was reported to error
tracking at error level, once per failing call, and the agent got
INTERNAL_ERROR. The catch blocks of callTool (#4592) and of the settings
writer loop (#4685) answered every non-refusal as a fault without asking
db/unavailable.ts, which the REST and app doors have used since #3506.

Both now ask databaseUnavailableCause first, through one helper in
domains/mcp/refusals.ts: such a call writes one warning line, reports
nothing and answers DATABASE_UNAVAILABLE with data.retryAfterMs 5000,
the REST door's Retry-After. A settings write answers it beside what
landed; a resource read, the resource list and a prompt answer -32603
with the code and the wait, never "resource not found". It counts as a
refusal, not a failure. Any other failure keeps INTERNAL_ERROR and its
report, a bare socket error no database client stamped included.

The MCP spec gains MCP-R43 (MCP-R8's example used a database outage as
its fault), the manual suite MCP-B3 and the error-code rows, the Tale
skill, the settings reference and the docs the code, and the contract
moves to 3.50.0.

Closes #4771
Task: TALE-149
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