Repository navigation
fix(platform): wait out a restarting database when the backend boots - #4031
Merged
Merged
Conversation
A backend process that started while the app database was restarting failed the migrator's first query with the restart's own refusal (57P03 "the database system is shutting down", "... is starting up", or a refused connection). The boot lane reported it at error level and the process exited; the orchestrator restarted it with a growing backoff and every attempt reported again. GlitchTip tale/tale#343 carries that title. runBootMigrations now reruns its whole advisory-locked step while the database is unavailable (isDatabaseUnavailable), 1 s doubling to 5 s apart, for up to ROUTINE_RESTART_MS: the 60 s after which /events already reports an outage. Any other error, and an outage that outlasts the wait, still fail the boot and are reported. A lock that was never taken is no longer "unlocked" over a second connection. withRetry gains maxDelayMs, and an Infinity attempt count leaves the time budget alone to end the retries.
yannickmonney
added a commit
that referenced
this pull request
Oct 1, 2026
#4031 adds PERF-B7 (a backend start during a database restart) to the same suite. Numbering this box PERF-B8 keeps the two IDs distinct whichever pull request lands first; the second to merge recounts the suite and readme totals.
Review follow-ups for the boot wait: - The wait was a budget from the start of the migration step, so time queued behind another process's migration lock (or spent applying migrations) used it up: a restart 55 s into the step failed the boot at once. The outage is now timed from its first refusal. - A lock that was taken is no longer "unlocked" after a failure that says the database is away: that only opened a new connection to it, and ending the session releases the lock anyway. - EHOSTUNREACH and ENETUNREACH from a database client count as the database being unavailable (a host that is down, or whose network is not up yet as it boots), as isTransientDbError already counts them. - The rerun-safety note no longer overclaims Better Auth's migrator, and PERF-B7 reads the restart count relative to the manual restart and uses compose service names like PERF-B5/B6.
Backend integration failed one check on 9919347: "busy retry, racing: while a delegated start holds the agent row ..." in checkAutomatedRetryAgentBusy (1252/1253 across 209/209 lanes). The same lane passed on c46fbef and passes alone on this head three times out of three; it is a known race in that lane, unrelated to the boot wait. The token cannot re-run a job, so this empty commit re-runs the checks.
…ited out main.ts calls runBootMigrations with no hint that the call can now pause for up to a minute while the database restarts. Say so where the boot sequence is read, and that only a longer outage reaches the fatal handler. The empty commit before this one did not start any workflow.
…s-out-database-restart # Conflicts: # services/platform/tests/manual/readme.md
…s-out-database-restart # Conflicts: # services/platform/tests/manual/suites/performance.md
Review notes on #4031, folded into one push: - e1: the outage's clock is performance.now() (injectable for tests), so a wall-clock step as the host syncs its time at boot neither cuts the wait short nor stretches it. A test leaps Date.now an hour per read and still sees every refusal waited out. - a: the clock stays one per boot, on purpose. Resetting it on progress would let a database that keeps going away hold the boot without it ever being reported. The docstring now says exactly that, including that a second outage shares the time between the two. - d, e2: the docs say the start fails if the database is still unreachable after the minute, and that a wrong host or port in DATABASE_URL takes about a minute to fail it. Note b (do not wait out a connection lost under the migration lock) was tried and dropped. Under a transaction, postgres.js reports an administrator's shutdown as CONNECTION_CLOSED or ECONNRESET, never 57P01, so the rule failed a routine restart mid-migration. A probe on a real PostgreSQL 16 showed it: the boot exited where the previous head reran and completed. A crashing migration is a follow-up instead.
This was referenced Oct 1, 2026
Contributor
Author
|
Independent review (TALE-416): approved at
|
This was referenced Oct 1, 2026
4 of 5 tasks
tale-review-bot
pushed a commit
that referenced
this pull request
Oct 30, 2026
A backend process that started while the knowledge database was restarting or still starting reported the refusal as an error event (the default corpus bootstrap, on the worker and all roles) and skipped the BM25 index verification of the default corpus for the life of the process, so an index a crash-mode stop corrupted was neither detected nor kept from taking writes. knowledge-db is not among the backend's compose dependencies, so such a start is an ordinary event. The boot's knowledge steps now wait out the knowledge database with createBootDatabaseWait, the helper #4031 added for the app database, on a clock of their own: bootDefaultKnowledge (domains/knowledge/boot.ts) waits up to ROUTINE_RESTART_MS (60 s) from the knowledge database's first refusal, then bootstraps the schema and verifies the indexes. healBm25Indexes takes the wait, reruns a scan the database refused whole on a fresh session, and reports a database that stays unavailable as the new status `unavailable`, with a warning instead of an error line; the report's effects still run once. An outage past the wait is reported once per boot, at error level with the boot's tag, and each step it skipped logs a warning saying it stays skipped until the process restarts. Any other failure is handled as before. The observability and container docs (EN/DE/FR) follow. Closes #4035 Task: TALE-51
tale-code-bot
added a commit
that referenced
this pull request
Oct 31, 2026
A backend process that started while the knowledge database was restarting or still starting reported the refusal as an error event (the default corpus bootstrap, on the worker and all roles) and skipped the BM25 index verification of the default corpus for the life of the process, so an index a crash-mode stop corrupted was neither detected nor kept from taking writes. knowledge-db is not among the backend's compose dependencies, so such a start is an ordinary event. The boot's knowledge steps now wait out the knowledge database with createBootDatabaseWait, the helper #4031 added for the app database, on a clock of their own: bootDefaultKnowledge (domains/knowledge/boot.ts) waits up to ROUTINE_RESTART_MS (60 s) from the knowledge database's first refusal, then bootstraps the schema and verifies the indexes. healBm25Indexes takes the wait, reruns a scan the database refused whole on a fresh session, and reports a database that stays unavailable as the new status `unavailable`, with a warning instead of an error line; the report's effects still run once. An outage past the wait is reported once per boot, at error level with the boot's tag, and each step it skipped logs a warning saying it stays skipped until the process restarts. Any other failure is handled as before. The observability and container docs (EN/DE/FR) follow. Closes #4035 Task: TALE-51
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 backend process that starts while the app database is restarting now waits for the database instead of reporting an error and exiting. The wait lasts up to a minute, the same threshold
/eventsalready uses. A database that is still unreachable after that fails the start and is reported, exactly as before.This came out of the triage of GlitchTip tale/tale#343,
PostgresError: the database system is shutting down, imported as task TALE-406. #4030 has the full classification. Short version: #3506 and #3548 made a database restart routine for requests, jobs, pg-boss and/events(0.5.62 and later). Boot was the path they left out.Closes #4030.
Problem
main.tscallsrunBootMigrationsfirst, and its first query ispg_advisory_lock. If the database is restarting at that moment, the query fails with the restart's own refusal: 57P03the database system is shutting down,… is starting up, orECONNREFUSED.main().catchthen:tale.lane: boot);The orchestrator restarts the process with a backoff that grows to a minute, and every attempt reports again. The docs promise the opposite ("A database restart is not reported as an error"), recovery is delayed by that backoff, and each refusal message becomes its own error-level GlitchTip issue.
Change
backend/db/migrate.ts.runBootMigrationsreruns its whole advisory-locked step throughwithRetrywhileisDatabaseUnavailable(error, { fromDatabase: true })holds.ROUTINE_RESTART_MS(60 s) has passed since the first refusal. Time queued behind another process's migration lock, or spent applying migrations, before that refusal does not count.performance.now(), injectable asnow), so a wall-clock step as the host syncs its time at boot neither cuts the wait short nor stretches it.fromDatabaseis set because every client the step opens is a database client, including Better Auth's node-postgres migrator.app_migrationsrow or not at all, so even an ambiguous commit is skipped on the rerun;backend/db/unavailable.ts.ROUTINE_RESTART_MS, the minute after which a database outage stops being a routine restart.realtime/sse.tsnow takes itsOUTAGE_REPORT_AFTER_MSfrom it (same value), so the two thresholds cannot drift apart.EHOSTUNREACHandENETUNREACHfrom a database client now count as the database being unavailable: a host that is down, or one whose network is not up yet as it boots.isTransientDbErroralready counted both.@tale/shared/db/retry.withRetrygainsmaxDelayMs, a ceiling for one backoff pause; its default is unbounded, so existing callers are unchanged. AnInfinityattempt count leaves the time budget alone to end the retries, and the log line then omits the/Ntotal.backend/main.ts. A comment at the migration call says a restart is waited out, and that only a longer outage reaches the fatal handler.PERF-B7(backend start during a database restart), with apins.mdrow and anautomation.mdrow. The suite and readme counts went up by one.Proof
Unit tests.
backend/db/migrate.test.ts(new) runs the realrunBootMigrationsagainst a local server that refuses each connection's startup with a FATAL.shutting downrefusals (pauses[1000, 2000]), then fails at once on 28P01.[1000, 2000, 4000, 5000, 5000, 5000]).Date.nowleaping an hour on every read, all three refusals are still waited out.migrate.ts: it rejects at the first 57P03, never retries, and opens a second connection to unlock a lock it never took.53b905d2c'smigrate.ts, whose clock wasDate.now.c46fbefd0, which had a budget from the start of the step: no pause at all.backend/db/unavailable.test.tsaddsEHOSTUNREACHandENETUNREACHto the database-client socket cases.packages/shared/src/db/retry.test.tsadds two cases: the delay stops doubling atmaxDelayMs, and anInfinityattempt count runs until the budget at the capped delay (with the/N-less log line).End to end, local and isolated. Setup:
ROLE=all);SENTRY_DSNpointed at a local fake ingest;b420851b7; boot code identical toa703a9598)PostgresError: the database system is shutting down(tale.lane: boot), exit 1 after 6 s[db] transient error on attempt 1–4 … the database system is shutting down, then… ECONNREFUSEDwhile the database was down. It answered/ping6 s after the database came back,/ready200, no eventError: connect ECONNREFUSED, exit 1 at once (the orchestrator then restarts it)tale.lane: boot) and exit 1. The persistent failure is still reportedThe table shows the first head (
c46fbefd0). On the second head (9919347cc), the same rounds behaved as follows:/ping1 s after the database came back,/ready200, no event;The same rig showed the rest of the restart class unchanged. #4030 has the details:
/eventsevent, by design;COMMITand none of them committed anyway.Independent review
A read-only adversarial review of
c46fbefd0found no high-severity defect. Its findings and what became of them:9919347cc: the outage is now timed from its first refusal, and the clock test pins it.EHOSTUNREACHandENETUNREACH. Fixed.PERF-B7steps. Reworded: the restart count is now read relative to the manual restart, and the steps use compose service names.fromDatabase: true(needed for Better Auth's bare node-postgres socket errors) has no unit test. Reaching that path needs a real database; the Backend integration check runs the happy path.08and a typo'd host or port now surface after the minute's wait instead of at once.Second review (TALE-416, Agent #2). The verdict was approve with optional notes a–e. The reviewer's real-PostgreSQL rounds passed on
3b4a5c93a: a mid-migration 57P01, Better Auth's pool refused while the lock session stays alive, 65 s queued behind the lock and then a cut, api and worker started together into an outage, and 57P03 for 30 s. What became of the notes incc36b1f41:CONNECTION_CLOSEDorECONNRESET, never 57P01, so the rule failed a routine restart mid-migration. A probe on a real PostgreSQL 16 against local commit782fe705e(never pushed) showed the boot exiting, where53b905d2candcc36b1f41rerun and complete.nextWrite. That is pre-existing and upstream: bug(platform): a Postgres server process that dies under an open transaction crashes the backend (postgres.js null-socket write) #4041, which also records b's rerun-cap idea for when that crash is fixed.Checks (run locally)
packages/shared: vitest passes (40 files, 634 tests);tsc --noEmitpasses.cc36b1f41(597 on9919347cc, 570 on the first head). The run covered:backend/db/,realtime/sse,error-reporting,auth.database-unavailable,http-shutdown,chat/routes,jobs/boss,jobs/runner,rest/v1,store-health;transactSerializableusers andcore/knowledge/pool;tests/guards/*, including the integration-scope guard;rest/error-codes,tasks/errors,handler_names, bothshimtests,openapi/spec,rate-limit,invalid-body-response).tscover the changed backend files plusbackend/main.ts(its whole import graph) passes.oxlinton the six changed TS files is clean.services/docs) passes: 37 files, 222 tests;bun run lint:manualandcheck-guide.tsonperformance.mdare OK.oxfmt --check,lint:conflictsand opengrep (0 findings) are clean;CI on the final head
cc36b1f41: all 58 checks are green, 13 skipped by design.@tale/platform.1ad5a5ecc.The earlier runs below are kept as they were.
CI on
53b905d2c. That head has origin/main929e9b162merged in, which includes TALE-405's #4033. The manual layer composes with it: itsPERF-B8and this PR'sPERF-B7both stay, and the totals readPERF-20 and 1064. Every check is green except one, Backend integration, which passed 1259 of 1260 checks.The one failure is not caused by this PR. It is the busy-retry lane's known race, "busy retry, racing: while a delegated start holds the agent row …", which open #4027 fixes (test-only). The race:
Each failing run logs
could not serialize access due to concurrent updatejust before the failure. Evidence that it is this race:3b4a5c93a.c46fbefd0passed in full.withRetrywith nomaxDelayMscomputes the same delays, andtransactSerializablepasses none.History:
c46fbefd0: green.9919347cc: the same race, 1252 of 1253.pull_requestworkflow then.3b4a5c93a: green, including Backend integration (1260 of 1260 across 210 lanes). Unit, Type check and Lint ran for platform, shared and docs ("cache miss, executing"). Playwright had no recovered-flake notice.53b905d2c: the race again.The token cannot re-run a job (403). Once #4027 lands, merging main, or a maintainer's re-run of the job, should turn the check green.
Not run here: the whole-workspace
tscand type-aware lint, the full platform suite,backend:integration, and E2E. The memory cap prevents the first ones, and the box has no Docker for E2E. CI runs them on this PR. This PR touches the backend, so the Backend integration check is owed.Not in this PR
Recorded in #4030, each needs a decision:
allprocess started while the knowledge database shuts down sends the same title at error level (ensureDefaultCorpusSchema), and boot continues with the default corpus's BM25 scan skipped. The fix needs a decision: wait at boot, or retry in the background. Going quiet would hide the skipped scan.DATABASE_UNAVAILABLEand goes unreported: bug(platform): an organization's own knowledge-database outage answers as the platform's DATABASE_UNAVAILABLE and goes unreported #4040.boss.start()still fails the boot.Coordination. TALE-405 (GlitchTip #109,
BackendApiErrorUPSTREAM_UNAVAILABLE) owns the browser and edge side and stays out ofservices/platform/backend/**. This PR touches no SPA, UI or proxy file. Refs #3273.