Repository navigation
ci(deploy-dev): fail the run when the new backend cannot serve chat - #1899
Merged
Merged
Conversation
A pod can pass readiness and still not serve chat. The backend decides once at boot whether Postgres is available, and /ready answers 200 in the degraded state. On 2026-09-25 a transient connect timeout at boot left /api/pg/messages unmounted on the only replica, chat history 404 for a few minutes, and Deploy Dev green. The new step asks the newest non-terminating backend pod from the inside: /api/pg/status must say available, and an unauthenticated GET of /api/pg/messages/<id> must answer 401 (mounted), not 404 (unmounted). Six attempts ten seconds apart, then a failed run naming the pod, both values and the restart that fixes it. It stands until readiness itself asserts the mount (TASK-168 item 1). Run against the live cluster: exit 0 on the healthy pod (available, 401). A copy probing an unmounted /api/pg path exits 1 with the named error. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RUTWqLu6zhFPraoPHZcjQP
samxu01
pushed a commit
that referenced
this pull request
Sep 25, 2026
…ASK-168)
Acceptance 2 of the production incident: a pod whose boot connect timed out had
no PG routes at all — `/api/pg/messages` 404'd, so chat history could not load —
and it answered `/api/health/ready` 200 anyway, so a rollout sent it 100% of the
traffic while the pod it replaced was healthy. Recovery required a human.
`98f20db9` made that pod retry and mount in place; this makes it say so.
WHAT WAS WRONG WITH THE OLD GATE. The handler asked whether a live PG query
worked and returned 200 when it failed (`degraded: ['postgresql']`). It could not
see the defect: `config/db-pg.ts` creates the pool lazily, so `SELECT 1` answered
the moment the transient passed while the routes stayed unmounted. Asking PG how
it feels is not the same question as whether this pod can serve chat, and lily's
20:57Z scope note asks for the second one: "readiness must not reuse that block's
outcome as its own evidence; assert the mount."
WHAT IT ASSERTS NOW. `/ready` returns 503 `{status:'not_ready', reason:'PostgreSQL
routes are not mounted on this pod'}` when `PG_HOST` is set and the PG router is
absent from the app — and 200 the moment the retry mounts it, with no restart.
PG's liveness after a successful mount stays ungated on purpose: failing every
pod's readiness on a shared-dependency blip would turn partial degradation into a
full API outage (values.yaml, readinessProbe; `health.ready.test.js` still pins
the degraded-200).
THE PROBE IS THE ROUTE TABLE, NOT A FLAG. `routerIsMounted(app, pgMessageRoutes)`
walks the Express stack for the router object by identity, so it cannot drift
from what is actually mounted, and it stays correct if the path changes. It is
deliberately not `pgBootState.mounted`/`pgAvailable`: a pod whose boot block
believes it is fine while the route table disagrees is exactly the 2026-09-25
shape. `server.ts` installs it before `createPgBoot`, so the answer is live.
A STRUCTURAL ASSERTION, and why. The states reachable in `server.test.js` cannot
tell the flag from the table — no PG, both false; PG working, both true. A
rewiring to `pgAvailable` would keep every behavioural case green while restoring
the exact blindness that caused the outage, so the test also reads `server.ts`
and refuses a probe wired to a flag (`routerIsMounted(app, pgMessageRoutes)`
required; `setPgMountProbe(() => pgAvailable|pgBootState)` refused).
EVIDENCE. Full backend suite 445 suites / 4158 tests green (`npx jest
--forceExit`, Node 22); `npm run lint:ts` 0 errors; `tsc --noEmit` clean (only
the pre-existing root-level `test-discord-interactions.ts` errors). Six
mutations, each anchored, each restored byte-identical with a green baseline
after: mount gate deleted → 2 red; gate back on the pool proxy → 2 red; probe
wired to `pgAvailable` → the structural assertion; probe wired to `true` → the
unmounted-route assertion; `routerIsMounted` answering true for anything → 4 red;
`mountRoutes` not registering the router → 1 red.
NOT VERIFIED. Not exercised against a real PG that is down at boot: every case
above injects the failure, so what is proven is the logic and the wiring, not the
end-to-end timing of a real connection timeout. `routeRateLimitGuard` and the
deploy-dev probe in #1899 are untouched.
DELIBERATELY NOT IN THIS COMMIT: deleting the Mongo chat fallback (`pgAvailable`
in the socket branch at `server.ts:607`, `pgAvailable()` in
messageController.ts). lily's note asks for it and the argument is sound — the
Mongo path's newest document is 2026-08-05, so it hides failures while serving
stale rows — but it is a user-visible behaviour change on the write path, not
part of "make the pod report the capability it is missing", and it should be
reviewed as its own change rather than inside an incident fix. Flagged on the row.
lilyshen0722
added a commit
to thantiklermcirony/commonly
that referenced
this pull request
Oct 9, 2026
…ssert the mount (TASK-168) (Team-Commonly#1901) * fix(pg): retry the boot connect and mount the PG routes when it succeeds (TASK-168) WHAT HAPPENED. On 2026-09-25 a production pod's startup PG connect timed out ("Connection terminated due to connection timeout"). `server.ts` called `connectPG()` once and treated a null result as "PostgreSQL is not available on this pod, forever": the pod reported `/api/pg/status` → available:false for its whole life, 404'd `/api/pg/messages` because the routes were never mounted (so chat history would not load), sent socket chat writes to Mongo, and never started pg-retention or installation-cleanup — while PG itself answered a probe from that same pod in 331ms. A rollout restart on the same image fixed it, i.e. the only recovery was a human noticing. A transient connect failure at boot is not a property of the deployment, so it must not be decided once. WHAT THIS COMMIT DOES (acceptance 1 and 3). - `services/pgBootService.ts`: a retrying boot. Synchronous attempts with exponential backoff (defaults: 5 attempts, 500ms base, 30s cap), then a background retry every 30s until it succeeds, and the routes mount on the first success. All four are env-tunable (PG_BOOT_RETRY_ATTEMPTS, _BASE_DELAY_MS, _MAX_DELAY_MS, _INTERVAL_MS). It never throws, and it mounts only after a connect AND a schema initialization both succeed — a pod must not serve 500s on a route it only pretends to have. `pgBootState` is the observable result (mounted / attempts / fellBack / lastError / mountedAt). - `server.ts`: the 98-line boot block (one connect, five copies of a `{available:false}` placeholder status handler, one per failure branch) becomes a `createPgBoot(...).start()`. `/api/pg/status` is now mounted unconditionally and NOT as a placeholder: `checkStatus` reads the pool and the schema itself, so it is correct in every state — including the retry window, where the placeholders could never tell the truth after a late mount. Its POST /sync-user is only ever called after a GET said available:true (SocketContext.tsx:45-49), i.e. only when the pool is up. - `__tests__/unit/services/pgBootService.test.js` (8 cases): the acceptance-3 case makes the FIRST connect time out and proves the SECOND attempt mounts the routes; plus the fallback-then-background-success case, the schema-not-applied case, exponential backoff and its cap, mount idempotence, a throwing connector, post-mount work only on success, and the timer being cancelled once it succeeds. Clock, scheduler, connector and initializer are all injected, so the retry SHAPE is asserted, not just the end state. - `__tests__/unit/server.test.js`: the `server pg status route` block asserted the placeholder contract (available:false on every failure branch) and is replaced by a `server pg boot routes` block that asserts what server.ts owns — the status router is mounted for every configuration, the message routes stay unmounted while the boot connect keeps failing and while schema initialization fails, and a first connect that times out followed by a success mounts them. The mocked pg-messages router gained a route so a mounted router is distinguishable from an absent one. ACCEPTANCE 2 (readiness) IS NOT IN HERE, deliberately. It is ruled on separately: readiness is `/api/health/ready` (values.yaml:86) and `values-dev.yaml:23` sets replicaCount 1, so making readiness fail whenever PG is unreachable would take the only pod out of the Service and turn a PG blip into a total API outage — including Mongo-backed routes — which is the opposite of what a written decision in values.yaml:80-83 and the comment in `routes/health.ts` chose. The fork is with lily-shen on the row. EVIDENCE. `lint:ts` 0 errors. Full backend suite 445 suites / 4148 tests, with one unrelated pre-existing flake (`__tests__/service/uploads.signedurl.integration.test.js`, a per-token rate-limit case that passes on its own and alongside this suite; that file builds its own express app and never imports server.ts). Nine mutations, each red on the assertion it should red, each restored byte-identical with a green baseline after: one boot attempt only; no background retry scheduled; routes mounted before the schema is initialized; no cap on the backoff; mount() no longer idempotent; a throwing connector propagating; the background canceller never called on success; an eager `app.use('/api/pg/messages', …)` at boot (reds the two negative server-level cases, i.e. the incident's own defect shape); and — the harness case that matters — the mount-timeout bump, which is what surfaced that this suite re-requires server.ts four times and needed an explicit budget under full-run load rather than jest's 30s default. NOT VERIFIED. The retry has not been exercised against a real PG that is down at boot; the production path it fixes is a 2-minute connect timeout, and the delays here are the configured ones rather than that wall-clock shape. * fix(pg): readiness asserts the PG mount, not the boot block's flag (TASK-168) Acceptance 2 of the production incident: a pod whose boot connect timed out had no PG routes at all — `/api/pg/messages` 404'd, so chat history could not load — and it answered `/api/health/ready` 200 anyway, so a rollout sent it 100% of the traffic while the pod it replaced was healthy. Recovery required a human. `98f20db9` made that pod retry and mount in place; this makes it say so. WHAT WAS WRONG WITH THE OLD GATE. The handler asked whether a live PG query worked and returned 200 when it failed (`degraded: ['postgresql']`). It could not see the defect: `config/db-pg.ts` creates the pool lazily, so `SELECT 1` answered the moment the transient passed while the routes stayed unmounted. Asking PG how it feels is not the same question as whether this pod can serve chat, and lily's 20:57Z scope note asks for the second one: "readiness must not reuse that block's outcome as its own evidence; assert the mount." WHAT IT ASSERTS NOW. `/ready` returns 503 `{status:'not_ready', reason:'PostgreSQL routes are not mounted on this pod'}` when `PG_HOST` is set and the PG router is absent from the app — and 200 the moment the retry mounts it, with no restart. PG's liveness after a successful mount stays ungated on purpose: failing every pod's readiness on a shared-dependency blip would turn partial degradation into a full API outage (values.yaml, readinessProbe; `health.ready.test.js` still pins the degraded-200). THE PROBE IS THE ROUTE TABLE, NOT A FLAG. `routerIsMounted(app, pgMessageRoutes)` walks the Express stack for the router object by identity, so it cannot drift from what is actually mounted, and it stays correct if the path changes. It is deliberately not `pgBootState.mounted`/`pgAvailable`: a pod whose boot block believes it is fine while the route table disagrees is exactly the 2026-09-25 shape. `server.ts` installs it before `createPgBoot`, so the answer is live. A STRUCTURAL ASSERTION, and why. The states reachable in `server.test.js` cannot tell the flag from the table — no PG, both false; PG working, both true. A rewiring to `pgAvailable` would keep every behavioural case green while restoring the exact blindness that caused the outage, so the test also reads `server.ts` and refuses a probe wired to a flag (`routerIsMounted(app, pgMessageRoutes)` required; `setPgMountProbe(() => pgAvailable|pgBootState)` refused). EVIDENCE. Full backend suite 445 suites / 4158 tests green (`npx jest --forceExit`, Node 22); `npm run lint:ts` 0 errors; `tsc --noEmit` clean (only the pre-existing root-level `test-discord-interactions.ts` errors). Six mutations, each anchored, each restored byte-identical with a green baseline after: mount gate deleted → 2 red; gate back on the pool proxy → 2 red; probe wired to `pgAvailable` → the structural assertion; probe wired to `true` → the unmounted-route assertion; `routerIsMounted` answering true for anything → 4 red; `mountRoutes` not registering the router → 1 red. NOT VERIFIED. Not exercised against a real PG that is down at boot: every case above injects the failure, so what is proven is the logic and the wiring, not the end-to-end timing of a real connection timeout. `routeRateLimitGuard` and the deploy-dev probe in Team-Commonly#1899 are untouched. DELIBERATELY NOT IN THIS COMMIT: deleting the Mongo chat fallback (`pgAvailable` in the socket branch at `server.ts:607`, `pgAvailable()` in messageController.ts). lily's note asks for it and the argument is sound — the Mongo path's newest document is 2026-08-05, so it hides failures while serving stale rows — but it is a user-visible behaviour change on the write path, not part of "make the pod report the capability it is missing", and it should be reviewed as its own change rather than inside an incident fix. Flagged on the row. * ci(smoke): dump backend logs and an in-cluster readiness probe when the deploy fails * fix(pg): honour PG_SSL_ENABLED and refuse an empty CA file (TASK-168) WHY THIS IS IN THIS PR. The new readiness gate turned Team-Commonly#1901's kind smoke test red on the deploy step — the backend pod stayed 0/1 for the full 300s while every other pod was Ready, and `helm --wait` timed out. The pod was not slow; it was in a state it could never leave. The cause is this file: SSL disabled — ... (old) "Using CA certificate from: /app/certs/ca.pem" "SSL configuration added with CA certificate" "PostgreSQL connection error: The server does not support SSL connections" The chart sets `PG_SSL_ENABLED` (false locally, true in dev/prod) and the local secrets file carries the comment "Empty cert — not used when PG_SSL_ENABLED=false", but `db-pg.ts` never read that variable: it turned SSL ON whenever the CA *path* existed as a file. The local chart mounts a zero-byte `ca.pem` under a real path, so the smoke cluster's backend went into SSL mode against an in-cluster Postgres with no TLS and could not connect at all. That has been true on main for as long as the local chart has existed. Nothing reported it because the old readiness probe ignored PG: the pod served Mongo-fallback chat, returned 200, and the smoke suite passed. So a green kind smoke never proved the PG routes were mounted — which is the same blindness, in the same place, that made the 2026-09-25 production incident possible. The gate did not create this bug; it is the first thing to see it. THREE FAILURES IN ONE DIRECTION, all "SSL on for a server that has none": 1. `PG_SSL_ENABLED` ignored — now a first-class input. Unset still means ON, so dev and prod (both set "true" with a real Aiven CA) are byte-identical in behaviour. 2. An EMPTY CA file counted as a CA, because `fs.existsSync` was the entire test. `{ ca: '' }` both forces TLS and gives Node nothing to verify against. Any instance whose CA secret materializes empty lands here, not just kind. 3. The decision can now be read/tested as a pure function (`resolvePgSsl`) rather than only as a side effect at import time — the chart documents the intended rule in two comments, and a rule that lives in a side effect is how it drifted from them. WHAT WAS DELIBERATELY NOT CHANGED. A missing or unreadable CA still disables SSL rather than blocking boot: an unstoppable pod is worse than an unencrypted one that fails its own readiness gate, and the reasons are now logged with the decision instead of looking like a decision that was made. `rejectUnauthorized: true` is unchanged where SSL is on. EVIDENCE. With a real Postgres and the app run from source, the smoke cluster's exact shape — `PG_SSL_ENABLED=false` plus a zero-byte `ca.pem` at a real path — went from "The server does not support SSL connections" / `connectPG() → null` to `PostgreSQL connected: PostgreSQL 17.10` / `connectPG() → pool`. 9 new cases in `db-pg.ssl.test.js` (including the empty, whitespace-only, missing, unreadable and explicitly-true shapes, and one structural assertion that the module calls the exported function rather than deciding inline a second time). Backend suite with node 22: 444 suites / 4166 tests passed, the 2 reds being `agentsRuntime.rateLimitTiers` ("socket hang up") and `oauthController` (TASK-133) under parallel load — both pass in isolation, neither imports this file. `tsc --noEmit` clean; `lint:ts` 0 errors. Also fixed while here: a comment in routes/health.ts still named the probe `pathIsMounted`, which is not what it is called. * fix(pg): an unusable CA keeps TLS on instead of silently going plaintext (TASK-168) sprint-review caught this on Team-Commonly#1901 and they are right: the empty-CA guard changed DIRECTION. Before it, a zero-byte ca.pem meant TLS against a server with no TLS — a failed handshake, loud, no plaintext. The first version of this fix turned that same shape into `ssl: false`, i.e. a *successful plaintext* connection. In the file whose entire job is transport security, that is a downgrade traded for a green build. A configured `PG_SSL_CA_PATH` with an unusable file is a misconfiguration, never a request for plaintext. So the unusable-CA branches now return `{ rejectUnauthorized: true }` with no custom CA: TLS stays required, verification falls to the system store, and the handshake fails loudly (readiness then reports it) rather than a pod reading and writing chat in the clear because a secret materialized empty. The dev/prod shape this was written for — `PG_SSL_ENABLED` explicit "true" plus a real Aiven CA — is untouched. Plaintext now has exactly two doors, both deliberate, and neither is "a CA file we could not use": an explicit `PG_SSL_ENABLED=false` (the kind cluster, which is why the smoke fix still holds — the flag short-circuits before the CA is consulted), and an unset `PG_SSL_CA_PATH`, which is the pre-existing behaviour and is left alone rather than tightened in this PR. Tests: 13 cases, and they assert the reason STRING as well as the ssl decision, so each branch pins why it ran — a decision about TLS that is only visible as an object equality is one refactor away from being unverifiable. A new case pins the whitespace-only CA path (a chart that renders an unset value into a space), and one names the direction explicitly: the pairing that yields plaintext. Mutations (each restored byte-identical, file sha 15a6c7e7608a before and after): attaching the empty CA again — the pre-fix shape — reds all 5 unusable-CA cases; ignoring PG_SSL_ENABLED reds 3; deleting the empty guard reds; removing the path trim reds the new whitespace case. Recorded for the next reader: my first attempt at mutation 1 returned "Tests: 0 total" — a suite that fails to RUN, not an assertion that fails, because `ssl: false` in that branch is a type error. That is the same trap as a mutation that never applied; the mutation has to compile. * fix(pg): a failed TLS intent warns, and blank is not unset (TASK-168) Two findings from the gate on `288591e7`, both in code this PR just wrote. 1. THE LEVEL. Main warned for a missing CA file (`console.warn`, and `console.error` when the read threw). The rewrite flattened every branch into one `SSL disabled — …` line at `console.log`, so the three ways an explicit TLS intent can fail reported as routine config — the silent-config-failure shape this row exists to kill, reintroduced by its own fix. `level` is now part of the returned decision and the module logs with it, so the caller cannot lose the distinction: deliberate config is info, a failed intent is warn. 2. PRESENT-BUT-BLANK IS NOT ABSENT. `unset` was decided on the TRIMMED value, so a whitespace-only `PG_SSL_CA_PATH` took the no-path branch and downgraded to plaintext — one line below the empty-FILE case that correctly fails closed. The discriminator is the key: absent means not configured, anything present but unusable means configured wrong and keeps TLS required. WHAT FAIL-CLOSED COSTS, and the two configs it broke. Any environment that sets `PG_SSL_CA_PATH` without a CA behind it now fails its connect instead of quietly going unencrypted. The chart and the CI workflows already said which they wanted (`values-local.yaml: pgSslEnabled: "false"`, `PG_SSL_ENABLED=false` in tests.yml/playwright.yml). docker-compose and backend/.env.example declared `/app/ca.pem`, a path the backend image does not contain, and relied on the silent downgrade — so both now state `PG_SSL_ENABLED=false`. Measured against a real Postgres 17 with no TLS, the exact compose shape (`PG_SSL_CA_PATH` set, file absent): flag unset → `SSL enabled — CA file not found … keeping TLS on …` (warn) `The server does not support SSL connections`, connectPG() null, rc 1 flag false → `SSL disabled — PG_SSL_ENABLED=false` (info) `PostgreSQL connected: PostgreSQL 17.10`, connectPG() → pool, rc 0 Evidence: ssl suite 15/15; config + health.ready + pgBootService + server 64/64; `tsc --noEmit` clean for `config/`; eslint 0 errors. Seven mutations, baseline green on both sides, each restored byte-identical: blank-path treated as unset again → 4 red; warn flattened to info → 8 red; empty CA counted as a CA → 3; `PG_SSL_ENABLED` ignored → 3; unusable CA downgraded to plaintext → 9; level flattened at the call site → 1; the CA file never read at all → 6 (the non-vacuity control).
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.
Item 2 of the infrastructure scope on TASK-168: Deploy Dev now fails when the new backend can't serve chat.
A pod can be Ready and still be unable to serve chat. The backend decides once at boot whether Postgres is available, and
/readyanswers 200 in the degraded state. On 2026-09-25 a transient connect timeout at boot left/api/pg/messagesunmounted on the only replica. Chat history returned 404 for a few minutes, and Deploy Dev went green.The new step runs after the rollout check. It asks the newest non-terminating backend pod from the inside, so Cloudflare isn't in the path:
/api/pg/statusmust sayavailable:trueGET /api/pg/messages/<id>must answer 401 (mounted), not 404 (unmounted)It makes six attempts ten seconds apart. If they all fail, the run fails with the pod name, both values, and the restart command that fixes it.
Tested against the live cluster:
available:true, 401)/api/pgpath: exit 1 with the named errorThe first run showed that kubectl's jsonpath has no
!negation, so terminating pods are filtered inawk. The YAML parses.This check stays until readiness itself asserts the mount (TASK-168 item 1, sprint-impl). Deploy-on-merge (item 3) waits for both.
Gate: Vera.
🤖 Generated with Claude Code
https://claude.ai/code/session_01RUTWqLu6zhFPraoPHZcjQP