diff --git a/server/src/services/online-durable-data-migration.test.ts b/server/src/services/online-durable-data-migration.test.ts index ea6292c4428..83da5636465 100644 --- a/server/src/services/online-durable-data-migration.test.ts +++ b/server/src/services/online-durable-data-migration.test.ts @@ -1,6 +1,8 @@ +import fs from "node:fs/promises"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; import type { StorageService } from "../storage/index.js"; +import { RUNTIME_SKILL_ASSETS_BLOCKER } from "./ephemeral-server-contract.js"; import { resetOnlineDurableDataMigrationProgressForTests, runOnlineDurableDataMigration } from "./online-durable-data-migration.js"; const db = {} as Db; @@ -283,6 +285,66 @@ describe("online durable-data migration pass", () => { expect(result.deferred).toMatchObject({ "workspace_operations:finalization_owner_busy": 2 }); }); + it("names the workspace codes from an earlier pass when the pass that finishes the round does not reach workspaces", async () => { + let clock = 0; + const fixture = owners({ + localWorkspaces: async () => { clock = 60_000; return [workspace(1), workspace(2)]; }, + inventoryWorkspace: async (_db: Db, input: { workspaceId: string }) => ({ reasons: [input.workspaceId === "w1" ? "active_execution" : "task_binding_required"] }), + eligibility: async () => ({ eligible: false, blockers: ["workspaces_require_migration"] }), + }); + const run = () => runOnlineDurableDataMigration(db, { budgetMs: 60_000, now: () => clock }, fixture.owners); + expect(await run()).toMatchObject({ state: "budget_exhausted", resumePhase: "native_harness_backups", + deferred: { "workspaces:active_execution": 1, "workspaces:task_binding_required": 1 } }); + clock = 0; + const result = await run(); + expect(result).toMatchObject({ state: "completed", blockers: ["workspaces_require_migration"] }); + expect(result.deferred).toMatchObject({ "workspaces:active_execution": 1, "workspaces:task_binding_required": 1 }); + }); + + it("names a workspace blocker that no inspected workspace explains", async () => { + const fixture = owners({ eligibility: async () => ({ eligible: false, blockers: ["workspaces_require_migration"] }) }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(result.deferred).toMatchObject({ "workspaces:pending_inspection": 1 }); + }); + + it("names every durable-data blocker that readiness can report", async () => { + const source = await fs.readFile(new URL("./ephemeral-server-contract.ts", import.meta.url), "utf8"); + const blockers = [...new Set([...source.matchAll(/blockers\.push\("([a-z_]+)"\)/g)].map(match => match[1]!)), RUNTIME_SKILL_ASSETS_BLOCKER]; + expect(blockers).toEqual(expect.arrayContaining(["workspaces_require_migration", "local_instruction_copies_require_settlement", "external_agent_instructions"])); + for (const blocker of blockers) { + resetOnlineDurableDataMigrationProgressForTests(); + const fixture = owners({ eligibility: async () => ({ eligible: false, blockers: [blocker] }), + agentFiles: async () => ({ results: [], next: null }), + skillObjects: async () => ({ inspected: 0, migrated: 0, busy: 0, after: null }), + skillInstallations: () => ({ installations: async () => ({ inspected: 0, after: null, results: [] }) }), + nativeHarnessBackups: async () => ({ inspected: 0, published: 0, current: 0, deferred: {} }) }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(Object.keys(result.deferred), blocker).toHaveLength(1); + } + }); + + it("names a local instruction copy that still needs settlement after the agent files are durable", async () => { + const fixture = owners({ agentFiles: async () => ({ results: [{ agentId: "a1", state: "durable" }], next: null }), + eligibility: async () => ({ eligible: false, blockers: ["local_instruction_copies_require_settlement"] }) }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(result.deferred).toEqual({ "skill_objects:owner_busy": 1, "skills:linked_local": 1, "native_harness:source_active": 2, + "agent_files:instruction_copy_unsettled": 1 }); + }); + + it("drops codes from an earlier round once the workspaces are inspected again", async () => { + let blocked = true; + const fixture = owners({ + localWorkspaces: async () => [workspace(1)], + inventoryWorkspace: async () => ({ reasons: blocked ? ["active_execution"] : [] }), + eligibility: async () => ({ eligible: false, blockers: ["workspaces_require_migration"] }), + }); + await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + blocked = false; + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(result.deferred).not.toHaveProperty("workspaces:active_execution"); + expect(result.deferred).toMatchObject({ "workspaces:pending_inspection": 1 }); + }); + it("migrates an idle workspace through the online owner with a bounded source-lock wait, never the offline mode", async () => { const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] })); const fixture = owners({ localWorkspaces: async () => [workspace(1)], migrateWorkspace }); diff --git a/server/src/services/online-durable-data-migration.ts b/server/src/services/online-durable-data-migration.ts index b2a45c7f5dc..d8baec60846 100644 --- a/server/src/services/online-durable-data-migration.ts +++ b/server/src/services/online-durable-data-migration.ts @@ -90,6 +90,25 @@ let running: Promise | null = null; let workspaceOwner: Promise | null = null; type Progress = { phase: number; after?: string; limit?: number; timeouts?: number }; let progress: Progress = { phase: 0 }; +let carried: Record = {}; +const PHASE_CODES: Record = { agent_files: ["agent_files"], skill_objects: ["skill_objects"], + skill_snapshots: ["skill_snapshots"], skill_versions: ["skill_versions"], skill_installations: ["skill_installations", "skills"], + runtime_skill_assets: ["runtime_skill_assets"], run_logs: ["run_logs"], provider_traces: ["provider_traces"], + workspace_operations: ["workspace_operations"], workspaces: ["workspaces"], + native_harness_backups: ["native_harness_backups", "native_harness"], native_controllers: ["native_controllers"] }; +const DATA_BLOCKER_CODES: Record = { + agent_files_require_migration: { phases: ["agent_files"], unexplained: "agent_files:pending_inspection" }, + local_instruction_copies_require_settlement: { phases: ["agent_files"], unexplained: "agent_files:instruction_copy_unsettled" }, + external_agent_instructions: { phases: [], unexplained: "agent_instructions:external_instructions_configured" }, + skills_require_migration: { phases: ["skill_objects", "skill_snapshots", "skill_versions", "skill_installations"], unexplained: "skills:pending_inspection" }, + runtime_skill_assets_require_migration: { phases: ["runtime_skill_assets"], unexplained: "runtime_skill_assets:pending_inspection" }, + run_logs_require_migration: { phases: ["run_logs"], unexplained: "run_logs:pending_inspection" }, + provider_traces_require_migration: { phases: ["provider_traces"], unexplained: "provider_traces:pending_inspection" }, + workspaces_require_migration: { phases: ["workspace_operations", "workspaces"], unexplained: "workspaces:pending_inspection" }, + native_harness_backups_require_migration: { phases: ["native_harness_backups"], unexplained: "native_harness:pending_inspection" }, + native_controllers_require_migration: { phases: ["native_controllers"], unexplained: "native_controllers:pending_inspection" }, +}; +const prefixOf = (key: string) => key.slice(0, key.indexOf(":")); const DEFAULT_LIMITS: Partial> = { agent_files: 5, skill_objects: 50, skill_snapshots: 50, skill_versions: 50, skill_installations: 50, runtime_skill_assets: 50, workspace_operations: 10, workspaces: 4 }; const WORKSPACE_SOURCE_LOCK_WAIT_MS = 1_000; @@ -106,6 +125,7 @@ function workspaceDeferrals(error: unknown): string[] { export function resetOnlineDurableDataMigrationProgressForTests() { progress = { phase: 0 }; + carried = {}; workspaceOwner = null; } @@ -134,8 +154,18 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, const counts: Record = {}; const deferred: Record = {}; const add = (bucket: Record, key: string, by = 1) => { if (by) bucket[key] = (bucket[key] ?? 0) + by; }; + const defer = (key: string, by = 1) => { add(deferred, key, by); add(carried, key, by); }; const finish = async (state: OnlineDurableDataMigrationResult["state"], reason?: string): Promise => { const { eligible, blockers } = await owners.eligibility(db); + for (const blocker of blockers) { + const codes = DATA_BLOCKER_CODES[blocker]; + if (!codes) continue; + const prefixes = codes.phases.flatMap(phase => PHASE_CODES[phase]); + if (Object.keys(deferred).some(key => prefixes.includes(prefixOf(key)))) continue; + const earlier = Object.entries(carried).filter(([key]) => prefixes.includes(prefixOf(key))); + for (const [key, count] of earlier) deferred[key] = count; + if (!earlier.length) deferred[codes.unexplained] = 1; + } const result: OnlineDurableDataMigrationResult = { state, ...(reason ? { reason } : {}), ...(state === "budget_exhausted" ? { resumePhase: PHASES[progress.phase] } : {}), counts, deferred, eligible, blockers }; await owners.record(db, result); @@ -157,14 +187,14 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, const result = await owners.agentFiles(db, { apply: true, writersStopped: false, after, limit, signal }); for (const row of result.results) { if (row.state === "durable") add(counts, "agentFiles"); - else add(deferred, `agent_files:${row.state}`); + else defer(`agent_files:${row.state}`); } return result.next ?? null; } case "skill_objects": { const result = await owners.skillObjects(db, { source: localSkills, destination: storage, writersStopped: false, online: true, signal, after, limit }); add(counts, "skillObjects", result.migrated); - add(deferred, "skill_objects:owner_busy", result.busy); + defer("skill_objects:owner_busy", result.busy); return result.inspected < limit || !result.after ? null : result.after; } case "skill_snapshots": @@ -178,7 +208,7 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, const result = await skills.installations({ apply: true, writersStopped: false, after, limit, signal }); for (const row of result.results) { if (row.status === "converted") add(counts, "skillInstallations"); - else if (row.status !== "unchanged") add(deferred, `skills:${row.status === "blocked" ? row.code ?? "blocked" : row.status}`); + else if (row.status !== "unchanged") defer(`skills:${row.status === "blocked" ? row.code ?? "blocked" : row.status}`); } return result.inspected < limit || !result.after ? null : result.after; } @@ -194,12 +224,12 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, kinds: [logs ? "log" : "trace"], limit, signal, ...(logs ? { afterRunId: after } : { afterTraceId: after }), }), signal); - if (result.busy) { add(deferred, `${phase}:owner_busy`); return null; } + if (result.busy) { defer(`${phase}:owner_busy`); return null; } for (const item of result.items) { if (item.state === "migrated") add(counts, logs ? "runLogs" : "providerTraces"); else if (item.state === "blocked") { const reason = item.reason && /^[a-z_]{1,60}$/.test(item.reason) ? item.reason : "migration_failed"; - add(deferred, `${phase}:${reason}`); + defer(`${phase}:${reason}`); } } return (logs ? result.nextRunId : result.nextTraceId) ?? null; @@ -209,13 +239,13 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, for (const companyId of companies) { const result = await owners.workspaceOperations(db, { companyId, signal }); add(counts, "workspaceOperations", result.reconciled); - for (const held of result.held) add(deferred, `workspace_operations:${held.reason}`); + for (const held of result.held) defer(`workspace_operations:${held.reason}`); } return companies.length < limit ? null : companies.at(-1)!; } case "workspaces": { if (workspaceOwner) { - add(deferred, "workspaces:owner_busy"); + defer("workspaces:owner_busy"); return null; } const rows = await owners.localWorkspaces(db, { after, limit }); @@ -237,21 +267,21 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, reasons = workspaceDeferrals(error); } if (!reasons.length) add(counts, "workspaces"); - for (const reason of reasons) add(deferred, `workspaces:${reason}`); + for (const reason of reasons) defer(`workspaces:${reason}`); } return rows.length < limit ? null : rows.at(-1)!.cursor; } case "native_harness_backups": { await owners.nativeHarnessBackups(db, { storage, signal, onOutcome: outcome => { if (outcome === "published") add(counts, "nativeHarnessBackups"); - else if (outcome !== "current") add(deferred, `native_harness:${outcome}`); + else if (outcome !== "current") defer(`native_harness:${outcome}`); } }); return null; } case "native_controllers": { await owners.nativeControllers(db, { storage, signal, onOutcome: outcome => { if (outcome === "imported") add(counts, "nativeControllers"); - else if (!["unchanged", "archived_failed", "source_already_absent"].includes(outcome)) add(deferred, `native_controllers:${outcome}`); + else if (!["unchanged", "archived_failed", "source_already_absent"].includes(outcome)) defer(`native_controllers:${outcome}`); } }); return null; } @@ -261,13 +291,17 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, while (progress.phase < PHASES.length) { if (spent()) return await finish("budget_exhausted"); const phase = PHASES[progress.phase]!; + if (progress.after === undefined) { + const prefixes = PHASE_CODES[phase]; + for (const key of Object.keys(carried)) if (prefixes.includes(prefixOf(key))) delete carried[key]; + } let next: string | null; try { next = await page(phase, progress.after, progress.limit ?? DEFAULT_LIMITS[phase] ?? 1); } catch (error) { if (signal.reason instanceof BudgetSpent) throw error; const code = error instanceof Error && /^[a-z_]{1,60}(?::[a-z_]{1,40})?$/.test(error.message) ? error.message : "owner_failed"; - add(deferred, `${phase}:${code}`); + defer(`${phase}:${code}`); next = null; } progress = next ? { phase: progress.phase, after: next, limit: progress.limit } : { phase: progress.phase + 1 }; @@ -281,7 +315,7 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, const limit = progress.limit ?? DEFAULT_LIMITS[phase] ?? 1; if (limit > 1) progress = { ...progress, limit: Math.max(1, Math.floor(limit / 2)), timeouts: 0 }; else if ((progress.timeouts ?? 0) + 1 >= 2) { - add(deferred, `${phase}:stalled`); + defer(`${phase}:stalled`); progress = { phase: progress.phase + 1 }; } else progress = { ...progress, timeouts: (progress.timeouts ?? 0) + 1 }; }