Skip to content

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): give migration 0002 an opt-in, archived repair for its own precondition (#228)

yetonea74670d49701
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index 2cfedb3..2894510 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -20,6 +20,19 @@ on:
description: 'Also update CUMORA_AGENT_COMPUTER_IMAGE (Y/N)'
required: false
default: 'Y'
+ repair_0002:
+ description: >-
+ Let migration 0002 repair its own precondition (off | archive-detach).
+ archive-detach copies every conversations.members id that has no
+ participant in that conversation's tenant into
+ conversation_members_detached_0002 (with its ordinal, so it is
+ reversible) and removes it from the array. Messages are untouched.
+ Runs inside 0002's transaction. Leave off unless you have read the
+ precheck report from a failed run.
+ required: false
+ default: 'off'
+ type: choice
+ options: ['off', 'archive-detach']
permissions:
contents: read
@@ -117,8 +130,16 @@ jobs:
id: migrate
env:
SERVER_IMAGE: ${{ steps.digest.outputs.server }}
+ REPAIR_0002: ${{ inputs.repair_0002 || 'off' }}
run: |
set -euo pipefail
+ case "$REPAIR_0002" in
+ off|archive-detach) ;;
+ *) echo "::error::repair_0002 must be 'off' or 'archive-detach' (got '$REPAIR_0002')"; exit 1 ;;
+ esac
+ if [ "$REPAIR_0002" != off ]; then
+ echo "::warning::migration 0002 will run repair mode '$REPAIR_0002' — it rewrites conversations.members and archives what it removes into conversation_members_detached_0002"
+ fi
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"
@@ -128,7 +149,7 @@ jobs:
# 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" '
+ jq --arg job "$JOB" --arg server "$SERVER_IMAGE" --arg repair "$REPAIR_0002" '
.spec.template.spec as $pod
| ([ $pod.initContainers[]?, $pod.containers[]? ]
| map(select(.name == "cloud-sql-proxy")) | first) as $proxy
@@ -169,6 +190,11 @@ jobs:
imagePullPolicy: "IfNotPresent",
command: ["npm", "run", "migrate"],
envFrom: [{ secretRef: { name: "cumora" } }],
+ # After envFrom on purpose: an explicit `env` entry
+ # wins over one supplied by envFrom, so the
+ # operator choice for this one run cannot be
+ # shadowed by whatever the Secret happens to hold.
+ env: [{ name: "MIGRATION_0002_REPAIR", value: $repair }],
resources: {
requests: { cpu: "100m", memory: "256Mi" },
limits: { cpu: "1000m", memory: "1Gi" }
diff --git a/docs/RELEASE.md b/docs/RELEASE.md
index 7b4b924..45d9c66 100644
--- a/docs/RELEASE.md
+++ b/docs/RELEASE.md
@@ -44,6 +44,8 @@ To deploy a candidate:
is available; Deploy resolves either tag to a digest before touching GKE.
3. Set `include_agent=Y` when the build changed `server/src/agents/**`, the
bundled CLI/runtime, or the agent-computer image. Otherwise use `N`.
+ Leave `repair_0002=off` unless you are clearing the migration 0002
+ precondition — see below.
4. Approve the protected `production` environment. The approver should not be
the person who built the feature for high-risk changes.
5. Verify the workflow summary contains the selected digest, previous server
@@ -59,6 +61,50 @@ a failed post-deploy smoke automatically runs
`kubectl rollout undo`, waits for the old revision to become ready, and fails
the workflow.
+#### When migration 0002 refuses to apply
+
+Migration 0002 normalizes conversation membership (ADR 0004) and fails closed
+when a `conversations.members` entry names an id with no participant in that
+conversation's tenant. The Job log carries a precheck report first — counts by
+category plus a masked sample — so read that before doing anything.
+
+These entries predate the tenant guard in `startPulledGroup` and grant nothing
+today: every read path is tenant-scoped, so a foreign member id is unreachable
+membership, and ADR 0004's composite FK cannot represent it at all. Rerunning
+Deploy with `repair_0002=archive-detach` lets 0002 clear its own precondition:
+
+- every offending `(conversation, member)` pair is copied into
+ `conversation_members_detached_0002` — with its ordinal *and* the whole
+ pre-detach members array — before it is removed;
+- `messages` is never touched, so an archived member that posted in the
+ conversation keeps its authorship;
+- the precheck re-runs afterwards, so anything a detach cannot fix (a
+ conversation with no `company_id`, say) still stops the deploy;
+- all of it runs inside 0002's transaction, so any later failure rolls the
+ detach back with it.
+
+The archive is a complete record, not a one-click undo. Once 0002 has applied,
+its projection trigger enforces ADR 0004 on every write, so putting a detached
+id back into `conversations.members` fails until that id is a real participant
+in that tenant — which is the invariant the migration exists to establish. What
+the archive gives you is the ability to see exactly what was removed and from
+where:
+
+```sql
+SELECT conversation_id, member_id, ordinal, authored_messages,
+ participant_elsewhere, original_members
+ FROM conversation_members_detached_0002
+ ORDER BY conversation_id, ordinal;
+```
+
+A genuine restore means first making the id resolvable (recreate or move the
+participant into that tenant), then re-adding it through `addConversationMember`.
+`original_members` records the exact pre-detach array to restore against.
+
+`repair_0002` applies to that one run only — it is passed as an explicit
+container `env` entry that overrides the `cumora` Secret, and defaults to
+`off`, so an ordinary deploy keeps failing closed.
+
Shipping features additionally track a production readback deadline, default
24 hours after a successful release. The Ship workspace surfaces due items;
the server turns missed deadlines into `overdue` release state plus high
diff --git a/server/src/__integration__/migration-0002-repair.test.ts b/server/src/__integration__/migration-0002-repair.test.ts
new file mode 100644
index 0000000..d0cb2a4
--- /dev/null
+++ b/server/src/__integration__/migration-0002-repair.test.ts
@@ -0,0 +1,155 @@
+/**
+ * Exercises the opt-in `archive-detach` repair for migration 0002 against a
+ * real PostgreSQL.
+ *
+ * The repair runs *before* 0002 installs `conversation_members` and its
+ * projection triggers, so the migrated schema these integration tests share
+ * cannot host the precondition it fixes — post-0002 you cannot even create an
+ * orphan, the trigger rejects it. So this builds the three tables the repair
+ * reads in a throwaway schema and runs the exact exported SQL against them.
+ * What is under test is the SQL itself: which ids get archived, that the
+ * ordinal is captured, that surviving members keep their order, and that
+ * `external:` markers and `messages` are left alone.
+ */
+import assert from 'node:assert/strict'
+import { after, before, test } from 'node:test'
+import { pool } from '../db/pool.js'
+import {
+ MIGRATION_0002_ARCHIVE_DDL,
+ MIGRATION_0002_ARCHIVE_TABLE,
+ repairConversationMembers,
+} from '../db/migrate.js'
+import { teardownAll } from './_helpers.js'
+
+const SCHEMA = 'migration_0002_repair_fixture'
+
+let client: import('pg').PoolClient
+
+before(async () => {
+ client = await pool.connect()
+ await client.query(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`)
+ await client.query(`CREATE SCHEMA ${SCHEMA}`)
+ await client.query(`SET search_path = ${SCHEMA}`)
+ await client.query(`
+ CREATE TABLE participants (
+ id TEXT NOT NULL,
+ company_id TEXT NOT NULL,
+ PRIMARY KEY (id, company_id)
+ );
+ CREATE TABLE conversations (
+ id TEXT PRIMARY KEY,
+ company_id TEXT,
+ members JSONB NOT NULL DEFAULT '[]'::jsonb
+ );
+ CREATE TABLE messages (
+ id TEXT PRIMARY KEY,
+ conversation_id TEXT NOT NULL,
+ author_id TEXT NOT NULL
+ );
+ `)
+})
+
+after(async () => {
+ await client.query(`RESET search_path`).catch(() => { /* best effort */ })
+ await client.query(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`).catch(() => { /* best effort */ })
+ // search_path is SESSION state and `release()` does not reset it — hand the
+ // connection back to the shared pool clean, or the next borrower inherits
+ // a schema that no longer exists.
+ client.release()
+ await teardownAll()
+})
+
+test('[integration] archive-detach removes only the unresolvable ids and keeps the rest in order', async () => {
+ await client.query(`
+ INSERT INTO participants (id, company_id) VALUES
+ ('alice', 'co-a'), ('bob', 'co-a'), ('nova', 'co-b');
+ INSERT INTO conversations (id, company_id, members) VALUES
+ ('pulled-1', 'co-a', '["alice","nova","bob","ghost","external:[email protected]"]'),
+ ('clean-1', 'co-a', '["alice","bob"]'),
+ ('tenantless', NULL, '["whoever"]');
+ INSERT INTO messages (id, conversation_id, author_id) VALUES
+ ('m1', 'pulled-1', 'nova'),
+ ('m2', 'pulled-1', 'alice');
+ `)
+
+ const summary = await repairConversationMembers(client)
+ assert.deepEqual(summary, { archived: 2, conversations: 1 })
+
+ const { rows: [conversation] } = await client.query<{ members: string[] }>(
+ `SELECT members FROM conversations WHERE id = 'pulled-1'`,
+ )
+ // 'nova' (other tenant) and 'ghost' (nowhere) are gone; the survivors keep
+ // their relative order and the external marker is untouched.
+ assert.deepEqual(conversation.members, ['alice', 'bob', 'external:[email protected]'])
+
+ const { rows: untouched } = await client.query<{ members: string[] }>(
+ `SELECT members FROM conversations WHERE id = 'clean-1'`,
+ )
+ assert.deepEqual(untouched[0].members, ['alice', 'bob'])
+
+ // A conversation with no tenant is outside the repair's remit — detaching
+ // members cannot fix it, and the precheck must still stop the deploy.
+ const { rows: tenantless } = await client.query<{ members: string[] }>(
+ `SELECT members FROM conversations WHERE id = 'tenantless'`,
+ )
+ assert.deepEqual(tenantless[0].members, ['whoever'])
+
+ const { rows: archived } = await client.query<{
+ member_id: string; ordinal: number; original_members: string[]
+ authored_messages: boolean; participant_elsewhere: boolean
+ }>(
+ `SELECT member_id, ordinal, original_members, authored_messages, participant_elsewhere
+ FROM ${MIGRATION_0002_ARCHIVE_TABLE} ORDER BY ordinal`,
+ )
+ const original = ['alice', 'nova', 'bob', 'ghost', 'external:[email protected]']
+ assert.deepEqual(archived, [
+ {
+ member_id: 'nova', ordinal: 1, original_members: original,
+ authored_messages: true, participant_elsewhere: true,
+ },
+ {
+ member_id: 'ghost', ordinal: 3, original_members: original,
+ authored_messages: false, participant_elsewhere: false,
+ },
+ ])
+
+ // Authorship is evidence of what happened and is never rewritten.
+ const { rows: [messages] } = await client.query<{ count: string }>(
+ `SELECT count(*) AS count FROM messages WHERE author_id = 'nova'`,
+ )
+ assert.equal(messages.count, '1')
+})
+
+test('[integration] the archive reconstructs the pre-detach array exactly', async () => {
+ // What original_members buys: the old state can be reproduced element for
+ // element rather than re-derived by interleaving ordinals. Post-0002 the
+ // projection trigger would reject writing an unresolvable id back — this
+ // fixture is the pre-0002 world, where the repair actually runs.
+ await client.query(`
+ UPDATE conversations c
+ SET members = a.original_members
+ FROM ${MIGRATION_0002_ARCHIVE_TABLE} a
+ WHERE a.conversation_id = c.id
+ `)
+
+ const { rows: [conversation] } = await client.query<{ members: string[] }>(
+ `SELECT members FROM conversations WHERE id = 'pulled-1'`,
+ )
+ assert.deepEqual(conversation.members, [
+ 'alice', 'nova', 'bob', 'ghost', 'external:[email protected]',
+ ])
+})
+
+test('[integration] the repair is idempotent on an already-clean database', async () => {
+ await client.query(`DELETE FROM ${MIGRATION_0002_ARCHIVE_TABLE}`)
+ await client.query(`DELETE FROM conversations WHERE company_id IS NULL`)
+ await client.query(`UPDATE conversations SET members = '["alice","bob"]'`)
+
+ const first = await repairConversationMembers(client)
+ assert.deepEqual(first, { archived: 0, conversations: 0 })
+ const second = await repairConversationMembers(client)
+ assert.deepEqual(second, { archived: 0, conversations: 0 })
+
+ // Re-running the DDL on an existing archive is a no-op, not an error.
+ await client.query(MIGRATION_0002_ARCHIVE_DDL)
+})
diff --git a/server/src/__tests__/migration-0002-precheck.test.ts b/server/src/__tests__/migration-0002-precheck.test.ts
index 8228e02..35a9323 100644
--- a/server/src/__tests__/migration-0002-precheck.test.ts
+++ b/server/src/__tests__/migration-0002-precheck.test.ts
@@ -4,7 +4,12 @@ import { test } from 'node:test'
process.env.CUMORA_RUNTIME_CLIENT = 'http'
process.env.OPENAI_API_KEY ??= 'test-key'
-const { checkConversationMembersResolvable } = await import('../db/migrate.js')
+const {
+ checkConversationMembersResolvable,
+ migration0002RepairMode,
+ repairConversationMembers,
+ MIGRATION_0002_ARCHIVE_TABLE,
+} = await import('../db/migrate.js')
const fakeClient = (summary: Record<string, unknown>, samples: Array<Record<string, unknown>> = []) => {
const statements: string[] = []
@@ -67,3 +72,43 @@ test('a conversation without a tenant is reported even when every member resolve
console.error = originalError
}
})
+
+test('the repair flag defaults to off and rejects anything it does not recognize', () => {
+ assert.equal(migration0002RepairMode(undefined), 'off')
+ assert.equal(migration0002RepairMode(''), 'off')
+ assert.equal(migration0002RepairMode(' OFF '), 'off')
+ assert.equal(migration0002RepairMode('Archive-Detach'), 'archive-detach')
+ // A typo must not read as "operator declined the repair".
+ assert.throws(() => migration0002RepairMode('true'), /must be unset/)
+ assert.throws(() => migration0002RepairMode('detach'), /got 'detach'/)
+})
+
+test('the repair archives every orphan with its ordinal before detaching it', async () => {
+ const statements: string[] = []
+ const client = {
+ async query(sql: string) {
+ statements.push(sql)
+ return { rows: [{ archived: '534', conversations: '23' }] }
+ },
+ }
+ const summary = await repairConversationMembers(client)
+ assert.deepEqual(summary, { archived: 534, conversations: 23 })
+
+ assert.equal(statements.length, 4)
+ assert.match(statements[0], new RegExp(`CREATE TABLE IF NOT EXISTS ${MIGRATION_0002_ARCHIVE_TABLE}`))
+ // The archive has to be written before the rows it describes are removed.
+ assert.match(statements[1], new RegExp(`^\\s*INSERT INTO ${MIGRATION_0002_ARCHIVE_TABLE}`))
+ assert.match(statements[2], /UPDATE conversations/)
+ assert.match(statements[1], /member\.ord - 1/)
+ assert.match(statements[1], /ON CONFLICT \(conversation_id, member_id\) DO NOTHING/)
+
+ // Messages are evidence of what happened; the repair must never rewrite them.
+ for (const sql of statements) {
+ assert.doesNotMatch(sql, /(?:UPDATE|DELETE\s+FROM)\s+messages\b/i)
+ assert.doesNotMatch(sql, /(?:UPDATE|DELETE\s+FROM|INSERT\s+INTO)\s+participants\b/i)
+ assert.doesNotMatch(sql, /DELETE\s+FROM\s+conversations\b/i)
+ }
+
+ // `external:` markers are not participants by design and must survive.
+ assert.match(statements[2], /member\.id LIKE 'external:%'/)
+})
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index 6d0cac3..42609bd 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -2365,8 +2365,148 @@ export async function checkConversationMembersResolvable(client: MigrationPreche
)
}
+/** Where `archive-detach` parks the member ids it removes from
+ * `conversations.members`, so the detach can be undone. */
+export const MIGRATION_0002_ARCHIVE_TABLE = 'conversation_members_detached_0002'
+
+export const MIGRATION_0002_ARCHIVE_DDL = `
+CREATE TABLE IF NOT EXISTS ${MIGRATION_0002_ARCHIVE_TABLE} (
+ conversation_id TEXT NOT NULL,
+ company_id TEXT NOT NULL,
+ member_id TEXT NOT NULL,
+ ordinal INTEGER NOT NULL,
+ original_members JSONB NOT NULL,
+ authored_messages BOOLEAN NOT NULL,
+ participant_elsewhere BOOLEAN NOT NULL,
+ archived_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (conversation_id, member_id)
+)`
+
+// Same predicate as UNRESOLVABLE_MEMBERS_CTE, plus everything needed to say
+// afterwards exactly what was removed: `ordinal` is where the id sat and
+// `original_members` is the whole pre-detach array, so the old state can be
+// reconstructed without re-deriving an interleaving. `authored_messages` /
+// `participant_elsewhere` record *why* the id was unresolvable.
+const MIGRATION_0002_ARCHIVE_ORPHANS = `
+INSERT INTO ${MIGRATION_0002_ARCHIVE_TABLE} (
+ conversation_id, company_id, member_id, ordinal, original_members,
+ authored_messages, participant_elsewhere
+)
+SELECT c.id, c.company_id, member.id, (member.ord - 1)::integer, c.members,
+ EXISTS (SELECT 1 FROM messages m
+ WHERE m.conversation_id = c.id AND m.author_id = member.id),
+ EXISTS (SELECT 1 FROM participants p WHERE p.id = member.id)
+ FROM conversations c
+ CROSS JOIN LATERAL jsonb_array_elements_text(c.members)
+ WITH ORDINALITY AS member(id, ord)
+ LEFT JOIN participants p
+ ON p.id = member.id AND p.company_id = c.company_id
+ WHERE c.company_id IS NOT NULL
+ AND p.id IS NULL
+ AND member.id NOT LIKE 'external:%'
+ON CONFLICT (conversation_id, member_id) DO NOTHING`
+
+// Rewrite only the affected conversations, preserving the relative order of
+// the members that stay. `external:` markers are kept on purpose — migration
+// 0002 strips them itself and they are not participants by design.
+const MIGRATION_0002_DETACH_ORPHANS = `
+WITH affected AS (
+ SELECT DISTINCT a.conversation_id FROM ${MIGRATION_0002_ARCHIVE_TABLE} a
+), kept AS (
+ SELECT c.id,
+ COALESCE(
+ jsonb_agg(member.id ORDER BY member.ord) FILTER (
+ WHERE member.id LIKE 'external:%'
+ OR EXISTS (SELECT 1 FROM participants p
+ WHERE p.id = member.id AND p.company_id = c.company_id)
+ ),
+ '[]'::jsonb
+ ) AS members
+ FROM conversations c
+ JOIN affected a ON a.conversation_id = c.id
+ CROSS JOIN LATERAL jsonb_array_elements_text(c.members)
+ WITH ORDINALITY AS member(id, ord)
+ GROUP BY c.id
+)
+UPDATE conversations c
+ SET members = kept.members
+ FROM kept
+ WHERE c.id = kept.id
+ AND c.members IS DISTINCT FROM kept.members`
+
+export type Migration0002RepairMode = 'off' | 'archive-detach'
+
+/**
+ * Read `MIGRATION_0002_REPAIR`. Unset means `off` — a deploy that has not
+ * asked for a repair keeps failing closed, which is the whole point of the
+ * precheck. An unrecognized value is a hard error rather than a silent `off`,
+ * because a typo in the one flag that touches production rows must not read
+ * as "operator declined".
+ */
+export function migration0002RepairMode(raw = process.env.MIGRATION_0002_REPAIR): Migration0002RepairMode {
+ const value = (raw ?? '').trim().toLowerCase()
+ if (value === '' || value === 'off') return 'off'
+ if (value === 'archive-detach') return 'archive-detach'
+ throw new Error(`MIGRATION_0002_REPAIR must be unset, 'off', or 'archive-detach' (got '${raw}')`)
+}
+
+/**
+ * Opt-in repair for the 0002 precondition (ADR 0004).
+ *
+ * The unresolvable rows are legacy `conversations.members` entries naming an
+ * id with no participant in that conversation's tenant — most of them ids
+ * that do exist, under a *different* company. They predate the tenant guard
+ * in `startPulledGroup`, which now refuses to build a cross-tenant members
+ * array at all. Such an id grants nothing today: every read path is
+ * tenant-scoped, so a foreign member id is unreachable membership, and ADR
+ * 0004's composite FK has no way to represent it in the first place.
+ *
+ * So the repair detaches them — but archives each one first, along with the
+ * conversation's whole pre-detach members array, so nothing is destroyed
+ * silently. That archive is a record, not a one-click undo: once 0002 has
+ * applied, its projection trigger enforces ADR 0004 on every write, so
+ * putting a detached id back requires making it a real participant in that
+ * tenant first. `messages` is never touched: an archived member that authored
+ * in the conversation keeps its authorship, it just stops being listed as a
+ * member.
+ *
+ * Runs inside migration 0002's transaction, so a failure later in the
+ * migration rolls the detach back with it.
+ */
+export async function repairConversationMembers(
+ client: MigrationPrecheckClient,
+): Promise<{ archived: number; conversations: number }> {
+ await client.query(MIGRATION_0002_ARCHIVE_DDL)
+ await client.query(MIGRATION_0002_ARCHIVE_ORPHANS)
+ await client.query(MIGRATION_0002_DETACH_ORPHANS)
+ const { rows: [totals] } = await client.query(`
+ SELECT count(*) AS archived, count(DISTINCT conversation_id) AS conversations
+ FROM ${MIGRATION_0002_ARCHIVE_TABLE}`)
+ return {
+ archived: Number(totals?.archived ?? 0),
+ conversations: Number(totals?.conversations ?? 0),
+ }
+}
+
async function applyNormalizedConversationMembers(client: import('pg').PoolClient): Promise<void> {
- await checkConversationMembersResolvable(client)
+ const repair = migration0002RepairMode()
+ try {
+ await checkConversationMembersResolvable(client)
+ } catch (error) {
+ // The precheck only SELECTs; the 23503 it raises is constructed in JS
+ // after those reads succeeded, so the surrounding transaction is still
+ // live and the repair can run on this same connection.
+ if (repair !== 'archive-detach' || (error as { code?: string }).code !== '23503') throw error
+ const repaired = await repairConversationMembers(client)
+ console.warn(
+ `[db] migration 0002 repair(archive-detach): detached ${repaired.archived} member id(s) ` +
+ `from ${repaired.conversations} conversation(s) into ${MIGRATION_0002_ARCHIVE_TABLE}`,
+ )
+ // Re-run rather than assume. A conversation with no company_id, for
+ // instance, is not something detaching members can fix, and must still
+ // stop the deploy.
+ await checkConversationMembersResolvable(client)
+ }
await client.query(NORMALIZED_CONVERSATION_MEMBERS_SQL)
}