mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 15:52:22 +01:00
Merge workspace recovery fix into sleep-08-decision-archive-delivery
Propagate the tested retained-workspace slot correction while preserving this PR boundary. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
2e1d8d389c
4 files changed
+90
-16
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.
|
||||
@@ -14,7 +14,7 @@ type SelectRow = Record<string, unknown>;
|
||||
function createSelectChain(rows: SelectRow[] | ((table: unknown) => SelectRow[])) {
|
||||
return {
|
||||
from(table: unknown) {
|
||||
const selectedRows = typeof rows === "function" ? rows(table) : rows;
|
||||
let selectedRows = typeof rows === "function" ? rows(table) : rows;
|
||||
const query = {
|
||||
innerJoin() {
|
||||
return query;
|
||||
@@ -25,6 +25,10 @@ function createSelectChain(rows: SelectRow[] | ((table: unknown) => SelectRow[])
|
||||
for() {
|
||||
return query;
|
||||
},
|
||||
limit(count: number) {
|
||||
selectedRows = selectedRows.slice(0, count);
|
||||
return query;
|
||||
},
|
||||
then(callback: (rows: SelectRow[]) => unknown) {
|
||||
return Promise.resolve(callback(selectedRows));
|
||||
},
|
||||
@@ -292,7 +296,7 @@ describe("issueThreadInteractionService", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("withdraws a pending interaction with attribution and rejects repeats", async () => {
|
||||
it("withdraws an unlinked pending interaction with attribution and rejects repeats", async () => {
|
||||
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
||||
const interactionRow = {
|
||||
id: "interaction-withdraw", companyId: "company-1", issueId: "11111111-1111-4111-8111-111111111111",
|
||||
@@ -308,8 +312,7 @@ describe("issueThreadInteractionService", () => {
|
||||
expect(withdrawn.status).toBe("cancelled");
|
||||
expect(withdrawn.result).toEqual({ version: 1, outcome: "withdrawn", reason: "Replanning" });
|
||||
expect(withdrawn.resolvedByAgentId).toBe("agent-1");
|
||||
expect(state.toolActionRequestUpdates).toHaveLength(1);
|
||||
expect(state.toolActionRequestUpdates[0]).toMatchObject({ status: "cancelled", resolvedByAgentId: "agent-1" });
|
||||
expect(state.toolActionRequestUpdates).toHaveLength(0);
|
||||
const resolvedState = createFakeDb({ interactionRow: { ...interactionRow, status: "accepted" } });
|
||||
const resolvedSvc = issueThreadInteractionService(resolvedState.db as never);
|
||||
await expect(resolvedSvc.withdrawInteraction(
|
||||
@@ -388,7 +391,9 @@ describe("issueThreadInteractionService", () => {
|
||||
},
|
||||
result: null, resolvedAt: null, createdAt: new Date("2026-07-25T10:00:00.000Z"), updatedAt: new Date("2026-07-25T10:00:00.000Z"),
|
||||
};
|
||||
const state = createFakeDb({ interactionRow });
|
||||
const state = createFakeDb({ interactionRow, parentRows: [{
|
||||
id: "33333333-3333-4333-8333-333333333333", companyId: "company-1", interactionId: interactionRow.id,
|
||||
}] });
|
||||
const svc = issueThreadInteractionService(state.db as never);
|
||||
const expired = await svc.expirePendingInteractionsForTerminalIssue(
|
||||
{ id: interactionRow.issueId, companyId: "company-1", status: "cancelled" },
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user