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): wrap versioned schema migrations and ledger records in transactions (#214)

cicadab365154f7c21
diff --git a/server/src/__integration__/schema-migrations.test.ts b/server/src/__integration__/schema-migrations.test.ts
index 50add25..9e105f4 100644
--- a/server/src/__integration__/schema-migrations.test.ts
+++ b/server/src/__integration__/schema-migrations.test.ts
@@ -1,7 +1,12 @@
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 {
+ applyPendingMigration,
+ ensureSchema,
+ REQUIRED_SCHEMA_INDEXES,
+ type VersionedMigration,
+} 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'
@@ -68,3 +73,38 @@ test('promotion-required indexes are valid, ready, and live', async () => {
assert.equal(row.indislive, true, `${name} must be live`)
}
})
+
+test('a failed versioned migration rolls back DDL changes and leaves no ledger entry on PostgreSQL', async () => {
+ const client = await pool.connect()
+ try {
+ const dummyMigration: VersionedMigration = {
+ version: 9999,
+ name: '9999-fail-atomicity',
+ checksum: 'f'.repeat(64),
+ sourceChecksum: 'f'.repeat(64),
+ transactional: true,
+ up: async (txClient) => {
+ await txClient.query('CREATE TABLE IF NOT EXISTS migration_atomicity_test_table (id INT)')
+ throw new Error('simulated DDL explosion')
+ },
+ }
+
+ await assert.rejects(
+ () => applyPendingMigration(client, dummyMigration),
+ /simulated DDL explosion/,
+ )
+
+ const { rows: tableRows } = await pool.query(
+ `SELECT 1 FROM information_schema.tables WHERE table_name = 'migration_atomicity_test_table'`,
+ )
+ assert.equal(tableRows.length, 0, 'rolled-back table must not exist in database')
+
+ const { rows: ledgerRows } = await pool.query(
+ `SELECT 1 FROM schema_migrations WHERE version = 9999`,
+ )
+ assert.equal(ledgerRows.length, 0, 'rolled-back ledger row must not exist')
+ } finally {
+ client.release()
+ }
+})
+
diff --git a/server/src/__tests__/migration-transaction-atomicity.test.ts b/server/src/__tests__/migration-transaction-atomicity.test.ts
new file mode 100644
index 0000000..5230bd0
--- /dev/null
+++ b/server/src/__tests__/migration-transaction-atomicity.test.ts
@@ -0,0 +1,155 @@
+/**
+ * Database migration transaction atomicity.
+ *
+ * Migration DDL and ledger record must be atomic. If a migration is interrupted
+ * or fails midway, PostgreSQL must roll back all partial schema changes and
+ * the schema_migrations ledger must have no record, allowing clean recovery
+ * on rerun.
+ *
+ * Run: node --import tsx --test server/src/__tests__/migration-transaction-atomicity.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import type { PoolClient } from 'pg'
+
+process.env.CUMORA_RUNTIME_CLIENT = 'http'
+process.env.OPENAI_API_KEY ??= 'test-key'
+
+const { applyPendingMigration } = await import('../db/migrate.js')
+type VersionedMigration = import('../db/migrate.js').VersionedMigration
+
+function fakeClient(opts: { failRollback?: boolean } = {}) {
+ const calls: { sql: string; params?: unknown[] }[] = []
+ const client = {
+ calls,
+ query: async (sql: string, params?: unknown[]) => {
+ calls.push({ sql: sql.trim(), params })
+ if (sql.trim() === 'ROLLBACK' && opts.failRollback) {
+ throw new Error('rollback network error')
+ }
+ return { rows: [] }
+ },
+ release: () => {},
+ } as unknown as PoolClient
+ return { client, calls }
+}
+
+test('transactional migration executes within BEGIN and COMMIT', async () => {
+ const { client, calls } = fakeClient()
+ let upCalled = false
+
+ const migration: VersionedMigration = {
+ version: 2,
+ name: '0002-test',
+ checksum: 'a'.repeat(64),
+ sourceChecksum: 'a'.repeat(64),
+ transactional: true,
+ up: async () => {
+ upCalled = true
+ calls.push({ sql: 'CREATE TABLE test_table (id INT)' })
+ },
+ }
+
+ await applyPendingMigration(client, migration)
+
+ assert.ok(upCalled, 'migration.up should be called')
+ assert.equal(calls[0].sql, 'BEGIN')
+ assert.equal(calls[1].sql, 'CREATE TABLE test_table (id INT)')
+ assert.match(calls[2].sql, /^INSERT INTO schema_migrations/i)
+ assert.equal(calls[3].sql, 'COMMIT')
+})
+
+test('transactional migration defaults to true when transactional is omitted for version >= 2', async () => {
+ const { client, calls } = fakeClient()
+
+ const migration: VersionedMigration = {
+ version: 5,
+ name: '0005-test-default',
+ checksum: 'b'.repeat(64),
+ sourceChecksum: 'b'.repeat(64),
+ up: async () => {
+ calls.push({ sql: 'ALTER TABLE test ADD COLUMN foo TEXT' })
+ },
+ }
+
+ await applyPendingMigration(client, migration)
+
+ assert.equal(calls[0].sql, 'BEGIN')
+ assert.equal(calls[1].sql, 'ALTER TABLE test ADD COLUMN foo TEXT')
+ assert.match(calls[2].sql, /^INSERT INTO schema_migrations/i)
+ assert.equal(calls[3].sql, 'COMMIT')
+})
+
+test('failing migration issues ROLLBACK and never records ledger entry', async () => {
+ const { client, calls } = fakeClient()
+
+ const migration: VersionedMigration = {
+ version: 3,
+ name: '0003-failing',
+ checksum: 'c'.repeat(64),
+ sourceChecksum: 'c'.repeat(64),
+ transactional: true,
+ up: async () => {
+ calls.push({ sql: 'ALTER TABLE bad ADD COLUMN bar INT' })
+ throw new Error('relation bad does not exist')
+ },
+ }
+
+ await assert.rejects(
+ () => applyPendingMigration(client, migration),
+ /relation bad does not exist/,
+ )
+
+ const statements = calls.map((c) => c.sql)
+ assert.equal(statements[0], 'BEGIN')
+ assert.equal(statements[1], 'ALTER TABLE bad ADD COLUMN bar INT')
+ assert.equal(statements[2], 'ROLLBACK')
+ assert.ok(!statements.includes('COMMIT'), 'COMMIT must never be called on failure')
+ assert.ok(
+ !statements.some((s) => s.startsWith('INSERT INTO schema_migrations')),
+ 'schema_migrations record must never be written on failure',
+ )
+})
+
+test('non-transactional migration (transactional: false) runs without BEGIN/COMMIT', async () => {
+ const { client, calls } = fakeClient()
+
+ const migration: VersionedMigration = {
+ version: 1,
+ name: '0001-baseline',
+ checksum: 'd'.repeat(64),
+ sourceChecksum: 'd'.repeat(64),
+ transactional: false,
+ up: async () => {
+ calls.push({ sql: 'CREATE INDEX CONCURRENTLY idx_foo ON foo(id)' })
+ },
+ }
+
+ await applyPendingMigration(client, migration)
+
+ const statements = calls.map((c) => c.sql)
+ assert.ok(!statements.includes('BEGIN'), 'BEGIN must not be called')
+ assert.ok(!statements.includes('COMMIT'), 'COMMIT must not be called')
+ assert.equal(statements[0], 'CREATE INDEX CONCURRENTLY idx_foo ON foo(id)')
+ assert.match(statements[1], /^INSERT INTO schema_migrations/i)
+})
+
+test('rollback failure still preserves original migration error', async () => {
+ const { client } = fakeClient({ failRollback: true })
+
+ const migration: VersionedMigration = {
+ version: 4,
+ name: '0004-rollback-failure',
+ checksum: 'e'.repeat(64),
+ sourceChecksum: 'e'.repeat(64),
+ transactional: true,
+ up: async () => {
+ throw new Error('primary migration error')
+ },
+ }
+
+ await assert.rejects(
+ () => applyPendingMigration(client, migration),
+ /primary migration error/,
+ )
+})
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index 6e5e9f8..dcb691e 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -2048,8 +2048,9 @@ export function computedBaselineMigrationChecksum(): string {
return createHash('sha256').update(DDL).digest('hex')
}
-interface VersionedMigration extends MigrationMetadata {
+export interface VersionedMigration extends MigrationMetadata {
sourceChecksum: string
+ transactional?: boolean
up(client: import('pg').PoolClient): Promise<void>
}
@@ -2369,25 +2370,60 @@ const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
{
...SCHEMA_MIGRATIONS[0],
sourceChecksum: computedBaselineMigrationChecksum(),
+ transactional: false,
up: applyLegacyBaseline,
},
{
...SCHEMA_MIGRATIONS[1],
sourceChecksum: normalizedConversationMembersChecksum(),
+ transactional: true,
up: applyNormalizedConversationMembers,
},
{
...SCHEMA_MIGRATIONS[2],
sourceChecksum: workspaceCleanupJobsChecksum(),
+ transactional: true,
up: applyWorkspaceCleanupJobs,
},
{
...SCHEMA_MIGRATIONS[3],
sourceChecksum: agentRuntimeAssignmentChecksum(),
+ transactional: true,
up: applyAgentRuntimeAssignment,
},
]
+export async function applyPendingMigration(
+ client: import('pg').PoolClient,
+ migration: VersionedMigration,
+): Promise<void> {
+ const started = Date.now()
+ console.log(`[db] applying migration ${migration.version} ${migration.name}`)
+ if (migration.transactional !== false) {
+ await client.query('BEGIN')
+ try {
+ 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],
+ )
+ await client.query('COMMIT')
+ } catch (err) {
+ await client.query('ROLLBACK').catch(() => { /* swallow rollback err */ })
+ throw err
+ }
+ } else {
+ 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`)
+}
+
function validateMigrationDefinitions(): void {
if (VERSIONED_MIGRATIONS.length !== SCHEMA_MIGRATIONS.length) {
throw new Error('migration definitions and immutable manifest have different lengths')
@@ -2445,15 +2481,7 @@ export async function ensureSchema(): Promise<void> {
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`)
+ await applyPendingMigration(client, migration)
}
const finalHistory = validateMigrationHistory(await readHistory())