Repository navigation
fix(platform): answer a database restart with 503, not a crash or 500 - #3506
Merged
Merged
Conversation
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.
This was referenced Sep 27, 2026
Closed
This was referenced Oct 11, 2026
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A database restart no longer takes the api process down or floods error tracking with events. Managed upgrades recreate
dbon every release, and on-prem hosts restart. Now requests answer a retryable503 DATABASE_UNAVAILABLEwithRetry-Afterand are not reported,/eventsbacks 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
pg.Poolhad no'error'listener, so an idle client's57P01became an uncaught exception. Reproduced on origin/main: the fast stop exited the process and sent afatalevent./eventsreported every failed poll, at a fixed 1 s backoff.INTERNAL_SERVER_ERRORwith no cause. So every session-gated route,/eventsreconnects included, looked like a defect.Fix
backend/db/unavailable.ts:isDatabaseUnavailable(error, {fromDatabase}). It follows thecausechain and covers:57P01/57P02/57P03and class08, from either driver;CONNECT_TIMEOUT/CONNECTION_CLOSED/CONNECTION_ENDED/CONNECTION_DESTROYED;Connection terminated unexpectedlyand…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.isTransientDbErrorandisConnectionFailure.auth/auth.ts):pool.on('error')), and on dropped checked-out clients fromacquireuntilrelease;logger.lognotes the database error behind the session read's bare 500 in a per-request slot (AsyncLocalStorage, opened inapp.ts). The same outage prints one warn line instead of an error stack.appErrorHandlerand the RESTonErroranswer503 {error, code: "DATABASE_UNAVAILABLE", requestId}withRetry-After: 5andCache-Control: no-store. They log one warn line and report nothing.Retry-After: 5matches the edge'sUPSTREAM_UNAVAILABLE./events:warninglevel, after about 60 s. The outage watch is shared by the handler's streams, so the report comes once however many streams wait.failed. pg-boss then retries it under the queue's own policy;retryLimit: 0lanes keep their watchdogs.DATABASE_UNAVAILABLEjoins the registry;/api/v1operation and both webhook doors document the 503, withRetry-After;openapi.jsonand the fingerprint are regenerated (the hashes are unchanged).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. ItsgetSessionthrows a cause-less 500 while theECONNREFUSEDis 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;levelreaches 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 withrequestId.realtime/sse.test.ts:jobs/runner.test.ts: quietfailedfor an outage; other failures are still reported.End to end against a real PostgreSQL 16 fast stop. A fast stop is the SIGINT the
dbimage'sSTOPSIGNALgivesdocker compose restart db. The backend ran withROLE=all, withSENTRY_DSNpointed at a fake ingest, an open/eventsstream, 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.57P01; onefataleventwarningevent (events-poll,outageMs65019)57P01through postgres.js, and through Better Auth's recovered cause); no eventThere was no 401 or 500 in any run.
Checks.
serverandpiiprojects: 807 files pass.render_fetch.test.ts(needs a browser) and oneopenai-compatembeddings case fail the same way on origin/main in this sandbox.lint:manual,check-guideonperformance.md, andoxfmt --checkpass.oxlintand opengrep find nothing on the changed files. knip on the platform shows only the existingoidcOrganizationClaimsfinding, which origin/main has too.tscand type-aware lint were OOM-killed at this sandbox's 4 GB memory cap.tscpassed on a config rooted at the changed files; throughapp.tsandspec.tsthat covers the whole backend import graph. CI runs the full ones.Checklist
bun run checkpasses (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:sastpasses (Opengrep), on the changed files: 0 findings.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.PERF-B5:curl …/api/v1/me, then rundocker compose restart db.DATABASE_UNAVAILABLEwithRetry-After: 5, never 401 or 500, then 200s again.backend-apirestart and no error-level event.Follow-up (not in this PR)
boss.on('error')as a fullconsole.errordump, 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.