Merge workspace recovery fix into sleep-05-approved-tool-recovery

Propagate the tested retained-workspace slot correction while preserving this PR boundary.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-26 19:28:03 -05:00
commit e7c2f2cbe4
3 files changed
+80 -11

No files matched your search

@@ -0,0 +1,53 @@
# Retained workspace recovery: fill a free slot across the cursor
This is a shared CI repair carried at the sleep-stack root. It fixes the existing
retained-workspace owner; it does not add another background duty or migrate the
remaining run/task recovery inventory. No PR is merged by this repair.
## Failure and ownership
The retained-workspace worker permits two physical exports. A held export stays
in the durable unfinished candidates, even though this process already owns it.
Discovery paginates by recovery-action ID and wraps only when its query returns
no rows. A page containing only a held export was nonempty, but its only row was
skipped in memory. Newly committed work before the cursor therefore waited for
another 15-second recovery pass despite a free slot.
The CI failure at PR #17446, run 40423925338 / job 121925042581, leaves the third
export `scheduled` at the existing 20-second assertion. The older #17450 failure
has the same observable result. A deterministic real-PostgreSQL/filesystem
regression reproduces it by starting the highest action ID, holding its provider
resume, completing a middle action, then requesting the lowest action. The
before-fix test failed at that same third-export assertion.
## Change and preserved boundaries
The existing candidate query accepts the locally in-flight run IDs and excludes
them before pagination on both unfinished and passive discovery paths. The
coordinator reads this set after its existing two-slot guard, so the exclusion
contains at most one run for an admitted discovery pass. An empty page can now
wrap in the same pass and find new work before the cursor. The in-memory duplicate
guard remains to handle changes while a query is running.
The retained-workspace module owns candidate selection. Its callers, SQL source
eligibility, physical ownership lock, retry policy, concurrency limit, completion
callbacks, and shutdown joins retain their existing contracts. Other-process
locks are still handled by the existing bounded cursor rotation. No new timer,
queue, table, provider branch, or retry authority is added. Held work remains
tracked as active and is not treated as settled or safe to sleep through.
## Verification
At the integrated pre-repair tip, the deterministic test failed with `scheduled`
instead of `complete`. After the repair, that regression and the existing
other-worker physical-lock rotation test both pass with real files and database
state. The free-slot test keeps the original 20-second completion bound, verifies
preserved files, no extra agent run, at most two concurrent resume operations,
and shutdown waiting for the held export before its final completion.
At the stack root, all 56 retained-workspace recovery cases pass on a dedicated
migrated PostgreSQL test database. The full suite also exercises retries,
exhaustion, stop verification, cleanup authorization, source bindings and saved
file recovery. Integrated workspace typecheck/build and fresh remote checks must
be recorded in the PR after parent propagation. This is not a full repository or
deployed-sleep claim.
+17 -5
View File
@@ -209,9 +209,16 @@ describe("automatic retained workspace recovery", () => {
} finally { await coordinator.stop(); await worker.stop(); }
}, 30_000);
it("fills a free export slot while another export is held and joins both at shutdown", async () => {
const held = await seed(), fast = await seed();
const fixtures = [held, fast];
it("fills a free export slot across the candidate cursor while another export is held and joins both at shutdown", async () => {
const orderedSeed = async (position: number) => {
const fixture = await seed();
const id = `00000002-000${position}-4000-8000-${randomUUID().slice(-12)}`;
await db.update(issueRecoveryActions).set({ id }).where(eq(issueRecoveryActions.id, fixture.actionId));
fixture.actionId = id; fixture.input.actionId = id;
return fixture;
};
const held = await orderedSeed(2);
const fixtures = [held];
const runtimeFor = (runId: string) => fixtures.find(fixture => fixture.runId === runId)!.environmentRuntime;
const runtime = { ...held.environmentRuntime,
resumeWorkspaceRecoveryLease: (input: Parameters<typeof held.environmentRuntime.resumeWorkspaceRecoveryLease>[0]) =>
@@ -228,15 +235,20 @@ describe("automatic retained workspace recovery", () => {
try { if (pause) await gate; return await resume(input); } finally { active -= 1; }
});
};
countExport(held, true); countExport(fast);
countExport(held, true);
const errors = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: errors });
const worker = registerWorkspaceRecoveryWork(db, coordinator, runtime, async () => {});
try {
await expect.poll(() => held.runtime.resumeRunLease.mock.calls.length, { timeout: 20_000 }).toBe(1);
// Start the middle candidate only after the highest candidate occupies
// one slot. The next producer then sorts before that saved cursor.
const fast = await orderedSeed(1); fixtures.push(fast); countExport(fast);
await requestTaskRetry({ db, companyId: fast.companyId, issueId: fast.issueId, actorId: "board",
observedRunId: fast.runId, idempotencyKey: randomUUID() });
await expect.poll(async () => readSystemRecovery((await action(fast.actionId)).evidence)?.state,
{ timeout: 20_000 }).toBe("complete");
const third = await seed(); fixtures.push(third); countExport(third);
const third = await orderedSeed(0); fixtures.push(third); countExport(third);
await requestTaskRetry({ db, companyId: third.companyId, issueId: third.issueId, actorId: "board",
observedRunId: third.runId, idempotencyKey: randomUUID() });
await expect.poll(async () => readSystemRecovery((await action(third.actionId)).evidence)?.state,
+10 -6
View File
@@ -2,7 +2,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio
import { beginIdleTrackedWork } from "./task-admission.js";
import { writeEnvironmentCleanup } from "./environment-cleanup-notifications.js";
import { resumePreservedResultFinalization } from "./preserved-result-finalization.js";
import { and, asc, eq, gt, inArray, ne, or, sql } from "drizzle-orm";
import { and, asc, eq, gt, inArray, ne, notInArray, or, sql } from "drizzle-orm";
import { agentWakeupRequests, environmentLeases, heartbeatRuns, issues, issueRecoveryActions, workspaceOperations, type Db } from "@paperclipai/db";
import type { Environment, EnvironmentLease } from "@paperclipai/shared";
import { conflict } from "../errors.js";
@@ -313,7 +313,7 @@ export async function scheduleRecoveredWorkspaceCleanup(db: Db, run: typeof hear
sql`${environmentLeases.metadata} = ${JSON.stringify(lease.metadata)}::jsonb`,
sql`${environmentLeases.metadata}->>'workspaceRecoveryCleanup' is null`)));
}
export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedOnly = false, obligationsOnly = false) {
export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedOnly = false, obligationsOnly = false, inFlightRunIds: string[] = []) {
const cleanup = sql`(${heartbeatRuns.runnerProfileJson}#>>'{nativeWorkspaceSync,resourceDisposition}' = 'destroy' and exists (
select 1 from ${environmentLeases} where ${environmentLeases.companyId} = ${heartbeatRuns.companyId}
and ${environmentLeases.heartbeatRunId} = ${heartbeatRuns.id}
@@ -339,6 +339,7 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedO
sql`(${issueRecoveryActions.evidence}#>>'{workspaceRecovery,status}' is distinct from 'recovered' or
${cleanup} or ${waitingInput})`,
cursor ? gt(issueRecoveryActions.id, cursor) : undefined,
inFlightRunIds.length ? notInArray(heartbeatRuns.id, inFlightRunIds) : undefined,
)).orderBy(asc(issueRecoveryActions.id)).limit(5);
}
@@ -351,11 +352,14 @@ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRu
let pending = workInFlight.get(db);
if (!pending) { pending = new Set(); workInFlight.set(db, pending); }
if (pending.size >= 2) return;
let rows = await retainedWorkspaceCandidates(db, unfinishedCursors.get(db), true);
if (!rows.length) rows = await retainedWorkspaceCandidates(db, undefined, true);
// Locally running exports already own their slot. Exclude them before
// pagination so a page containing only held work cannot prevent wrapping.
const inFlightRunIds = [...pending];
let rows = await retainedWorkspaceCandidates(db, unfinishedCursors.get(db), true, false, inFlightRunIds);
if (!rows.length) rows = await retainedWorkspaceCandidates(db, undefined, true, false, inFlightRunIds);
const unfinished = rows.length > 0;
if (!rows.length) rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly);
if (!rows.length && !passiveSweep) rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly);
if (!rows.length) rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly, inFlightRunIds);
if (!rows.length && !passiveSweep) rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds);
const work: Promise<void>[] = [];
let hasUnvisited = false;
for (const { action, run } of rows) {