From 6bc52f0bf84f2efe9d39ffa25145ebf2dfb86398 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 22:57:08 -0500 Subject: [PATCH] fix(server): keep workspace retry deadlines stable across inspections Co-Authored-By: Paperclip --- doc/idle-terminal-workspace-pagination.md | 28 ++++++++++++++++++- .../isolated-repository-rehome.test.ts | 22 ++++++++++----- .../__tests__/nested-clone-migration.test.ts | 18 ++++++++---- server/src/services/execution-workspaces.ts | 14 ++++++---- 4 files changed, 63 insertions(+), 19 deletions(-) diff --git a/doc/idle-terminal-workspace-pagination.md b/doc/idle-terminal-workspace-pagination.md index e52e04a061f..5b5d77e65f7 100644 --- a/doc/idle-terminal-workspace-pagination.md +++ b/doc/idle-terminal-workspace-pagination.md @@ -1,4 +1,4 @@ -# Terminal workspace recovery pagination +# Terminal workspace scan and retry deadline precision Terminal workspace maintenance already uses the shared delivery coordinator and retains deadlines only for outstanding work. Its bounded scan must progress past @@ -40,3 +40,29 @@ Review follow-up reproduced the missing-schema failure against a newly created, unmigrated disposable database. The setup repair migrates that same database inside the suite; the full workspace-service selection then runs without manual schema preparation. The production cursor implementation is unchanged. + +## Preserve one retry deadline through early inspection + +Nested-clone migration and isolated-source rehoming kept a retry guard and a +separate advertised scheduler deadline. Each value called the clock separately. +When the clock advanced between those calls, an early inspection copied the +earlier guard back into the advertised deadline. CI observed a one-millisecond +backward change in an otherwise unchanged retry. + +Each path now computes one retry timestamp and stores that value in all of its +retry and scheduling state. The cadence, cleanup eligibility, quiet conditions, +rotation, and wake contract do not change. No new timer, queue, or table is added. + +The existing nested-clone regression and the isolated-rehome dry-run case now +use a clock that advances one millisecond per read. Both failed before the fix +with the same one-millisecond drift. Both exact-deadline assertions remain. The +complete migration suites passed all 49 cases afterward, using real PostgreSQL +and Git, including preserved files/history and interrupted migration recovery. +The complete workspace-service and terminal-worker suites passed another 87 +cases; server typechecking passed. The two focused pre-fix failures used a name +filter intentionally; the reported final 136 cases are four complete suites +without skips. Validated external test database hooks keep each migration suite +on its own disposable database and retain the existing embedded fixture fallback. + +These are local correctness and scheduling results, not deployed host-sleep or +external-wake proof. Remote acceptance must be checked at the published head. diff --git a/server/src/__tests__/isolated-repository-rehome.test.ts b/server/src/__tests__/isolated-repository-rehome.test.ts index 889b0ffa63f..9898635a01c 100644 --- a/server/src/__tests__/isolated-repository-rehome.test.ts +++ b/server/src/__tests__/isolated-repository-rehome.test.ts @@ -25,17 +25,20 @@ const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, const exists = (target: string) => fs.lstat(target).then(() => true, () => false); const DAY_MS = 24 * 60 * 60 * 1000; -const support = await getEmbeddedPostgresTestSupport(); +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_ISOLATED_REHOME_TEST_DATABASE_URL"); +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = support.supported ? describe : describe.skip; describeEmbeddedPostgres("isolated repository source re-home", () => { let db: ReturnType; - let database: Awaited>; + let database: Awaited> | undefined; let root: string; const previousHome = process.env.PAPERCLIP_HOME; const previousInstance = process.env.PAPERCLIP_INSTANCE_ID; beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase("isolated-repository-rehome-"); - db = createDb(database.connectionString); + if (!external) database = await startEmbeddedPostgresTestDatabase("isolated-repository-rehome-"); + db = createDb(external ?? database!.connectionString); root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-isolated-rehome-")); process.env.PAPERCLIP_HOME = path.join(root, "home"); process.env.PAPERCLIP_INSTANCE_ID = "default"; @@ -50,7 +53,7 @@ describeEmbeddedPostgres("isolated repository source re-home", () => { vi.unstubAllEnvs(); if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome; if (previousInstance === undefined) delete process.env.PAPERCLIP_INSTANCE_ID; else process.env.PAPERCLIP_INSTANCE_ID = previousInstance; - await db.$client.end({ timeout: 1 }); await database.cleanup(); await fs.rm(root, { recursive: true, force: true }); + await db.$client.end({ timeout: 1 }); await database?.cleanup(); await fs.rm(root, { recursive: true, force: true }); }); async function fixture(options: { sharedBase?: boolean; issueStatus?: "in_progress" | "done" } = {}) { @@ -409,11 +412,16 @@ describeEmbeddedPostgres("isolated repository source re-home", () => { await executionWorkspaceService(db, { gitCacheExpirationEnabled: true }).sweepTerminalWorkspaces(); await executionWorkspaceService(db, { isolatedSourceRehomeEnabled: true }).sweepTerminalWorkspaces(); await expectUntouched(f, before); - const dryRun = executionWorkspaceService(db, { gitCacheExpirationEnabled: true, isolatedSourceRehomeEnabled: true, isolatedSourceRehomeDryRun: true }); + let tick = Date.now(); + const dryRun = executionWorkspaceService(db, { gitCacheExpirationEnabled: true, isolatedSourceRehomeEnabled: true, + isolatedSourceRehomeDryRun: true, now: () => new Date(tick++) }); await dryRun.sweepTerminalWorkspaces(); await expectUntouched(f, before); expect(await exists(f.clone)).toBe(true); - expect(await dryRun.nextTerminalWorkspaceSweepAt()).toBeGreaterThan(Date.now()); + const retryAt = await dryRun.nextTerminalWorkspaceSweepAt(); + expect(retryAt).toBeGreaterThan(Date.now()); + await dryRun.sweepTerminalWorkspaces(); + expect(await dryRun.nextTerminalWorkspaceSweepAt()).toBe(retryAt); expect(await rehomeIsolatedRepositoryWorkspace(db, await f.row(), { dryRun: true })).toMatchObject({ outcome: "dry_run", rehomed: false, to: f.target }); await expectUntouched(f, before); }); diff --git a/server/src/__tests__/nested-clone-migration.test.ts b/server/src/__tests__/nested-clone-migration.test.ts index b417a4ce897..52d7fb5bad9 100644 --- a/server/src/__tests__/nested-clone-migration.test.ts +++ b/server/src/__tests__/nested-clone-migration.test.ts @@ -44,17 +44,20 @@ describe("nested clone migration batches", () => { }); }); -const support = await getEmbeddedPostgresTestSupport(); +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_NESTED_CLONE_TEST_DATABASE_URL"); +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = support.supported ? describe : describe.skip; describeEmbeddedPostgres("nested repository clone migration", () => { let db: ReturnType; - let database: Awaited>; + let database: Awaited> | undefined; let root: string; const previousHome = process.env.PAPERCLIP_HOME; const previousInstance = process.env.PAPERCLIP_INSTANCE_ID; beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase("nested-clone-migration-"); - db = createDb(database.connectionString); + if (!external) database = await startEmbeddedPostgresTestDatabase("nested-clone-migration-"); + db = createDb(external ?? database!.connectionString); root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-nested-migration-")); process.env.PAPERCLIP_HOME = path.join(root, "home"); process.env.PAPERCLIP_INSTANCE_ID = "default"; @@ -68,7 +71,7 @@ describeEmbeddedPostgres("nested repository clone migration", () => { vi.unstubAllEnvs(); if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome; if (previousInstance === undefined) delete process.env.PAPERCLIP_INSTANCE_ID; else process.env.PAPERCLIP_INSTANCE_ID = previousInstance; - await db.$client.end({ timeout: 1 }); await database.cleanup(); await fs.rm(root, { recursive: true, force: true }); + await db.$client.end({ timeout: 1 }); await database?.cleanup(); await fs.rm(root, { recursive: true, force: true }); }); async function repository(location: string, name: string, files: Record) { @@ -504,7 +507,10 @@ describeEmbeddedPostgres("nested repository clone migration", () => { const agentId = randomUUID(); await db.insert(agents).values({ id: agentId, companyId: f.companyId, name: "Fixture", role: "engineer", adapterType: "process" }); const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId, issueId: f.issueId, status: "running" }).returning(); - const busy = executionWorkspaceService(db, { nestedCloneMigrationEnabled: true }); + // Make a second clock read observably different without changing the + // scheduler's saved business deadline during an early inspection. + let tick = Date.now(); + const busy = executionWorkspaceService(db, { nestedCloneMigrationEnabled: true, now: () => new Date(tick++) }); await busy.sweepTerminalWorkspaces(); await expectUntouched(f, before); const retryAt = await busy.nextTerminalWorkspaceSweepAt(); diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index db1a5a46598..ef4c2da940f 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -3483,8 +3483,9 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic const [after] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace.id)); if (after && (isIsolatedRepositoryRehomeCandidate(after) || hasPendingIsolatedRepositoryRehomeCleanup(after))) { if (isolatedRehomeNotBefore.size >= 4096) isolatedRehomeNotBefore.delete(isolatedRehomeNotBefore.keys().next().value!); - isolatedRehomeNotBefore.set(workspace.id, now().getTime() + ISOLATED_REHOME_RETRY_MS); - isolatedRehomeDeadlines.set(workspace.id, now().getTime() + ISOLATED_REHOME_RETRY_MS); + const retryAt = now().getTime() + ISOLATED_REHOME_RETRY_MS; + isolatedRehomeNotBefore.set(workspace.id, retryAt); + isolatedRehomeDeadlines.set(workspace.id, retryAt); } else { isolatedRehomeNotBefore.delete(workspace.id); isolatedRehomeDeadlines.delete(workspace.id); @@ -3521,14 +3522,17 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } const [after] = names.length > 0 ? await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace.id)) : [workspace]; if (!dryRun && after && hasPendingNestedCloneMigration(after)) retry = true; + // The retry gate and advertised deadline describe one obligation. + // An early inspection must not move it by reading the clock again. + const retryAt = now().getTime() + ISOLATED_REHOME_RETRY_MS; if (remaining) { if (nestedCloneMigrationNotBefore.size >= 4096) nestedCloneMigrationNotBefore.delete(nestedCloneMigrationNotBefore.keys().next().value!); - nestedCloneMigrationNotBefore.set(workspace.id, now().getTime() + ISOLATED_REHOME_RETRY_MS); + nestedCloneMigrationNotBefore.set(workspace.id, retryAt); } else nestedCloneMigrationNotBefore.delete(workspace.id); if (retry) { if (nestedCloneMigrationRetryAt.size >= 4096) nestedCloneMigrationRetryAt.delete(nestedCloneMigrationRetryAt.keys().next().value!); - nestedCloneMigrationRetryAt.set(workspace.id, now().getTime() + ISOLATED_REHOME_RETRY_MS); - nestedCloneMigrationDeadlines.set(workspace.id, now().getTime() + ISOLATED_REHOME_RETRY_MS); + nestedCloneMigrationRetryAt.set(workspace.id, retryAt); + nestedCloneMigrationDeadlines.set(workspace.id, retryAt); } else { nestedCloneMigrationRetryAt.delete(workspace.id); nestedCloneMigrationDeadlines.delete(workspace.id);