diff --git a/src/main/runtime/orchestration/db.ts b/src/main/runtime/orchestration/db.ts index 7dd39a614..dfcdc81f5 100644 --- a/src/main/runtime/orchestration/db.ts +++ b/src/main/runtime/orchestration/db.ts @@ -34,6 +34,7 @@ import { buildOrchestrationTaskDisplayMetadata } from '../../../shared/orchestra import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../shared/orchestration-rpc-contract' import { parsePaneKey } from '../../../shared/stable-pane-id' import { OrchestrationError } from './orchestration-error' +import { resolveOrchestrationMigrationStartVersion } from './orchestration-schema-version-skew' // Why: leaf UUID is the remint-stable pane identity (tab half changes on break-out); exact match covers legacy/unparseable keys. function isEquivalentPaneKey(a: string, b: string): boolean { @@ -143,8 +144,8 @@ function exposeQuestionTimestamps(question: QuestionRow): QuestionRow { export const LEGACY_RUN_ID = ORCHESTRATION_LEGACY_RUN_ID -// Schema versions: v2 'heartbeat'+last_heartbeat_at, v3 delivered_at, v4 task-creator terminal, v5 task_title/display_name, v6 pane identity, v7 lightweight Runs, v8 crash-safe Run deliveries, v9 durable question threads, v10 Dispatch capabilities, v11 durable mutation receipts, v12 composed worker state. -const SCHEMA_VERSION = 17 +// Schema versions: v2 'heartbeat'+last_heartbeat_at, v3 delivered_at, v4 task-creator terminal, v5 task_title/display_name, v6 pane identity, v7 lightweight Runs, v8 crash-safe Run deliveries, v9 durable question threads, v10 Dispatch capabilities, v11 durable mutation receipts, v12 composed worker state, v18 post-v6 version-skew repair. +const SCHEMA_VERSION = 18 function hardenOrchestrationDatabaseFiles(dbPath: string | ':memory:'): void { if (dbPath === ':memory:' || process.platform === 'win32') { @@ -416,7 +417,12 @@ export class OrchestrationDb { // Why: CREATE TABLE IF NOT EXISTS won't alter existing DBs; migrate in a txn that bumps user_version only on success (atomic all-or-nothing). private migrate(): void { - const current = this.db.pragma('user_version', { simple: true }) as number + const storedVersion = this.db.pragma('user_version', { simple: true }) as number + const current = resolveOrchestrationMigrationStartVersion( + this.db, + storedVersion, + SCHEMA_VERSION + ) if (current >= SCHEMA_VERSION) { return } diff --git a/src/main/runtime/orchestration/orchestration-schema-version-skew.ts b/src/main/runtime/orchestration/orchestration-schema-version-skew.ts new file mode 100644 index 000000000..9939974b4 --- /dev/null +++ b/src/main/runtime/orchestration/orchestration-schema-version-skew.ts @@ -0,0 +1,67 @@ +import type Database from '../../sqlite/sync-database' + +const POST_V6_COLUMNS = [ + ['messages', 'run_id'], + ['tasks', 'run_id'], + ['dispatch_contexts', 'run_id'], + ['dispatch_contexts', 'capability_hash'], + ['dispatch_contexts', 'process_incarnation'], + ['dispatch_contexts', 'capability_revoked_at'], + ['decision_gates', 'run_id'], + ['question_threads', 'run_id'], + ['worker_dispatches', 'runtime_epoch'], + ['federated_dispatches', 'to_home_imported_sequence'], + ['remote_dispatch_attachments', 'to_worker_imported_sequence'], + ['remote_dispatch_attachments', 'protocol_version'], + ['federation_relay_items', 'dispatch_id'], + ['remote_questions', 'message_id'] +] as const + +const POST_V6_INDEXES = [ + 'idx_messages_run_sequence', + 'idx_tasks_run_status', + 'idx_dispatch_run_status', + 'idx_gates_run_status', + 'idx_runs_coordinator_pane', + 'idx_deliveries_one_outstanding', + 'idx_deliveries_run_created', + 'idx_questions_dispatch_status', + 'idx_federation_relay_pending', + 'idx_remote_questions_dispatch_status' +] as const + +function hasOrchestrationColumn(db: Database.Database, table: string, column: string): boolean { + const rows = db.pragma(`table_info(${table})`) as { name: string }[] + return rows.some((row) => row.name === column) +} + +function hasOrchestrationIndex(db: Database.Database, index: string): boolean { + return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?").get(index) +} + +function messagesAllowQuestions(db: Database.Database): boolean { + const row = db + .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'messages'") + .get() as { sql: string } | undefined + return !!row && row.sql.includes("'question'") +} + +function hasCompletePostV6Schema(db: Database.Database): boolean { + return ( + POST_V6_COLUMNS.every(([table, column]) => hasOrchestrationColumn(db, table, column)) && + POST_V6_INDEXES.every((index) => hasOrchestrationIndex(db, index)) && + messagesAllowQuestions(db) + ) +} + +export function resolveOrchestrationMigrationStartVersion( + db: Database.Database, + storedVersion: number, + schemaVersion: number +): number { + if (storedVersion >= schemaVersion || hasCompletePostV6Schema(db)) { + return storedVersion + } + // Why: version-skewed pre-Run databases can claim the post-v6 range while retaining v6 tables. + return Math.min(storedVersion, 6) +} diff --git a/src/main/runtime/orchestration/orchestration-version-skew-migration.test.ts b/src/main/runtime/orchestration/orchestration-version-skew-migration.test.ts new file mode 100644 index 000000000..f8a97aa1e --- /dev/null +++ b/src/main/runtime/orchestration/orchestration-version-skew-migration.test.ts @@ -0,0 +1,171 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import Database from '../../sqlite/sync-database' +import { LEGACY_RUN_ID, OrchestrationDb } from './db' + +describe('OrchestrationDb version-skew migration', () => { + let db: OrchestrationDb | undefined + let tempDir: string | undefined + + afterEach(() => { + db?.close() + if (tempDir) { + rmSync(tempDir, { recursive: true, force: true }) + } + }) + + function createLegacySchemaClaimingVersion17(): string { + tempDir = mkdtempSync(join(tmpdir(), 'orca-db-version-skew-')) + const dbPath = join(tempDir, 'orchestration.db') + const raw = new Database(dbPath) + raw.exec(` + CREATE TABLE messages ( + id TEXT NOT NULL, + from_handle TEXT NOT NULL, + to_handle TEXT NOT NULL, + subject TEXT NOT NULL, + body TEXT NOT NULL DEFAULT '', + type TEXT NOT NULL DEFAULT 'status' + CHECK(type IN ( + 'status', 'dispatch', 'worker_done', 'merge_ready', + 'escalation', 'handoff', 'decision_gate', 'heartbeat' + )), + priority TEXT NOT NULL DEFAULT 'normal' + CHECK(priority IN ('normal', 'high', 'urgent')), + thread_id TEXT, + payload TEXT, + read INTEGER NOT NULL DEFAULT 0, + sequence INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + delivered_at TEXT, + sender_pane_key TEXT + ); + CREATE UNIQUE INDEX idx_messages_id ON messages(id); + CREATE INDEX idx_inbox ON messages(to_handle, read); + CREATE INDEX idx_thread ON messages(thread_id); + + CREATE TABLE tasks ( + id TEXT PRIMARY KEY, + parent_id TEXT, + created_by_terminal_handle TEXT, + task_title TEXT, + display_name TEXT, + spec TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending' + CHECK(status IN ('pending','ready','dispatched','completed','failed','blocked')), + deps TEXT NOT NULL DEFAULT '[]', + result TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + completed_at TEXT + ); + CREATE INDEX idx_tasks_status ON tasks(status); + CREATE INDEX idx_tasks_parent ON tasks(parent_id); + + CREATE TABLE dispatch_contexts ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL, + assignee_handle TEXT, + assignee_pane_key TEXT, + status TEXT NOT NULL DEFAULT 'pending' + CHECK(status IN ('pending','dispatched','completed','failed','circuit_broken')), + failure_count INTEGER NOT NULL DEFAULT 0, + last_failure TEXT, + dispatched_at TEXT, + completed_at TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_heartbeat_at TEXT + ); + CREATE INDEX idx_dispatch_task ON dispatch_contexts(task_id); + CREATE INDEX idx_dispatch_status ON dispatch_contexts(status); + + CREATE TABLE decision_gates ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL, + question TEXT NOT NULL, + options TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'pending' + CHECK(status IN ('pending','resolved','timeout')), + resolution TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + resolved_at TEXT + ); + CREATE INDEX idx_gates_task ON decision_gates(task_id); + CREATE INDEX idx_gates_status ON decision_gates(status); + + CREATE TABLE coordinator_runs ( + id TEXT PRIMARY KEY, + spec TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'idle' + CHECK(status IN ('idle','running','completed','failed')), + coordinator_handle TEXT NOT NULL, + poll_interval_ms INTEGER NOT NULL DEFAULT 2000, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + completed_at TEXT + ); + + INSERT INTO messages ( + id, from_handle, to_handle, subject, body, type + ) VALUES ( + 'msg_legacy', 'term_worker', 'term_coord', 'retained message', 'done', 'status' + ); + INSERT INTO tasks ( + id, created_by_terminal_handle, task_title, display_name, spec, status + ) VALUES ( + 'task_legacy', 'term_coord', 'Legacy task', 'Legacy task', 'retained task', 'dispatched' + ); + INSERT INTO dispatch_contexts ( + id, task_id, assignee_handle, assignee_pane_key, status + ) VALUES ( + 'ctx_legacy', 'task_legacy', 'term_worker', 'tab_legacy:leaf_legacy', 'dispatched' + ); + INSERT INTO decision_gates ( + id, task_id, question + ) VALUES ( + 'gate_legacy', 'task_legacy', 'retained gate' + ); + `) + raw.pragma('user_version = 17') + raw.close() + return dbPath + } + + it('repairs retained v6 rows when the database already claims v17', () => { + const dbPath = createLegacySchemaClaimingVersion17() + db = new OrchestrationDb(dbPath) + + expect(db.getRun(LEGACY_RUN_ID)).toMatchObject({ legacy: 1 }) + expect(db.getMessageById('msg_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID }) + expect(db.getTask('task_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID }) + expect(db.getDispatchContextById('ctx_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID }) + expect(db.getGate('gate_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID }) + + const run = db.createRun({ + objective: 'verify repaired orchestration', + coordinatorHandle: 'term_coord_v2', + coordinatorPaneKey: 'tab_v2:leaf_coord' + }) + const task = db.createTask({ spec: 'reply with ack', runId: run.id }) + const dispatch = db.createDispatchContext(task.id, 'term_worker_v2', 'tab_v2:leaf_worker') + const question = db.createQuestion({ + runId: run.id, + dispatchId: dispatch.id, + askerHandle: 'term_worker_v2', + question: 'ack?' + }) + const delivery = db.getOrCreateRunDelivery({ + runId: run.id, + consumerGeneration: run.consumer_generation + }) + expect(question.message.type).toBe('question') + expect(delivery?.messages.map((message) => message.id)).toContain(question.message.id) + + db.close() + db = undefined + db = new OrchestrationDb(dbPath) + expect(db.listTasks({ runId: LEGACY_RUN_ID }).map((row) => row.id)).toEqual(['task_legacy']) + expect(db.getRun(run.id)).toBeDefined() + expect(db.getQuestion(question.message.id)).toMatchObject({ status: 'pending' }) + }) +})