Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(db): version schema migrations (#167)
OKNOTOK269e182a4af5
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.ymlindex 803afb6..2cfedb3 100644--- a/.github/workflows/deploy.yml+++ b/.github/workflows/deploy.yml@@ -36,7 +36,7 @@ jobs:deploy:name: Roll cumora-serverruns-on: ubuntu-latest- timeout-minutes: 15+ timeout-minutes: 30environment:name: productionurl: https://api.cumora.ai@@ -113,6 +113,104 @@ jobs:fifi+ - name: Run candidate migrations once+ id: migrate+ env:+ SERVER_IMAGE: ${{ steps.digest.outputs.server }}+ run: |+ set -euo pipefail+ JOB="cumora-migrate-${GITHUB_SHA:0:7}-${GITHUB_RUN_ATTEMPT}"+ DEPLOY_JSON="$RUNNER_TEMP/cumora-deployment.json"+ JOB_JSON="$RUNNER_TEMP/cumora-migration-job.json"++ # DATABASE_URL points at 127.0.0.1 because production reaches Cloud+ # SQL through the proxy. Copy the live proxy container and workload+ # identity settings into one candidate migration Job. A native+ # sidecar init container exits automatically when the Job completes.+ kubectl get deployment cumora-server -o json > "$DEPLOY_JSON"+ jq --arg job "$JOB" --arg server "$SERVER_IMAGE" '+ .spec.template.spec as $pod+ | ([ $pod.initContainers[]?, $pod.containers[]? ]+ | map(select(.name == "cloud-sql-proxy")) | first) as $proxy+ | if $proxy == null then+ error("cumora-server has no cloud-sql-proxy container")+ else+ {+ apiVersion: "batch/v1",+ kind: "Job",+ metadata: {+ name: $job,+ labels: { app: "cumora-schema-migration" }+ },+ spec: {+ backoffLimit: 0,+ activeDeadlineSeconds: 600,+ ttlSecondsAfterFinished: 600,+ template: {+ metadata: { labels: { app: "cumora-schema-migration" } },+ spec: {+ serviceAccountName: $pod.serviceAccountName,+ imagePullSecrets: ($pod.imagePullSecrets // []),+ restartPolicy: "Never",+ initContainers: [+ ($proxy+ | del(.readinessProbe, .livenessProbe, .lifecycle)+ | .restartPolicy = "Always"+ | .startupProbe = (.startupProbe // {+ httpGet: { path: "/readiness", port: 9090 },+ periodSeconds: 1,+ failureThreshold: 60+ }))+ ],+ containers: [+ {+ name: "migrate",+ image: $server,+ imagePullPolicy: "IfNotPresent",+ command: ["npm", "run", "migrate"],+ envFrom: [{ secretRef: { name: "cumora" } }],+ resources: {+ requests: { cpu: "100m", memory: "256Mi" },+ limits: { cpu: "1000m", memory: "1Gi" }+ }+ }+ ]+ }+ }+ }+ }+ end+ ' "$DEPLOY_JSON" > "$JOB_JSON"++ kubectl delete job "$JOB" --ignore-not-found --wait=true+ kubectl apply -f "$JOB_JSON"++ SUCCEEDED=N+ for _ in $(seq 1 120); do+ STATUS=$(kubectl get job "$JOB" -o json)+ if [ "$(echo "$STATUS" | jq -r '.status.succeeded // 0')" -ge 1 ]; then+ SUCCEEDED=Y+ break+ fi+ if [ "$(echo "$STATUS" | jq -r '.status.failed // 0')" -ge 1 ]; then+ break+ fi+ sleep 5+ done++ echo "::group::Migration output"+ kubectl logs "job/$JOB" -c migrate --tail=300 2>&1 || true+ echo "::endgroup::"+ if [ "$SUCCEEDED" != "Y" ]; then+ kubectl describe job "$JOB"+ kubectl get pods -l job-name="$JOB" -o wide+ echo "::error::Candidate database migration did not complete; deployment was not mutated."+ exit 1+ fi++ kubectl delete job "$JOB" --wait=true+ echo "job=$JOB" >> "$GITHUB_OUTPUT"+- name: Patch deploymentid: patchrun: |@@ -125,12 +223,9 @@ jobs:echo "→ rollback baseline server: $PREVIOUS_SERVER"echo "→ rollback baseline agent: ${PREVIOUS_AGENT:-'(unset)'}"- # Both the migrate init container and the main server container- # use the same image. set-image updates the main container; the- # init container needs an explicit JSON patch (its index is 1- # because cloud-sql-proxy lives at index 0 as a native sidecar).- #- # We also re-assert the liveness probe path here: liveness MUST hit+ # Apply one atomic Pod-template patch: select the candidate server,+ # remove the retired per-replica migration init container, and+ # re-assert the liveness probe path. Liveness MUST hit# /api/livez (a DB-free "process alive" check), NOT /api/health# (which runs SELECT 1). A DB-backed liveness probe let a slow /# overloaded DB fail the probe and SIGTERM-kill otherwise-healthy@@ -140,17 +235,26 @@ jobs:# path is already /api/livez. This keeps the fix durable even if the# Deployment is ever recreated from a base manifest that still has# the old /api/health liveness path.- kubectl set image deployment/cumora-server server="$SERVER"- kubectl patch deployment cumora-server --type=json -p="[- {\"op\":\"replace\",\"path\":\"/spec/template/spec/initContainers/1/image\",\"value\":\"$SERVER\"},- {\"op\":\"replace\",\"path\":\"/spec/template/spec/containers/0/livenessProbe/httpGet/path\",\"value\":\"/api/livez\"}- ]"-AGENT="${{ steps.digest.outputs.agent }}"- if [ -n "$AGENT" ]; then- kubectl set env deployment/cumora-server -c server \- CUMORA_AGENT_COMPUTER_IMAGE="$AGENT"- fi+ PATCH=$(jq -nc --arg server "$SERVER" --arg agent "$AGENT" '+ {+ spec: { template: { spec: {+ initContainers: [+ { name: "migrate", "$patch": "delete" }+ ],+ containers: [+ ({+ name: "server",+ image: $server,+ livenessProbe: { httpGet: { path: "/api/livez" } }+ } + if $agent == "" then {} else {+ env: [{ name: "CUMORA_AGENT_COMPUTER_IMAGE", value: $agent }]+ } end)+ ]+ } } }+ }+ ')+ kubectl patch deployment cumora-server --type=strategic -p="$PATCH"- name: Wait for rolloutid: rollout@@ -186,12 +290,6 @@ jobs:echo "::group::Recent cluster events"kubectl get events --sort-by=.lastTimestamp 2>&1 | tail -30echo "::endgroup::"- echo "::group::Migrate init container logs (each pod)"- for POD in $(kubectl get pods -l app=cumora-server -o jsonpath='{.items[*].metadata.name}'); do- echo "==== $POD ===="- kubectl logs "$POD" -c migrate --tail=100 2>&1 || true- done- echo "::endgroup::"echo "::group::Server container logs (current run)"for POD in $(kubectl get pods -l app=cumora-server -o jsonpath='{.items[*].metadata.name}'); doecho "==== $POD ===="@@ -239,5 +337,6 @@ jobs:echo "- server: \`${{ steps.digest.outputs.server }}\`" >> $GITHUB_STEP_SUMMARYecho "- agent: \`${{ steps.digest.outputs.agent || '(unchanged)' }}\`" >> $GITHUB_STEP_SUMMARYecho "- previous server: \`${{ steps.patch.outputs.previous_server }}\`" >> $GITHUB_STEP_SUMMARY+ echo "- migration owner: one pre-deploy Job (\`${{ steps.migrate.outputs.job }}\`)" >> $GITHUB_STEP_SUMMARYecho "- authenticated smoke: passed" >> $GITHUB_STEP_SUMMARYecho "- cluster: \`${{ env.CLUSTER }}\` / \`${{ env.CLUSTER_LOCATION }}\`" >> $GITHUB_STEP_SUMMARYdiff --git a/docs/RELEASE.md b/docs/RELEASE.mdindex 3e8fedd..b64743e 100644--- a/docs/RELEASE.md+++ b/docs/RELEASE.md@@ -48,10 +48,12 @@ To deploy a candidate:image, completed rollout, and passed authenticated smoke.Deploy first proves that the existing production API and smoke credential are-healthy, records the current revision as the rollback baseline, updates the-server/init-container (and optionally agent runtime) by digest, waits for GKE,-then exercises real authenticated tenant paths: auth, conversations, and the-Shipping overview/schema. A failed post-deploy smoke automatically runs+healthy, runs one candidate-image migration Job and verifies its immutable+ledger/index gates, records the current revision as the rollback baseline,+updates the server (and optionally agent runtime) by digest, waits for GKE, then+exercises real authenticated tenant paths: auth, conversations, and the+Shipping overview/schema. A migration failure leaves the Deployment untouched;+a failed post-deploy smoke automatically runs`kubectl rollout undo`, waits for the old revision to become ready, and failsthe workflow.diff --git a/docs/decisions/0003-versioned-schema-migration-ownership.md b/docs/decisions/0003-versioned-schema-migration-ownership.mdnew file mode 100644index 0000000..7cff40a--- /dev/null+++ b/docs/decisions/0003-versioned-schema-migration-ownership.md@@ -0,0 +1,65 @@+# ADR 0003: Versioned schema migrations with one deployment owner++- Status: Accepted+- Date: 2026-09-03++## Context++The server historically called one large idempotent DDL batch before opening+its HTTP listener. Kubernetes also ran the same command in every application+Pod's init container. An advisory lock serialized replicas, but restart,+autoscaling, rollout, and schema ownership still shared one failure domain.+Even a no-op batch requested locks across many hot tables, and a derived+sentinel probe had previously declared a partially upgraded schema current.++The repository already has a standalone migration entry point and a manually+approved Deploy workflow. Those are the appropriate ownership boundary; an+application replica has no reason to create or alter schema while starting.++## Decision++- Schema changes are an append-only ordered manifest. PostgreSQL records each+ exact `version`, `name`, and SHA-256 checksum in `schema_migrations`.+- An applied entry may never be edited or reordered. A checksum mismatch,+ missing prefix, or unknown future entry fails closed.+- One candidate-image Kubernetes Job runs `npm run migrate` before the Deploy+ workflow mutates the application Deployment. Failure leaves the current+ ReplicaSet untouched.+- The migration Job copies the production Cloud SQL proxy and workload identity+ settings, runs required index validity gates, and exits before rollout.+- Application Pods contain no migration init container. Startup performs one+ read-only ledger query and accepts only the schema range declared by that+ application build.+- An advisory lock remains defense in depth for accidentally duplicated deploy+ jobs; it is no longer coordination among application replicas.+- Future schema changes use expand/contract sequencing. A migration must remain+ compatible with the old application revision serving during a rolling+ update; destructive contraction occurs only after the old revision can no+ longer be restored.++## Consequences++- Restarting or scaling the API does not acquire DDL locks and cannot replay+ historical backfills.+- Deployment has an explicit schema promotion gate with durable, auditable+ version identity and required-index health.+- A first adoption run executes the frozen legacy baseline once and records it.+ Subsequent runs read the ledger and execute only newly appended versions.+- Local development and manual Kubernetes installation must run+ `npm run migrate` before starting the server; `npm run dev:all` performs that+ one explicit step automatically.+- Rollback compatibility is a release-design responsibility. A schema change+ outside the old build's declared range can intentionally prevent unsafe+ rollback rather than letting an old binary interpret unknown state.++## Alternatives considered++- **Keep DDL on every startup behind an advisory lock:** rejected because the+ lock serializes writers but does not separate schema failure from replica+ availability or prevent repeated hot-table lock attempts.+- **Keep a per-Pod migration init container:** rejected because every surge,+ restart, and scale-out becomes a schema owner and delays readiness.+- **Infer currency from tables, columns, or sentinel indexes:** rejected because+ absence lists drift and cannot prove which immutable transformation ran.+- **Allow checksum drift for idempotent SQL:** rejected because changing the+ meaning of an applied version destroys reproducibility and rollback evidence.diff --git a/docs/email.md b/docs/email.mdindex 5130f07..f98a61b 100644--- a/docs/email.md+++ b/docs/email.md@@ -97,9 +97,9 @@ EMAIL_DOMAIN=cumora.aiEMAIL_INBOUND_HMAC_SECRET=<openssl rand -hex 32>```-Restart the server. The migration (`server/src/db/migrate.ts`) runs-automatically and adds the `participants.email`, `email_messages`,-`email_contacts` tables.+Run `npm run migrate` once, then restart the server. The versioned migration+adds the `participants.email`, `email_messages`, and `email_contacts` tables;+normal server startup only verifies the migration ledger.### 2. Resenddiff --git a/package.json b/package.jsonindex 9ef3d83..6ed20af 100644--- a/package.json+++ b/package.json@@ -21,7 +21,7 @@"scripts": {"setup": "npm install && npm install --prefix workers/email-gate","dev": "vite --port 5180 --strictPort",- "dev:all": "concurrently -k -n web,api -c blue,magenta \"npm:dev\" \"npm:server:dev\"",+ "dev:all": "npm run migrate && concurrently -k -n web,api -c blue,magenta \"npm:dev\" \"npm:server:dev\"","build": "tsc -b && vite build","preview": "vite preview --host --port 5180","typecheck": "tsc --noEmit",diff --git a/server/docker/cumora-server.Dockerfile b/server/docker/cumora-server.Dockerfileindex 727be45..b1eb9e9 100644--- a/server/docker/cumora-server.Dockerfile+++ b/server/docker/cumora-server.Dockerfile@@ -7,7 +7,7 @@## Entry points:# npm run server:start → tsx server/src/index.ts (main runtime)-# npm run migrate → tsx server/src/migrate-bin.ts (init container)+# npm run migrate → tsx server/src/migrate-bin.ts (pre-deploy Job)## Why it ships kubectl: the orchestrator# (server/src/agents/runtime/orchestrator.ts) shells out to kubectl@@ -109,6 +109,6 @@ COPY --from=spa-build /app/dist ./distENV NODE_ENV=production# tini for PID-1 reaping. Default command runs the server; the-# init-container in our k8s manifests overrides to `npm run migrate`.+# dedicated pre-deploy Job overrides it with `npm run migrate`.ENTRYPOINT ["/usr/bin/tini", "--"]CMD ["npm", "run", "server:start"]diff --git a/server/k8s/cumora-server.gke.yaml b/server/k8s/cumora-server.gke.yamlindex cf0dbfb..6425720 100644--- a/server/k8s/cumora-server.gke.yaml+++ b/server/k8s/cumora-server.gke.yaml@@ -71,9 +71,8 @@ roleRef:name: cumora-server-agent-podsapiGroup: rbac.authorization.k8s.io----# Deployment — 2 replicas by default (wake-bus is Redis-pubsub-# backed, dedup via SETNX, advisory-locked migrations all make-# multi-replica safe).+# Deployment — 2 replicas by default. Database migrations are owned by one+# pre-deploy Job; application replicas only verify schema compatibility.apiVersion: apps/v1kind: Deploymentmetadata:@@ -99,18 +98,6 @@ spec:# --docker-username=... --docker-password=...imagePullSecrets:- name: quay-pull- initContainers:- - name: migrate- # REPLACE with the cumora-server image you pushed to a real- # registry. Tag with git sha or semver in prod, NOT :dev.- image: quay.io/yetoneful/cumora-server:REPLACE-TAG- imagePullPolicy: IfNotPresent- command: ["npm", "run", "migrate"]- envFrom:- - secretRef: { name: cumora }- resources:- requests: { cpu: "100m", memory: "256Mi" }- limits: { cpu: "500m", memory: "512Mi" }containers:# Cloud SQL Proxy sidecar — exposes Cloud SQL on 127.0.0.1:5432.# Authentication via Workload Identity, no SA key file needed.diff --git a/server/k8s/cumora-server.orbstack.yaml b/server/k8s/cumora-server.orbstack.yamlindex 0653948..d9039c3 100644--- a/server/k8s/cumora-server.orbstack.yaml+++ b/server/k8s/cumora-server.orbstack.yaml@@ -54,10 +54,9 @@ roleRef:name: cumora-server-agent-podsapiGroup: rbac.authorization.k8s.io----# Deployment — init container runs `npm run migrate` (advisory-lock-# protected, idempotent), main container starts the server.-# Multiple replicas: see e5e01e0 (wake-bus moved to Redis pubsub) +-# 0c5f11d (migration advisory lock) — replicas: 2+ is now safe.+# Deployment — run `npm run migrate` once before applying this manifest.+# Application replicas only verify the immutable migration ledger and never+# execute DDL while starting.apiVersion: apps/v1kind: Deploymentmetadata:@@ -72,13 +71,6 @@ spec:labels: { app: cumora-server }spec:serviceAccountName: cumora-server- initContainers:- - name: migrate- image: quay.io/yetoneful/cumora-server:dev- imagePullPolicy: IfNotPresent- command: ["npm", "run", "migrate"]- envFrom:- - secretRef: { name: cumora }containers:- name: serverimage: quay.io/yetoneful/cumora-server:devdiff --git a/server/k8s/gke.md b/server/k8s/gke.mdindex 69c0f44..4fb6961 100644--- a/server/k8s/gke.md+++ b/server/k8s/gke.md@@ -195,13 +195,16 @@ After replacing `REPLACE-*` placeholders in`server/k8s/cumora-server.gke.yaml`:```sh+# For a manual installation, run the candidate image's migration command once+# against the same DATABASE_URL before starting application replicas. The+# production Deploy workflow creates and verifies this one-shot Job for you.+npm run migratekubectl apply -f server/k8s/cumora-server.gke.yamlkubectl rollout status deployment/cumora-server```-The init container runs migrations (advisory-locked, so the 2-replicas don't race). Then the main container + Cloud SQL Proxy-sidecar start.+The application Pods only read `schema_migrations` and refuse to start outside+their supported version range. They never execute DDL during startup.## 7. Verify end-to-end@@ -232,12 +235,11 @@ kubectl logs agent-<id>duplicate the Role + RoleBinding scoped there.- **Image upgrades** — tag both images with the same git sha;redeploy by updating both the server Deployment image and- `CUMORA_AGENT_COMPUTER_IMAGE` to the same tag. Migrations run in the init- container before the main rollout proceeds.-- **PG schema changes** — the advisory lock means multiple init- containers in a rolling update will serialize. Each migration- must remain backward-compatible with the OLD server version- (still running on N-1 replicas during the rollout window).+ `CUMORA_AGENT_COMPUTER_IMAGE` to the same tag. The Deploy workflow runs one+ candidate migration Job before mutating the Deployment.+- **PG schema changes** — append an immutable version and checksum; never edit+ an applied migration. Use expand/contract changes that remain compatible with+ the old server version still serving during the rolling-update window.- **Idle scheduler** — runs in-process on EACH server replica.That's fine because idle's tick currently publishes toCH_MESSAGE_NEW which SETNX-dedups; only one replica handlesdiff --git a/server/src/__integration__/_helpers.ts b/server/src/__integration__/_helpers.tsindex 9c497ae..8c6c60d 100644--- a/server/src/__integration__/_helpers.ts+++ b/server/src/__integration__/_helpers.ts@@ -20,8 +20,8 @@ import { env } from '../env.js'let schemaReady: Promise<void> | null = null-/** Run the schema migrator exactly once per test process. Idempotent —- * ensureSchema is itself `IF NOT EXISTS` throughout. */+/** Run the versioned schema migrator exactly once per test process. Applied+ * ledger entries are immutable and are never replayed. */export function ensureSchemaOnce(): Promise<void> {if (!schemaReady) schemaReady = ensureSchema()return schemaReadydiff --git a/server/src/__integration__/board-column-kind.test.ts b/server/src/__integration__/board-column-kind.test.tsindex 5efe091..5791d67 100644--- a/server/src/__integration__/board-column-kind.test.ts+++ b/server/src/__integration__/board-column-kind.test.ts@@ -14,6 +14,7 @@ import { after, before, beforeEach, test } from 'node:test'import assert from 'node:assert/strict'import { randomUUID } from 'node:crypto'import { pool } from '../db/pool.js'+import { BASELINE_BOARD_COLUMN_KIND_BACKFILL_SQL } from '../db/migrate.js'import { runCli } from '../agents/cli.js'import { ensureSchemaOnce, resetAllTables, seedCompanyWithAgent, teardownAll } from './_helpers.js'@@ -112,9 +113,9 @@ test('the migration classifies conventional columns and leaves custom ones aloneconst custom = await seedBoard(companyId, [['Backlog', null], ['In flight', null], ['Shipped', null]])const spaced = await seedBoard(companyId, [[' To Do ', null]])- // Re-run the migrator; it is idempotent and re-applies the backfill.- const { ensureSchema } = await import('../db/migrate.js')- await ensureSchema()+ // Exercise the exact frozen migration-0001 backfill without replaying the+ // versioned migration ledger (applied migrations must never run again).+ await pool.query(BASELINE_BOARD_COLUMN_KIND_BACKFILL_SQL)const kinds = async (ids: string[]): Promise<Array<string | null>> => {const { rows } = await pool.query<{ id: string; kind: string | null }>(@@ -135,8 +136,7 @@ test('the backfill does not overwrite a column that already has a kind', async (const { companyId } = await seedCompanyWithAgent()const { columnIds } = await seedBoard(companyId, [['Done', 'todo']])- const { ensureSchema } = await import('../db/migrate.js')- await ensureSchema()+ await pool.query(BASELINE_BOARD_COLUMN_KIND_BACKFILL_SQL)const { rows } = await pool.query<{ kind: string | null }>(`SELECT kind FROM board_columns WHERE id = $1`, [columnIds[0]],diff --git a/server/src/__integration__/schema-migrations.test.ts b/server/src/__integration__/schema-migrations.test.tsnew file mode 100644index 0000000..50add25--- /dev/null+++ b/server/src/__integration__/schema-migrations.test.ts@@ -0,0 +1,70 @@+import { after, before, test } from 'node:test'+import assert from 'node:assert/strict'+import { pool } from '../db/pool.js'+import { ensureSchema, REQUIRED_SCHEMA_INDEXES } from '../db/migrate.js'+import { SCHEMA_MIGRATIONS } from '../db/migrations/manifest.js'+import { verifySchemaCompatibility } from '../db/schema-version.js'+import { ensureSchemaOnce, teardownAll } from './_helpers.js'++before(async () => { await ensureSchemaOnce() })+after(async () => { await teardownAll() })++test('PostgreSQL records the exact immutable migration manifest', async () => {+ const { rows } = await pool.query<{+ version: number+ name: string+ checksum: string+ execution_ms: number+ applied_at: Date+ }>(+ `SELECT version, name, checksum, execution_ms, applied_at+ FROM schema_migrations+ ORDER BY version ASC`,+ )+ assert.deepEqual(+ rows.map(({ version, name, checksum }) => ({ version, name, checksum })),+ SCHEMA_MIGRATIONS,+ )+ assert.ok(rows.every((row) => row.execution_ms >= 0))+ assert.ok(rows.every((row) => row.applied_at instanceof Date))+})++test('rerunning the migration owner does not rewrite applied history', async () => {+ const before = await pool.query<{ version: number; applied_at: Date }>(+ `SELECT version, applied_at FROM schema_migrations ORDER BY version`,+ )+ await ensureSchema()+ const after = await pool.query<{ version: number; applied_at: Date }>(+ `SELECT version, applied_at FROM schema_migrations ORDER BY version`,+ )+ assert.deepEqual(after.rows, before.rows)+})++test('application compatibility gate accepts the migrated database read-only', async () => {+ assert.equal(await verifySchemaCompatibility(pool), SCHEMA_MIGRATIONS.at(-1)?.version)+})++test('promotion-required indexes are valid, ready, and live', async () => {+ const { rows } = await pool.query<{+ name: string+ indisvalid: boolean+ indisready: boolean+ indislive: boolean+ }>(+ `SELECT c.relname AS name, i.indisvalid, i.indisready, i.indislive+ FROM pg_class c+ JOIN pg_index i ON i.indexrelid = c.oid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema()+ AND c.relname = ANY($1::text[])`,+ [[...REQUIRED_SCHEMA_INDEXES]],+ )+ const byName = new Map(rows.map((row) => [row.name, row]))+ for (const name of REQUIRED_SCHEMA_INDEXES) {+ const row = byName.get(name)+ assert.ok(row, `${name} must exist`)+ assert.equal(row.indisvalid, true, `${name} must be valid`)+ assert.equal(row.indisready, true, `${name} must be ready`)+ assert.equal(row.indislive, true, `${name} must be live`)+ }+})diff --git a/server/src/__tests__/db-schema-sentinels.test.ts b/server/src/__tests__/db-schema-sentinels.test.tsdeleted file mode 100644index a1b0d9c..0000000--- a/server/src/__tests__/db-schema-sentinels.test.ts+++ /dev/null@@ -1,66 +0,0 @@-/**- * The lock-contention shortcut must never declare a schema "current" while a- * column the DDL promises is absent.- *- * On 2026-08-31 it did exactly that: #133 added `messages.delivery_recipient_id`- * to the DDL but not to the hand-kept sentinel list, a loaded production lost- * the lock race on `messages` (55P03), the shortcut answered "current", migrate- * exited 0, and every BYOA daemon's /inbox 500'd on the missing column. The- * expectations are now derived from the DDL text, so these tests pin that the- * derivation actually sees what the DDL declares.- *- * Run: node --import tsx --test server/src/__tests__/db-schema-sentinels.test.ts- */-import { test } from 'node:test'-import assert from 'node:assert/strict'--process.env.CUMORA_RUNTIME_CLIENT = 'http'-process.env.OPENAI_API_KEY ??= 'test-key'--const { ddlExpectations } = await import('../db/migrate.js')--test('every ADD COLUMN IF NOT EXISTS in the DDL becomes an expectation', () => {- const { columns } = ddlExpectations()- const has = (t: string, c: string) => columns.some((x) => x.table === t && x.column === c)-- // The column whose omission caused the outage.- assert.ok(has('messages', 'delivery_recipient_id'), 'messages.delivery_recipient_id must be expected')- // Its neighbours, which were present in prod and masked the gap.- assert.ok(has('messages', 'client_id'))- assert.ok(has('messages', 'quoted_message_id'))-- assert.ok(columns.length > 20, `expected many derived columns, got ${columns.length}`)-})--test('CREATE TABLE IF NOT EXISTS names become table expectations', () => {- const { tables } = ddlExpectations()- for (const t of ['messages', 'conversations', 'participants', 'llm_calls', 'shipping_features']) {- assert.ok(tables.includes(t), `${t} must be expected`)- }- assert.equal(new Set(tables).size, tables.length, 'table list must be deduplicated')-})--test('commented-out DDL does not become a phantom expectation', () => {- const { columns } = ddlExpectations()- // A phantom would make schemaAlreadyCurrent permanently false and disable the- // shortcut entirely, turning every loaded deploy into a crash-loop.- for (const c of columns) {- assert.match(c.table, /^[a-z_][a-z0-9_]*$/)- assert.match(c.column, /^[a-z_][a-z0-9_]*$/)- }-})--test('a table the DDL creates and later drops is not an expectation', () => {- const { tables, columns } = ddlExpectations()- // The DDL still carries `CREATE TABLE IF NOT EXISTS email_verification_tokens`- // followed by the migration that dropped it when password auth was removed.- // Deriving expectations from the CREATEs alone made it a phantom: production- // could never be "current", the 40P01 shortcut never fired, and the v0.13.1- // rollout on 2026-09-02 crash-looped its migrate init container under load.- for (const t of ['email_verification_tokens', 'password_reset_tokens', 'notion_pages', 'github_branches']) {- assert.ok(!tables.includes(t), `${t} is dropped by the DDL and must not be expected`)- assert.ok(!columns.some((c) => c.table === t), `no column of dropped table ${t} may be expected`)- }- // The live tables next to them are still promised.- for (const t of ['users', 'sessions', 'user_identities']) assert.ok(tables.includes(t), `${t} must be expected`)-})diff --git a/server/src/__tests__/migrate-boot-retry.test.ts b/server/src/__tests__/migrate-boot-retry.test.tsdeleted file mode 100644index 903f184..0000000--- a/server/src/__tests__/migrate-boot-retry.test.ts+++ /dev/null@@ -1,144 +0,0 @@-/**- * Unit tests for ensureSchemaWithBootRetry — the boot-time wrapper that- * keeps the server alive across transient pg-pool acquire timeouts- * during the first few seconds after a DB hiccup.- *- * Run: node --import tsx --test server/src/__tests__/migrate-boot-retry.test.ts- */-import { test } from 'node:test'-import assert from 'node:assert/strict'-import { ensureSchemaWithBootRetry } from '../db/migrate.js'--const noSleep = async (_ms: number): Promise<void> => {}--test('passes through when schemaFn succeeds on first try', async () => {- let calls = 0- await ensureSchemaWithBootRetry({- schemaFn: async () => { calls++ },- sleep: noSleep,- })- assert.equal(calls, 1)-})--test('retries transport-shaped errors and recovers', async () => {- let calls = 0- await ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- if (calls < 3) throw new Error('Connection terminated due to connection timeout')- },- sleep: noSleep,- })- assert.equal(calls, 3)-})--test('retries on ECONNREFUSED', async () => {- let calls = 0- await ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- if (calls < 2) throw new Error('connect ECONNREFUSED 127.0.0.1:5432')- },- sleep: noSleep,- })- assert.equal(calls, 2)-})--test('retries lock-contention errors (40P01 deadlock) and recovers', async () => {- // Regression: a boot migration that loses a deadlock against live traffic- // used to fail fast and crashloop the pod; with two replicas down at once the- // LB served 502. A 40P01 (and 55P03 / 40001) must now be retried.- let calls = 0- await ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- if (calls < 3) {- const err = new Error('deadlock detected') as Error & { code: string }- err.code = '40P01'- throw err- }- },- sleep: noSleep,- })- assert.equal(calls, 3)-})--test('retries lock_not_available (55P03) from lock_timeout', async () => {- let calls = 0- await ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- if (calls < 2) {- const err = new Error('canceling statement due to lock timeout') as Error & { code: string }- err.code = '55P03'- throw err- }- },- sleep: noSleep,- })- assert.equal(calls, 2)-})--test('throws on the last attempt even if transport-shaped', async () => {- let calls = 0- await assert.rejects(- () => ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- throw new Error('timeout exceeded when trying to connect')- },- sleep: noSleep,- maxAttempts: 3,- }),- /timeout exceeded/,- )- assert.equal(calls, 3)-})--test('fails fast on non-transport errors (no retry)', async () => {- let calls = 0- await assert.rejects(- () => ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- throw new Error('permission denied for relation users')- },- sleep: noSleep,- }),- /permission denied/,- )- assert.equal(calls, 1)-})--test('does not retry on syntax errors', async () => {- let calls = 0- await assert.rejects(- () => ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- throw new Error('syntax error at or near "CRAETE"')- },- sleep: noSleep,- }),- /syntax error/,- )- assert.equal(calls, 1)-})--test('uses exponential backoff sequence (1s, 2s, 4s, 8s, 16s, 30s cap)', async () => {- const delays: number[] = []- let calls = 0- await assert.rejects(- () => ensureSchemaWithBootRetry({- schemaFn: async () => {- calls++- throw new Error('Connection terminated unexpectedly')- },- sleep: async (ms) => { delays.push(ms) },- maxAttempts: 6,- }),- )- assert.equal(calls, 6)- // 5 sleeps between 6 attempts; final attempt throws without sleeping.- assert.deepEqual(delays, [1_000, 2_000, 4_000, 8_000, 16_000])-})diff --git a/server/src/__tests__/migration-ownership.test.ts b/server/src/__tests__/migration-ownership.test.tsnew file mode 100644index 0000000..7136e96--- /dev/null+++ b/server/src/__tests__/migration-ownership.test.ts@@ -0,0 +1,37 @@+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { readFile } from 'node:fs/promises'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')+const readRepo = (path: string): Promise<string> => readFile(resolve(repoRoot, path), 'utf8')++test('application startup verifies schema compatibility and imports no migrator', async () => {+ const source = await readRepo('server/src/index.ts')+ assert.match(source, /verifySchemaWithBootRetry/)+ assert.doesNotMatch(source, /from ['"]\.\/db\/migrate\.js['"]/)+ assert.doesNotMatch(source, /ensureSchema/)+})++test('application Pod manifests contain no per-replica migration container', async () => {+ for (const path of [+ 'server/k8s/cumora-server.gke.yaml',+ 'server/k8s/cumora-server.orbstack.yaml',+ ]) {+ const manifest = await readRepo(path)+ assert.doesNotMatch(manifest, /^\s*- name: migrate\s*$/m, `${path} must not run DDL per replica`)+ assert.doesNotMatch(manifest, /command:\s*\["npm",\s*"run",\s*"migrate"\]/)+ }+})++test('production deploy migrates before one atomic Deployment mutation', async () => {+ const workflow = await readRepo('.github/workflows/deploy.yml')+ const migrationAt = workflow.indexOf('- name: Run candidate migrations once')+ const patchAt = workflow.indexOf('- name: Patch deployment')+ assert.ok(migrationAt >= 0, 'deploy must create a single candidate migration Job')+ assert.ok(patchAt > migrationAt, 'migration must complete before Deployment mutation')+ assert.match(workflow, /kind:\s*"Job"/)+ assert.match(workflow, /Candidate database migration did not complete; deployment was not mutated/)+ assert.match(workflow, /\{ name: "migrate", "\$patch": "delete" \}/)+})diff --git a/server/src/__tests__/schema-boot-retry.test.ts b/server/src/__tests__/schema-boot-retry.test.tsnew file mode 100644index 0000000..71049e9--- /dev/null+++ b/server/src/__tests__/schema-boot-retry.test.ts@@ -0,0 +1,123 @@+/** Read-only schema verification may ride out a brief DB transport failure,+ * but migration/history problems must fail startup immediately. */+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { MigrationHistoryError } from '../db/migrations/manifest.js'++process.env.CUMORA_RUNTIME_CLIENT = 'http'+process.env.OPENAI_API_KEY ??= 'test-key'++const { verifySchemaWithBootRetry } = await import('../db/schema-version.js')+const noSleep = async (_ms: number): Promise<void> => {}++test('returns the compatible version on the first probe', async () => {+ let calls = 0+ const version = await verifySchemaWithBootRetry({+ verifyFn: async () => { calls++; return 1 },+ sleep: noSleep,+ })+ assert.equal(version, 1)+ assert.equal(calls, 1)+})++test('retries transport-shaped failures and recovers', async () => {+ let calls = 0+ const version = await verifySchemaWithBootRetry({+ verifyFn: async () => {+ calls+++ if (calls < 3) throw new Error('Connection terminated due to connection timeout')+ return 1+ },+ sleep: noSleep,+ })+ assert.equal(version, 1)+ assert.equal(calls, 3)+})++test('retries ECONNREFUSED', async () => {+ let calls = 0+ await verifySchemaWithBootRetry({+ verifyFn: async () => {+ calls+++ if (calls < 2) throw new Error('connect ECONNREFUSED 127.0.0.1:5432')+ return 1+ },+ sleep: noSleep,+ })+ assert.equal(calls, 2)+})++test('fails fast on schema-history errors', async () => {+ let calls = 0+ await assert.rejects(+ () => verifySchemaWithBootRetry({+ verifyFn: async () => {+ calls+++ throw new MigrationHistoryError('schema_behind', 'run migrations')+ },+ sleep: noSleep,+ }),+ /run migrations/,+ )+ assert.equal(calls, 1)+})++test('does not treat migration lock errors as replica-startup retries', async () => {+ let calls = 0+ await assert.rejects(+ () => verifySchemaWithBootRetry({+ verifyFn: async () => {+ calls+++ const err = new Error('deadlock detected') as Error & { code: string }+ err.code = '40P01'+ throw err+ },+ sleep: noSleep,+ }),+ /deadlock detected/,+ )+ assert.equal(calls, 1)+})++test('throws on the last attempt even if transport-shaped', async () => {+ let calls = 0+ await assert.rejects(+ () => verifySchemaWithBootRetry({+ verifyFn: async () => {+ calls+++ throw new Error('timeout exceeded when trying to connect')+ },+ sleep: noSleep,+ maxAttempts: 3,+ }),+ /timeout exceeded/,+ )+ assert.equal(calls, 3)+})++test('fails fast on non-transport errors', async () => {+ let calls = 0+ await assert.rejects(+ () => verifySchemaWithBootRetry({+ verifyFn: async () => {+ calls+++ throw new Error('permission denied for relation schema_migrations')+ },+ sleep: noSleep,+ }),+ /permission denied/,+ )+ assert.equal(calls, 1)+})++test('uses exponential backoff with a 30 second cap', async () => {+ const delays: number[] = []+ await assert.rejects(+ () => verifySchemaWithBootRetry({+ verifyFn: async () => { throw new Error('Connection terminated unexpectedly') },+ sleep: async (ms) => { delays.push(ms) },+ maxAttempts: 7,+ }),+ )+ assert.deepEqual(delays, [1_000, 2_000, 4_000, 8_000, 16_000, 30_000])+})diff --git a/server/src/__tests__/schema-migrations.test.ts b/server/src/__tests__/schema-migrations.test.tsnew file mode 100644index 0000000..1dc7ad0--- /dev/null+++ b/server/src/__tests__/schema-migrations.test.ts@@ -0,0 +1,80 @@+import { test } from 'node:test'+import assert from 'node:assert/strict'+import type { QueryResult, QueryResultRow } from 'pg'+import {+ type AppliedMigration,+ MAX_SUPPORTED_SCHEMA_VERSION,+ MigrationHistoryError,+ SCHEMA_MIGRATIONS,+ validateMigrationHistory,+} from '../db/migrations/manifest.js'++process.env.CUMORA_RUNTIME_CLIENT = 'http'+process.env.OPENAI_API_KEY ??= 'test-key'++const { computedBaselineMigrationChecksum } = await import('../db/migrate.js')+const { verifySchemaCompatibility } = await import('../db/schema-version.js')+type SchemaVersionQueryable = import('../db/schema-version.js').SchemaVersionQueryable++const current = (): AppliedMigration[] => SCHEMA_MIGRATIONS.map((migration) => ({ ...migration }))++test('the frozen baseline SQL matches its immutable manifest checksum', () => {+ assert.equal(computedBaselineMigrationChecksum(), SCHEMA_MIGRATIONS[0].checksum)+})++test('the migration owner accepts an exact prefix and reports its pending suffix', () => {+ const empty = validateMigrationHistory([], { allowPending: true })+ assert.equal(empty.currentVersion, 0)+ assert.deepEqual(empty.pending, SCHEMA_MIGRATIONS)++ const complete = validateMigrationHistory(current(), { allowPending: true })+ assert.equal(complete.currentVersion, MAX_SUPPORTED_SCHEMA_VERSION)+ assert.deepEqual(complete.pending, [])+})++test('application startup rejects uninitialized, changed, and newer histories', () => {+ assert.throws(+ () => validateMigrationHistory([]),+ (err) => err instanceof MigrationHistoryError && err.code === 'schema_uninitialized',+ )+ assert.throws(+ () => validateMigrationHistory([{ ...current()[0], checksum: '0'.repeat(64) }]),+ (err) => err instanceof MigrationHistoryError && err.code === 'migration_history_invalid',+ )+ assert.throws(+ () => validateMigrationHistory([+ ...current(),+ { version: MAX_SUPPORTED_SCHEMA_VERSION + 1, name: 'future', checksum: 'f'.repeat(64) },+ ]),+ (err) => err instanceof MigrationHistoryError && err.code === 'schema_ahead',+ )+})++test('startup compatibility verification is a read-only ledger query', async () => {+ const statements: string[] = []+ const queryable: SchemaVersionQueryable = {+ async query<T extends QueryResultRow = QueryResultRow>(sql: string): Promise<QueryResult<T>> {+ statements.push(sql)+ return { rows: current() as unknown as T[], rowCount: current().length } as QueryResult<T>+ },+ }++ assert.equal(await verifySchemaCompatibility(queryable), MAX_SUPPORTED_SCHEMA_VERSION)+ assert.equal(statements.length, 1)+ assert.match(statements[0], /^SELECT\s/i)+ assert.doesNotMatch(statements[0], /\b(?:CREATE|ALTER|DROP|INSERT|UPDATE|DELETE)\b/i)+})++test('a missing schema_migrations table becomes an actionable startup error', async () => {+ const queryable: SchemaVersionQueryable = {+ async query<T extends QueryResultRow = QueryResultRow>(): Promise<QueryResult<T>> {+ const err = new Error('relation schema_migrations does not exist') as Error & { code: string }+ err.code = '42P01'+ throw err+ },+ }+ await assert.rejects(+ () => verifySchemaCompatibility(queryable),+ (err) => err instanceof MigrationHistoryError && err.code === 'schema_uninitialized',+ )+})diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex 0449fad..0d3e4f7 100644--- a/server/src/db/migrate.ts+++ b/server/src/db/migrate.ts@@ -1,9 +1,27 @@/**- * Idempotent boot-time schema initializer.- * For production we'd use drizzle-kit migrations; for now we ensure the- * schema exists via plain DDL so a fresh DATABASE_URL becomes a working app.+ * Versioned schema migrator.+ *+ * Only the standalone migration command calls this module in production.+ * Application replicas use the read-only compatibility gate in+ * schema-version.ts and never execute DDL while starting.*/+import { createHash } from 'node:crypto'import { pool } from './pool.js'+import {+ type AppliedMigration,+ type MigrationMetadata,+ SCHEMA_MIGRATIONS,+ validateMigrationHistory,+} from './migrations/manifest.js'++/** Frozen data backfill embedded in migration 0001. Exported so its behavior+ * can be exercised against PostgreSQL without replaying the whole migration. */+export const BASELINE_BOARD_COLUMN_KIND_BACKFILL_SQL = `UPDATE board_columns SET kind = 'todo'+ WHERE kind IS NULL AND lower(btrim(title)) IN ('todo', 'to do');+UPDATE board_columns SET kind = 'doing'+ WHERE kind IS NULL AND lower(btrim(title)) = 'doing';+UPDATE board_columns SET kind = 'done'+ WHERE kind IS NULL AND lower(btrim(title)) = 'done';`const DDL = `CREATE TABLE IF NOT EXISTS conversations (@@ -680,8 +698,9 @@ CREATE INDEX IF NOT EXISTS idx_conversations_company ON conversations(company_id-- NOT built here. A plain CREATE INDEX on this hot table holds a build-long lock-- that blocks live member-writes and deadlocks (40P01) under traffic — and since-- the build then never commits, every pod retried it forever and none could--- boot. It's built CONCURRENTLY + best-effort in buildConcurrentIndexes() below,--- outside this transaction. See idx_conversations_members_gin there.+-- boot. The dedicated migration owner builds it CONCURRENTLY outside this+-- transaction and treats readiness as a promotion requirement. See+-- buildConcurrentIndexes() below.CREATE INDEX IF NOT EXISTS idx_messages_company ON messages(company_id, created_at DESC);CREATE INDEX IF NOT EXISTS idx_agent_memory_company ON agent_memory(company_id, agent_id);CREATE INDEX IF NOT EXISTS idx_agent_log_company ON agent_log(company_id, agent_id);@@ -1360,12 +1379,7 @@ ALTER TABLE board_columns ADD COLUMN IF NOT EXISTS kind TEXT;-- flight / Shipped" is better left NULL (nothing moves automatically) than-- guessed at, and a wrong guess would silently move a user's cards. Runs once;-- already-classified columns are left alone so a later manual choice sticks.-UPDATE board_columns SET kind = 'todo'- WHERE kind IS NULL AND lower(btrim(title)) IN ('todo', 'to do');-UPDATE board_columns SET kind = 'doing'- WHERE kind IS NULL AND lower(btrim(title)) = 'doing';-UPDATE board_columns SET kind = 'done'- WHERE kind IS NULL AND lower(btrim(title)) = 'done';+${BASELINE_BOARD_COLUMN_KIND_BACKFILL_SQL}-- Cards live in a column. The "mentions" column is the deduped list of-- @-targets parsed from title+description on every write — clients can@@ -1834,60 +1848,6 @@ UPDATE participants p* pg_advisory_lock the same database. */const SCHEMA_LOCK_KEY = 7_643_178_926_104n-/**- * Boot-time wrapper around `ensureSchema` that retries with exponential- * backoff when the DB is briefly unreachable. Without this, a single- * pg-pool acquire timeout at startup crashes the process; k8s restarts- * it; the next attempt hits the same hiccup; pod crashloops until the- * blip clears — even though `ensureSchema` itself is idempotent and a- * 1–2s delay would have recovered.- *- * Retries on two retryable classes, fails fast on everything else- * (DDL / permission / syntax errors need a human, not a retry):- * - transport-shaped errors (connection timeout, EOF, terminated,- * ECONNREFUSED/RESET) — a DB blip during boot.- * - lock-contention errors (40P01 deadlock_detected, 55P03- * lock_not_available, 40001 serialization_failure) — the migration- * is idempotent + lock_timeout-bounded, so a blocked/deadlocked DDL- * just needs a short backoff and another try. NOT retrying these is- * what crashlooped the pod; with two replicas down at once the LB- * served 502.- *- * Total max wait: 1+2+4+8+16+30·4 = 151s across 9 attempts.- *- * `opts.schemaFn` and `opts.sleep` exist only for tests — production- * callers pass nothing.- */-export async function ensureSchemaWithBootRetry(opts: {- schemaFn?: () => Promise<void>- sleep?: (ms: number) => Promise<void>- maxAttempts?: number-} = {}): Promise<void> {- const schemaFn = opts.schemaFn ?? ensureSchema- const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)))- const maxAttempts = opts.maxAttempts ?? 9- let delayMs = 1_000- for (let attempt = 1; attempt <= maxAttempts; attempt++) {- try {- await schemaFn()- if (attempt > 1) {- console.log(`[boot] ensureSchema recovered on attempt ${attempt}/${maxAttempts}`)- }- return- } catch (e) {- const msg = e instanceof Error ? e.message : String(e)- const code = (e && typeof e === 'object' && 'code' in e) ? String((e as { code?: unknown }).code) : ''- const transportShaped = /timeout|terminated|ECONNREFUSED|ECONNRESET|EOF/i.test(msg)- const lockContention = code === '40P01' || code === '55P03' || code === '40001'- if ((!transportShaped && !lockContention) || attempt === maxAttempts) throw e- const kind = lockContention ? `lock-contention (${code})` : 'transient'- console.warn(`[boot] ensureSchema attempt ${attempt}/${maxAttempts} ${kind} failure: ${msg} — retrying in ${delayMs}ms`)- await sleep(delayMs)- delayMs = Math.min(delayMs * 2, 30_000)- }- }-}-/** Tables that store an agent id by value. Each entry carries a SQL* fragment (`scopeSql`) bound to `$2` = loser company_id, used as* the WHERE condition that limits the rename to that one tenant's@@ -2072,128 +2032,142 @@ async function renameAgentIdCollisions(client: import('pg').PoolClient): Promise}}+export function computedBaselineMigrationChecksum(): string {+ return createHash('sha256').update(DDL).digest('hex')+}++interface VersionedMigration extends MigrationMetadata {+ sourceChecksum: string+ up(client: import('pg').PoolClient): Promise<void>+}++async function applyLegacyBaseline(client: import('pg').PoolClient): Promise<void> {+ // pgvector remains optional: deployments without the extension retain the+ // recency-only memory path. All other baseline objects are mandatory.+ try {+ await client.query('CREATE EXTENSION IF NOT EXISTS vector')+ } catch (err) {+ console.warn(+ '[db] pgvector unavailable — semantic memory disabled:',+ err instanceof Error ? err.message : String(err),+ )+ }++ // This is the frozen baseline for databases that predate versioned+ // migrations. It runs once, from the dedicated migration owner, and is never+ // re-applied by application replicas.+ await client.query(DDL)+ await client.query(`+ DO $migrate$+ BEGIN+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'vector') THEN+ EXECUTE 'ALTER TABLE agent_workspace ADD COLUMN IF NOT EXISTS embedding vector(1536)';+ EXECUTE 'CREATE INDEX IF NOT EXISTS idx_workspace_embed_hnsw+ ON agent_workspace+ USING hnsw (embedding vector_cosine_ops)+ WHERE path LIKE ''memory/%''';+ END IF;+ END+ $migrate$;+ `)++ await renameAgentIdCollisions(client)+ await client.query(`+ CREATE UNIQUE INDEX IF NOT EXISTS participants_agent_id_unique+ ON participants(id) WHERE kind = 'agent'+ `)+ await client.query(`+ CREATE UNIQUE INDEX IF NOT EXISTS uniq_participants_agent_creation_request+ ON participants(company_id, creation_request_id)+ WHERE kind = 'agent' AND creation_request_id IS NOT NULL+ `)+ await ensureMessageClientIdIndex(client)+ await buildConcurrentIndexes(client)+ await verifyRequiredIndexes(client)+}++const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [+ {+ ...SCHEMA_MIGRATIONS[0],+ sourceChecksum: computedBaselineMigrationChecksum(),+ up: applyLegacyBaseline,+ },+]++function validateMigrationDefinitions(): void {+ if (VERSIONED_MIGRATIONS.length !== SCHEMA_MIGRATIONS.length) {+ throw new Error('migration definitions and immutable manifest have different lengths')+ }+ for (let i = 0; i < VERSIONED_MIGRATIONS.length; i++) {+ const definition = VERSIONED_MIGRATIONS[i]+ const metadata = SCHEMA_MIGRATIONS[i]+ if (+ definition.version !== metadata.version ||+ definition.name !== metadata.name ||+ definition.sourceChecksum !== metadata.checksum+ ) {+ throw new Error(+ `migration ${metadata.version} source checksum changed; append a new migration instead of editing applied history`,+ )+ }+ }+}++/**+ * Apply the immutable migration suffix exactly once.+ *+ * The advisory lock is defense in depth for an accidentally duplicated+ * pre-deploy job. Normal server startup never calls this function.+ */export async function ensureSchema(): Promise<void> {- // Two server instances booting at the same moment used to deadlock- // on concurrent CREATE TABLE / ALTER TABLE — Postgres serializes- // each DDL statement on system-catalog locks, but TWO migration- // sessions racing each other can wait on each other's catalog- // locks in a circle and PG aborts one with `40P01 deadlock- // detected`. Wrap the whole migration in a session-scoped advisory- // lock so only one instance migrates at a time; the rest queue up- // and find every DDL is already a no-op (everything is `IF NOT- // EXISTS` shaped). If the holder crashes mid-migration its- // connection drops and PG releases the lock automatically — next- // boot just picks up.+ validateMigrationDefinitions()const client = await pool.connect()try {- // Exempt this session from the pool's default statement_timeout: the- // advisory-lock acquisition below is intentionally unbounded (cross-instance- // serialization), and CONCURRENTLY index builds run for minutes. lock_timeout- // (set after the advisory lock) still bounds DDL lock WAITS to fail fast.await client.query('SET statement_timeout = 0')await client.query('SET idle_in_transaction_session_timeout = 0')await client.query('SELECT pg_advisory_lock($1)', [SCHEMA_LOCK_KEY])- // Bound how long any DDL will WAIT to acquire a table lock. The advisory- // lock above only serializes migration-vs-migration; it does nothing about- // migration-vs-live-traffic. Migrations are almost always no-ops (every- // statement is `IF NOT EXISTS`-shaped), but a no-op ALTER still needs a brief- // AccessExclusiveLock, and against constant agent/server queries that wait can- // turn into a `40P01 deadlock` — or stall a hot table long enough to fail the- // OTHER (healthy) pod's /api/health probe, which is how both replicas went- // unhealthy at once and the LB returned 502. With lock_timeout a blocked DDL- // aborts fast (`55P03`) and the boot-retry wrapper retries in a quieter- // moment instead of holding locks hostage. Set AFTER the advisory lock so the- // cross-instance serialization wait itself stays unbounded.await client.query("SET lock_timeout = '5s'")try {- // pgvector for semantic memory retrieval. Best-effort: if the- // extension isn't installed (or the DB user lacks CREATE- // EXTENSION grants) we silently skip and `loadMemory` falls- // back to its recency-only path. The column + index DDL below- // is gated on the extension actually being present.- try {- await client.query('CREATE EXTENSION IF NOT EXISTS vector')- } catch (e) {- console.warn('[db] pgvector unavailable — semantic memory disabled:', e instanceof Error ? e.message : String(e))- }- // The idempotent DDL batch below runs as ONE implicit transaction (node-pg- // simple protocol), so it briefly AccessExclusive-locks ~30 tables and HOLDS- // them all until commit. On an already-migrated prod DB every statement is a- // no-op, but under sustained write traffic those lock waits form a cycle and- // Postgres aborts the migration with 40P01 (deadlock) on EVERY boot — so no- // new pod could start (a hard outage; this is exactly what wedged prod). If- // the batch hits a lock error but the schema is already at the current shape- // (sentinels present), it had nothing to do anyway: log + proceed instead of- // crash-looping. A genuinely un-migrated DB (fresh / dev / CI) has no traffic- // and no sentinels, so it still runs + retries to completion.- try {- await client.query(DDL)- // Conditionally add the embedding column + HNSW index — only- // if pgvector was actually installed. Wrapped in DO $$ so the- // whole statement is a no-op when the extension isn't there.await client.query(`- DO $migrate$- BEGIN- IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'vector') THEN- EXECUTE 'ALTER TABLE agent_workspace ADD COLUMN IF NOT EXISTS embedding vector(1536)';- -- HNSW index is partial — only memory paths get it, so skills /- -- scripts files don't bloat the index with rows we never- -- semantic-search against.- EXECUTE 'CREATE INDEX IF NOT EXISTS idx_workspace_embed_hnsw- ON agent_workspace- USING hnsw (embedding vector_cosine_ops)- WHERE path LIKE ''memory/%''';- END IF;- END- $migrate$;+ CREATE TABLE IF NOT EXISTS schema_migrations (+ version INTEGER PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ checksum TEXT NOT NULL,+ execution_ms INTEGER NOT NULL CHECK (execution_ms >= 0),+ applied_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()+ )`)- // ============== Agent id global-uniqueness migration ==============- //- // The participants table's composite PK `(id, company_id)` was a- // multi-tenancy bolt-on that accidentally let the same agent id- // exist in multiple workspaces (humans use their user_id, which- // IS designed to be cross-workspace — but agents are supposed to- // be per-workspace and globally unique). The runtime resolves- // agents by id alone in many paths (persona cache, pod dedupe,- // `cumora doc ls` / `cumora kanban ls` company resolution), so- // any cross-tenant agent id collision causes the wrong tenant's- // library to be returned. Fix: rename the colliding rows so each- // agent id is globally unique, then enforce that with a partial- // unique index. Re-runs are no-ops (the SELECT finds 0 rows).- await renameAgentIdCollisions(client)- await client.query(`- CREATE UNIQUE INDEX IF NOT EXISTS participants_agent_id_unique- ON participants(id) WHERE kind = 'agent'- `)- await client.query(`- CREATE UNIQUE INDEX IF NOT EXISTS uniq_participants_agent_creation_request- ON participants(company_id, creation_request_id)- WHERE kind = 'agent' AND creation_request_id IS NOT NULL- `)- await ensureMessageClientIdIndex(client)-- console.log('[db] schema ensured')- } catch (e) {- const code = (e as { code?: string } | null)?.code- if ((code === '40P01' || code === '55P03') && (await schemaAlreadyCurrent(client))) {- console.warn(`[db] schema DDL hit lock contention (${code}) but schema is already current — proceeding without re-applying (idempotent no-op under live load)`)- } else {- throw e- }+ const readHistory = async (): Promise<AppliedMigration[]> => (+ await client.query<AppliedMigration>(+ `SELECT version, name, checksum, applied_at+ FROM schema_migrations+ ORDER BY version ASC`,+ )+ ).rows++ const history = validateMigrationHistory(await readHistory(), { allowPending: true })+ for (const metadata of history.pending) {+ const migration = VERSIONED_MIGRATIONS.find((candidate) => candidate.version === metadata.version)+ if (!migration) throw new Error(`migration ${metadata.version} has metadata but no implementation`)++ const started = Date.now()+ console.log(`[db] applying migration ${migration.version} ${migration.name}`)+ await migration.up(client)+ await client.query(+ `INSERT INTO schema_migrations (version, name, checksum, execution_ms)+ VALUES ($1, $2, $3, $4)`,+ [migration.version, migration.name, migration.checksum, Date.now() - started],+ )+ console.log(`[db] applied migration ${migration.version} in ${Date.now() - started}ms`)}++ const finalHistory = validateMigrationHistory(await readHistory())+ await verifyRequiredIndexes(client)+ console.log(`[db] schema is current at version ${finalHistory.currentVersion}`)} finally {- // Release on the same connection the lock was taken on.- // `pool.release(client)` below would do it implicitly via- // session close, but releasing explicitly lets the conn- // re-enter the pool with no lock state — cleaner.await client.query('SELECT pg_advisory_unlock($1)', [SCHEMA_LOCK_KEY]).catch(() => { /* swallow */ })}- // Heavy index builds run AFTER the advisory lock is released and OUTSIDE- // the migration transaction (CONCURRENTLY can't run in a txn, and we don't- // want a slow build to make other booting pods queue behind the advisory- // lock). Best-effort + non-fatal — see the helper.- await buildConcurrentIndexes(client)} finally {await releaseMigrationClient(client)}@@ -2227,126 +2201,17 @@ export async function releaseMigrationClient(client: MigrationClient): Promise<vclient.release()}-/**- * Cheap probe: are the schema's most-recently-added objects already present?- *- * Used to decide whether a lock-contention failure on the big DDL batch is safe- * to ignore. If these sentinels all exist, the idempotent batch was a guaranteed- * no-op, so a 40P01 / 55P03 trying to re-apply it changes nothing — we proceed- * rather than crash-loop. Read-only, so it's fine to run on the same connection- * right after the failed (auto-rolled-back) DDL.- *- * The expectations are derived FROM `DDL` itself rather than hand-listed. A- * hand-kept list is a whitelist of things that must be present, so an entry- * nobody remembered to add does not block the shortcut — its absence is simply- * never checked. That is not benign, and this comment used to claim it was: on- * 2026-08-31 #133 added `messages.delivery_recipient_id` without a sentinel, a- * loaded prod lost the lock race on the hot `messages` table (55P03), this- * function answered "current", migrate exited 0, and every daemon's /inbox 500'd- * on the missing column until production was rolled back. The same shape had- * already been caught twice before (llm_calls, llm_calls_rollup) — hence- * deriving the list instead of remembering it.- */-/** Every table and column `DDL` promises, read out of the DDL text so this can- * never fall behind it. Comments are stripped first so a commented-out example- * cannot become a phantom expectation. */-export function ddlExpectations(): { tables: string[]; columns: Array<{ table: string; column: string }> } {- const sql = DDL.replace(/--[^\n]*/g, '')- // A table the DDL creates and LATER drops (the retired auth-token tables) is- // not a promise — it is history. Left in, it is a phantom expectation that can- // never be satisfied: `schemaAlreadyCurrent` answers "not current" on every- // boot, the lock-contention shortcut below never fires, and a deploy under- // sustained traffic crash-loops on 40P01 with nothing to actually apply.- // That is exactly how the v0.13.1 rollout wedged on 2026-09-02.- // "Later" is by position in the DDL: a DROP that precedes a CREATE of the same- // name is a reset, and the re-created table is still promised.- const lastDropAt = new Map<string, number>()- for (const m of sql.matchAll(/DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-z_][a-z0-9_]*)/gi)) {- lastDropAt.set((m[1] as string).toLowerCase(), m.index ?? 0)- }- for (const m of sql.matchAll(/ALTER\s+TABLE\s+([a-z_][a-z0-9_]*)\s+DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?([a-z_][a-z0-9_]*)/gi)) {- lastDropAt.set(`${(m[1] as string).toLowerCase()}.${(m[2] as string).toLowerCase()}`, m.index ?? 0)- }- const droppedAfter = (key: string, at: number) => (lastDropAt.get(key) ?? -1) > at- const tables = [...sql.matchAll(/CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+([a-z_][a-z0-9_]*)/gi)]- .map((m) => ({ name: (m[1] as string).toLowerCase(), at: m.index ?? 0 }))- .filter((t) => !droppedAfter(t.name, t.at))- .map((t) => t.name)- const columns = [...sql.matchAll(/ALTER\s+TABLE\s+([a-z_][a-z0-9_]*)\s+ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+([a-z_][a-z0-9_]*)/gi)]- .map((m) => ({ table: (m[1] as string).toLowerCase(), column: (m[2] as string).toLowerCase(), at: m.index ?? 0 }))- .filter((c) => !droppedAfter(c.table, c.at) && !droppedAfter(`${c.table}.${c.column}`, c.at))- .map((c) => ({ table: c.table, column: c.column }))- return { tables: [...new Set(tables)], columns }-}--async function schemaAlreadyCurrent(client: import('pg').PoolClient): Promise<boolean> {- try {- const { tables, columns } = ddlExpectations()- // Indexes are not derivable the same way (partial/concurrent/renamed), so- // the few that gate correctness stay explicit.- const indexes = [- 'participants_agent_id_unique',- 'uniq_participants_agent_creation_request',- 'uniq_messages_client_id',- 'uniq_board_creation_request',- 'uniq_document_creation_request',- 'uniq_calendar_event_creation_request',- 'idx_realtime_outbox_pending',- ]- const { rows } = await client.query<{- missing_tables: string[]; missing_columns: string[]; missing_indexes: string[]- }>(- `WITH want_t(name) AS (SELECT unnest($1::text[])),- want_c(t, c) AS (SELECT unnest($2::text[]), unnest($3::text[])),- want_i(name) AS (SELECT unnest($4::text[]))- SELECT- COALESCE(ARRAY(- SELECT w.name FROM want_t w- WHERE NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = w.name)- ), '{}') AS missing_tables,- COALESCE(ARRAY(- SELECT w.t || '.' || w.c FROM want_c w- WHERE NOT EXISTS (- SELECT 1 FROM information_schema.columns- WHERE table_name = w.t AND column_name = w.c- )- ), '{}') AS missing_columns,- COALESCE(ARRAY(- SELECT w.name FROM want_i w- WHERE NOT EXISTS (- SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid- WHERE c.relname = w.name AND i.indisvalid- )- ), '{}') AS missing_indexes`,- [tables, columns.map((c) => c.table), columns.map((c) => c.column), indexes],- )- const missing = [- ...(rows[0]?.missing_tables ?? []),- ...(rows[0]?.missing_columns ?? []),- ...(rows[0]?.missing_indexes ?? []),- ]- if (missing.length > 0) {- // Say what is missing. The failure this replaces was invisible: migrate- // logged "schema ensured" and exited 0 while a column the app queries on- // every request did not exist.- console.warn(`[db] schema is NOT current — missing: ${missing.slice(0, 20).join(', ')}${missing.length > 20 ? ` (+${missing.length - 20} more)` : ''}`)- return false- }- return true- } catch {- return false- }-}-/** Correctness index for message idempotency. Build it concurrently so adding* the feature cannot block writes to the hot messages table. */async function ensureMessageClientIdIndex(client: import('pg').PoolClient): Promise<void> {- const { rows } = await client.query<{ indisvalid: boolean }>(- `SELECT i.indisvalid FROM pg_class c+ const { rows } = await client.query<{ indisvalid: boolean; indisready: boolean; indislive: boolean }>(+ `SELECT i.indisvalid, i.indisready, i.indislive FROM pg_class cJOIN pg_index i ON i.indexrelid = c.oid- WHERE c.relname = 'uniq_messages_client_id'`,+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema()+ AND c.relname = 'uniq_messages_client_id'`,)- if (rows[0]?.indisvalid) return+ if (rows[0]?.indisvalid && rows[0].indisready && rows[0].indislive) returnawait client.query("SET lock_timeout = '0'")try {if (rows[0]) await client.query('DROP INDEX CONCURRENTLY IF EXISTS uniq_messages_client_id')@@ -2369,20 +2234,18 @@ async function ensureMessageClientIdIndex(client: import('pg').PoolClient): Prom** `CREATE INDEX CONCURRENTLY` lets writes proceed during the build, so there is* no blocking lock and no deadlock. It MUST run outside any transaction — hence- * its own statements here, after the DDL batch committed and the advisory lock- * was released.+ * its own statements here, after the DDL batch committed.*- * Best-effort + NON-FATAL: these indexes are query optimizations, never a- * correctness requirement. A lock_timeout / interruption must never block boot- * (that was the whole bug). A previously-interrupted concurrent build leaves an- * INVALID index behind; `IF NOT EXISTS` would then skip it forever, so we drop- * any dead one first and rebuild.+ * These are now promotion requirements. A previously interrupted concurrent+ * build leaves an INVALID index behind; `IF NOT EXISTS` would then skip it+ * forever, so the migration owner drops the dead entry and rebuilds it. Failure+ * stops promotion but cannot crash-loop application replicas because replicas+ * never run this code.*/async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<void> {- const indexes: Array<{ name: string; table: string; create: string }> = [+ const indexes: Array<{ name: string; create: string }> = [{name: 'idx_conversations_members_gin',- table: 'conversations',// members @> [agentId] containment — the hottest read path (loadInbox /// loadContext / inbox-triage, called per wake + poll). Without it each// call seq-scans every conversation and saturates the pool.@@ -2391,7 +2254,6 @@ async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<},{name: 'idx_messages_author_created',- table: 'messages',// MAX(created_at) WHERE author_id = $1 — the idle scheduler's "when did// this agent last speak?" probe (idle.ts). Without it that subquery// SEQ-SCANNED the whole messages table per agent (~8s, 20+ concurrent),@@ -2401,7 +2263,6 @@ async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<},{name: 'idx_llm_calls_created_brin',- table: 'llm_calls',// Every Observability aggregation filters `created_at > NOW() - Ndays`,// and the DEFAULT admin view passes no companyId — so NONE of the other// llm_calls indexes (all led by company_id / run_id / agent_id / model /@@ -2420,26 +2281,60 @@ async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<},]for (const ix of indexes) {- try {- const { rows } = await client.query<{ indisvalid: boolean }>(- `SELECT i.indisvalid FROM pg_class c- JOIN pg_index i ON i.indexrelid = c.oid- WHERE c.relname = $1`,- [ix.name],- )- if (rows[0]?.indisvalid === false) {- console.warn(`[db] dropping invalid leftover index ${ix.name} before rebuild`)- await client.query(`DROP INDEX IF EXISTS ${ix.name}`)- } else if (rows[0]) {- continue // already present and valid — nothing to do- }- await client.query(ix.create)- console.log(`[db] concurrent index ready: ${ix.name}`)- } catch (e) {- console.warn(- `[db] concurrent index ${ix.name} skipped (non-fatal, retries next boot):`,- e instanceof Error ? e.message : String(e),- )+ const { rows } = await client.query<{ indisvalid: boolean; indisready: boolean; indislive: boolean }>(+ `SELECT i.indisvalid, i.indisready, i.indislive FROM pg_class c+ JOIN pg_index i ON i.indexrelid = c.oid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = $1`,+ [ix.name],+ )+ if (rows[0] && (!rows[0].indisvalid || !rows[0].indisready || !rows[0].indislive)) {+ console.warn(`[db] dropping invalid leftover index ${ix.name} before rebuild`)+ await client.query(`DROP INDEX CONCURRENTLY IF EXISTS ${ix.name}`)+ } else if (rows[0]) {+ continue}+ await client.query(ix.create)+ console.log(`[db] concurrent index ready: ${ix.name}`)+ }+}++export const REQUIRED_SCHEMA_INDEXES = [+ 'participants_agent_id_unique',+ 'uniq_participants_agent_creation_request',+ 'uniq_messages_client_id',+ 'uniq_board_creation_request',+ 'uniq_document_creation_request',+ 'uniq_calendar_event_creation_request',+ 'idx_realtime_outbox_pending',+ 'idx_conversations_members_gin',+ 'idx_messages_author_created',+ 'idx_llm_calls_created_brin',+] as const++/** Promotion gate: every required index must exist and be valid, ready, and+ * live. An interrupted CREATE INDEX CONCURRENTLY must never look healthy. */+async function verifyRequiredIndexes(client: import('pg').PoolClient): Promise<void> {+ const { rows } = await client.query<{+ name: string+ indisvalid: boolean+ indisready: boolean+ indislive: boolean+ }>(+ `SELECT c.relname AS name, i.indisvalid, i.indisready, i.indislive+ FROM pg_class c+ JOIN pg_index i ON i.indexrelid = c.oid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema()+ AND c.relname = ANY($1::text[])`,+ [[...REQUIRED_SCHEMA_INDEXES]],+ )+ const byName = new Map(rows.map((row) => [row.name, row]))+ const invalid = REQUIRED_SCHEMA_INDEXES.filter((name) => {+ const row = byName.get(name)+ return !row || !row.indisvalid || !row.indisready || !row.indislive+ })+ if (invalid.length > 0) {+ throw new Error(`required schema indexes missing or invalid: ${invalid.join(', ')}`)}}diff --git a/server/src/db/migrations/manifest.ts b/server/src/db/migrations/manifest.tsnew file mode 100644index 0000000..424911b--- /dev/null+++ b/server/src/db/migrations/manifest.ts@@ -0,0 +1,134 @@+/**+ * Immutable database-migration ledger understood by this application build.+ *+ * Append new entries; never edit or reorder an applied entry. The checksum is+ * stored in PostgreSQL and compared on every migration run and application+ * startup, so changing historical SQL fails closed instead of silently+ * redefining what an old version meant.+ */+export interface MigrationMetadata {+ version: number+ name: string+ checksum: string+}++export interface AppliedMigration extends MigrationMetadata {+ applied_at?: Date | string+}++export const SCHEMA_MIGRATIONS = [+ {+ version: 1,+ name: '0001_legacy_baseline',+ checksum: '5250b63e17bb5a028483b72a799b868418b875e7c0802be4168175b9930aa7d0',+ },+] as const satisfies readonly MigrationMetadata[]++/** This build intentionally supports one exact schema range. Expand/contract+ * releases may widen the range, but both bounds must remain explicit. */+export const MIN_SUPPORTED_SCHEMA_VERSION = 1+export const MAX_SUPPORTED_SCHEMA_VERSION = 1++function assertManifestShape(): void {+ for (let i = 0; i < SCHEMA_MIGRATIONS.length; i++) {+ const migration = SCHEMA_MIGRATIONS[i]+ if (migration.version !== i + 1) throw new Error('schema migration versions must be contiguous from 1')+ if (!/^\d{4}_[a-z0-9_]+$/.test(migration.name)) throw new Error(`invalid migration name: ${migration.name}`)+ if (!/^[a-f0-9]{64}$/.test(migration.checksum)) throw new Error(`invalid migration checksum: ${migration.name}`)+ }+ if (MAX_SUPPORTED_SCHEMA_VERSION !== SCHEMA_MIGRATIONS.at(-1)?.version) {+ throw new Error('maximum supported schema version must match the manifest tip')+ }+ if (MIN_SUPPORTED_SCHEMA_VERSION < 1 || MIN_SUPPORTED_SCHEMA_VERSION > MAX_SUPPORTED_SCHEMA_VERSION) {+ throw new Error('invalid supported schema version range')+ }+}++assertManifestShape()++export class MigrationHistoryError extends Error {+ readonly code: 'schema_uninitialized' | 'schema_behind' | 'schema_ahead' | 'migration_history_invalid'++ constructor(+ code: MigrationHistoryError['code'],+ message: string,+ ) {+ super(message)+ this.name = 'MigrationHistoryError'+ this.code = code+ }+}++export interface MigrationHistoryState {+ currentVersion: number+ pending: readonly MigrationMetadata[]+}++/**+ * Validate that the persisted ledger is an exact, contiguous prefix of this+ * build's immutable manifest. Migrators may accept a pending suffix; normal+ * application startup requires the supported range to already be present.+ */+export function validateMigrationHistory(+ appliedRows: readonly AppliedMigration[],+ opts: { allowPending?: boolean } = {},+): MigrationHistoryState {+ const applied = [...appliedRows].sort((a, b) => a.version - b.version)++ if ((applied.at(-1)?.version ?? 0) > MAX_SUPPORTED_SCHEMA_VERSION) {+ throw new MigrationHistoryError(+ 'schema_ahead',+ `database schema version ${applied.at(-1)?.version} is newer than this application supports (${MAX_SUPPORTED_SCHEMA_VERSION})`,+ )+ }++ if (applied.length > SCHEMA_MIGRATIONS.length) {+ throw new MigrationHistoryError(+ 'schema_ahead',+ `database schema version ${applied.at(-1)?.version ?? 'unknown'} is newer than this application supports (${MAX_SUPPORTED_SCHEMA_VERSION})`,+ )+ }++ for (let i = 0; i < applied.length; i++) {+ const actual = applied[i]+ const expected = SCHEMA_MIGRATIONS[i]+ if (!expected || actual.version !== expected.version) {+ throw new MigrationHistoryError(+ 'migration_history_invalid',+ `migration history is not a contiguous prefix at position ${i + 1}`,+ )+ }+ if (actual.name !== expected.name || actual.checksum !== expected.checksum) {+ throw new MigrationHistoryError(+ 'migration_history_invalid',+ `migration ${actual.version} does not match immutable manifest metadata`,+ )+ }+ }++ const currentVersion = applied.at(-1)?.version ?? 0+ const pending = SCHEMA_MIGRATIONS.slice(applied.length)+ if (opts.allowPending) return { currentVersion, pending }++ if (currentVersion === 0) {+ throw new MigrationHistoryError(+ 'schema_uninitialized',+ 'database schema is uninitialized; run `npm run migrate` before starting the server',+ )+ }+ if (currentVersion < MIN_SUPPORTED_SCHEMA_VERSION) {+ throw new MigrationHistoryError(+ 'schema_behind',+ `database schema version ${currentVersion} is behind the supported range ${MIN_SUPPORTED_SCHEMA_VERSION}-${MAX_SUPPORTED_SCHEMA_VERSION}; run ` ++ '`npm run migrate` before starting the server',+ )+ }+ if (currentVersion > MAX_SUPPORTED_SCHEMA_VERSION) {+ throw new MigrationHistoryError(+ 'schema_ahead',+ `database schema version ${currentVersion} is newer than the supported range ${MIN_SUPPORTED_SCHEMA_VERSION}-${MAX_SUPPORTED_SCHEMA_VERSION}`,+ )+ }++ return { currentVersion, pending }+}diff --git a/server/src/db/pool.ts b/server/src/db/pool.tsindex cbd8b1e..9bd6db8 100644--- a/server/src/db/pool.ts+++ b/server/src/db/pool.ts@@ -13,9 +13,9 @@ export const pool = new Pool({// un-indexed hot query (idle.ts' MAX(created_at) seq-scan) held all 20 slots// at ~8s each and 503-ed the entire API. 60s is far above any healthy request// (sub-second) but reaps genuine runaways; idle-in-transaction reaps leaked- // transactions holding a slot open doing nothing. Boot migrations and- // CONCURRENTLY index builds legitimately run longer and disable these on their- // own session (see ensureSchema -> `SET statement_timeout = 0`).+ // transactions holding a slot open doing nothing. The standalone migration+ // owner and CONCURRENTLY index builds legitimately run longer and disable+ // these on their own session (see ensureSchema -> `SET statement_timeout = 0`).statement_timeout: 60_000,idle_in_transaction_session_timeout: 30_000,})diff --git a/server/src/db/schema-version.ts b/server/src/db/schema-version.tsnew file mode 100644index 0000000..71ecc56--- /dev/null+++ b/server/src/db/schema-version.ts@@ -0,0 +1,78 @@+import type { QueryResult } from 'pg'+import { pool } from './pool.js'+import {+ type AppliedMigration,+ MigrationHistoryError,+ validateMigrationHistory,+} from './migrations/manifest.js'++export interface SchemaVersionQueryable {+ query<T extends import('pg').QueryResultRow = import('pg').QueryResultRow>(+ sql: string,+ values?: unknown[],+ ): Promise<QueryResult<T>>+}++/**+ * Read-only application-startup gate. This function deliberately contains no+ * CREATE/ALTER/DROP path: deployment owns migrations, while replicas only+ * confirm that the database is inside this build's supported version range.+ */+export async function verifySchemaCompatibility(+ queryable: SchemaVersionQueryable = pool,+): Promise<number> {+ let rows: AppliedMigration[]+ try {+ const result = await queryable.query<AppliedMigration>(+ `SELECT version, name, checksum, applied_at+ FROM schema_migrations+ ORDER BY version ASC`,+ )+ rows = result.rows+ } catch (err) {+ if ((err as { code?: unknown } | null)?.code === '42P01') {+ throw new MigrationHistoryError(+ 'schema_uninitialized',+ 'schema_migrations is missing; run `npm run migrate` before starting the server',+ )+ }+ throw err+ }++ return validateMigrationHistory(rows).currentVersion+}++/** Retry only transient database transport failures around the read-only+ * startup probe. Migration, checksum, and supported-range errors fail fast. */+export async function verifySchemaWithBootRetry(opts: {+ verifyFn?: () => Promise<number>+ sleep?: (ms: number) => Promise<void>+ maxAttempts?: number+} = {}): Promise<number> {+ const verifyFn = opts.verifyFn ?? verifySchemaCompatibility+ const sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))+ const maxAttempts = opts.maxAttempts ?? 9+ let delayMs = 1_000++ for (let attempt = 1; attempt <= maxAttempts; attempt++) {+ try {+ const version = await verifyFn()+ if (attempt > 1) {+ console.log(`[boot] schema verification recovered on attempt ${attempt}/${maxAttempts}`)+ }+ return version+ } catch (err) {+ if (err instanceof MigrationHistoryError) throw err+ const message = err instanceof Error ? err.message : String(err)+ const transient = /timeout|terminated|ECONNREFUSED|ECONNRESET|EOF/i.test(message)+ if (!transient || attempt === maxAttempts) throw err+ console.warn(+ `[boot] schema verification attempt ${attempt}/${maxAttempts} transient failure: ${message} — retrying in ${delayMs}ms`,+ )+ await sleep(delayMs)+ delayMs = Math.min(delayMs * 2, 30_000)+ }+ }++ throw new Error('schema verification retry loop exhausted')+}diff --git a/server/src/index.ts b/server/src/index.tsindex c324d1d..9493066 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -5,7 +5,7 @@ import { mkdir } from 'node:fs/promises'import { existsSync } from 'node:fs'import { join, resolve } from 'node:path'import { env } from './env.js'-import { ensureSchemaWithBootRetry } from './db/migrate.js'+import { verifySchemaWithBootRetry } from './db/schema-version.js'import { seedIfEmpty } from './seed.js'import { api } from './api/router.js'import { storage, UPLOAD_DIR } from './storage.js'@@ -37,7 +37,8 @@ import { startShippingMaintenance } from './shipping-maintenance.js'import { startRealtimeOutboxWorker, stopRealtimeOutboxWorker } from './realtime-outbox.js'async function main() {- await ensureSchemaWithBootRetry()+ const schemaVersion = await verifySchemaWithBootRetry()+ console.log(`[boot] schema version ${schemaVersion} is compatible`)await seedIfEmpty()// Promote CUMORA_ADMIN_EMAILS members to is_admin on every boot —// idempotent, only flips FALSE→TRUE. Demotion goes through the panel.diff --git a/server/src/migrate-bin.ts b/server/src/migrate-bin.tsindex 7d81d8a..5116363 100644--- a/server/src/migrate-bin.ts+++ b/server/src/migrate-bin.ts@@ -4,27 +4,26 @@* npx tsx server/src/migrate-bin.ts* # or, in package.json scripts: npm run migrate*- * Designed to be the entry point of a Kubernetes init container or- * a pre-deploy Job. Runs `ensureSchema()` and exits — no HTTP- * listener, no scheduler, no Redis subscription. In K8s init-- * container shape:+ * Designed to be the entry point of one pre-deploy Kubernetes Job. Runs+ * `ensureSchema()` and exits — no HTTP listener, scheduler, or Redis+ * subscription. Application Pods must not run this command as an init+ * container; their startup path is read-only schema verification.*+ * kind: Job* spec:- * initContainers:- * - name: migrate- * image: ghcr.io/yetoneful/cumora-server:<version>- * command: ["node", "/app/migrate-bin.cjs"]- * env:- * - { name: DATABASE_URL, valueFrom: { secretKeyRef: ... } }- * containers:- * - name: server- * ...+ * template:+ * spec:+ * containers:+ * - name: migrate+ * image: ghcr.io/yetoneful/cumora-server:<version>+ * command: ["node", "/app/migrate-bin.cjs"]+ * env:+ * - { name: DATABASE_URL, valueFrom: { secretKeyRef: ... } }*- * The migration is wrapped in a pg_advisory_lock (see db/migrate.ts)- * so multiple concurrent runners (rolling deploy, parallel init- * containers across replicas) serialize cleanly. The DDL is fully- * idempotent (IF NOT EXISTS / IF EXISTS shapes), so re-runs are- * no-ops.+ * The migration is wrapped in a pg_advisory_lock (see db/migrate.ts) as+ * defense in depth against duplicate deploy jobs. Applied immutable versions+ * are recorded in schema_migrations, so a rerun reads the ledger and executes+ * no historical DDL.** Exit codes:* 0 schema is up to date (or was, and migration finished cleanly)@@ -34,20 +33,18 @@import { pool } from './db/pool.js'import { ensureSchema } from './db/migrate.js'-// Postgres SQLSTATE codes for transient lock contention. ensureSchema is fully-// idempotent (every DDL is IF NOT EXISTS / IF EXISTS shaped) and advisory-lock-// serialized across replicas, so on these it is ALWAYS safe to back off and-// re-run the whole thing:+// Postgres SQLSTATE codes for transient lock contention. ensureSchema records+// only completed immutable versions and is advisory-lock serialized, so a+// failed attempt can safely back off and resume from the durable ledger:// 40P01 = deadlock_detected — a no-op ALTER's brief AccessExclusiveLock// raced a live agent/server query into a cycle// and PG aborted one. Under constant traffic this-// recurs, so a bare K8s init-container restart just-// crash-loops the rollout to failure (the outage-// this fixes) unless we retry IN-PROCESS in a-// quieter moment.+// recurs under sustained traffic, so the one+// pre-deploy Job retries in-process in a quieter+// moment instead of mutating the Deployment.// 55P03 = lock_not_available — lock_timeout (set inside ensureSchema) tripped// while WAITING for a table lock.-const TRANSIENT_LOCK_CODES = new Set(['40P01', '55P03'])+const TRANSIENT_LOCK_CODES = new Set(['40P01', '55P03', '40001'])const MAX_ATTEMPTS = 8async function main(): Promise<void> {@@ -60,15 +57,16 @@ async function main(): Promise<void> {process.exit(0)} catch (err) {const code = (err as { code?: unknown } | null)?.code- if (typeof code === 'string' && TRANSIENT_LOCK_CODES.has(code) && attempt < MAX_ATTEMPTS) {+ const message = err instanceof Error ? err.message : String(err)+ const lockContention = typeof code === 'string' && TRANSIENT_LOCK_CODES.has(code)+ const transportFailure = /timeout|terminated|ECONNREFUSED|ECONNRESET|EOF/i.test(message)+ if ((lockContention || transportFailure) && attempt < MAX_ATTEMPTS) {// The advisory lock is released on the failed attempt (ensureSchema's- // finally), so each retry re-acquires cleanly and the idempotent DDL- // re-runs as no-ops up to the statement that lost the race, then retries- // that one. Exponential backoff + jitter, capped at 15s — this is the- // "retry in a quieter moment" the surrounding comments promised but the- // runner never actually did.+ // finally), so each retry re-acquires cleanly and resumes from the last+ // recorded version. Exponential backoff + jitter is capped at 15s.const backoffMs = Math.min(15_000, 1_000 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500)- console.warn(`[migrate-bin] transient lock error ${code} (attempt ${attempt}/${MAX_ATTEMPTS}) — retrying in ${backoffMs}ms`)+ const kind = lockContention ? `lock error ${code}` : 'transport error'+ console.warn(`[migrate-bin] transient ${kind} (attempt ${attempt}/${MAX_ATTEMPTS}) — retrying in ${backoffMs}ms`)await new Promise((r) => setTimeout(r, backoffMs))continue}