From 9b16044bf146619921e9042748ced53557aa62e9 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:35:56 -0600 Subject: [PATCH] fix(cloud): move idle local workspaces in the online durable-data pass (#22270) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A hosted server can move to volume-free storage only when no durable data stays on its local volume > - The online durable-data pass moves that data while the server keeps serving, one bounded and resumable pass at a time > - The pass does not move local execution workspaces, so servers with local workspaces stay ineligible (`workspaces_require_migration`) > - Online-safe owners for workspaces already exist: the online remote workspace migration and the online workspace operation reconciliation > - This pull request adds workspace phases to the pass that call those owners, and defers busy or unsupported workspaces with a reason > - The benefit is that idle workspaces move with no outage, and operators can see which workspaces cannot move and why ## Linked Issues or Issue Description **What happened?** The online durable-data pass never moves local execution workspaces. A server with local workspaces keeps the `workspaces_require_migration` blocker after every pass. **Expected behavior** The pass moves each idle local workspace to shared storage through the online owner. It defers a busy or unsupported workspace and reports the reason. **Steps to reproduce** 1. Run the online durable-data pass on a server that has a local `local_fs` execution workspace. 2. Read the pass result and the eligibility blockers. 3. The workspace stays local and `workspaces_require_migration` stays. **Deployment mode** Hosted server that moves from a local volume to volume-free storage. ## What Changed - Add two phases to the online durable-data pass, after `runtime_skill_assets` and before the native phases: - `workspace_operations`: pages companies that have local workspaces and calls `reconcileOnlineWorkspaceOperations` for each. It counts `workspaceOperations` and defers each held operation as `workspace_operations:`. - `workspaces`: pages local workspaces (same filter as the eligibility check), deepest path first so nested workspaces go before their parents. For each workspace it reads `inventoryRemoteWorkspaceMigration`. If the workspace is eligible, it calls `migrateRemoteWorkspace` in online mode (never `writersStopped`) with the pass signal and a 1 s source-lock wait. - A workspace that the owner refuses is deferred with each owner reason as `workspaces:`, for example `workspaces:active_execution`, `workspaces:task_binding_required`, `workspaces:workspace_provider_unsupported`, `workspaces:workspace_source_busy`, or `workspaces:execution_rows_busy`. An unknown error becomes `workspaces:owner_failed` and its message is not echoed. The page continues with the next workspace. - Both phases use a cursor and a limit that the pass can halve after a budget timeout, like the other phases. - Add `listLocalWorkspaceCompanies` and `listLocalWorkspaces` next to `localWorkspaceDependencyWhere`. - The pass stops waiting for a workspace owner at the budget. It reports `workspaces:owner_busy` until that owner settles. ## Verification - `cd server && npx vitest run src/services/online-durable-data-migration.test.ts src/services/online-durable-data-migration-postgres.test.ts` - Unit tests with injected owners: phase order, online mode and lock wait, deferral codes, owner refusal under locks, cursor resume across budget-limited calls, and page halving that keeps finished workspaces. Seven tests fail without the change and pass with it. - Embedded PostgreSQL test with the real owners: an idle managed-project workspace moves to a committed snapshot and its files restore from it. A workspace with a running task run is deferred as `workspaces:active_execution`, and its record, files, and operations stay unchanged. The test fails without the change and passes with it. - Embedded PostgreSQL test for the workspace and company cursors: ten workspaces in two companies, with equal and different path lengths, across pages of three. Each workspace appears once, deepest first. - `pnpm verify` selected 2934 of 3802 test files (almost the full suite). It was not run to the end. Required CI covers the full suite. ## Risks - A workspace move that takes longer than one pass budget (60 s) stops at the budget. The workspace keeps its in-progress move marker, so new runs for that workspace are refused until a later pass resumes the move. The pass resumes the same page on the next call. If one workspace times out twice at page size 1, the pass reports `workspaces:stalled` and goes on; the next cycle resumes it again. A very large workspace can therefore stay blocked for runs across passes. The operator online workspace tool can resume it with a longer deadline. - A workspace with no proven online source uses the owner's lifecycle lock, which waits without a timeout. The pass does not wait for it past the budget. The pass returns at the budget, and the owner stops at its next abort check after it gets the lock. Until that owner settles, later passes skip the workspace phase and report `workspaces:owner_busy`, so two moves never run at the same time. - Workspaces that can never move online (for example unsupported providers or workspaces without a task binding) are reported each pass and are not changed. This change makes no product decision for them. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../services/local-workspace-dependencies.ts | 21 ++- ...ne-durable-data-migration-postgres.test.ts | 136 ++++++++++++++++++ .../online-durable-data-migration.test.ts | 127 +++++++++++++++- .../services/online-durable-data-migration.ts | 77 +++++++++- 4 files changed, 357 insertions(+), 4 deletions(-) create mode 100644 server/src/services/online-durable-data-migration-postgres.test.ts diff --git a/server/src/services/local-workspace-dependencies.ts b/server/src/services/local-workspace-dependencies.ts index e145204c0e3..a787f6721a9 100644 --- a/server/src/services/local-workspace-dependencies.ts +++ b/server/src/services/local-workspace-dependencies.ts @@ -1,4 +1,4 @@ -import { and, eq, isNotNull, notExists, sql } from "drizzle-orm"; +import { and, asc, desc, eq, gt, isNotNull, notExists, sql } from "drizzle-orm"; import { agents, environments, executionWorkspaces, type Db } from "@paperclipai/db"; export function localWorkspaceDependencyWhere(db: Pick) { @@ -25,3 +25,22 @@ export function localWorkspaceDependencyWhere(db: Pick) { notExists(pluginTaskWorkspace), ); } + +export async function listLocalWorkspaceCompanies(db: Pick, input: { after?: string; limit: number }) { + const rows = await db.selectDistinct({ companyId: executionWorkspaces.companyId }).from(executionWorkspaces) + .where(and(localWorkspaceDependencyWhere(db), input.after ? gt(executionWorkspaces.companyId, input.after) : undefined)) + .orderBy(asc(executionWorkspaces.companyId)).limit(input.limit); + return rows.map(row => row.companyId); +} + +export async function listLocalWorkspaces(db: Pick, input: { after?: string; limit: number }) { + const depth = sql`length(${executionWorkspaces.cwd})`; + const cursor = input.after?.match(/^(\d{1,9}):([0-9a-f-]{36})$/); + if (input.after && !cursor) throw new Error("local_workspace_cursor_invalid"); + const rows = await db.select({ companyId: executionWorkspaces.companyId, workspaceId: executionWorkspaces.id, depth }) + .from(executionWorkspaces).where(and(localWorkspaceDependencyWhere(db), cursor + ? sql`(${depth} < ${Number(cursor[1])} or (${depth} = ${Number(cursor[1])} and ${executionWorkspaces.id} > ${cursor[2]}::uuid))` + : undefined)) + .orderBy(desc(depth), asc(executionWorkspaces.id)).limit(input.limit); + return rows.map(row => ({ companyId: row.companyId, workspaceId: row.workspaceId, cursor: `${Number(row.depth)}:${row.workspaceId}` })); +} diff --git a/server/src/services/online-durable-data-migration-postgres.test.ts b/server/src/services/online-durable-data-migration-postgres.test.ts new file mode 100644 index 00000000000..5b22b9dce2d --- /dev/null +++ b/server/src/services/online-durable-data-migration-postgres.test.ts @@ -0,0 +1,136 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { activityLog, agents, companies, createDb, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, issues, projects, workspaceOperations } from "@paperclipai/db"; +import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveManagedProjectWorkspaceDir } from "../home-paths.js"; +import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; +import { createStorageService } from "../storage/service.js"; +import type { StorageService } from "../storage/types.js"; +import { listLocalWorkspaceCompanies, listLocalWorkspaces } from "./local-workspace-dependencies.js"; +import { reconcileOnlineWorkspaceOperations } from "./offline-workspace-operation-reconciliation.js"; +import { inventoryRemoteWorkspaceMigration, migrateRemoteWorkspace } from "./remote-workspace-migration.js"; +import { getWorkspaceSnapshot, loadWorkspaceSnapshotArchive } from "./remote-workspace-snapshot-storage.js"; +import { restoreRemoteWorkspaceArchive } from "./remote-workspace-snapshot-archive.js"; +import { resetOnlineDurableDataMigrationProgressForTests, runOnlineDurableDataMigration } from "./online-durable-data-migration.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("online durable-data migration of local workspaces", () => { + let database: Awaited>; + let db: ReturnType, home: string, storage: StorageService; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("online-durable-workspaces-"); + db = createDb(database.connectionString); + await db.execute(sql`set client_min_messages = warning`); + }, 90_000); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); }); + beforeEach(async () => { + resetOnlineDurableDataMigrationProgressForTests(); + home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "pc-online-durable-"))); + vi.stubEnv("PAPERCLIP_HOME", home); + storage = { ...createStorageService(createLocalDiskStorageProvider(path.join(home, "objects"))), provider: "s3" } as StorageService; + }); + afterEach(async () => { + await db.delete(activityLog); + await db.delete(workspaceOperations); + await db.delete(executionWorkspaceSnapshots); + await db.delete(heartbeatRuns); + await db.delete(issues); + await db.delete(agents); + await db.delete(executionWorkspaces); + await db.delete(projects); + await db.delete(companies); + vi.unstubAllEnvs(); + await fs.rm(home, { recursive: true, force: true }); + }); + + async function localWorkspace(companyId: string, text: string) { + const [project] = await db.insert(projects).values({ companyId, name: `Project ${text}` }).returning(); + const cwd = resolveManagedProjectWorkspaceDir({ companyId, projectId: project.id }); + await fs.mkdir(cwd, { recursive: true }); + await fs.writeFile(path.join(cwd, "saved.txt"), text); + const [issue] = await db.insert(issues).values({ companyId, projectId: project.id, title: `Task ${text}` }).returning(); + const [workspace] = await db.insert(executionWorkspaces).values({ companyId, projectId: project.id, sourceIssueId: issue.id, + name: `Workspace ${text}`, mode: "shared_workspace", strategyType: "project_primary", providerType: "local_fs", cwd, providerRef: cwd }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace.id }).where(eq(issues.id, issue.id)); + return { workspace, issue, cwd }; + } + + const done = async () => ({ results: [], inspected: 0, migrated: 0, busy: 0, after: null, next: null }); + const owners = () => ({ + storage: () => storage, + localSkillStorage: () => storage, + durableAgentFiles: () => true, + agentFiles: done, + skillObjects: done, + skillPackages: () => ({ migrateSnapshots: done, migrateVersions: done }), + skillInstallations: () => ({ installations: done }), + runtimeSkillAssets: done, + workspaceCompanies: listLocalWorkspaceCompanies, + workspaceOperations: reconcileOnlineWorkspaceOperations, + localWorkspaces: listLocalWorkspaces, + inventoryWorkspace: inventoryRemoteWorkspaceMigration, + migrateWorkspace: migrateRemoteWorkspace, + nativeHarnessBackups: async () => undefined, + nativeControllers: async () => undefined, + eligibility: async () => ({ eligible: false, blockers: [] }), + record: async () => undefined, + }) as never; + + it("moves an idle local workspace to shared storage while serving and leaves a workspace with an active run in place", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Online workspaces", issuePrefix: `W${companyId.slice(0, 6)}` }); + const idle = await localWorkspace(companyId, "idle work\n"); + const busy = await localWorkspace(companyId, "busy work\n"); + const [agent] = await db.insert(agents).values({ companyId, name: "Writer" }).returning(); + await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, issueId: busy.issue.id, status: "running", runtimeMode: "legacy" }); + const busyBefore = (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, busy.workspace.id)))[0]; + + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, owners()); + + expect(result).toMatchObject({ state: "completed", counts: { workspaces: 1 }, deferred: { "workspaces:active_execution": 1 } }); + const [moved] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, idle.workspace.id)); + const authority = readRemoteWorkspaceAuthority(moved.metadata)!; + expect(moved.providerType).toBe("cloud_sandbox"); + expect(authority.snapshotId).toEqual(expect.any(String)); + const reference = await getWorkspaceSnapshot(db, { companyId, workspaceId: idle.workspace.id, snapshotId: authority.snapshotId! }); + const archivePath = path.join(home, "idle.pcws"), restored = path.join(home, "idle-restored"); + await loadWorkspaceSnapshotArchive({ storage, reference: reference!, targetPath: archivePath }); + await restoreRemoteWorkspaceArchive({ archivePath, targetDir: restored, expectedManifestDigest: reference!.manifestDigest }); + expect(await fs.readFile(path.join(restored, "saved.txt"), "utf8")).toBe("idle work\n"); + + expect((await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, busy.workspace.id)))[0]).toEqual(busyBefore); + expect(await fs.readFile(path.join(busy.cwd, "saved.txt"), "utf8")).toBe("busy work\n"); + expect(await db.select().from(workspaceOperations).where(eq(workspaceOperations.executionWorkspaceId, busy.workspace.id))).toEqual([]); + }, 60_000); + + it("pages local workspaces deepest first and pages companies, with no skips or repeats across page boundaries", async () => { + const expected: Array<{ id: string; depth: number }> = []; + const companyIds = [randomUUID(), randomUUID()].sort(); + for (const companyId of companyIds) { + await db.insert(companies).values({ id: companyId, name: "Paging", issuePrefix: `P${companyId.slice(0, 6)}` }); + for (const cwd of ["/a/b", "/a/bb", "/a/bb", "/a/b/c/d", "/a/b/c"]) { + const [row] = await db.insert(executionWorkspaces).values({ companyId, name: cwd, mode: "shared_workspace", + strategyType: "project_primary", providerType: "local_fs", cwd, providerRef: cwd }).returning(); + expected.push({ id: row.id, depth: cwd.length }); + } + } + expected.sort((a, b) => b.depth - a.depth || a.id.localeCompare(b.id)); + const seen: string[] = []; + let after: string | undefined; + for (;;) { + const page = await listLocalWorkspaces(db, { after, limit: 3 }); + seen.push(...page.map(row => row.workspaceId)); + if (page.length < 3) break; + after = page.at(-1)!.cursor; + } + expect(seen).toEqual(expected.map(row => row.id)); + expect(await listLocalWorkspaceCompanies(db, { limit: 1 })).toEqual([companyIds[0]]); + expect(await listLocalWorkspaceCompanies(db, { after: companyIds[0], limit: 1 })).toEqual([companyIds[1]]); + expect(await listLocalWorkspaceCompanies(db, { after: companyIds[1], limit: 1 })).toEqual([]); + }); +}); diff --git a/server/src/services/online-durable-data-migration.test.ts b/server/src/services/online-durable-data-migration.test.ts index 2933c455b82..a157952367c 100644 --- a/server/src/services/online-durable-data-migration.test.ts +++ b/server/src/services/online-durable-data-migration.test.ts @@ -24,6 +24,11 @@ function owners(overrides: Record = {}) { { skillId: "s1", companyId: "c", status: "converted" }, { skillId: "s2", companyId: "c", status: "unchanged" }, { skillId: "s3", companyId: "c", status: "linked_local" }] }) }), runtimeSkillAssets: page("runtimeSkillAssets", { inspected: 1, after: null, results: [{ runId: "r1", status: "preserved" }] }), + workspaceCompanies: page("workspaceCompanies", []), + workspaceOperations: page("workspaceOperations", { reconciled: 0, held: [] }), + localWorkspaces: page("localWorkspaces", []), + inventoryWorkspace: page("inventoryWorkspace", { reasons: [] }), + migrateWorkspace: page("migrateWorkspace", { alreadyMigrated: true, reasons: [] }), nativeHarnessBackups: async (_db: Db, input: { onOutcome?: (outcome: string) => void }) => { calls.push("nativeHarnessBackups"); for (const outcome of ["published", "current", "source_active", "source_active"]) input.onOutcome?.(outcome); @@ -48,7 +53,7 @@ describe("online durable-data migration pass", () => { const fixture = owners(); const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); expect(fixture.calls).toEqual(["agentFiles", "skillObjects", "skillSnapshots", "skillVersions", "skillInstallations", - "runtimeSkillAssets", "nativeHarnessBackups", "nativeControllers"]); + "runtimeSkillAssets", "workspaceCompanies", "localWorkspaces", "nativeHarnessBackups", "nativeControllers"]); expect(result).toEqual({ state: "completed", counts: { agentFiles: 1, skillObjects: 1, skillSnapshots: 1, skillInstallations: 1, runtimeSkillRuns: 1, nativeHarnessBackups: 1, nativeControllers: 1 }, @@ -194,4 +199,124 @@ describe("online durable-data migration pass", () => { expect(await second).toBe(await first); expect(agentFiles).toHaveBeenCalledOnce(); }); + + describe("workspaces", () => { + const workspace = (n: number) => ({ companyId: "c1", workspaceId: `w${n}`, cursor: `20:w${n}` }); + + it("reconciles stale workspace operations per company before migrating workspaces, then runs the native owners", async () => { + const workspaceOperations = vi.fn(async (_db: Db, input: { companyId: string }) => { + fixture.calls.push(`reconcile:${input.companyId}`); + return { reconciled: input.companyId === "c1" ? 2 : 0, held: [{ reason: "finalization_owner_busy" }] }; + }); + const fixture = owners({ + workspaceCompanies: vi.fn(async () => { fixture.calls.push("workspaceCompanies"); return ["c1", "c2"]; }), + workspaceOperations, + localWorkspaces: vi.fn(async () => { fixture.calls.push("localWorkspaces"); return [workspace(1)]; }), + migrateWorkspace: vi.fn(async () => { fixture.calls.push("migrateWorkspace"); return { alreadyMigrated: true, reasons: [] }; }), + }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(fixture.calls.slice(fixture.calls.indexOf("runtimeSkillAssets"))).toEqual(["runtimeSkillAssets", "workspaceCompanies", + "reconcile:c1", "reconcile:c2", "localWorkspaces", "inventoryWorkspace", "migrateWorkspace", "nativeHarnessBackups", "nativeControllers"]); + expect(workspaceOperations).toHaveBeenCalledWith(db, { companyId: "c1", signal: expect.any(AbortSignal) }); + expect(result.counts).toMatchObject({ workspaceOperations: 2, workspaces: 1 }); + expect(result.deferred).toMatchObject({ "workspace_operations:finalization_owner_busy": 2 }); + }); + + 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 }); + await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(migrateWorkspace).toHaveBeenCalledWith({ db, storage: s3, companyId: "c1", workspaceId: "w1", apply: true, + signal: expect.any(AbortSignal), sourceLockWaitMs: 1_000 }); + expect(migrateWorkspace.mock.calls[0]).not.toEqual([expect.objectContaining({ writersStopped: expect.anything() })]); + }); + + it("defers busy and unsupported workspaces with their owner reasons and does not force them", async () => { + const reasons: Record = { w1: ["active_execution"], w2: ["task_binding_required", "workspace_provider_unsupported"], w3: [] }; + const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] })); + const fixture = owners({ + localWorkspaces: async () => [workspace(1), workspace(2), workspace(3)], + inventoryWorkspace: async (_db: Db, input: { workspaceId: string }) => ({ reasons: reasons[input.workspaceId] }), + migrateWorkspace, + }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(migrateWorkspace).toHaveBeenCalledOnce(); + expect(migrateWorkspace).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: "w3" })); + expect(result.counts).toMatchObject({ workspaces: 1 }); + expect(result.deferred).toMatchObject({ "workspaces:active_execution": 1, "workspaces:task_binding_required": 1, + "workspaces:workspace_provider_unsupported": 1 }); + }); + + it("defers a workspace that the owner refuses under its locks and continues with the rest of the page", async () => { + const failures: Record = { + w1: new Error("remote_workspace_migration_blocked:active_execution,workspace_runtime_owned"), + w2: new Error("workspace_source_busy"), + w3: new Error("EACCES: permission denied, open '/private/path'"), + }; + const fixture = owners({ + localWorkspaces: async (_db: Db, input: { after?: string }) => input.after ? [] : [workspace(1), workspace(2), workspace(3), workspace(4)], + migrateWorkspace: async (input: { workspaceId: string }) => { + if (failures[input.workspaceId]) throw failures[input.workspaceId]; + return { alreadyMigrated: true, reasons: [] }; + }, + }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(result.counts).toMatchObject({ workspaces: 1 }); + expect(result.deferred).toMatchObject({ "workspaces:active_execution": 1, "workspaces:workspace_runtime_owned": 1, + "workspaces:workspace_source_busy": 1, "workspaces:owner_failed": 1 }); + expect(JSON.stringify(result)).not.toContain("private"); + }); + + it("pages workspaces with the owner cursor and resumes the same page after the budget ends", async () => { + let clock = 0; + const pages: Array<{ after?: string; limit: number }> = []; + const localWorkspaces = vi.fn(async (_db: Db, input: { after?: string; limit: number }) => { + pages.push(input); + const start = input.after ? Number(input.after.split(":w")[1]) : 0; + return start >= 8 ? [] : Array.from({ length: input.limit }, (_, index) => workspace(start + index + 1)); + }); + const migrateWorkspace = vi.fn(async () => { clock += 10_000; return { alreadyMigrated: true, reasons: [] }; }); + const fixture = owners({ localWorkspaces, migrateWorkspace }); + const run = () => runOnlineDurableDataMigration(db, { budgetMs: 60_000, now: () => clock }, fixture.owners); + expect(await run()).toMatchObject({ state: "budget_exhausted", resumePhase: "workspaces", counts: expect.objectContaining({ workspaces: 8 }) }); + expect(await run()).toMatchObject({ state: "completed" }); + expect(pages).toEqual([{ limit: 4, after: undefined }, { limit: 4, after: "20:w4" }, { limit: 4, after: "20:w8" }]); + expect(fixture.calls.filter(call => call === "agentFiles")).toHaveLength(1); + }); + + it("halves a workspace page that overruns the budget and keeps the workspaces it already moved", async () => { + const limits: number[] = []; + const localWorkspaces = vi.fn(async (_db: Db, input: { limit: number }) => { + limits.push(input.limit); + return Array.from({ length: input.limit }, (_, index) => workspace(index + 1)); + }); + const migrateWorkspace = vi.fn(async (input: { workspaceId: string; signal: AbortSignal }) => { + if (input.workspaceId === "w1") return { alreadyMigrated: true, reasons: [] }; + return new Promise((_resolve, reject) => { + input.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true }); + }); + }); + const fixture = owners({ localWorkspaces, migrateWorkspace }); + const first = await runOnlineDurableDataMigration(db, { budgetMs: 20 }, fixture.owners); + expect(first).toMatchObject({ state: "budget_exhausted", resumePhase: "workspaces", counts: expect.objectContaining({ workspaces: 1 }) }); + expect(first.deferred).not.toHaveProperty("workspaces:owner_failed"); + await runOnlineDurableDataMigration(db, { budgetMs: 20 }, fixture.owners); + expect(limits).toEqual([4, 2]); + }); + + it("returns at the budget while the owner waits on a lock, and skips workspaces until that owner settles", async () => { + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + const migrateWorkspace = vi.fn(async () => { await held; return { alreadyMigrated: true, reasons: [] }; }); + const fixture = owners({ localWorkspaces: async (_db: Db, input: { after?: string }) => input.after ? [] : [workspace(1)], migrateWorkspace }); + expect(await runOnlineDurableDataMigration(db, { budgetMs: 20 }, fixture.owners)).toMatchObject({ state: "budget_exhausted", resumePhase: "workspaces" }); + const busy = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(busy).toMatchObject({ state: "completed", deferred: expect.objectContaining({ "workspaces:owner_busy": 1 }) }); + expect(migrateWorkspace).toHaveBeenCalledOnce(); + release(); + await held; + await new Promise(resolve => setTimeout(resolve, 0)); + expect(await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners)).toMatchObject({ counts: expect.objectContaining({ workspaces: 1 }) }); + }); + }); }); diff --git a/server/src/services/online-durable-data-migration.ts b/server/src/services/online-durable-data-migration.ts index 69bb195d933..635c3c16326 100644 --- a/server/src/services/online-durable-data-migration.ts +++ b/server/src/services/online-durable-data-migration.ts @@ -14,6 +14,9 @@ import { skillInstallationMaintenance } from "./skill-installation-maintenance.j import { migrateRuntimeSkillAssets } from "./native-runtime/runtime-skill-preservation.js"; import { prestageNativeHarnessBackups } from "./native-runtime/native-harness-backup-migration.js"; import { prestageNativeControllers } from "./native-runtime/native-controller-migration.js"; +import { listLocalWorkspaceCompanies, listLocalWorkspaces } from "./local-workspace-dependencies.js"; +import { reconcileOnlineWorkspaceOperations } from "./offline-workspace-operation-reconciliation.js"; +import { inventoryRemoteWorkspaceMigration, migrateRemoteWorkspace } from "./remote-workspace-migration.js"; export type OnlineDurableDataMigrationResult = { state: "completed" | "budget_exhausted" | "unsupported"; @@ -36,6 +39,12 @@ type Owners = { skillPackages: (db: Db, storage: StorageService) => Pick, "migrateSnapshots" | "migrateVersions">; skillInstallations: (db: Db, storage: StorageService) => Pick, "installations">; runtimeSkillAssets: typeof migrateRuntimeSkillAssets; + workspaceCompanies: typeof listLocalWorkspaceCompanies; + workspaceOperations: (db: Db, input: { companyId: string; signal: AbortSignal }) => Promise<{ reconciled: number; held: Array<{ reason: string }> }>; + localWorkspaces: typeof listLocalWorkspaces; + inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[] }>; + migrateWorkspace: (input: { db: Db; storage: StorageService; companyId: string; workspaceId: string; apply: true; + signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>; nativeHarnessBackups: typeof prestageNativeHarnessBackups; nativeControllers: typeof prestageNativeControllers; eligibility: (db: Db) => Promise<{ eligible: boolean; blockers: string[] }>; @@ -59,6 +68,11 @@ const defaultOwners: Owners = { skillPackages: skillPackageMaintenance, skillInstallations: skillInstallationMaintenance, runtimeSkillAssets: migrateRuntimeSkillAssets, + workspaceCompanies: listLocalWorkspaceCompanies, + workspaceOperations: reconcileOnlineWorkspaceOperations, + localWorkspaces: listLocalWorkspaces, + inventoryWorkspace: inventoryRemoteWorkspaceMigration, + migrateWorkspace: migrateRemoteWorkspace, nativeHarnessBackups: prestageNativeHarnessBackups, nativeControllers: prestageNativeControllers, eligibility: readOnlineEphemeralEnrollmentEligibility, @@ -66,17 +80,39 @@ const defaultOwners: Owners = { }; const PHASES = ["agent_files", "skill_objects", "skill_snapshots", "skill_versions", "skill_installations", - "runtime_skill_assets", "native_harness_backups", "native_controllers"] as const; + "runtime_skill_assets", "workspace_operations", "workspaces", "native_harness_backups", "native_controllers"] as const; type Phase = typeof PHASES[number]; 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 }; const DEFAULT_LIMITS: Partial> = { agent_files: 5, skill_objects: 50, skill_snapshots: 50, skill_versions: 50, - skill_installations: 50, runtime_skill_assets: 50 }; + skill_installations: 50, runtime_skill_assets: 50, workspace_operations: 10, workspaces: 4 }; +const WORKSPACE_SOURCE_LOCK_WAIT_MS = 1_000; +const WORKSPACE_BLOCKED = "remote_workspace_migration_blocked:"; + +function workspaceDeferrals(error: unknown): string[] { + const message = error instanceof Error ? error.message : ""; + if (message.startsWith(WORKSPACE_BLOCKED)) { + const reasons = message.slice(WORKSPACE_BLOCKED.length).split(",").filter(reason => /^[a-z_]{1,80}$/.test(reason)); + if (reasons.length) return reasons; + } + return [/^[a-z_]{1,80}$/.test(message) ? message : "owner_failed"]; +} export function resetOnlineDurableDataMigrationProgressForTests() { progress = { phase: 0 }; + workspaceOwner = null; +} + +function untilAborted(work: Promise, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const abort = () => reject(signal.reason); + if (signal.aborted) return abort(); + signal.addEventListener("abort", abort, { once: true }); + work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort)); + }); } export function runOnlineDurableDataMigration(db: Db, input: { budgetMs: number; now?: () => number }, owners: Owners = defaultOwners) { @@ -148,6 +184,43 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, add(counts, "runtimeSkillRuns", result.results.filter(row => row.status === "preserved").length); return result.inspected < limit || !result.after ? null : result.after; } + case "workspace_operations": { + const companies = await owners.workspaceCompanies(db, { after, limit }); + 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}`); + } + return companies.length < limit ? null : companies.at(-1)!; + } + case "workspaces": { + if (workspaceOwner) { + add(deferred, "workspaces:owner_busy"); + return null; + } + const rows = await owners.localWorkspaces(db, { after, limit }); + for (const { companyId, workspaceId } of rows) { + let reasons: string[]; + try { + reasons = (await owners.inventoryWorkspace(db, { companyId, workspaceId })).reasons; + if (!reasons.length) { + const work = owners.migrateWorkspace({ db, storage, companyId, workspaceId, apply: true, signal, + sourceLockWaitMs: WORKSPACE_SOURCE_LOCK_WAIT_MS }); + const tracked: Promise = work.then(() => undefined, () => undefined) + .finally(() => { if (workspaceOwner === tracked) workspaceOwner = null; }); + workspaceOwner = tracked; + const result = await untilAborted(work, signal); + reasons = result.alreadyMigrated ? [] : result.reasons.length ? result.reasons : ["not_migrated"]; + } + } catch (error) { + if (signal.aborted) throw error; + reasons = workspaceDeferrals(error); + } + if (!reasons.length) add(counts, "workspaces"); + for (const reason of reasons) add(deferred, `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");