mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
fix(native-runtime): fix plugin task predecessor resume and confirmed-unavailable retirement (#23772)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The native runtime executes `per_turn` plugin Runner tasks across remote sandboxes and verifies predecessor lease authority before it reads checkpoints or resumes sessions. > - Three coupled defects in predecessor resolution and retirement caused valid follow-up and retry turns to fail with `Plugin Runner retained session is not authorized (reason: predecessor_candidate_missing)`. > - First, same-run checkpoint reads called `resolvePluginTaskResume` without `inspectCheckpoint: true`, which rejected an unsettled predecessor lease before `read_state` could re-attest its status. > - Second, cross-run checkpoint recovery skipped verified backups and refused to retire a confirmed-unavailable plugin checkpoint when prior verification returned `verified`, leaving the unretired root in place to fail launch resume. > - Third, `admission_rejected` cleared `runnerTaskIdentity` on the rejected lease but kept `runnerTaskResumeFrom`, which disqualified the original predecessor lease on retry; when clearing `runnerTaskResumeFrom`, the attempted predecessor must still be recorded inside `runnerTaskAdmissionRejection` so `materializeNativeResumeRefusedContinuation` preserves automatic fresh-session continuation. > - This pull request fixes all three paths while keeping all stop-proof, scope, and retirement fences intact, and adds red-before-fix regression tests for each case. > - The benefit is that `per_turn` plugin Runner tasks recover, retire confirmed-unavailable checkpoints cleanly, and retry or continue after admission rejection without spurious authorization failures. ## Linked Issues or Issue Description **What happened?** `per_turn` plugin Runner tasks failed on same-run recovery, cross-run confirmed-unavailable checkpoint retirement, and retry after `admission_rejected` with `Plugin Runner retained session is not authorized (reason: predecessor_candidate_missing)`. **Expected behavior** 1. Same-run checkpoint reads pass `inspectCheckpoint: true` to `resolvePluginTaskResume` so `read_state` can re-attest status on the predecessor lease. 2. Cross-run follow-ups inspect verified backups and retire finished `per_turn` plugin owners (including archiving a verified suspended `plugin-runner-state.json` receipt) when the provider confirms the prior checkpoint is stopped and unavailable. 3. `admission_rejected` clears `runnerTaskResumeFrom` alongside `runnerTaskIdentity` so a subsequent retry lease still resolves the original predecessor lease, while recording the attempted `resumeFrom` inside `runnerTaskAdmissionRejection` so `materializeNativeResumeRefusedContinuation` still schedules a fresh-session continuation. **Steps to reproduce** 1. Run a same-run plugin Runner recovery (`resume_dead_runner` or disposition retry) when the predecessor lease has `runnerTaskSessionRetained: false`; `migrateRunnerdStateRoot` calls `resolvePluginTaskResume` without `inspectCheckpoint: true` and fails with `predecessor_candidate_missing`. 2. Run a cross-run `per_turn` plugin Runner follow-up when the prior root verifies via `plugin-runner-state.json` or a verified harness backup and `read_state` confirms `executionStopped: true, sessionStateAvailable: false`; the prior root is not retired and launch resume fails with `predecessor_candidate_missing`. 3. Submit a plugin Runner task on `lease2` with `resumeFrom: "task-1"` that returns `admission_rejected`, release `lease2`, and call `resolvePluginTaskResume` for `lease3` on the same run; stale `runnerTaskResumeFrom` on `lease2` disqualifies `lease1` with `predecessor_candidate_missing`. **Paperclip version or commit** `f4baaa4f48` (`master`) **Deployment mode** Self-hosted server ## What Changed - Pass `inspectCheckpoint: true` to `resolvePluginTaskResume` in `migrateRunnerdStateRoot` (`server/src/services/native-runtime/native-session-executor.ts`) before issuing same-run `read_state`, matching `recoverPluginRunnerCheckpoint` and `environment-task-runtime.ts`. - Inspect plugin checkpoints in `recoverPluginRunnerCheckpoint` when `direct === "absent" && prior === "verified"` (verified harness backup on disk). - Allow `retireFinishedPerTurnRunnerdOwner` in `migrateRunnerdStateRoot` when `pluginCheckpointUnavailableConfirmed && verification === "verified"`, preserving all existing stop-proof, lease, journal, and recovery fences. - Accept a verified suspended `plugin-runner-state.json` receipt in `readSettledRunnerdProjection` when `options.confirmedGonePluginTask` is true, and archive `plugin-runner-state.json` alongside continuity entries in `moveNativeContinuityState` when retiring a confirmed-unavailable plugin owner. - Strip `'runnerTaskResumeFrom'` alongside `'runnerTaskIdentity'` on `admission_rejected` in `executeEnvironmentTask` (`server/src/services/environment-task-runtime.ts`), record the attempted `resumeFrom` inside `runnerTaskAdmissionRejection`, and update `materializeNativeResumeRefusedContinuation` (`server/src/services/native-runtime/native-provider-capacity-retry.ts`) to read `runnerTaskAdmissionRejection.resumeFrom` with fallback to legacy `runnerTaskResumeFrom`. - Add focused red-before-fix regression tests in `server/src/services/native-runtime/native-session-executor.test.ts`, `server/src/__tests__/environment-task-authority.integration.test.ts`, and `server/src/services/native-runtime/native-resume-refused-continuation.integration.test.ts`. ## Verification - Confirmed all 5 new regression test cases failed with `predecessor_candidate_missing` or stale `runnerTaskResumeFrom` before applying the production fixes. - Ran `pnpm --dir server exec vitest run src/services/native-runtime/native-session-executor.test.ts src/services/native-runtime/native-session-root-entries.test.ts src/__tests__/environment-task-authority.integration.test.ts` — 3 test files passed (1591 passed, 7 skipped, 0 failed). - Ran `pnpm --dir server exec vitest run src/services/native-runtime/native-resume-refused-continuation.integration.test.ts` — 1 test file passed (9 passed, 0 failed). - Ran `pnpm --dir server typecheck` — passed cleanly across all layers. ## Risks - Low risk. All existing stop-proof (`remoteExecutionHasStopped`), prior lease end (`priorRemoteSandboxLeasesEnded`), released controller lease, and settled journal fences remain enforced before any confirmed-unavailable plugin checkpoint is retired. - `plugin-runner-state.json` remains in `NATIVE_SESSION_ROOT_HELD_ENTRIES` and is only accepted and archived when `confirmedGonePluginTask` is proven true and `pluginRunnerdAuthorityLifecycle` matches the exact suspended identity with no direct `runner/runner-state.json`. - `materializeNativeResumeRefusedContinuation` falls back to legacy `runnerTaskResumeFrom` for any lease written before this change. - No database schema changes or migrations are included. ## Model Used - Google DeepMind Gemini 4 Neon (Medium reasoning budget) 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
7838a12f5c
commit
ba1fc8884c
6 files changed
+375
-16
No files matched your search
@@ -590,4 +590,80 @@ databaseSuite("environment task lease authority", () => {
|
||||
expect(await remoteExecutionHasReleased(db, companyId, currentRunId)).toBe(false);
|
||||
});
|
||||
|
||||
it("clears runnerTaskResumeFrom on admission_rejected so a later retry still resolves the original predecessor lease", async () => {
|
||||
const { companyId, agentId, environmentId, pin } = await seedTaskPlugin("admission-rejected-resume-from");
|
||||
const runId = randomUUID(), lease1Id = randomUUID(), lease2Id = randomUUID(), lease3Id = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" });
|
||||
const priorIdentity = { runnerInstanceId: "runner", normalizedSessionId: "session", environmentLeaseId: lease1Id, runId };
|
||||
const runner = { runnerId: "runner", leaseId: lease1Id, runId, sessionId: "session", turnId: "turn-1", itemId: "item-1", harness: "codex" as const, protocolMin: 1, protocolMax: 1 };
|
||||
const lease1 = { id: lease1Id, companyId, environmentId, heartbeatRunId: runId, provider: "plugin:fixture:tasks", providerLeaseId: "task-1" };
|
||||
await db.insert(environmentLeases).values([
|
||||
{
|
||||
...lease1,
|
||||
status: "released",
|
||||
cleanupStatus: "success",
|
||||
releasedAt: new Date(),
|
||||
metadata: {
|
||||
...pin,
|
||||
runnerTaskDispatched: true,
|
||||
runnerTaskExecutionStopped: true,
|
||||
runnerTaskSessionRetained: true,
|
||||
runnerTaskIdentity: runner,
|
||||
remoteExecutionTermination: remoteTerminationReceipt(lease1, { providerLeaseId: "task-1", state: "stopped" }),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: lease2Id, companyId, environmentId, heartbeatRunId: runId, provider: lease1.provider, providerLeaseId: "task-2",
|
||||
status: "active", metadata: pin,
|
||||
},
|
||||
]);
|
||||
|
||||
const call = vi.fn(async (_id: string, _method: string, params: any) => params.operation.kind === "submit"
|
||||
? { kind: "admission_rejected", taskId: params.taskId, reason: "session_state_unavailable" }
|
||||
: { kind: "accepted", taskId: params.taskId });
|
||||
const runtime = environmentRuntimeService(db, {
|
||||
pluginWorkerManager: { getWorker: () => ({ supportedMethods: ["environmentTask"] }), call } as unknown as PluginWorkerManager,
|
||||
});
|
||||
|
||||
await expect(runtime.task({
|
||||
companyId,
|
||||
leaseId: lease2Id,
|
||||
operation: {
|
||||
kind: "submit",
|
||||
preparedLaunchId: "fixture",
|
||||
projectIds: [],
|
||||
bootstrapTicket: "fixture",
|
||||
runner,
|
||||
resumeFrom: "task-1",
|
||||
},
|
||||
})).resolves.toMatchObject({ kind: "admission_rejected", reason: "session_state_unavailable" });
|
||||
|
||||
const [rejectedLease2] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease2Id));
|
||||
expect(rejectedLease2?.metadata?.runnerTaskIdentity).toBeUndefined();
|
||||
expect(rejectedLease2?.metadata?.runnerTaskResumeFrom).toBeUndefined();
|
||||
expect(rejectedLease2?.metadata?.runnerTaskAdmissionRejection).toEqual({
|
||||
taskId: "task-2",
|
||||
reason: "session_state_unavailable",
|
||||
resumeFrom: "task-1",
|
||||
});
|
||||
|
||||
// Mark lease2 released with a stop receipt so lease3 can retry resuming from lease1.
|
||||
await db.update(environmentLeases).set({
|
||||
status: "released",
|
||||
cleanupStatus: "success",
|
||||
releasedAt: new Date(),
|
||||
metadata: {
|
||||
...rejectedLease2!.metadata,
|
||||
remoteExecutionTermination: remoteTerminationReceipt(rejectedLease2!, { providerLeaseId: "task-2", state: "stopped" }),
|
||||
},
|
||||
}).where(eq(environmentLeases.id, lease2Id));
|
||||
|
||||
await db.insert(environmentLeases).values({
|
||||
id: lease3Id, companyId, environmentId, heartbeatRunId: runId, provider: lease1.provider, providerLeaseId: "task-3",
|
||||
status: "active", metadata: pin,
|
||||
});
|
||||
|
||||
await expect(resolvePluginTaskResume(db, { companyId, leaseId: lease3Id, priorIdentity })).resolves.toBe("task-1");
|
||||
});
|
||||
|
||||
});
|
||||
@@ -623,8 +623,12 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
const parsed = parseEnvironmentTaskResult(operation, taskId, result);
|
||||
if (operation.kind === "submit" && parsed.kind === "admission_rejected") {
|
||||
const recorded = await db.update(environmentLeases).set({
|
||||
metadata: sql`(coalesce(${environmentLeases.metadata}, '{}'::jsonb) - 'runnerTaskIdentity') || ${JSON.stringify({
|
||||
runnerTaskAdmissionRejection: { taskId, reason: parsed.reason },
|
||||
metadata: sql`(coalesce(${environmentLeases.metadata}, '{}'::jsonb) - 'runnerTaskIdentity' - 'runnerTaskResumeFrom') || ${JSON.stringify({
|
||||
runnerTaskAdmissionRejection: {
|
||||
taskId,
|
||||
reason: parsed.reason,
|
||||
...(operation.resumeFrom ? { resumeFrom: operation.resumeFrom } : {}),
|
||||
},
|
||||
runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: false,
|
||||
})}::jsonb`,
|
||||
}).where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, input.companyId),
|
||||
|
||||
@@ -111,7 +111,7 @@ export async function materializeNativeResumeRefusedContinuation(input: NativeRe
|
||||
const [refusedResume] = await input.tx.select({ reason: refusalReason }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, run.id),
|
||||
inArray(refusalReason, [...NATIVE_RESUME_REFUSAL_REASONS]),
|
||||
sql`coalesce(${environmentLeases.metadata}->>'runnerTaskResumeFrom', '') <> ''`,
|
||||
sql`coalesce(${environmentLeases.metadata}#>>'{runnerTaskAdmissionRejection,resumeFrom}', ${environmentLeases.metadata}->>'runnerTaskResumeFrom', '') <> ''`,
|
||||
)).limit(1);
|
||||
if (!refusedResume) return null;
|
||||
const reason = refusedResume.reason as NativeResumeRefusalReason;
|
||||
|
||||
+69
-2
@@ -1,10 +1,14 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, companyMemberships, completionContracts, createDb, environmentLeases, heartbeatRuns, issueRecoveryActions,
|
||||
issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { agents, companies, companyMemberships, completionContracts, createDb, environmentLeases, environments, heartbeatRuns, issueRecoveryActions,
|
||||
issues, nativeRunFinalizations, plugins } from "@paperclipai/db";
|
||||
import type { NativeExecutionInputV1 } from "@paperclipai/paperclip-runner";
|
||||
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
||||
import type { PluginWorkerManager } from "../plugin-worker-manager.js";
|
||||
import { executeEnvironmentTask } from "../environment-task-runtime.js";
|
||||
import { remoteTerminationReceipt } from "../remote-execution-termination.js";
|
||||
import { materializeNativeResumeRefusedContinuation } from "./native-provider-capacity-retry.js";
|
||||
|
||||
const provider = vi.hoisted(() => ({ execute: vi.fn() }));
|
||||
vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({
|
||||
@@ -133,4 +137,67 @@ describe("native run whose environment refuses to resume its saved session", ()
|
||||
expect(refused.retries).toHaveLength(0);
|
||||
expect(refused.coordinator.failureDetail).not.toHaveProperty("successorRunId");
|
||||
}, 120_000);
|
||||
|
||||
it("continues a resumed session refused through executeEnvironmentTask even after runnerTaskResumeFrom is cleared", async () => {
|
||||
const issueId = randomUUID(), runId = randomUUID(), priorRunId = randomUUID();
|
||||
const environmentId = randomUUID(), pluginId = randomUUID(), priorLeaseId = randomUUID(), leaseId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Resume via executeEnvironmentTask", status: "in_progress",
|
||||
workMode: "standard", assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" });
|
||||
await db.insert(environments).values({ id: environmentId, name: `Env ${environmentId}`, driver: "plugin",
|
||||
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
|
||||
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: `fixture-${pluginId}`, version: "1.0.0",
|
||||
status: "ready", manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }] } as never });
|
||||
await db.insert(heartbeatRuns).values([
|
||||
{ id: priorRunId, companyId, agentId, status: "succeeded", runtimeMode: "native", nativeIssueId: issueId,
|
||||
responsibleUserId: "board-user", invocationSource: "automation", triggerDetail: "system" },
|
||||
{ id: runId, companyId, agentId, status: "running", runtimeMode: "native", nativeIssueId: issueId,
|
||||
responsibleUserId: "board-user", invocationSource: "automation", triggerDetail: "system",
|
||||
contextSnapshot: { issueId, wakeCommentId: "original-message" } },
|
||||
]);
|
||||
const pin = { driver: "plugin", pluginId, driverKey: "tasks", environmentId, runnerTaskLease: true,
|
||||
runnerTaskProjectAuthValidation: { configurationId: "fixture", provider: "openai", projectIds: [] } };
|
||||
const priorRunner = { runnerId: "runner", leaseId: priorLeaseId, runId: priorRunId, sessionId: "session", turnId: "turn-1", itemId: "item-1", harness: "codex" as const, protocolMin: 1, protocolMax: 1 };
|
||||
const priorLease = { id: priorLeaseId, companyId, issueId, environmentId, heartbeatRunId: priorRunId, provider: "plugin:fixture:tasks", providerLeaseId: "prior-task" };
|
||||
await db.insert(environmentLeases).values([
|
||||
{ ...priorLease, status: "released", cleanupStatus: "success", releasedAt: new Date(), metadata: {
|
||||
...pin, runnerTaskDispatched: true, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true,
|
||||
runnerTaskIdentity: priorRunner,
|
||||
remoteExecutionTermination: remoteTerminationReceipt(priorLease, { providerLeaseId: "prior-task", state: "stopped" }),
|
||||
} },
|
||||
{ id: leaseId, companyId, issueId, environmentId, heartbeatRunId: runId, provider: priorLease.provider,
|
||||
providerLeaseId: "attempt-task", status: "active", metadata: pin },
|
||||
]);
|
||||
const workers = {
|
||||
getWorker: () => ({ supportedMethods: ["environmentTask"] }),
|
||||
call: vi.fn(async () => ({ kind: "admission_rejected", taskId: "attempt-task", reason: "session_state_unavailable" })),
|
||||
} as unknown as PluginWorkerManager;
|
||||
|
||||
const result = await executeEnvironmentTask(db, workers, {
|
||||
companyId,
|
||||
leaseId,
|
||||
operation: {
|
||||
kind: "submit",
|
||||
preparedLaunchId: "fixture",
|
||||
projectIds: [],
|
||||
bootstrapTicket: "fixture",
|
||||
runner: { ...priorRunner, runId },
|
||||
resumeFrom: "prior-task",
|
||||
},
|
||||
});
|
||||
expect(result).toMatchObject({ kind: "admission_rejected", reason: "session_state_unavailable" });
|
||||
|
||||
const [leaseAfter] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId));
|
||||
expect(leaseAfter?.metadata?.runnerTaskResumeFrom).toBeUndefined();
|
||||
expect(leaseAfter?.metadata?.runnerTaskAdmissionRejection).toEqual({
|
||||
taskId: "attempt-task",
|
||||
reason: "session_state_unavailable",
|
||||
resumeFrom: "prior-task",
|
||||
});
|
||||
|
||||
const continuation = await db.transaction(tx =>
|
||||
materializeNativeResumeRefusedContinuation({ tx: tx as unknown as typeof db, companyId, issueId, runId, agentId }),
|
||||
);
|
||||
expect(continuation).toMatchObject({ reason: "session_state_unavailable" });
|
||||
expect(continuation?.retryId).toBeTruthy();
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -20245,6 +20245,153 @@ describe("runnerd provider runtime wiring", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["plugin-receipt", "verified-backup"] as const)(
|
||||
"retires a finished per-turn plugin owner whose checkpoint is confirmed unavailable even when prior state verified via %s",
|
||||
async mode => {
|
||||
const first = {
|
||||
...scopedNativeExecution(`plugin-verified-unavailable-${mode}`),
|
||||
schema: "paperclip.native-execution-input.v5", executionMode: "default", planningContext: null, runtimeContext: nativeRuntimeContextFixture(),
|
||||
provider: { kind: "codex", model: null, approvalPolicy: "never" },
|
||||
session: {
|
||||
...execution.session, driverKind: "codex_app_server",
|
||||
normalizedSessionId: `plugin-verified-unavailable-${mode}`, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
|
||||
},
|
||||
} as NativeExecutionInput;
|
||||
parseNativeExecutionInput(first);
|
||||
const next = { ...first, binding: { ...first.binding, runId: `${first.binding.runId}-followup` } };
|
||||
const identity = {
|
||||
runId: first.binding.runId, normalizedSessionId: first.session.normalizedSessionId!,
|
||||
runnerInstanceId: "plugin-runner", environmentLeaseId: "old-lease", turnId: "old-turn", itemId: "old-item",
|
||||
};
|
||||
const scoped = await initializeScopedRunnerRoot(first, identity.runnerInstanceId);
|
||||
await mkdir(join(scoped, "control-plane"), { recursive: true });
|
||||
const journal = JSON.stringify({
|
||||
...durableControlPlaneState(identity),
|
||||
commands: [{ type: "turn.start", status: "completed" }],
|
||||
committedEvents: [{ eventType: "run.terminal", envelope: { ...identity, payload: { reportedWorkDisposition: "done" } } }],
|
||||
});
|
||||
await writeFile(join(scoped, "control-plane/control-plane-state.json"), journal);
|
||||
if (mode === "plugin-receipt") {
|
||||
await writeFile(join(scoped, "plugin-runner-state.json"), JSON.stringify(durableRunnerState(identity, "suspended")));
|
||||
} else {
|
||||
const backupRoot = join(scoped, "failover-backups/current");
|
||||
for (const directory of resolveNativeHarnessPersistenceProfile(first).directories)
|
||||
await mkdir(join(backupRoot, directory.name), { recursive: true });
|
||||
await writeFile(join(backupRoot, "runner/runner-state.json"), JSON.stringify(durableRunnerState(identity, "suspended")));
|
||||
await writeFile(join(backupRoot, "manifest.json"), JSON.stringify(buildNativeHarnessBackupManifest({
|
||||
backupRoot, execution: first, runnerInstanceId: identity.runnerInstanceId, sourceProviderLeaseId: "old-task",
|
||||
providerSessionIdentity: { providerSessionId: "retained-provider-thread", providerBackendSessionId: null, providerSessionIdentity: null },
|
||||
})));
|
||||
}
|
||||
|
||||
const db = leaseDb(next);
|
||||
const ordinarySelect = db.select.bind(db);
|
||||
const { currentNativeControllerIdentity } = await import("./native-restart-recovery.js");
|
||||
const controller = await currentNativeControllerIdentity();
|
||||
const committedPrior = {
|
||||
run: {
|
||||
id: first.binding.runId, companyId: first.binding.companyId, agentId: first.binding.agentId,
|
||||
nativeIssueId: first.binding.issueId, runtimeMode: "native", status: "succeeded",
|
||||
runnerProfileJson: { nativeExecutionInput: first },
|
||||
processPid: null, processGroupId: null, processStartedAt: null,
|
||||
},
|
||||
owner: {
|
||||
runId: first.binding.runId, companyId: first.binding.companyId, issueId: first.binding.issueId,
|
||||
phase: "committed", resultId: "result-1", leaseOwner: null, recoveryState: null,
|
||||
controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt,
|
||||
controllerBootId: controller.bootId,
|
||||
},
|
||||
};
|
||||
const priorEndedLease = {
|
||||
id: "old-lease", companyId: first.binding.companyId, heartbeatRunId: first.binding.runId,
|
||||
status: "released", releasedAt: new Date(), cleanupStatus: "success",
|
||||
provider: "plugin:test:tasks", providerLeaseId: "old-task",
|
||||
metadata: {
|
||||
driver: "plugin",
|
||||
runnerTaskExecutionStopped: true,
|
||||
runnerTaskSessionRetained: false,
|
||||
remoteExecutionTermination: {
|
||||
schema: "paperclip.remote-termination.v1",
|
||||
companyId: first.binding.companyId,
|
||||
runId: first.binding.runId,
|
||||
leaseId: "old-lease",
|
||||
provider: "plugin:test:tasks",
|
||||
providerLeaseId: "old-task",
|
||||
state: "stopped",
|
||||
confirmedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
};
|
||||
db.select = ((fields?: Record<string, unknown>) => {
|
||||
if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) {
|
||||
return priorNativeRunDb(first, committedPrior.run.status).select(fields as never);
|
||||
}
|
||||
if (fields && "run" in fields && "owner" in fields) {
|
||||
return {
|
||||
from: () => ({
|
||||
innerJoin: () => ({
|
||||
where: () => ({ limit: async () => [committedPrior] }),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (fields && "providerLeaseId" in fields && "status" in fields) {
|
||||
return { from: () => ({ where: async () => [priorEndedLease] }) };
|
||||
}
|
||||
if (fields === undefined) {
|
||||
return {
|
||||
from: (table: unknown) => table === environmentLeases
|
||||
? { where: async () => [priorEndedLease] }
|
||||
: ordinarySelect().from(table as never),
|
||||
};
|
||||
}
|
||||
return ordinarySelect(fields as never);
|
||||
}) as Db["select"];
|
||||
|
||||
const resume = vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockImplementation(async (_db, request) => {
|
||||
if (!request.inspectCheckpoint) {
|
||||
throw new Error("Plugin Runner retained session is not authorized (reason: predecessor_candidate_missing)");
|
||||
}
|
||||
return "old-task";
|
||||
});
|
||||
const task = vi.fn(async (operation: any) => {
|
||||
environmentTaskOperationSchema.parse(operation);
|
||||
if (operation.kind === "read_state") {
|
||||
throw environmentTaskRuntime.createUnconfirmedPluginCheckpointError({
|
||||
executionStopped: true,
|
||||
sessionStateAvailable: false,
|
||||
});
|
||||
}
|
||||
return {
|
||||
kind: "description", taskId: "replacement-task", launchPreparationVersion: 1, projectAuthCheckVersion: 1, warmTaskVersion: 1,
|
||||
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` },
|
||||
};
|
||||
});
|
||||
state.createBackend.mockClear();
|
||||
const home = join(isolatedStateDirectory, `checkpoint-verified-unavailable-${mode}`);
|
||||
await mkdir(home, { recursive: true });
|
||||
await writeFile(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: "synthetic-fixture" }), { mode: 0o600 });
|
||||
try {
|
||||
const launch = {
|
||||
db, execution: next, runnerInstanceId: "replacement-runner", runnerIngressAuthorized: true,
|
||||
managedAiCredentialHome: home, managedAiCredentialIdentity: "revision", managedAiAccountIdentity: "account",
|
||||
runnerEnvironment: { ANTHROPIC_API_KEY: "synthetic-fixture" },
|
||||
runnerExecutionTarget: {
|
||||
kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "replacement-lease", runnerTask: task,
|
||||
sandboxLeaseAcquisition: { outcome: "replacement", providerLeaseId: "replacement-task" },
|
||||
} as never,
|
||||
};
|
||||
await expect(createRunnerdBackend(launch)).resolves.toBeDefined();
|
||||
expect(state.createBackend).toHaveBeenCalledOnce();
|
||||
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(true);
|
||||
expect(existsSync(join(scoped, "plugin-runner-state.json"))).toBe(false);
|
||||
expect(task).toHaveBeenCalledWith({ kind: "read_state", identity, resumeFrom: "old-task" });
|
||||
} finally {
|
||||
resume.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"destroyed-after-turn",
|
||||
"destroyed-after-turn-active-goal",
|
||||
@@ -20684,6 +20831,60 @@ describe("runnerd provider runtime wiring", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["resume-dead-runner", "disposition-retry"] as const)(
|
||||
"passes inspectCheckpoint: true when reading a same-run plugin checkpoint before resume: %s",
|
||||
async mode => {
|
||||
const current = scopedNativeExecution(`plugin-same-run-inspect-${mode}`);
|
||||
const identity = {
|
||||
runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!,
|
||||
runnerInstanceId: "plugin-runner", environmentLeaseId: "old-task-lease", turnId: "old-turn", itemId: "old-item",
|
||||
};
|
||||
const root = await initializeScopedRunnerRoot(current, identity.runnerInstanceId);
|
||||
await mkdir(join(root, "control-plane"), { recursive: true });
|
||||
await writeFile(join(root, "control-plane/control-plane-state.json"), JSON.stringify(durableControlPlaneState(identity)));
|
||||
let checkpointReAttested = false;
|
||||
const resume = vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockImplementation(async (_db, request) => {
|
||||
if (!request.inspectCheckpoint && !checkpointReAttested) {
|
||||
throw new Error("Plugin Runner retained session is not authorized (reason: predecessor_candidate_missing)");
|
||||
}
|
||||
return "prior-task";
|
||||
});
|
||||
const task = vi.fn(async (operation: any) => {
|
||||
environmentTaskOperationSchema.parse(operation);
|
||||
if (operation.kind === "read_state") {
|
||||
checkpointReAttested = true;
|
||||
return { kind: "state", taskId: "next-task", state: durableRunnerState(identity, "ready") };
|
||||
}
|
||||
return {
|
||||
kind: "description", launchPreparationVersion: 1, projectAuthCheckVersion: 1, taskId: "next-task",
|
||||
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` },
|
||||
};
|
||||
});
|
||||
state.createBackend.mockClear();
|
||||
try {
|
||||
const db = leaseDb(current);
|
||||
await expect(createRunnerdBackend({
|
||||
db, execution: current, runnerInstanceId: identity.runnerInstanceId,
|
||||
runnerIngressAuthorized: true,
|
||||
runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "new-task-lease", runnerTask: task },
|
||||
...(mode === "resume-dead-runner" ? {
|
||||
restartRecovery: {
|
||||
kind: "resume_dead_runner" as const, runId: current.binding.runId, leaseOwner: "controller", controllerGeneration: 2,
|
||||
providerAttempt: 2, restartKind: "hard" as const, recoveryRequestId: null,
|
||||
},
|
||||
} : {}),
|
||||
})).resolves.toBeDefined();
|
||||
expect(resume).toHaveBeenCalledWith(db, expect.objectContaining({
|
||||
leaseId: "new-task-lease", priorIdentity: identity, inspectCheckpoint: true,
|
||||
}));
|
||||
expect(task).toHaveBeenCalledWith({ kind: "read_state", identity, resumeFrom: "prior-task" });
|
||||
expect(state.createBackend).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
resume.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["verified", "portable", "wrong-claim", "wrong-state", "wrong-lease"] as const)("reattaches a surviving plugin task through its owner: %s", async mode => {
|
||||
const current = scopedNativeExecution(`plugin-live-${mode}`);
|
||||
const moved = mode === "portable" || mode === "wrong-claim";
|
||||
|
||||
@@ -6073,7 +6073,7 @@ async function recoverPluginRunnerCheckpoint(input: {
|
||||
}
|
||||
await assertCleanupActivationCommitted(input.db, root, input.execution);
|
||||
const prior = await verifyPriorRunnerdStateForSessionScope({ ...input, root, identity, allowVerifiedBackup: true });
|
||||
if (prior !== "terminal_state_indeterminate" && !((quarantined || verifiedPluginReceipt) && prior === "verified")) {
|
||||
if (prior !== "terminal_state_indeterminate" && !((quarantined || verifiedPluginReceipt || direct === "absent") && prior === "verified")) {
|
||||
if (quarantined) return deny("quarantined_prior_owner_unverified");
|
||||
return;
|
||||
}
|
||||
@@ -6106,8 +6106,8 @@ async function recoverPluginRunnerCheckpoint(input: {
|
||||
}
|
||||
}
|
||||
|
||||
function moveNativeContinuityState(root: string, archiveRoot: string): void {
|
||||
for (const name of NATIVE_CONTINUITY_STATE_ENTRIES) {
|
||||
function moveNativeContinuityState(root: string, archiveRoot: string, extraEntries: readonly string[] = []): void {
|
||||
for (const name of [...NATIVE_CONTINUITY_STATE_ENTRIES, ...extraEntries]) {
|
||||
const source = resolve(root, name);
|
||||
if (existsSync(source)) renameSync(source, resolve(archiveRoot, name));
|
||||
}
|
||||
@@ -6137,18 +6137,23 @@ const GONE_REMOTE_RUNNER_DELIVERY_COMMANDS = new Set(["run.attach", "semantic_to
|
||||
"session.goal.get"]);
|
||||
|
||||
function readSettledRunnerdProjection(root: string, identity: Record<string, string>,
|
||||
options: { localRunner?: boolean; controlBytes?: string; remoteRunnerGone?: boolean; parkedGovernedWait?: boolean } = {}): SettledRunnerdProjection {
|
||||
options: { localRunner?: boolean; controlBytes?: string; remoteRunnerGone?: boolean; parkedGovernedWait?: boolean; confirmedGonePluginTask?: boolean } = {}): SettledRunnerdProjection {
|
||||
const refuse = (refused: string): SettledRunnerdProjection => ({ refused });
|
||||
try {
|
||||
if (!isSafeNativeStateDirectory(root)) return refuse("root_unsafe");
|
||||
const lifecycle = runnerdAuthorityLifecycle(root, identity as RunnerdDurableIdentity);
|
||||
if (lifecycle !== "absent" && !(options.localRunner && lifecycle === "not_suspended")) {
|
||||
const verifiedPluginReceipt = options.confirmedGonePluginTask && lifecycle === "suspended"
|
||||
&& !existsSync(resolve(root, "runner", "runner-state.json"))
|
||||
&& pluginRunnerdAuthorityLifecycle(root, identity as RunnerdDurableIdentity) === "suspended";
|
||||
if (lifecycle !== "absent" && !(options.localRunner && lifecycle === "not_suspended") && !verifiedPluginReceipt) {
|
||||
return refuse(`runner_lifecycle_${lifecycle}`);
|
||||
}
|
||||
// Every legitimate writer's entry is classified in native-session-root-entries.ts.
|
||||
// Held entries are known evidence that needs its own settlement; anything
|
||||
// else is writer drift. Name each kind separately.
|
||||
const unknown = readdirSync(root).filter(name => !isKnownNativeSessionRootEntry(name));
|
||||
const unknown = readdirSync(root).filter(
|
||||
name => !isKnownNativeSessionRootEntry(name) && !(verifiedPluginReceipt && name === "plugin-runner-state.json"),
|
||||
);
|
||||
const held = unknown.filter(name => NATIVE_SESSION_ROOT_HELD_ENTRIES.includes(name));
|
||||
if (held.length > 0) return refuse(`held_root_entry(${describeUnexpectedNativeSessionRootEntries(held)})`);
|
||||
if (unknown.length > 0) return refuse(`unexpected_root_entry(${describeUnexpectedNativeSessionRootEntries(unknown)})`);
|
||||
@@ -6301,7 +6306,7 @@ async function inspectFinishedPerTurnRunnerdOwner(input: {
|
||||
}
|
||||
const parkedGovernedWait = remoteRunnerGone && await priorRunParkedOnGovernedWait(input.db, {
|
||||
companyId: binding.companyId, issueId: binding.issueId, runId: identity.runId });
|
||||
const projectionOptions = { localRunner, controlBytes: input.projectedControlBytes, remoteRunnerGone, parkedGovernedWait };
|
||||
const projectionOptions = { localRunner, controlBytes: input.projectedControlBytes, remoteRunnerGone, parkedGovernedWait, confirmedGonePluginTask };
|
||||
const projection = readSettledRunnerdProjection(input.root, identity, projectionOptions);
|
||||
if (projection.refused !== undefined) return refuse(projection.refused);
|
||||
const controlBytes = projection.bytes;
|
||||
@@ -6369,7 +6374,7 @@ async function inspectFinishedPerTurnRunnerdOwner(input: {
|
||||
for (const name of readdirSync(quarantine)) {
|
||||
if (!name.startsWith(`${basename(input.root)}.`)) continue;
|
||||
if (quarantinedBootstrapOfOwnerHeldNoProviderWork(resolve(quarantine, name), identity, localRunner)) continue;
|
||||
const copy = readSettledRunnerdProjection(resolve(quarantine, name), identity, { localRunner, remoteRunnerGone, parkedGovernedWait });
|
||||
const copy = readSettledRunnerdProjection(resolve(quarantine, name), identity, { localRunner, remoteRunnerGone, parkedGovernedWait, confirmedGonePluginTask });
|
||||
if (copy.refused !== undefined) return refuse(`quarantine_${copy.refused}`);
|
||||
}
|
||||
}
|
||||
@@ -6488,7 +6493,11 @@ async function retireFinishedPerTurnRunnerdOwner(input: Parameters<typeof inspec
|
||||
const archiveRoot = resolve(input.root, "continuity-breaks", `${archivedAt}-${randomUUID()}`);
|
||||
mkdirSync(archiveRoot, { recursive: true, mode: 0o700 });
|
||||
noteNativeRunnerEvidence(archivedAt);
|
||||
moveNativeContinuityState(input.root, archiveRoot);
|
||||
moveNativeContinuityState(
|
||||
input.root,
|
||||
archiveRoot,
|
||||
input.pluginCheckpointUnavailableConfirmed ? ["plugin-runner-state.json"] : [],
|
||||
);
|
||||
await input.onLog?.(
|
||||
"stdout",
|
||||
`[paperclip-runner] Run ${input.identity.runId} finished without a saved runner checkpoint; starting a new runner for this conversation.\n`,
|
||||
@@ -6718,7 +6727,7 @@ async function migrateRunnerdStateRoot(input: {
|
||||
&& (input.restartRecovery?.kind === "resume_dead_runner"
|
||||
|| (!input.restartRecovery && identity.environmentLeaseId !== taskTarget.leaseId))) {
|
||||
const resumeFrom = taskTarget.sandboxLeaseAcquisition?.outcome === "resumed" ? undefined : await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
|
||||
leaseId: taskTarget.leaseId, priorIdentity: identity });
|
||||
leaseId: taskTarget.leaseId, priorIdentity: identity, inspectCheckpoint: true });
|
||||
await readAndSavePluginRunnerCheckpoint(scoped, taskTarget.runnerTask, identity, resumeFrom);
|
||||
}
|
||||
if (input.restartRecovery?.kind === "bootstrap_incomplete" && identity.runId === input.execution.binding.runId) {
|
||||
@@ -6813,7 +6822,9 @@ async function migrateRunnerdStateRoot(input: {
|
||||
// Name the failed retirement proof: the shared error otherwise hides
|
||||
// which of several independent fences held the follow-up.
|
||||
let retirementRefusedReason: string | null = null;
|
||||
if (verification === "terminal_state_indeterminate" && !input.retainedWarmOwnerRunId
|
||||
if ((verification === "terminal_state_indeterminate"
|
||||
|| (pluginCheckpointUnavailableConfirmed && verification === "verified"))
|
||||
&& !input.retainedWarmOwnerRunId
|
||||
&& (!input.restartRecovery || input.restartRecovery.kind === "bootstrap_incomplete")) {
|
||||
const retirement = await retireFinishedPerTurnRunnerdOwner({ ...input, root: scoped, identity, pluginCheckpointUnavailableConfirmed });
|
||||
if (retirement.retired) {
|
||||
|
||||
Reference in new issue
Block a user