mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
fix(server): wait for workspace restore before shutdown lease release
Interrupt owned legacy adapters through their cancellation controls and join settlement before releasing sandbox access. Preserve current copy-back evidence and retain exact sources when settlement exceeds the shutdown deadline. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
de9ab8e7e0
commit
1624f715bd
3 files changed
+124
-4
No files matched your search
@@ -1136,6 +1136,15 @@ An interrupted conversation does not permanently block its task. For local conve
|
||||
|
||||
Shutdown, process loss, and provider failure use the existing durable failure retry counter and delay. Ordinary failure recovery permits at most two automatic retries in a failure chain. Accepted-interaction infrastructure recovery retains its existing bounded policy. Repeated scheduler visits reuse the same successor; restarting the server does not reset the counter. After exhaustion, automatic attempts stop. A new explicit user message can start a fresh run and failure budget. Productive max-turn continuation and confirmed workspace waits keep their separate existing semantics.
|
||||
|
||||
Graceful shutdown interrupts an owned legacy adapter through its cancellation
|
||||
control, then waits up to 30 seconds for provider stop and adapter settlement.
|
||||
The sandbox lease remains available during workspace export and instruction
|
||||
collection. Lease release and recovery classification follow settlement and use
|
||||
the current execution evidence. If settlement exceeds the deadline with an
|
||||
active sandbox source, shutdown records a restore failure and pins the exact
|
||||
source for stop and retention before cleanup. A later run must pass the normal
|
||||
workspace repair gate. Native runner ownership keeps its existing restart path.
|
||||
|
||||
Real gates still apply: company and task ownership, active provider ownership, budget limits, agent availability, dependencies, pending approval/review paths, and explicit pause holds. Native runner reattachment and finalization retain their existing ownership protocol. Process, HTTP, and gateway adapters retain their recovery rules because invoking those adapters can itself repeat an external action rather than start a conversation turn.
|
||||
|
||||
An operator Stop waits for provider termination. Remote sandbox providers may return a stopped/deleted receipt after their control-plane operation completes. Paperclip binds that receipt to the company, run, and exact lease; successful file cleanup, a terminal run row, or an in-sandbox shutdown event is not sufficient. Legacy conversational runs receive their cancellation acknowledgement after all remote leases have confirmed termination. Stop alone never creates a continuation. A user message queued during remote cleanup is reconsidered when the provider confirms termination; it still passes normal admission and adopts pending comment IDs in order. Once stopped, the next explicit wake uses the same queue. A compatible saved ACP session can resume, and an unavailable or incompatible session can start fresh with the full task context. Run credentials and scratch paths remain scoped to the new run. A subtree pause requires Resume; a message does not bypass it.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environmentLeases, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
||||
@@ -10,6 +10,7 @@ import { createHeartbeatRecovery, type HeartbeatRecoveryDependencies } from "./r
|
||||
import type { HotRestartIntent } from "../hot-restart.js";
|
||||
import type { NativeRestartRecoveryClaim, NativeRestartRecoveryDisposition } from "../native-runtime/index.js";
|
||||
import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "../native-runtime/native-runner-ownership.js";
|
||||
import { adapterExecutionControls, createAdapterExecutionControl } from "../adapter-execution-control.js";
|
||||
|
||||
type Run = typeof heartbeatRuns.$inferSelect;
|
||||
|
||||
@@ -184,6 +185,79 @@ describePostgres("heartbeat recovery module ownership", () => {
|
||||
return (await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, issueId, invocationSource: "automation", status: "running", runtimeMode: "legacy" }).returning())[0];
|
||||
}
|
||||
|
||||
it.each(["restored", "restore_failed"])("keeps the sandbox available until adapter workspace settlement: %s", async outcome => {
|
||||
const run = await seedRun();
|
||||
const deps = callbacks(db);
|
||||
deps.setRunStatusIfRunning.mockImplementation(async (id, status, patch) => {
|
||||
const [updated] = await db.update(heartbeatRuns).set({ ...patch, status }).where(eq(heartbeatRuns.id, id)).returning();
|
||||
return { updated: true, run: updated };
|
||||
});
|
||||
deps.getRun.mockImplementation(async id => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0] ?? null);
|
||||
const control = createAdapterExecutionControl();
|
||||
adapterExecutionControls.set(run.id, control);
|
||||
const drain = createHeartbeatRecovery(db, deps).drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id]);
|
||||
try {
|
||||
await vi.waitFor(() => expect(control.controller.signal.aborted).toBe(true));
|
||||
expect(deps.releaseEnvironmentLeasesForRun).not.toHaveBeenCalled();
|
||||
expect(deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled();
|
||||
expect((await deps.getRun(run.id))?.status).toBe("interrupted");
|
||||
const resultJson = outcome === "restore_failed" ? { workspaceRestoreFailure: "restore_failed",
|
||||
workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [randomUUID()] } }
|
||||
: { workspaceRestored: true };
|
||||
await db.update(heartbeatRuns).set({ resultJson }).where(eq(heartbeatRuns.id, run.id));
|
||||
control.finish();
|
||||
await drain;
|
||||
expect(deps.releaseEnvironmentLeasesForRun).toHaveBeenCalledOnce();
|
||||
expect(deps.classifyAndPersistRunLiveness).toHaveBeenCalledWith(expect.objectContaining({
|
||||
resultJson: expect.objectContaining(resultJson) }), expect.anything());
|
||||
} finally {
|
||||
control.finish();
|
||||
adapterExecutionControls.delete(run.id);
|
||||
await drain;
|
||||
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id));
|
||||
}
|
||||
});
|
||||
|
||||
it("pins an unjoined sandbox restore for repair before bounded shutdown cleanup", async () => {
|
||||
const run = await seedRun();
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: run.issueId } }).where(eq(heartbeatRuns.id, run.id));
|
||||
const [lease] = await db.insert(environmentLeases).values({ companyId: run.companyId, heartbeatRunId: run.id,
|
||||
issueId: run.issueId, status: "active", provider: "daytona", providerLeaseId: randomUUID(), leasePolicy: "ephemeral",
|
||||
metadata: { driver: "sandbox", sandboxProviderPlugin: true, pluginId: "fixture-plugin", remoteCwd: "/home/daytona/workspace" } }).returning();
|
||||
const deps = callbacks(db);
|
||||
deps.setRunStatusIfRunning.mockImplementation(async (id, status, patch) => {
|
||||
const [updated] = await db.update(heartbeatRuns).set({ ...patch, status }).where(eq(heartbeatRuns.id, id)).returning();
|
||||
return { updated: true, run: updated };
|
||||
});
|
||||
deps.getRun.mockImplementation(async id => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0] ?? null);
|
||||
deps.releaseEnvironmentLeasesForRun.mockImplementation(async () => {
|
||||
expect((await deps.getRun(run.id))?.resultJson).toMatchObject({ workspaceRestoreFailure: "restore_failed",
|
||||
workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [lease.id] } });
|
||||
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0]).toMatchObject({
|
||||
status: "pending_cleanup", leasePolicy: "retain_on_failure", metadata: { sandboxStopAndRetain: { leaseId: lease.id } } });
|
||||
});
|
||||
const control = createAdapterExecutionControl();
|
||||
adapterExecutionControls.set(run.id, control);
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
const drain = createHeartbeatRecovery(db, deps).drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id]);
|
||||
try {
|
||||
await vi.waitFor(() => expect(control.controller.signal.aborted).toBe(true));
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
await drain;
|
||||
expect(deps.releaseEnvironmentLeasesForRun).toHaveBeenCalledOnce();
|
||||
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, run.issueId!)))
|
||||
.toEqual([expect.objectContaining({ evidence: expect.objectContaining({ workspaceRestoreFailure: "restore_failed" }) })]);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
control.finish();
|
||||
adapterExecutionControls.delete(run.id);
|
||||
await drain;
|
||||
await db.delete(environmentLeases).where(eq(environmentLeases.id, lease.id));
|
||||
await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, run.issueId!));
|
||||
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id));
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the shared live-execution set after construction across two factories", async () => {
|
||||
const run = await seedRun();
|
||||
const deps = callbacks(db);
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from "../legacy-controller-lease.js";
|
||||
import { remoteTerminationReceipt } from "../remote-execution-termination.js";
|
||||
import { runUsedConversationAdapter } from "../conversation-continuation.js";
|
||||
import { legacyExecutionNeedsReconciliationWithEvidence } from "../legacy-execution-recovery.js";
|
||||
import { legacyExecutionNeedsReconciliationWithEvidence, terminalizeLegacyExecution } from "../legacy-execution-recovery.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
and,
|
||||
@@ -72,6 +72,7 @@ import {
|
||||
type HotRestartReportRun,
|
||||
} from "../hot-restart.js";
|
||||
import { serverVersion } from "../../version.js";
|
||||
import { adapterExecutionControls, waitForAdapterStop } from "../adapter-execution-control.js";
|
||||
|
||||
import type { environmentService } from "../environments.js";
|
||||
import type { environmentRuntimeService, ProviderResourceDisposition } from "../environment-runtime.js";
|
||||
@@ -1156,6 +1157,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
}
|
||||
const message = `Interrupted by graceful server shutdown (${signal})`;
|
||||
const running = runningProcesses.get(run.id);
|
||||
const control = run.runtimeMode === "legacy" ? adapterExecutionControls.get(run.id) : undefined;
|
||||
try {
|
||||
if (run.runtimeMode === "native") {
|
||||
await cancelHeartbeatNativeRun({
|
||||
@@ -1165,7 +1167,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
runtimeMode: run.runtimeMode,
|
||||
});
|
||||
}
|
||||
if (running) {
|
||||
if (running && !control) {
|
||||
await terminateHeartbeatRunProcess({
|
||||
pid: running.child.pid,
|
||||
processGroupId: running.processGroupId,
|
||||
@@ -1173,7 +1175,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
runningProcesses.delete(run.id);
|
||||
if (!control && runningProcesses.get(run.id) === running) runningProcesses.delete(run.id);
|
||||
}
|
||||
|
||||
const persistedCancellationResult =
|
||||
@@ -1201,6 +1203,41 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
);
|
||||
if (!interruptedStatus.updated || !interruptedStatus.run) continue;
|
||||
let interrupted = interruptedStatus.run;
|
||||
if (control) {
|
||||
// Keep the exact lease open while its adapter stops the provider and
|
||||
// copies files back. Provider release closes command admission and
|
||||
// must not race the adapter's git export or instruction collection.
|
||||
control.controller.abort(new Error(message));
|
||||
try {
|
||||
await waitForAdapterStop(control.settled, 30_000, {
|
||||
runId: run.id, adapterType: agent.adapterType, runtimeMode: run.runtimeMode,
|
||||
abortRequested: true,
|
||||
}, control);
|
||||
} catch {
|
||||
logger.warn({ runId: run.id }, "Shutdown adapter settlement timed out; retaining the sandbox through normal cleanup");
|
||||
const [sandbox] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
|
||||
eq(environmentLeases.status, "active"), ne(environmentLeases.provider, "local"),
|
||||
or(sql`${environmentLeases.metadata}->>'driver' = 'sandbox'`,
|
||||
sql`${environmentLeases.metadata}->>'sandboxProviderPlugin' = 'true'`),
|
||||
)).limit(1);
|
||||
if (sandbox) {
|
||||
// An unjoined restore cannot certify saved files. Record the exact
|
||||
// stop-only sources and repair hold before provider cleanup starts.
|
||||
const current = await getRun(run.id, { includeExecutionEvidence: true });
|
||||
if (current) await terminalizeLegacyExecution({ db, run: current, status: current.status,
|
||||
recordRestoreFailureOnly: true, patch: { resultJson: { workspaceRestoreFailure: "restore_failed" } } });
|
||||
}
|
||||
if (runningProcesses.get(run.id) === running && running) {
|
||||
await terminateHeartbeatRunProcess({ pid: running.child.pid, processGroupId: running.processGroupId,
|
||||
graceMs: Math.max(1, running.graceSec) * 1000 });
|
||||
if (runningProcesses.get(run.id) === running) runningProcesses.delete(run.id);
|
||||
}
|
||||
}
|
||||
// Settlement can save restore-failure evidence after the shutdown CAS.
|
||||
// Classification and retry must use the current row, not its snapshot.
|
||||
interrupted = (await getRun(run.id, { includeExecutionEvidence: true })) ?? interrupted;
|
||||
}
|
||||
await setWakeupStatus(run.wakeupRequestId, "cancelled", {
|
||||
finishedAt: now,
|
||||
error: null,
|
||||
|
||||
Reference in new issue
Block a user