mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 04:54:00 +01:00
Persist portable Runner ownership through controller recovery (#21066)
## Thinking Path > - Paperclip delegates remote Runner execution to environment plugins. > - A plugin can move a session to another task allocation. > - The Core controller can lose an ownership reply or restart before the Runner starts. > - The source and target need a durable record of the same request. > - This change binds restart and attachment to that request and the original unlaunched task lease. ## Linked Issues or Issue Description **What existing behavior does this improve?** Recovery of plugin Runner sessions on replacement compute. **Current behavior** Core cannot replay a session ownership request from saved lease state during startup. **Proposed behavior** Record the operation on both leases and check the matched ownership receipt before attaching. Preserve the original pre-admission lease across controller restart. Managed environment configuration is in [#21065](https://github.com/paperclipai/paperclip/pull/21065). Related warm sandbox cleanup is in [#20065](https://github.com/paperclipai/paperclip/pull/20065). This layer preserves the same-sandbox fallback from [#21001](https://github.com/paperclipai/paperclip/pull/21001). Workspace placement follows in [#20743](https://github.com/paperclipai/paperclip/pull/20743). ## What Changed - Add the optional `sessionHandoffVersion` capability and the ownership task operation. - Save matching ownership claims and fence source checkpoint access. Replay a pending request on the original target. - Restore a portable session using the durable claim and the current credentials for the same account. Start a fresh conversation when the provider reports an unavailable checkpoint, or when Core's persisted compatibility decision selects a different session after transfer. The latter requires an unlaunched target; subsequent recovery must match the fresh task's saved identity. Both paths retain the workspace transfer and source fencing. - Reuse the original unlaunched task lease after hard or graceful controller restart. After a move has attached, validate the surviving Runner through the saved claim rather than requiring its logical lease ID to equal the new physical lease. - Keep older retained leases without a saved account identity on the existing resume path. - Apply the existing supported MCP-only compatibility rule to warm recovery and predecessor accounting. Persist the capability discovered at admission and reuse it after restart without repeating discovery. - Keep predecessor-retirement fallback scoped to the same physical sandbox. A refusal after a portable move preserves the session instead of requesting a replacement that the plugin driver cannot enforce. ## Verification - On `1eb527be27`, server typecheck (including Runner build and SDK dependencies) passed. - Independent final verification passed 168 tests across portable source recovery, session resume, controller recovery, and task authority; two existing tests were skipped. The full portable source integration suite passed 64 tests. - The new integration follows confirmed ownership through an incompatible instruction change, persisted fresh admission, target-only prepare/auth/submit without the source checkpoint, and reattachment after controller replacement. It also rejects unpersisted session selection, ambiguous target leases, and incorrect saved identities. - Before this final change, independent verification passed 1,667 tests across executor, session resume, recovery usage, remote warm recovery, runtime selection, and runtime execution; the environment lifecycle suite passed 208 tests. - Existing regressions cover previous-release account metadata, supported and unsupported MCP changes, provider/instruction incompatibility, and admission capability reuse without another discovery call. - On `51d7eec373`, all four S3 multipart throttle tests passed independently. CI exposed an existing timing-sensitive test twice; its 20 ms overlap assumption now uses synchronized retries and an event-loop yield. Production upload code is unchanged. Temporary concurrency caps of one and eight both fail the retained exact-four assertion. - Exact SDK source-pin checks passed for both stack heads. The upper #20743 code patch remains unchanged; its documentation preserves both layers' behavior. ## Risks - The handoff protocol is opt-in. Existing plugin leases without portable ownership metadata keep the previous release's resume path. Live attachment still requires end-to-end qualification. An unverified claim blocks startup. Git workspaces prepared on a portable allocation also need the workspace placement layer. ## Model Used - OpenAI Codex GPT-6 with GPT-6.1 Sol agents for implementation and independent review. ## Checklist - [x] Thinking path and model are included. - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] The issue is described using the enhancement template. - [x] Local checks passed and new behavior has tests. - [x] All Paperclip CI gates are green. - [x] Greptile is 5/5 with no open findings. --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
a4a0668a5c
commit
a924d2e2c7
40 files changed
+1585
-223
No files matched your search
@@ -509,8 +509,16 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
await db.update(nativeRunFinalizations).set({ phase: "committed", leaseOwner: null, leaseExpiresAt: null })
|
||||
.where(eq(nativeRunFinalizations.runId, fixture.scope.runId));
|
||||
await expect(readSandbox()).resolves.toEqual({ remoteCwd: "/workspace" });
|
||||
await expect(inspect({ readControlState: () => ({ identity, commands: [{ status: "pending" }],
|
||||
committedEvents: [{ eventType: "run.terminal", envelope: identity }] }) })).rejects.toBeInstanceOf(NativePredecessorRetirementUnprovenError);
|
||||
const readUnsettledControlState = () => ({ identity, commands: [{ status: "pending" }],
|
||||
committedEvents: [{ eventType: "run.terminal", envelope: identity }] });
|
||||
await expect(inspect({ readControlState: readUnsettledControlState }))
|
||||
.rejects.toBeInstanceOf(NativePredecessorRetirementUnprovenError);
|
||||
const movedFailure = await inspect({
|
||||
target: { ...target, sandboxLeaseAcquisition: { outcome: "replacement", providerLeaseId: "new-sandbox" } } as never,
|
||||
portableSourceTaskId: "retained-sandbox", readControlState: readUnsettledControlState,
|
||||
}).catch(error => error);
|
||||
expect(movedFailure).not.toBeInstanceOf(NativePredecessorRetirementUnprovenError);
|
||||
expect(movedFailure.message).toBe(`${denied}; warm_recovery_refused=journal_unsettled`);
|
||||
// A created or replacement sandbox holds no Runner to adopt. Live adoption
|
||||
// steps aside so ordinary admission can retire the finished owner, instead
|
||||
// of denying with prior_owner_terminal_state_indeterminate (Nov 10 staging).
|
||||
|
||||
@@ -123,6 +123,7 @@ export type NativeRestartRecoveryClaim =
|
||||
providerAttempt: number;
|
||||
restartKind: NativeRestartKind;
|
||||
recoveryRequestId: string | null;
|
||||
portablePreparationLeaseId?: string;
|
||||
/** False when the prior controller suspended this run in a clean drain. */
|
||||
chargesProviderAttempt?: boolean;
|
||||
};
|
||||
@@ -1546,6 +1547,12 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
const continuedSessionOnly = hasCheckpoint && checkpointIdentityMatches && providerEvents.length === 0
|
||||
&& !pendingInheritedRequests && checkpointRecord.activeTurnId == null && checkpointRecord.semanticResult == null
|
||||
&& checkpointRecord.terminal == null;
|
||||
const portablePreparation = pluginTask?.unlaunchedPortable === true && row.run.status === "running" &&
|
||||
row.coordinator.phase === "observed" && !durableAuthority && !row.run.sessionIdAfter &&
|
||||
row.run.runnerProfileJson?.nativePreparationFencingVersion === NATIVE_PREPARATION_FENCING_VERSION &&
|
||||
(hasCheckpoint ? admissionCheckpointOnly && providerEvents.length === 0 : !hasProviderEvidence) &&
|
||||
(!row.run.processPid && !row.run.processGroupId && !row.run.processStartedAt || await carriesInheritedRunnerIdentity(tx, row.run)) &&
|
||||
!(await hasNativeExecutionStartEvidence(tx, row.run));
|
||||
const remoteRunnerNeverLaunched = !unclaimedBootstrap && remoteWorkspace?.state === "prepared" && !pluginTask
|
||||
&& !durableAuthority && stagedAttachment === null
|
||||
&& row.run.runnerProfileJson?.nativePreparationFencingVersion === NATIVE_PREPARATION_FENCING_VERSION
|
||||
@@ -1672,11 +1679,11 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
: await restartResumeKeepsAttempt(tx, { runId: row.run.id, coordinator: row.coordinator });
|
||||
const resumeKeepsAttempt = restartCredit.keepsAttempt;
|
||||
const classification = classifyNativeRunnerRecoveryEvidence({
|
||||
remoteSandbox: remoteSandbox || Boolean(pluginTask && durableAuthority),
|
||||
unclaimedBootstrap,
|
||||
remoteSandbox: remoteSandbox || Boolean(pluginTask && durableAuthority) || portablePreparation,
|
||||
unclaimedBootstrap: unclaimedBootstrap || portablePreparation && row.coordinator.attempt === 0,
|
||||
remoteBootstrapProvenIncomplete: remoteBootstrapProvenIncomplete || remoteRunnerNeverLaunched
|
||||
|| remoteRunnerExitedBeforeProviderWork || remoteRunnerNeverReceivedCommands || remoteFollowUpNeverAttached,
|
||||
remoteBootstrapIncompleteReason: remoteRunnerNeverLaunched ? "remote_runner_never_launched"
|
||||
|| remoteRunnerExitedBeforeProviderWork || remoteRunnerNeverReceivedCommands || remoteFollowUpNeverAttached || portablePreparation,
|
||||
remoteBootstrapIncompleteReason: remoteRunnerNeverLaunched || portablePreparation ? "remote_runner_never_launched"
|
||||
: remoteRunnerExitedBeforeProviderWork ? "remote_runner_exited_before_provider_work"
|
||||
: remoteRunnerNeverReceivedCommands ? "remote_runner_never_received_commands"
|
||||
: remoteFollowUpNeverAttached ? "remote_follow_up_never_attached"
|
||||
@@ -1687,13 +1694,13 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
knownProviderProcessAlive: providerProcesses.livePids.length > 0,
|
||||
knownProviderProcessIdentityAmbiguous:
|
||||
providerProcesses.ambiguousLivePids.length > 0,
|
||||
hasCheckpoint: hasCheckpoint && !remoteRunnerNeverReceivedCommands && !(unclaimedBootstrap && inheritedCheckpointOnly)
|
||||
hasCheckpoint: hasCheckpoint && !portablePreparation && !remoteRunnerNeverReceivedCommands && !(unclaimedBootstrap && inheritedCheckpointOnly)
|
||||
&& !remoteRunnerNeverLaunched && !remoteFollowUpNeverAttached && !(remoteBootstrapProvenIncomplete && reboundSessionOnly),
|
||||
stagedAttachmentVerified: stagedAttachment !== null,
|
||||
checkpointIdentityMatches:
|
||||
checkpointIdentityMatches &&
|
||||
(!remoteSandbox || remoteWorkspace !== null),
|
||||
hasProviderEvidence: hasProviderEvidence && !(unclaimedBootstrap && inheritedCheckpointOnly),
|
||||
hasProviderEvidence: hasProviderEvidence && !portablePreparation && !(unclaimedBootstrap && inheritedCheckpointOnly),
|
||||
checkpointFailed:
|
||||
(checkpointRecord.terminal as Record<string, unknown> | undefined)
|
||||
?.runTerminalState === "failed" &&
|
||||
@@ -1893,7 +1900,7 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
leaseOwner,
|
||||
// Cleanup and earlier candidates can outlive the batch observation.
|
||||
// The owner row is locked: grant the full lease at this write.
|
||||
leaseExpiresAt: sql`clock_timestamp() + ${durableAuthority ? REMOTE_CONTROLLER_LEASE_MS : 20 * 60_000} * interval '1 millisecond'`,
|
||||
leaseExpiresAt: sql`clock_timestamp() + ${durableAuthority || portablePreparation ? REMOTE_CONTROLLER_LEASE_MS : 20 * 60_000} * interval '1 millisecond'`,
|
||||
controllerBootId: controller.bootId,
|
||||
controllerHostHash,
|
||||
controllerPid: controller.pid,
|
||||
@@ -1981,7 +1988,7 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
await restoreNativeSessionExecution(tx as unknown as Db, { issue, run: row.run, agentName: resumptionAgent.name, now });
|
||||
}
|
||||
|
||||
claimScope = { companyId: row.run.companyId, issueId: row.coordinator.issueId, controller, remote: Boolean(durableAuthority) };
|
||||
claimScope = { companyId: row.run.companyId, issueId: row.coordinator.issueId, controller, remote: Boolean(durableAuthority || portablePreparation) };
|
||||
const common = {
|
||||
runId: row.run.id,
|
||||
leaseOwner,
|
||||
@@ -2021,6 +2028,7 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
return {
|
||||
kind: claimKind,
|
||||
...common,
|
||||
...(claimKind === "bootstrap_incomplete" && portablePreparation && pluginTask ? { portablePreparationLeaseId: pluginTask.id } : {}),
|
||||
} satisfies NativeRestartRecoveryClaim;
|
||||
}).catch((error: unknown) => {
|
||||
// The whole candidate transaction rolled back, so this run's state is
|
||||
|
||||
@@ -3,6 +3,7 @@ import { environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } fro
|
||||
import { and, desc, eq, inArray, isNull, or, sql } from "drizzle-orm";
|
||||
import { remoteExecutionHasStopped } from "../remote-execution-termination.js";
|
||||
import { readSystemRecovery } from "../system-recovery-state.js";
|
||||
import { unlaunchedPortableTaskLease } from "../plugin-task-ownership.js";
|
||||
|
||||
type NativeRemoteExecutionScope = {
|
||||
run: Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "runnerProfileJson">;
|
||||
@@ -13,6 +14,7 @@ export async function readNativeRemoteExecutionOwnershipForRuns(db: Db, inputs:
|
||||
const key = (companyId: string, issueId: string, runId: string) => `${companyId}:${issueId}:${runId}`;
|
||||
const leases = inputs.length ? await db.select({ id: environmentLeases.id, companyId: environmentLeases.companyId,
|
||||
issueId: environmentLeases.issueId, runId: environmentLeases.heartbeatRunId,
|
||||
unlaunchedPortable: unlaunchedPortableTaskLease(),
|
||||
metadata: sql<Record<string, unknown>>`jsonb_build_object('runnerTaskStartup', ${environmentLeases.metadata}->'runnerTaskStartup')`,
|
||||
}).from(environmentLeases).where(and(
|
||||
or(...inputs.map(input => and(eq(environmentLeases.companyId, input.run.companyId),
|
||||
|
||||
@@ -9,8 +9,10 @@ import * as stagedAttachmentRecovery from "./native-staged-attachment-recovery.j
|
||||
import * as controllerRecovery from "./native-controller-recovery.js";
|
||||
import { isSettledRemoteWarmControlState } from "./remote-warm-session-recovery.js";
|
||||
import * as remoteWarmRecoveryRuntime from "./remote-warm-session-recovery.js";
|
||||
import * as pluginTaskOwnership from "../plugin-task-ownership.js";
|
||||
import { DurablePrpControlPlane } from "../../vendor/paperclip-runner/index.js";
|
||||
import * as environmentTaskRuntime from "../environment-task-runtime.js";
|
||||
import * as pluginCredentialWriteback from "../plugin-task-credential-writeback.js";
|
||||
import * as pluginTaskRuntime from "./plugin-runner-task.js";
|
||||
import * as completionFeedback from "./native-completion-feedback.js";
|
||||
import { environmentTaskOperationSchema } from "@paperclipai/plugin-sdk";
|
||||
@@ -19,7 +21,7 @@ import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@open
|
||||
import { configuredEnvironment, configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js";
|
||||
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import { createSystemRecovery, failSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure } from "../system-recovery-state.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { once } from "node:events";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import type { SQL } from "drizzle-orm";
|
||||
@@ -14176,15 +14178,20 @@ describe("native warm session supervision", () => {
|
||||
{ name: "rotated provider key", firstEnvironment: { OPENAI_API_KEY: "fixture-key" }, secondEnvironment: { OPENAI_API_KEY: "fixture-rotated-key" }, reuse: false },
|
||||
{ name: "rotated Claude token", firstEnvironment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-token" }, secondEnvironment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-rotated-token" }, reuse: false },
|
||||
{ name: "tool refresh", refreshTools: true, reuse: false },
|
||||
{ name: "unsupported tool refresh", refreshTools: true, unsupportedRefresh: true, reuse: false },
|
||||
{ name: "network access change", firstEnvironment: { PAPERCLIP_RUNNER_NETWORK_ACCESS: "disabled" }, secondEnvironment: { PAPERCLIP_RUNNER_NETWORK_ACCESS: "enabled" }, reuse: false },
|
||||
{ name: "run-scoped environment broker", firstEnvironment: { PAPERCLIP_GITHUB_BROKER_TOKEN: "first-run-capability" }, secondEnvironment: { PAPERCLIP_GITHUB_BROKER_TOKEN: "second-run-capability" }, reuse: false },
|
||||
{ name: "Core-hosted GitHub access", managedGitHub: true, reuse: true, adoptionReuse: false },
|
||||
] as Array<{ name: string; firstEnvironment?: Record<string, string>; secondEnvironment?: Record<string, string>;
|
||||
refreshTools?: boolean; managedGitHub?: boolean; reuse: boolean; adoptionReuse?: boolean }>)(
|
||||
refreshTools?: boolean; unsupportedRefresh?: boolean; managedGitHub?: boolean; reuse: boolean; adoptionReuse?: boolean }>)(
|
||||
"decides warm and adopted process reuse from one key: $name",
|
||||
async ({ name, firstEnvironment = {}, secondEnvironment = {}, refreshTools, managedGitHub = false, reuse, adoptionReuse = reuse }) => {
|
||||
async ({ name, firstEnvironment = {}, secondEnvironment = {}, refreshTools, unsupportedRefresh = false,
|
||||
managedGitHub = false, reuse, adoptionReuse = reuse }) => {
|
||||
const decisions: Record<string, boolean> = {};
|
||||
for (const path of ["warm", "adoption"] as const) {
|
||||
for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : [])] as const) {
|
||||
const portable = path === "portable" || path === "portable-bootstrap";
|
||||
const bootstrap = path === "portable-bootstrap";
|
||||
const pluginRecovery = portable || path === "legacy-plugin";
|
||||
githubAccess.create.mockReset().mockImplementation(async () => ({ env: {}, ready: true, duplexRequested: false,
|
||||
activate: githubAccess.activate.mockReset().mockImplementation(() => vi.fn()), stop: githubAccess.stop.mockReset().mockResolvedValue(undefined) }));
|
||||
const stateBase = await mkdtemp(join(tmpdir(), "paperclip-runnerd-reuse-key-"));
|
||||
@@ -14195,15 +14202,24 @@ describe("native warm session supervision", () => {
|
||||
const scope = `${path}-${name.replaceAll(" ", "-")}`;
|
||||
const first = {
|
||||
...execution,
|
||||
...(pluginRecovery ? { schema: "paperclip.native-execution-input.v5", executionMode: "default",
|
||||
provider: { ...execution.provider, approvalPolicy: "never" }, planningContext: null, runtimeContext: nativeRuntimeContextFixture() } as const : {}),
|
||||
binding: { ...execution.binding, runId: `run-reuse-key-first-${scope}`, executionWorkspaceId: "workspace-reuse-key" },
|
||||
workspace: { cwd: "/tmp/runnerd-reuse-key", repoUrl: null, repoRef: null, branchName: null },
|
||||
session: { normalizedSessionId: `session-reuse-key-${scope}`, driverKind: "codex_app_server" as const,
|
||||
protocolVersion: 1 as const, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const second = { ...first, binding: { ...first.binding, runId: `run-reuse-key-second-${scope}` } } as NativeExecutionInputV1;
|
||||
} as NativeExecutionInput;
|
||||
if (pluginRecovery) parseNativeExecutionInput(first);
|
||||
const second = { ...first, binding: { ...first.binding, runId: `run-reuse-key-second-${scope}` } };
|
||||
if ("runtimeContext" in second) {
|
||||
second.runtimeContext = structuredClone(second.runtimeContext);
|
||||
second.runtimeContext.mcp.digest = "1".repeat(64);
|
||||
second.runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(second.runtimeContext);
|
||||
}
|
||||
const target = { kind: "remote" as const, transport: "sandbox" as const, environmentId: "environment-reuse-key",
|
||||
remoteCwd: "/home/daytona/paperclip-workspace", runner: { execute: vi.fn() } } as never;
|
||||
remoteCwd: "/home/daytona/paperclip-workspace", runner: { execute: vi.fn() } };
|
||||
const firstSession = { close: vi.fn(async () => undefined) };
|
||||
const recoveredSession = { close: vi.fn(async () => undefined), snapshot: vi.fn() };
|
||||
const result = { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: "turn",
|
||||
normalizedSessionId: first.session.normalizedSessionId, providerSessionId: "provider-reuse-key", driverKind: "test",
|
||||
driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
@@ -14219,36 +14235,138 @@ describe("native warm session supervision", () => {
|
||||
return result;
|
||||
})
|
||||
.mockImplementationOnce(async (options) => {
|
||||
decisions[path] = options.existingSession === firstSession;
|
||||
decisions[path] = options.existingSession === (portable ? recoveredSession : firstSession);
|
||||
return result;
|
||||
});
|
||||
const inspected = vi.spyOn(remoteWarmRecoveryRuntime, "inspectRemoteWarmSessionRecovery").mockImplementation(async request => {
|
||||
decisions[path] = request.canReuseProcess(first);
|
||||
const reuseProcess = request.canReuseProcess(first);
|
||||
if (pluginRecovery) {
|
||||
expect(reuseProcess).toBe(false);
|
||||
expect(request.matchesExecution(first)).toBe(!unsupportedRefresh);
|
||||
if (unsupportedRefresh) throw new Error("fixture unsupported tool refresh refused");
|
||||
expect(request.matchesExecution({ ...first, provider: { ...first.provider, model: "another-model" } } as NativeExecutionInput)).toBe(false);
|
||||
if ("runtimeContext" in first) {
|
||||
const changed = structuredClone(first);
|
||||
changed.runtimeContext.instructions.bundle.digest = "2".repeat(64);
|
||||
changed.runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(changed.runtimeContext);
|
||||
expect(request.matchesExecution(changed)).toBe(false);
|
||||
}
|
||||
const checkpoint = request.loadCheckpoint(first);
|
||||
expect(checkpoint?.identity.runId).toBe(first.binding.runId);
|
||||
recoveredSession.snapshot.mockResolvedValue(checkpoint);
|
||||
return { identity: request.identity as Record<string, string>, checkpoint: checkpoint!,
|
||||
previousExecution: first, reuseProcess, ...(portable ? { portableSourceTaskId: "source-task" } : {}),
|
||||
remote: { providerLeaseId: "target-task", remoteCwd: target.remoteCwd }, revalidate: async () => {} };
|
||||
}
|
||||
decisions[path] = reuseProcess;
|
||||
throw new Error("fixture adoption decision recorded");
|
||||
});
|
||||
const ownership = portable
|
||||
? vi.spyOn(pluginTaskOwnership, "readyPortableTaskSource").mockImplementation(async (_db, _company, _lease, identity, scope) => {
|
||||
expect(scope?.accountIdentity).toBe("fixture-account");
|
||||
return { taskId: "source-task", identity: identity as NonNullable<Awaited<ReturnType<typeof pluginTaskOwnership.readyPortableTaskSource>>>["identity"] };
|
||||
}) : undefined;
|
||||
const projection = vi.spyOn(controllerRecovery, "resolveNativeControllerRecovery").mockResolvedValue({ kind: "no_prior_execution" });
|
||||
const restore = path === "legacy-plugin" ? vi.spyOn(runnerCheckpoint, "restoreNativeRunnerCheckpoint")
|
||||
.mockImplementation(async (_db, binding) => binding.runId === first.binding.runId && recoveredSession.close.mock.calls.length ? {} as never : null) : undefined;
|
||||
const issueProjection = path === "legacy-plugin" ? vi.spyOn(issueServiceModule, "issueService")
|
||||
.mockReturnValue({ update: vi.fn(async () => null) } as never) : undefined;
|
||||
try {
|
||||
await executePaperclipNativeSession({ db: leaseDb(first), execution: first, runnerInstanceId: "runner-reuse-key",
|
||||
useRunnerd: true, managedGitHub, runnerExecutionTarget: target,
|
||||
useRunnerd: true, managedGitHub, runnerExecutionTarget: target as never,
|
||||
...(portable ? { managedAiAccountIdentity: "fixture-account", managedAiCredentialIdentity: "old-revision" } : {}),
|
||||
runnerEnvironment: { PAPERCLIP_GITHUB_AUTH_MODE: "managed", ...firstEnvironment } });
|
||||
const durableRoot = (await readdir(stateBase, { withFileTypes: true }))
|
||||
.filter(entry => entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)).map(entry => join(stateBase, entry.name))[0]!;
|
||||
const durableIdentity = { runId: first.binding.runId, normalizedSessionId: first.session.normalizedSessionId,
|
||||
runnerInstanceId: "runner-reuse-key", environmentLeaseId: first.binding.executionWorkspaceId };
|
||||
runnerInstanceId: "runner-reuse-key", environmentLeaseId: first.binding.executionWorkspaceId,
|
||||
turnId: "prior-turn", itemId: "prior-item" };
|
||||
await mkdir(join(durableRoot, "control-plane"), { recursive: true });
|
||||
await writeFile(join(durableRoot, "control-plane", "control-plane-state.json"), JSON.stringify(durableControlPlaneState(durableIdentity)));
|
||||
await mkdir(join(durableRoot, "runner"), { recursive: true });
|
||||
await writeFile(join(durableRoot, "runner", "runner-state.json"), JSON.stringify(durableRunnerState(durableIdentity, "ready")));
|
||||
if (path === "adoption") expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] });
|
||||
if (path !== "warm") expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] });
|
||||
if (portable) {
|
||||
const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions");
|
||||
const path = join(directory, (await readdir(directory))[0]!);
|
||||
const { snapshot, configDigest, processConfigDigest } = JSON.parse(await readFile(path, "utf8"));
|
||||
await rm(path);
|
||||
await rm(durableRoot, { recursive: true });
|
||||
projection.mockResolvedValueOnce({
|
||||
kind: "recoverable", snapshot,
|
||||
metadata: controllerRecovery.createNativeControllerRecovery(snapshot, { configDigest, processConfigDigest }, null),
|
||||
checkpoint: { restoreSessionDirectory(root: string) {
|
||||
mkdirSync(join(root, "control-plane"), { recursive: true });
|
||||
writeFileSync(join(root, "control-plane/control-plane-state.json"), JSON.stringify(durableControlPlaneState(durableIdentity)));
|
||||
} } as never,
|
||||
});
|
||||
}
|
||||
if (pluginRecovery) state.createBackend.mockReturnValueOnce({
|
||||
kind: "test", recoverSession: async () => ({ recovered: true, session: recoveredSession }),
|
||||
} as never);
|
||||
const pluginTaskDescription = { kind: "description", taskId: "target-task", warmTaskVersion: 1,
|
||||
launchPreparationVersion: 1, projectAuthCheckVersion: 1, releaseResumeVersion: 1,
|
||||
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } } as const;
|
||||
const portableTarget = { ...target, runner: undefined, leaseId: "target-lease",
|
||||
sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" ? "resumed" : "created", providerLeaseId: "target-task" },
|
||||
runnerTask: vi.fn(async (operation: { kind: string }) => {
|
||||
if (path === "legacy-plugin") {
|
||||
expect(recoveredSession.close).toHaveBeenCalledOnce();
|
||||
expect(operation.kind).toBe("describe");
|
||||
throw new Error("fixture replacement inspection reached");
|
||||
}
|
||||
return pluginTaskDescription;
|
||||
}),
|
||||
};
|
||||
if (pluginRecovery) await writeFile(join(stateBase, "auth.json"),
|
||||
JSON.stringify({ OPENAI_API_KEY: "synthetic-fixture" }), { mode: 0o600 });
|
||||
const leaseOwner = bootstrap ? "bootstrap-recovery-owner" : undefined;
|
||||
const controller = bootstrap ? await import("./native-restart-recovery.js").then(module => module.currentNativeControllerIdentity()) : undefined;
|
||||
const db = leaseDb(second, controller ? { leaseOwner, controllerBootId: controller.bootId,
|
||||
controllerPid: controller.pid, controllerGeneration: 1, leaseExpiresAt: new Date(Date.now() + 60_000) } : {});
|
||||
const select = db.select.bind(db);
|
||||
db.select = ((fields?: Record<string, unknown>) => {
|
||||
if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) {
|
||||
return { from: () => ({ where: () => ({ limit: async () =>
|
||||
[{ status: "succeeded", runnerProfileJson: { nativeExecutionInput: first } }] }) }) };
|
||||
}
|
||||
if (pluginRecovery && fields?.metadata === environmentLeases.metadata) {
|
||||
return { from: () => ({ where: async () => [{ providerLeaseId: pluginTaskDescription.taskId, unlaunchedPortable: bootstrap,
|
||||
metadata: ownership ? { portableTaskPreviousLeaseId: "source-lease", portableTaskOwnershipReady: true } : {} }] }) };
|
||||
}
|
||||
return select(fields as never);
|
||||
}) as Db["select"];
|
||||
const continuation = executePaperclipNativeSession({
|
||||
db: { ...leaseDb(second), select: () => ({ from: () => ({ where: () => ({ limit: () =>
|
||||
Promise.resolve([{ status: "succeeded", runnerProfileJson: { nativeExecutionInput: first } }]) }) }) }) } as unknown as Db,
|
||||
execution: second, runnerInstanceId: "runner-reuse-key", useRunnerd: true, managedGitHub, refreshTools,
|
||||
runnerExecutionTarget: target, runnerEnvironment: { PAPERCLIP_GITHUB_AUTH_MODE: "managed", ...secondEnvironment } });
|
||||
db, execution: second, runnerInstanceId: "runner-reuse-key", useRunnerd: true, managedGitHub, refreshTools, toolRefreshOnResume: !unsupportedRefresh,
|
||||
runnerExecutionTarget: (pluginRecovery ? portableTarget : target) as never,
|
||||
...(leaseOwner ? { leaseOwner, restartRecovery: { kind: "bootstrap_incomplete" as const, runId: second.binding.runId,
|
||||
leaseOwner, controllerGeneration: 1, providerAttempt: 0, restartKind: "hard" as const, recoveryRequestId: null,
|
||||
portablePreparationLeaseId: portableTarget.leaseId } } : {}),
|
||||
...(pluginRecovery ? { pluginTaskDescription, runnerIngressAuthorized: true, managedAiCredentialHome: stateBase,
|
||||
managedAiAccountIdentity: "fixture-account", managedAiCredentialIdentity: "current-revision" } : {}),
|
||||
runnerEnvironment: { PAPERCLIP_GITHUB_AUTH_MODE: "managed", ...secondEnvironment } });
|
||||
if (pluginRecovery && unsupportedRefresh) {
|
||||
await expect(continuation).rejects.toThrow("fixture unsupported tool refresh refused");
|
||||
continue;
|
||||
}
|
||||
if (path === "legacy-plugin") {
|
||||
await expect(continuation).rejects.toThrow("fixture replacement inspection reached");
|
||||
expect(portableTarget.runnerTask).toHaveBeenCalledOnce();
|
||||
continue;
|
||||
}
|
||||
if (path === "adoption") await expect(continuation).rejects.toThrow("fixture adoption decision recorded");
|
||||
else await continuation;
|
||||
expect(decisions[path]).toBe(path === "adoption" ? adoptionReuse : reuse);
|
||||
expect(decisions[path]).toBe(portable ? true : path === "adoption" ? adoptionReuse : reuse);
|
||||
if (portable) {
|
||||
expect(portableTarget.runnerTask).not.toHaveBeenCalled();
|
||||
expect(recoveredSession.close).not.toHaveBeenCalled();
|
||||
}
|
||||
if (path === "warm") expect(firstSession.close).toHaveBeenCalledTimes(reuse ? 0 : 1);
|
||||
} finally {
|
||||
projection.mockRestore();
|
||||
restore?.mockRestore();
|
||||
issueProjection?.mockRestore();
|
||||
ownership?.mockRestore();
|
||||
inspected.mockRestore();
|
||||
await closeIdleWarmNativeSessionsForRestart();
|
||||
if (previousStateDirectory === undefined) delete process.env.PAPERCLIP_RUNNER_STATE_DIR;
|
||||
@@ -14258,7 +14376,7 @@ describe("native warm session supervision", () => {
|
||||
await rm(stateBase, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
expect(decisions).toEqual({ warm: reuse, adoption: adoptionReuse });
|
||||
expect(decisions).toEqual({ warm: reuse, adoption: adoptionReuse, ...(refreshTools && !unsupportedRefresh ? { portable: true, "portable-bootstrap": true } : {}) });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -17963,8 +18081,9 @@ describe("runnerd provider runtime wiring", () => {
|
||||
} finally { resume.mockRestore(); }
|
||||
});
|
||||
|
||||
it.each(["verified", "wrong-state", "wrong-lease"] as const)("reattaches a surviving plugin task through its owner: %s", async mode => {
|
||||
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";
|
||||
const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!,
|
||||
runnerInstanceId: "plugin-runner", environmentLeaseId: "same-task-lease", turnId: "admitted-turn", itemId: "admitted-item" };
|
||||
const root = await initializeScopedRunnerRoot(current, identity.runnerInstanceId);
|
||||
@@ -17980,24 +18099,35 @@ describe("runnerd provider runtime wiring", () => {
|
||||
runner: { version: "new-artifact", digest: `sha256:${"b".repeat(64)}` } };
|
||||
});
|
||||
state.createBackend.mockClear(); state.createTransport.mockClear();
|
||||
const backend = createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: identity.runnerInstanceId,
|
||||
runnerIngressAuthorized: true, runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: ".",
|
||||
leaseId: mode === "wrong-lease" ? "replacement-task" : identity.environmentLeaseId, runnerTask: task },
|
||||
controllerPersistence: { bootId: "successor", runnerArtifact: { version: "admitted-artifact", digest: `sha256:${"a".repeat(64)}` } },
|
||||
restartRecovery: { kind: "reattach_remote_runner", runId: current.binding.runId, leaseOwner: "controller", controllerGeneration: 2,
|
||||
providerAttempt: 1, restartKind: "hard", recoveryRequestId: null, remote: { kind: "plugin_task", leaseId: identity.environmentLeaseId } } });
|
||||
if (mode !== "verified") {
|
||||
await expect(backend).rejects.toThrow(mode === "wrong-state" ? "adoption identity mismatch" : "recovery_lease_mismatch");
|
||||
expect(state.createBackend).not.toHaveBeenCalled();
|
||||
return;
|
||||
}
|
||||
await backend;
|
||||
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
|
||||
const options = state.createTransport.mock.calls.at(-1)![0];
|
||||
expect(options).toMatchObject({ prpIdentity: identity, adoptExistingRunner: { pid: null, startedAt: null },
|
||||
runnerArtifact: { version: "admitted-artifact" } });
|
||||
expect(options).toMatchObject({ runnerReconnectGraceMs: 420_000 });
|
||||
expect(task.mock.calls.some(([op]) => ["prepare", "submit", "stop"].includes(op.kind))).toBe(false);
|
||||
const portable = moved ? vi.spyOn(pluginTaskOwnership, "assertAttachedPortableTask")
|
||||
.mockImplementation(async () => {
|
||||
if (mode === "wrong-claim") throw new Error("native_portable_task_ownership_unverified");
|
||||
}) : undefined;
|
||||
const leaseId = moved ? "moved-task-lease" : identity.environmentLeaseId;
|
||||
try {
|
||||
const backend = createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: identity.runnerInstanceId,
|
||||
runnerIngressAuthorized: true, runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: ".",
|
||||
leaseId: mode === "wrong-lease" ? "replacement-task" : leaseId, runnerTask: task,
|
||||
...(moved ? { sandboxLeaseAcquisition: { outcome: "resumed" as const, providerLeaseId: "same-task" } } : {}) },
|
||||
controllerPersistence: { bootId: "successor", runnerArtifact: { version: "admitted-artifact", digest: `sha256:${"a".repeat(64)}` } },
|
||||
restartRecovery: { kind: "reattach_remote_runner", runId: current.binding.runId, leaseOwner: "controller", controllerGeneration: 2,
|
||||
providerAttempt: 1, restartKind: "hard", recoveryRequestId: null, remote: { kind: "plugin_task", leaseId } } });
|
||||
if (mode !== "verified" && mode !== "portable") {
|
||||
await expect(backend).rejects.toThrow(mode === "wrong-state" ? "adoption identity mismatch" : mode === "wrong-claim" ? "ownership_unverified" : "recovery_lease_mismatch");
|
||||
expect(state.createBackend).not.toHaveBeenCalled();
|
||||
return;
|
||||
}
|
||||
await backend;
|
||||
if (moved) expect(portable).toHaveBeenCalledWith(expect.anything(), {
|
||||
companyId: current.binding.companyId, leaseId, taskId: "same-task", runId: current.binding.runId, identity,
|
||||
});
|
||||
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
|
||||
const options = state.createTransport.mock.calls.at(-1)![0];
|
||||
expect(options).toMatchObject({ prpIdentity: identity, adoptExistingRunner: { pid: null, startedAt: null },
|
||||
runnerArtifact: { version: "admitted-artifact" } });
|
||||
expect(options).toMatchObject({ runnerReconnectGraceMs: 420_000 });
|
||||
expect(task.mock.calls.some(([op]) => ["prepare", "submit", "stop"].includes(op.kind))).toBe(false);
|
||||
} finally { portable?.mockRestore(); }
|
||||
});
|
||||
|
||||
it.each(["codex", "acpx-codex", "grok"] as const)("writes managed %s events through the current warm exporter without per-turn reads", async provider => {
|
||||
@@ -18175,8 +18305,11 @@ describe("runnerd provider runtime wiring", () => {
|
||||
} finally {owner.mockRestore();await rm(home,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
it.each((["codex", "claude"] as const).flatMap(provider => [true, false].map(reuseProcess => [provider, reuseProcess] as const)))("reconnects task-only %s warm recovery under the saved identity before reuse or retirement: %s", async (provider, reuseProcess) => {
|
||||
const current=scopedNativeExecution(`plugin-restart-${provider}-${reuseProcess}`);
|
||||
it.each([
|
||||
...(["codex", "claude"] as const).flatMap(provider => [true, false].map(reuseProcess => [provider, reuseProcess, false] as const)),
|
||||
["codex", true, true] as const,
|
||||
])("reconnects task-only %s warm recovery under the saved identity before reuse or retirement: %s (portable=%s)", async (provider, reuseProcess, portable) => {
|
||||
const current=scopedNativeExecution(`plugin-restart-${provider}-${reuseProcess}-${portable}`);
|
||||
if(provider === "claude") current.provider={kind:"acpx",agent:"claude",model:"fixture",permissionMode:"deny-all"} as never;
|
||||
current.session.lifecyclePolicy={mode:"warm",idleTimeoutMs:300000};
|
||||
const identity={runnerInstanceId:"old-runner",environmentLeaseId:"old-lease",runId:"old-run",
|
||||
@@ -18184,22 +18317,29 @@ describe("runnerd provider runtime wiring", () => {
|
||||
const home=await mkdtemp(join(tmpdir(),"plugin-restart-account-"));
|
||||
await writeFile(join(home,"auth.json"),JSON.stringify({OPENAI_API_KEY:"synthetic-fixture"}),{mode:0o600});
|
||||
const owner=vi.spyOn(pluginTaskRuntime,"createPluginRunnerTaskOwner");
|
||||
const register = vi.spyOn(pluginCredentialWriteback, "registerPluginTaskCredentialHandoff").mockResolvedValue(undefined);
|
||||
const binding = { grantId: randomUUID(), secretId: randomUUID(), sessionEpoch: 1, versionSelector: "latest" as const };
|
||||
const task=vi.fn(async()=>({kind:"description",taskId:"saved-task",launchPreparationVersion:1,projectAuthCheckVersion:1,
|
||||
warmTaskVersion:1,runner:{version:"fixture",digest:`sha256:${"a".repeat(64)}`}}));
|
||||
state.createBackend.mockClear();state.createTransport.mockClear();
|
||||
try {
|
||||
await createRunnerdBackend({db:leaseDb(current),execution:current,runnerInstanceId:"new-runner",runnerIngressAuthorized:true,
|
||||
runnerEnvironment:{ANTHROPIC_API_KEY:"synthetic-fixture"},managedAiCredentialHome:home,managedAiCredentialIdentity:reuseProcess ? "old-revision" : "new-revision",managedAiAccountIdentity:"account",
|
||||
managedAiCredentialWriteback:{} as never,
|
||||
managedAiCredentialWriteback: binding,
|
||||
remoteWarmRecovery:{identity,reuseProcess,previousExecution:current,checkpoint:{} as never,
|
||||
remote:{providerLeaseId:"saved-task",remoteCwd:"."},revalidate:async()=>{}},
|
||||
remote:{providerLeaseId:"saved-task",remoteCwd:"."},revalidate:async()=>{},
|
||||
...(portable ? { portableSourceTaskId: "old-task" } : {})},
|
||||
runnerExecutionTarget:{kind:"remote",transport:"sandbox",leaseId:"new-lease",remoteCwd:".",runnerTask:task,
|
||||
sandboxLeaseAcquisition:{outcome:"resumed",providerLeaseId:"saved-task"}}});
|
||||
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
|
||||
expect(state.createTransport.mock.calls.at(-1)![0].prpIdentity).toEqual(identity);
|
||||
expect(owner.mock.calls.at(-1)![0].adoptIdentity).toEqual(identity);
|
||||
expect(task.mock.calls).toEqual([[{kind:"describe"}]]);
|
||||
} finally {owner.mockRestore();await rm(home,{recursive:true,force:true});}
|
||||
if (portable) expect(register).toHaveBeenCalledExactlyOnceWith(expect.anything(), {
|
||||
companyId: current.binding.companyId, leaseId: "new-lease",
|
||||
}, "account", binding);
|
||||
else expect(register).not.toHaveBeenCalled();
|
||||
} finally {register.mockRestore(); owner.mockRestore();await rm(home,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
it.each((["codex", "claude"] as const).flatMap(provider => [
|
||||
|
||||
@@ -54,7 +54,8 @@ import { writeExecutionControl } from "../execution-control-notifications.js";
|
||||
import { notifyExecutionRunWork } from "../execution-control-notifications.js";
|
||||
import { createRunUsageRecorder } from "../usage-receipts.js";
|
||||
import { syncPluginTaskCredentialHandoff, registerPluginTaskCredentialHandoff } from "../plugin-task-credential-writeback.js";
|
||||
import { resolvePluginTaskResume } from "../environment-task-runtime.js";
|
||||
import { resolvePluginTaskResume, type PluginTaskDescription } from "../environment-task-runtime.js";
|
||||
import { assertAttachedPortableTask, readyPortableTaskSource, unlaunchedPortableTaskLease } from "../plugin-task-ownership.js";
|
||||
import { environmentTaskOperationSchema, environmentTaskResultSchema } from "@paperclipai/plugin-sdk";
|
||||
import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js";
|
||||
import { createPluginRunnerTaskOwner, verifyPluginRunnerTaskReattachment } from "./plugin-runner-task.js";
|
||||
@@ -278,7 +279,7 @@ import {
|
||||
renderNativeRunnerStagedAttachmentPrompt,
|
||||
stageNativeRunnerWakeAttachments,
|
||||
} from "./native-runner-file-handoff.js";
|
||||
import { NATIVE_PROVIDER_SIDE_EFFECT_PENDING, NATIVE_PROVIDER_STATE_INCOMPATIBLE, nativeRuntimeContractForProvider, nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
|
||||
import { NATIVE_PROVIDER_SIDE_EFFECT_PENDING, NATIVE_PROVIDER_STATE_INCOMPATIBLE, nativeRuntimeContextsMatch, nativeRuntimeContractForProvider, nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
|
||||
import { clearRunProviderStateUnsaved, markAcceptedRunProviderStateUnsaved } from "./native-provider-state-unsaved.js";
|
||||
import { verifyRetainedMaintenanceNoLaunch } from "./native-maintenance-no-launch.js";
|
||||
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
|
||||
@@ -6247,6 +6248,29 @@ async function recordPriorOwnerFenceRefusal(input: { db: Db; execution: NativeEx
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function assertPluginTaskReattachmentBinding(input: {
|
||||
db: Db;
|
||||
execution: NativeExecutionInput;
|
||||
restartRecovery?: NativeRestartRecoveryClaim;
|
||||
}, target: Extract<AdapterExecutionTarget, { kind: "remote" }>, identity: Record<string, unknown> | null | undefined) {
|
||||
const claim = input.restartRecovery;
|
||||
const leaseId = target.leaseId;
|
||||
if (claim?.kind !== "reattach_remote_runner" || claim.remote.kind !== "plugin_task" ||
|
||||
claim.runId !== input.execution.binding.runId || !leaseId || claim.remote.leaseId !== leaseId ||
|
||||
!identity || !durableIdentityMatchesExecution(identity, input.execution) ||
|
||||
typeof identity.turnId !== "string" || !identity.turnId || typeof identity.itemId !== "string" || !identity.itemId) {
|
||||
throw new Error("native_plugin_recovery_lease_mismatch");
|
||||
}
|
||||
const taskId = target.transport === "sandbox" ? target.sandboxLeaseAcquisition?.providerLeaseId : undefined;
|
||||
if (identity.environmentLeaseId !== leaseId) {
|
||||
if (!taskId) throw new Error("native_plugin_recovery_lease_mismatch");
|
||||
await assertAttachedPortableTask(input.db, {
|
||||
companyId: input.execution.binding.companyId, leaseId, taskId, runId: claim.runId, identity,
|
||||
});
|
||||
}
|
||||
return taskId;
|
||||
}
|
||||
|
||||
async function migrateRunnerdStateRootForExecution(input: {
|
||||
db: Db;
|
||||
execution: NativeExecutionInput;
|
||||
@@ -6370,12 +6394,12 @@ async function migrateRunnerdStateRootForExecution(input: {
|
||||
if (input.restartRecovery?.kind === "reattach_remote_runner") {
|
||||
if (input.restartRecovery.remote.kind === "plugin_task") {
|
||||
const target = input.runnerExecutionTarget;
|
||||
if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|
||||
|| target.leaseId !== input.restartRecovery.remote.leaseId || identity.environmentLeaseId !== target.leaseId
|
||||
|| !durableIdentityMatchesExecution(identity, input.execution)) {
|
||||
if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask) {
|
||||
throw new Error("native_plugin_recovery_lease_mismatch");
|
||||
}
|
||||
await verifyPluginRunnerTaskReattachment(target.runnerTask, identity);
|
||||
const taskId = await assertPluginTaskReattachmentBinding(input, target, identity);
|
||||
await verifyPluginRunnerTaskReattachment(operation => target.runnerTask!(operation,
|
||||
taskId ? { expectedTaskId: taskId } : undefined), identity);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -7281,6 +7305,19 @@ function nativeSessionConfigDigest(
|
||||
.digest("hex")}`;
|
||||
}
|
||||
|
||||
function matchesRemoteWarmExecution(
|
||||
previous: NativeExecutionInput,
|
||||
current: NativeExecutionInput,
|
||||
toolRefreshOnResume?: boolean,
|
||||
): boolean {
|
||||
if (nativeSessionScopeKey(previous) !== nativeSessionScopeKey(current)) return false;
|
||||
const currentDigest = nativeSessionConfigDigest(current, "remote");
|
||||
if (nativeSessionConfigDigest(previous, "remote") === currentDigest) return true;
|
||||
return toolRefreshOnResume === true && "runtimeContext" in previous && "runtimeContext" in current &&
|
||||
nativeRuntimeContextsMatch(previous.runtimeContext, current.runtimeContext, toolRefreshOnResume) &&
|
||||
nativeSessionConfigDigest({ ...previous, runtimeContext: current.runtimeContext }, "remote") === currentDigest;
|
||||
}
|
||||
|
||||
export function nativeControllerMigrationDescriptor(execution: NativeExecutionInput, recordedToolContractFingerprint: unknown) {
|
||||
if (typeof recordedToolContractFingerprint !== "string" || !/^sha256:[a-f0-9]{64}$/.test(recordedToolContractFingerprint)) {
|
||||
throw new Error("native_controller_migration_tool_contract_missing");
|
||||
@@ -10203,6 +10240,7 @@ export async function executePaperclipNativeSession(input: {
|
||||
getFreshSessionHandoff?: () => Promise<string | null>;
|
||||
/** Retire a retained transport so recovery can replace provider tool declarations. */
|
||||
refreshTools?: boolean;
|
||||
toolRefreshOnResume?: boolean;
|
||||
db: Db;
|
||||
execution: NativeExecutionInput;
|
||||
/** Private server preparation proof; never persisted or accepted from a tool. */
|
||||
@@ -10259,6 +10297,7 @@ export async function executePaperclipNativeSession(input: {
|
||||
managedAiCredentialWriteback?: ManagedAiCredentialWritebackBinding;
|
||||
billingIdentity?: Pick<AdapterExecutionResult, "provider" | "biller" | "billingType">;
|
||||
onTaskDispatched?: () => Promise<void> | void;
|
||||
pluginTaskDescription?: PluginTaskDescription;
|
||||
runnerExecutionTarget?: AdapterExecutionTarget | null;
|
||||
/** Resolved per-run authorization; not an independent instance setting. */
|
||||
runnerIngressAuthorized?: boolean;
|
||||
@@ -10657,7 +10696,22 @@ async function executePaperclipNativeSessionAttempt(
|
||||
const stagedRestart = input.restartRecovery?.kind === "reattach_remote_runner"
|
||||
? await verifyStagedAttachmentRestart(input) : null;
|
||||
const timeController = createRunPreparationTiming(input.execution.binding.runId, "native.controller");
|
||||
if (input.useRunnerd) await timeController("warm_restore", () => restoreWarmRunnerdController(input));
|
||||
const target = input.runnerExecutionTarget;
|
||||
const portableTarget = target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask ? target : undefined;
|
||||
const companyId = input.execution.binding.companyId;
|
||||
const portablePreparationLeaseId = input.restartRecovery?.kind === "bootstrap_incomplete"
|
||||
? input.restartRecovery.portablePreparationLeaseId : undefined;
|
||||
const targetLease = portableTarget?.leaseId ? (await input.db.select({
|
||||
metadata: environmentLeases.metadata, providerLeaseId: environmentLeases.providerLeaseId,
|
||||
...(portablePreparationLeaseId ? { unlaunchedPortable: unlaunchedPortableTaskLease() } : {}),
|
||||
}).from(environmentLeases).where(and(eq(environmentLeases.companyId, companyId), eq(environmentLeases.id, portableTarget.leaseId))))[0] : undefined;
|
||||
if (portablePreparationLeaseId && (portableTarget?.leaseId !== portablePreparationLeaseId || targetLease?.unlaunchedPortable !== true)) {
|
||||
throw remoteRecoveryLeaseMismatch("runner_verification", "plugin_task");
|
||||
}
|
||||
const replayPortablePreparation = portablePreparationLeaseId !== undefined;
|
||||
const canRecoverWarmOwner = !input.restartRecovery || replayPortablePreparation;
|
||||
if (input.useRunnerd) await timeController("warm_restore", () => restoreWarmRunnerdController(
|
||||
replayPortablePreparation ? { ...input, restartRecovery: undefined } : input));
|
||||
const identityRedactor = createAgentIdentityRedactor(input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY);
|
||||
const redactIdentityText = (text: string) => redactSensitiveText(
|
||||
identityRedactor.chunk("diagnostic", text) + identityRedactor.finish("diagnostic"),
|
||||
@@ -10757,29 +10811,51 @@ async function executePaperclipNativeSessionAttempt(
|
||||
});
|
||||
let retainedTransition: VerifiedWarmTransitionBinding | undefined;
|
||||
let remoteWarmRecovery: RemoteWarmSessionRecovery | undefined;
|
||||
let pluginTaskDescription: Extract<ReturnType<typeof environmentTaskResultSchema.parse>,{kind:"description"}> | undefined;
|
||||
let pluginTaskDescription: PluginTaskDescription | undefined;
|
||||
let portableSource: Awaited<ReturnType<typeof readyPortableTaskSource>>;
|
||||
if (portableTarget?.runnerTask && portableTarget.leaseId) {
|
||||
if (input.pluginTaskDescription && input.pluginTaskDescription.taskId === targetLease?.providerLeaseId) {
|
||||
pluginTaskDescription = input.pluginTaskDescription;
|
||||
}
|
||||
if (targetLease?.metadata?.portableTaskPreviousLeaseId || targetLease?.metadata?.portableTaskPredecessor) {
|
||||
const description = targetLease.metadata.portableTaskOwnershipReady === true && pluginTaskDescription
|
||||
? pluginTaskDescription : environmentTaskResultSchema.parse(await portableTarget.runnerTask({ kind: "describe" }));
|
||||
if (description.kind !== "description") throw new Error("Plugin Runner description unavailable");
|
||||
pluginTaskDescription = description;
|
||||
portableSource = await readyPortableTaskSource(input.db, companyId, portableTarget.leaseId,
|
||||
readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution)), {
|
||||
attachedRunId: input.execution.binding.runId,
|
||||
selectedSessionId: nativeSessionKey(input.execution),
|
||||
accountIdentity: input.managedAiAccountIdentity ?? input.managedAiCredentialIdentity,
|
||||
});
|
||||
}
|
||||
}
|
||||
const cachedReleasedOwner = warmNativeSessions.get(nativeSessionScopeKey(input.execution));
|
||||
if (cachedReleasedOwner?.released) {
|
||||
const proof = releasedWarmRunner(readWarmNativeEnvelope(input.execution));
|
||||
const proof = portableSource ? undefined : releasedWarmRunner(readWarmNativeEnvelope(input.execution));
|
||||
const identity = readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution));
|
||||
const target = input.runnerExecutionTarget;
|
||||
if (proof && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId
|
||||
&& target.sandboxLeaseAcquisition?.outcome === "created" && proof.taskId !== target.sandboxLeaseAcquisition.providerLeaseId) {
|
||||
const source = portableSource ?? (proof && { taskId: proof.taskId, identity: proof.source });
|
||||
if (source && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId
|
||||
&& (portableSource || target.sandboxLeaseAcquisition?.outcome === "created")
|
||||
&& source.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
|
||||
const ownInstructionPreparation = cachedReleasedOwner.instructionPreparationRunId === input.execution.binding.runId
|
||||
&& input.instructionWorkingCopy?.runId === input.execution.binding.runId;
|
||||
if ((cachedReleasedOwner.busy && !ownInstructionPreparation)
|
||||
|| cachedReleasedOwner.preparingRunId && cachedReleasedOwner.preparingRunId !== input.execution.binding.runId
|
||||
|| cachedReleasedOwner.instructionPreparationRunId && !ownInstructionPreparation
|
||||
|| cachedReleasedOwner.closeOnReleaseReason) throw new Error("native_session_supervisor_busy");
|
||||
if (proof.taskId !== cachedReleasedOwner.pluginTaskId || proof.scopeDigest !== releasedWarmScope(input)
|
||||
|| canonicalJson(proof.source) !== canonicalJson(identity)) throw new Error("native_session_released_owner_scope_mismatch");
|
||||
if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId ||
|
||||
(proof && (proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)))) {
|
||||
throw new Error("native_session_released_owner_scope_mismatch");
|
||||
}
|
||||
const wasBusy = cachedReleasedOwner.busy;
|
||||
cachedReleasedOwner.busy = true;
|
||||
try {
|
||||
// Only physical stop releases the cached controller; ordinary checkpoint admission still proves continuation.
|
||||
const resumeFrom = await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
|
||||
leaseId: target.leaseId, priorIdentity: proof.source, inspectCheckpoint: true });
|
||||
if (resumeFrom !== proof.taskId) throw new Error("native_session_released_owner_scope_mismatch");
|
||||
// Ordinary replacement still needs a stop receipt for the old task.
|
||||
const resumeFrom = portableSource?.taskId ?? await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
|
||||
leaseId: target.leaseId, priorIdentity: source.identity, inspectCheckpoint: true });
|
||||
if (resumeFrom !== source.taskId) throw new Error("native_session_released_owner_scope_mismatch");
|
||||
try {
|
||||
await detachReleasedWarmNativeSession(cachedReleasedOwner);
|
||||
} catch (error) {
|
||||
@@ -10790,7 +10866,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
} finally { cachedReleasedOwner.busy = wasBusy; }
|
||||
} else requireReleasedWarmScope(input, proof, identity);
|
||||
}
|
||||
if (input.useRunnerd && !input.restartRecovery && !input.backend &&
|
||||
if (input.useRunnerd && canRecoverWarmOwner && !input.backend &&
|
||||
input.runnerExecutionTarget?.kind === "remote" &&
|
||||
input.execution.session.lifecyclePolicy.mode === "warm" &&
|
||||
!idleWarmNativeSessionOwnerRunId(input)) {
|
||||
@@ -10800,10 +10876,12 @@ async function executePaperclipNativeSessionAttempt(
|
||||
if (taskTarget.transport === "sandbox" && taskTarget.runnerTask && taskTarget.leaseId &&
|
||||
durableIdentityMatchesSession(identity,input.execution) && identity.runId !== input.execution.binding.runId) {
|
||||
// Inspection can replace a stopped retained task before deciding between adoption and checkpoint recovery.
|
||||
const description = environmentTaskResultSchema.parse(await taskTarget.runnerTask({kind:"describe"}));
|
||||
if (description.kind !== "description") throw new Error("Plugin Runner description unavailable");
|
||||
pluginTaskDescription = description;
|
||||
if (taskTarget.sandboxLeaseAcquisition?.outcome !== "resumed") {
|
||||
if (!pluginTaskDescription || pluginTaskDescription.taskId !== taskTarget.sandboxLeaseAcquisition?.providerLeaseId) {
|
||||
const description = environmentTaskResultSchema.parse(await taskTarget.runnerTask({ kind: "describe" }));
|
||||
if (description.kind !== "description") throw new Error("Plugin Runner description unavailable");
|
||||
pluginTaskDescription = description;
|
||||
}
|
||||
if (taskTarget.sandboxLeaseAcquisition?.outcome !== "resumed" && !portableSource) {
|
||||
await recoverPluginRunnerCheckpoint(input, root);
|
||||
}
|
||||
}
|
||||
@@ -10817,22 +10895,23 @@ async function executePaperclipNativeSessionAttempt(
|
||||
}
|
||||
if (durableIdentityMatchesSession(identity, input.execution) && identity.runId !== input.execution.binding.runId &&
|
||||
runnerdAuthorityLifecycleWithVerifiedBackup({ root, identity, execution: input.execution, allowVerifiedBackup: true }) !== "suspended") {
|
||||
let releasedSource: DurableRecoveryIdentity | undefined;
|
||||
let releasedSource = portableSource?.identity;
|
||||
remoteWarmRecovery = await inspectRemoteWarmSessionRecovery({
|
||||
db: input.db, execution: input.execution, target: input.runnerExecutionTarget, identity,
|
||||
portableSourceTaskId: portableSource?.taskId,
|
||||
readControlState: () => record(JSON.parse(readBoundedNativeFile(
|
||||
resolve(root, "control-plane", "control-plane-state.json"), NATIVE_CONTROL_PLANE_STATE_MAX_BYTES,
|
||||
"runner_durable_identity_too_large").toString("utf8"))),
|
||||
matchesExecution: previous => nativeSessionScopeKey(previous) === nativeSessionScopeKey(input.execution) &&
|
||||
nativeSessionConfigDigest(previous, "remote") === nativeSessionConfigDigest(input.execution, "remote"),
|
||||
matchesExecution: previous => matchesRemoteWarmExecution(previous, input.execution, input.toolRefreshOnResume),
|
||||
loadCheckpoint: previous => {
|
||||
const proof = releasedWarmRunner(readWarmNativeEnvelope(previous));
|
||||
if (proof) {
|
||||
releasedSource = requireReleasedWarmScope(input, proof, identity);
|
||||
if (!portableSource) {
|
||||
const proof = releasedWarmRunner(readWarmNativeEnvelope(previous));
|
||||
if (proof) releasedSource = requireReleasedWarmScope(input, proof, identity);
|
||||
}
|
||||
return loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote");
|
||||
},
|
||||
canReuseProcess: previous => !needsCoreGitHubAccess(input) && canReuseNativeProcess(input,
|
||||
canReuseProcess: previous => !portableSource && !needsCoreGitHubAccess(input) &&
|
||||
nativeSessionConfigDigest(previous, "remote") === nativeSessionConfigDigest(input.execution, "remote") && canReuseNativeProcess(input,
|
||||
record(JSON.parse(readBoundedNativeFile(nativeSessionCheckpointPath(previous),
|
||||
NATIVE_WARM_CHECKPOINT_MAX_BYTES, "native_session_supervisor_checkpoint_too_large").toString("utf8"))).processConfigDigest),
|
||||
}) ?? undefined;
|
||||
@@ -11061,7 +11140,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
: coordinator.controllerGeneration + 1;
|
||||
const target = input.runnerExecutionTarget;
|
||||
const retained = warmNativeSessions.get(nativeSessionScopeKey(input.execution));
|
||||
if (!input.restartRecovery && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId &&
|
||||
if (canRecoverWarmOwner && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId &&
|
||||
((retained?.pluginTaskId && idleWarmNativeSessionOwnerRunId(input) !== undefined) || remoteWarmRecovery?.releasedSource) &&
|
||||
(input.execution.provider.kind === "codex" || (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude"))) {
|
||||
claimedStartupContext = new NativeExecutionContext(input.execution, Math.min(executionLeaseTtlMs,
|
||||
@@ -11801,7 +11880,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
executionContext = undefined;
|
||||
startupForAdmission!.executionContext = undefined;
|
||||
};
|
||||
if (warmSessionId !== null && warmConfigDigest !== null && !input.restartRecovery) {
|
||||
if (warmSessionId !== null && warmConfigDigest !== null && canRecoverWarmOwner) {
|
||||
const registered = warmNativeSessions.get(warmSessionId);
|
||||
const entry = registered && forgetUnretiredOwnerOnOtherSandbox(warmSessionId, registered, input.runnerExecutionTarget)
|
||||
? undefined : registered;
|
||||
@@ -12088,11 +12167,15 @@ async function executePaperclipNativeSessionAttempt(
|
||||
signal: executionContext?.signal ?? new AbortController().signal,
|
||||
});
|
||||
if (!recovered?.recovered || !recovered.session) throw new Error("runner_state_identity_mismatch: remote_warm_session_unproven");
|
||||
if (remoteWarmRecovery.reuseProcess) {
|
||||
const movedSession = remoteWarmRecovery.portableSourceTaskId !== undefined;
|
||||
// A portable resume already starts a new Runner. Its run attachment
|
||||
// prepares the current tools and runtime on the verified target.
|
||||
if (movedSession || remoteWarmRecovery.reuseProcess) {
|
||||
existingWarmSession = recovered.session;
|
||||
await emitStartupReuse(input.onEvent, "runner", { state: "reused", reason: "verified_reuse" });
|
||||
await emitStartupReuse(input.onEvent, "runner", movedSession
|
||||
? { state: "fresh", reason: "replacement" } : { state: "reused", reason: "verified_reuse" });
|
||||
await emitStartupReuse(input.onEvent, "provider_session", { state: "reused", reason: "verified_reuse" });
|
||||
trace.setBudgetStart("warm");
|
||||
if (!movedSession) trace.setBudgetStart("warm");
|
||||
persistedWarmSession = null;
|
||||
} else {
|
||||
await recovered.session.close({ reason: "recovered warm session requires current process configuration" });
|
||||
@@ -12104,12 +12187,22 @@ async function executePaperclipNativeSessionAttempt(
|
||||
remoteWarmRecovery.previousExecution.binding, scopedRunnerdStateRoot(input.execution),
|
||||
nativeSessionKey(input.execution));
|
||||
if (!suspendedController) throw new Error("native_runner_checkpoint_missing_after_suspension");
|
||||
persistWarmNativeCheckpoint(remoteWarmRecovery.previousExecution,
|
||||
nativeSessionConfigDigest(remoteWarmRecovery.previousExecution, "remote"), await recovered.session.snapshot());
|
||||
persistedWarmSession = loadWarmNativeCheckpoint(input.execution, warmConfigDigest!, "remote");
|
||||
runnerdBackend = await createRunnerdBackend({ ...input, onDiagnosticLease: ownDiagnosticLease, providerPackAdmissionSource, recoveryPurpose: claimedStopCleanup ? "stop_cleanup" : "execution", onAccountingEvent: producerUsage?.capture, runnerInstanceId: effectiveRunnerInstanceId,
|
||||
const verifiedConfigDigest = nativeSessionConfigDigest(remoteWarmRecovery.previousExecution, "remote");
|
||||
persistWarmNativeCheckpoint(remoteWarmRecovery.previousExecution, verifiedConfigDigest, await recovered.session.snapshot());
|
||||
persistedWarmSession = loadWarmNativeCheckpoint(input.execution, verifiedConfigDigest, "remote");
|
||||
runnerdBackend = await createRunnerdBackend({
|
||||
...input,
|
||||
pluginTaskDescription: undefined,
|
||||
onDiagnosticLease: ownDiagnosticLease,
|
||||
providerPackAdmissionSource,
|
||||
recoveryPurpose: claimedStopCleanup ? "stop_cleanup" : "execution",
|
||||
onAccountingEvent: producerUsage?.capture,
|
||||
runnerInstanceId: effectiveRunnerInstanceId,
|
||||
controllerPersistence: input.runnerExecutionTarget?.kind === "remote" ? { bootId: controller.bootId } : undefined,
|
||||
durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId, trace, toolTrace });
|
||||
durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId,
|
||||
trace,
|
||||
toolTrace,
|
||||
});
|
||||
}
|
||||
}
|
||||
const readRemoteCleanupLease = async () => input.runnerExecutionTarget?.kind === "remote" &&
|
||||
@@ -15710,6 +15803,7 @@ export function remoteCheckpointIncompleteFailure(
|
||||
export async function createRunnerdBackend(input: {
|
||||
executionContext?: NativeExecutionContext;
|
||||
casesEnabled?: boolean;
|
||||
toolRefreshOnResume?: boolean;
|
||||
db: Db;
|
||||
providerPackAdmissionSource?: NativeProviderPackAdmissionSource;
|
||||
controllerPersistence?: { bootId: string; runnerArtifact?: { version: string; digest: string } };
|
||||
@@ -15724,7 +15818,7 @@ export async function createRunnerdBackend(input: {
|
||||
remoteWarmRecovery?: Omit<RemoteWarmSessionRecovery, "revalidate"> & { revalidate: () => Promise<void> };
|
||||
retainedPluginTaskOwner?: ReturnType<typeof createPluginRunnerTaskOwner>;
|
||||
beginRetainedRunAttachment?: () => void;
|
||||
pluginTaskDescription?: Extract<ReturnType<typeof environmentTaskResultSchema.parse>,{kind:"description"}>;
|
||||
pluginTaskDescription?: PluginTaskDescription;
|
||||
onSpawn?: (meta: {
|
||||
pid: number;
|
||||
processGroupId: number | null;
|
||||
@@ -16128,8 +16222,10 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
const recoveryUsage = input.onAccountingEvent && recoveryUsageIdentity
|
||||
? createNativeRecoveryUsageDelivery({
|
||||
db: input.db, execution: input.execution, sourceIdentity: { ...recoveryUsageIdentity },
|
||||
matchesExecution: previous => nativeSessionScopeKey(previous) === nativeSessionScopeKey(input.execution) &&
|
||||
nativeSessionConfigDigest(previous, target.kind) === nativeSessionConfigDigest(input.execution, target.kind),
|
||||
matchesExecution: previous => input.remoteWarmRecovery
|
||||
? matchesRemoteWarmExecution(previous, input.execution, input.toolRefreshOnResume)
|
||||
: nativeSessionScopeKey(previous) === nativeSessionScopeKey(input.execution) &&
|
||||
nativeSessionConfigDigest(previous, target.kind) === nativeSessionConfigDigest(input.execution, target.kind),
|
||||
})
|
||||
: undefined;
|
||||
const accountingTransportOptions = {
|
||||
@@ -16185,15 +16281,19 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
const { root, durableIdentity, durableBinding } = durableState ??= readDurableState();
|
||||
const provider = input.execution.provider;
|
||||
if (provider.kind !== "codex" && provider.kind !== "opencode" && provider.kind !== "acpx") throw new Error("Plugin Runner tasks require a workspace harness");
|
||||
if (input.restartRecovery?.kind === "reattach_remote_runner") {
|
||||
await assertPluginTaskReattachmentBinding(input, remoteTarget, durableBinding ? durableIdentity : null);
|
||||
}
|
||||
let priorDescription = input.pluginTaskDescription?.taskId === remoteTarget.sandboxLeaseAcquisition?.providerLeaseId
|
||||
? input.pluginTaskDescription : undefined;
|
||||
if (remoteTarget.sandboxLeaseAcquisition?.outcome === "resumed" && !durableBinding && !input.retainedPluginTaskOwner && !input.remoteWarmRecovery) {
|
||||
// A new logical session (including fresh retries) cannot inherit the old process authority.
|
||||
await pluginTask({kind:"stop"});
|
||||
const stopped=environmentTaskResultSchema.parse(await pluginTask({kind:"status"}));
|
||||
if(stopped.kind!=="status" || stopped.executionStopped!==true) throw new Error("Plugin Runner termination is unconfirmed; reconcile the saved task");
|
||||
await pluginTask({kind:"complete"});
|
||||
priorDescription = undefined;
|
||||
}
|
||||
const priorDescription = input.pluginTaskDescription?.taskId === remoteTarget.sandboxLeaseAcquisition?.providerLeaseId
|
||||
? input.pluginTaskDescription : undefined;
|
||||
const description = priorDescription ?? environmentTaskResultSchema.parse(await pluginTask({ kind: "describe" }));
|
||||
if (description.kind !== "description" || description.launchPreparationVersion !== 1 || description.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner launch preparation v1 unavailable");
|
||||
const saved = durableBinding ? durableIdentity as RunnerdDurableIdentity : undefined;
|
||||
@@ -16212,9 +16312,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
normalizedSessionId: input.remoteWarmRecovery.identity.normalizedSessionId,
|
||||
turnId: input.remoteWarmRecovery.identity.turnId, itemId: input.remoteWarmRecovery.identity.itemId,
|
||||
} : undefined;
|
||||
if (input.restartRecovery?.kind === "reattach_remote_runner" && (!prior || !prior.turnId || !prior.itemId || prior.environmentLeaseId !== remoteTarget.leaseId)) {
|
||||
throw new Error("native_plugin_recovery_lease_mismatch");
|
||||
}
|
||||
|
||||
const resumeFrom = !retainedOwner && !adopting && prior && prior.environmentLeaseId !== remoteTarget.leaseId
|
||||
? await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
|
||||
leaseId: remoteTarget.leaseId!, priorIdentity: prior }) : undefined;
|
||||
@@ -16224,7 +16322,8 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
home: input.managedAiCredentialHome, environment: input.runnerEnvironment ?? {},
|
||||
});
|
||||
if (credentials.needsWriteback && !input.managedAiCredentialWriteback) throw new Error("Plugin Runner credential writeback authority unavailable");
|
||||
if (!adopting && input.managedAiCredentialWriteback && credentials.accountIdentity) {
|
||||
// Same-lease recovery already has a writeback binding. A portable move creates a new lease.
|
||||
if ((!adopting || input.remoteWarmRecovery?.portableSourceTaskId) && input.managedAiCredentialWriteback && credentials.accountIdentity) {
|
||||
if (!remoteTarget.leaseId) throw new Error("Plugin Runner credential lease unavailable");
|
||||
await registerPluginTaskCredentialHandoff(input.db, { companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId },
|
||||
credentials.accountIdentity, input.managedAiCredentialWriteback);
|
||||
@@ -16251,7 +16350,8 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
releaseResumeVersion: description.releaseResumeVersion,
|
||||
authorityRunId: description.releaseResumeVersion === 1 ? input.execution.binding.runId : undefined,
|
||||
releasedSource: input.remoteWarmRecovery?.releasedSource,
|
||||
onResumed: async source => updateReleasedWarmRunner(input.execution, source, description.taskId, null),
|
||||
sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId,
|
||||
onResumed: async source => updateReleasedWarmRunner(input.execution, source, input.remoteWarmRecovery?.portableSourceTaskId ?? description.taskId, null),
|
||||
onRetired: async source => updateReleasedWarmRunner(input.execution, source, description.taskId, null),
|
||||
adoptIdentity: adoptionIdentity ?? (adopting && prior ? {
|
||||
runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
NativeExecutionInput,
|
||||
PersistedNativeSession,
|
||||
} from "../../vendor/paperclip-runner/index.js";
|
||||
import { canonicalNativeRuntimeContextDigest, parseNativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { canonicalNativeRuntimeContextDigest, parseNativeExecutionInput, type NativeRuntimeContextSnapshot } from "../../vendor/paperclip-runner/index.js";
|
||||
|
||||
export type NativeToolExecutionTargetKind = "local" | "remote";
|
||||
|
||||
@@ -612,6 +612,15 @@ export function buildNativeExecutionWithCheckpoint(input: {
|
||||
};
|
||||
}
|
||||
|
||||
export function nativeRuntimeContextsMatch(
|
||||
previous: NativeRuntimeContextSnapshot,
|
||||
current: NativeRuntimeContextSnapshot,
|
||||
toolRefreshOnResume?: boolean,
|
||||
): boolean {
|
||||
return previous.aggregateDigest === current.aggregateDigest ||
|
||||
(toolRefreshOnResume === true && canonicalNativeRuntimeContextDigest({ ...previous, mcp: current.mcp }) === current.aggregateDigest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebind a completed prior run's provider checkpoint to a new heartbeat run.
|
||||
* The provider/driver session identity is retained, while every per-turn and
|
||||
@@ -697,12 +706,7 @@ export function rebindNativeSessionCheckpoint(input: {
|
||||
("homeMode" in previousExecution ? previousExecution.homeMode : "isolated") !== ("homeMode" in current ? current.homeMode : "isolated") ||
|
||||
("runtimeContext" in previousExecution &&
|
||||
"runtimeContext" in current &&
|
||||
previousExecution.runtimeContext.aggregateDigest !== current.runtimeContext.aggregateDigest &&
|
||||
!(input.toolRefreshOnResume === true &&
|
||||
canonicalNativeRuntimeContextDigest({
|
||||
...previousExecution.runtimeContext,
|
||||
mcp: current.runtimeContext.mcp,
|
||||
}) === current.runtimeContext.aggregateDigest))
|
||||
!nativeRuntimeContextsMatch(previousExecution.runtimeContext, current.runtimeContext, input.toolRefreshOnResume))
|
||||
)
|
||||
return null;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { and, asc, eq, exists, inArray, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, exists, inArray, or, sql } from "drizzle-orm";
|
||||
import { environmentLeases, nativeRunFinalizations, nativeRunnerCheckpoints, type Db } from "@paperclipai/db";
|
||||
import { inspectDurablePrpCheckpointHeader, type DurablePrpCheckpoint } from "../../vendor/paperclip-runner/index.js";
|
||||
import { nativeSha256 } from "./canonical.js";
|
||||
|
||||
type Transaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
@@ -18,7 +19,8 @@ export async function readNativeSourceConsumers(tx: Transaction, companyId: stri
|
||||
sql`${nativeRunnerCheckpoints.material}->>'schema' like 'paperclip.native-runner-checkpoint-retirement.%'`)));
|
||||
return tx.select({ id: environmentLeases.id, metadata: environmentLeases.metadata, retired }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId),
|
||||
sql`${environmentLeases.metadata}->'runnerTaskSourceConsumer' is not null`));
|
||||
or(sql`${environmentLeases.metadata}->'runnerTaskSourceConsumer' is not null`,
|
||||
sql`${environmentLeases.metadata}->'portableTaskSuccessor' is not null`)));
|
||||
}
|
||||
|
||||
/** Physical source consumption revokes the completed controller's late writer. */
|
||||
@@ -30,13 +32,26 @@ export async function assertNativeSourceCheckpointConsumer(tx: Transaction, owne
|
||||
if (!rows.length) return;
|
||||
const deny = (): never => { throw new Error("native_runner_checkpoint_owner_lost"); };
|
||||
if (owner.runId === owner.authorityRunId || rows.length !== 1 || !checkpoint) return deny();
|
||||
const source = rows[0]!, consumer = record(source.metadata?.runnerTaskSourceConsumer);
|
||||
const source = rows[0]!;
|
||||
const header = checkpoint.records.get("header");
|
||||
const identity = header ? inspectDurablePrpCheckpointHeader(header) : null;
|
||||
const portable = record(source.metadata?.portableTaskSuccessor);
|
||||
if (source.metadata?.portableTaskSuccessor !== undefined) {
|
||||
if (typeof portable.targetLeaseId !== "string" || portable.sourceLeaseId !== source.id ||
|
||||
!identity || nativeSha256(record(portable.operation).identity ?? null) !== nativeSha256(identity)) return deny();
|
||||
const [target] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId),
|
||||
eq(environmentLeases.id, portable.targetLeaseId)));
|
||||
if (!target || target.heartbeatRunId !== owner.authorityRunId || target.status !== "active" || target.releasedAt ||
|
||||
target.expiresAt && target.expiresAt.getTime() <= Date.now() ||
|
||||
target.metadata?.portableTaskOwnershipReady !== true || target.metadata.portableTaskSuccessor !== undefined ||
|
||||
nativeSha256(target.metadata.portableTaskPredecessor ?? null) !== nativeSha256(portable)) return deny();
|
||||
return;
|
||||
}
|
||||
const consumer = record(source.metadata?.runnerTaskSourceConsumer);
|
||||
if (typeof consumer.leaseId !== "string" || consumer.runId !== owner.authorityRunId) return deny();
|
||||
const [lease] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId),
|
||||
eq(environmentLeases.id, consumer.leaseId)));
|
||||
const recovery = record(lease?.metadata?.runnerTaskSourceRecovery);
|
||||
const header = checkpoint.records.get("header");
|
||||
const identity = header ? inspectDurablePrpCheckpointHeader(header) : null;
|
||||
const expected = record(recovery.identity);
|
||||
if (!lease || lease.heartbeatRunId !== owner.authorityRunId || lease.status !== "active" || lease.releasedAt ||
|
||||
lease.expiresAt && lease.expiresAt.getTime() <= Date.now() ||
|
||||
|
||||
@@ -553,6 +553,18 @@ describe("plugin Runner release/resume facade", () => {
|
||||
? { kind: "released", taskId: "task" }
|
||||
: { kind: "resume", taskId: "task", outcome: "resumed" });
|
||||
|
||||
it.each([true, false])("sends the current Claude credential only for session handoff (%s)", async sessionHandoff => {
|
||||
const task = lifecycleTask();
|
||||
const environment = { CLAUDE_CODE_OAUTH_TOKEN: "fixture-current-token" };
|
||||
const owner = createPluginRunnerTaskOwner({ ...input("claude"), task, sessionHandoff,
|
||||
credential: { type: "claude-env", environment } });
|
||||
await expect(owner.resume(requirements.identity, "transient-ticket")).resolves.toBe("resumed");
|
||||
expect(task).toHaveBeenCalledExactlyOnceWith({
|
||||
kind: "resume", identity: requirements.identity, bootstrapTicket: "transient-ticket",
|
||||
...(sessionHandoff ? { handoffCredential: { accountIdentity: "selected-account", environment } } : {}),
|
||||
}, { expectedTaskId: "task" });
|
||||
});
|
||||
|
||||
it.each(["codex", "claude"])("quiesces %s before release and closes only after its ACK", async harness => {
|
||||
const { task } = provider();
|
||||
const perform = task.getMockImplementation()!;
|
||||
|
||||
@@ -50,6 +50,7 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
warmTaskVersion?: 1;
|
||||
releaseResumeVersion?: 1;
|
||||
releasedSource?: DurableRecoveryIdentity;
|
||||
sessionHandoff?: boolean;
|
||||
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
|
||||
onRetired?: (identity: DurableRecoveryIdentity) => Promise<void>;
|
||||
githubBroker?: { url: string; token: string };
|
||||
@@ -418,7 +419,12 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
};
|
||||
const resume = async (identity: DurableRecoveryIdentity, bootstrapTicket: string): Promise<"resumed" | "unavailable"> => {
|
||||
requireReleaseResume();
|
||||
const result = await call(environmentTaskOperationSchema.parse({ kind: "resume", identity, bootstrapTicket }));
|
||||
const handoffCredential = input.sessionHandoff && input.credential?.type === "claude-env"
|
||||
? { accountIdentity: input.accountIdentity, environment: input.credential.environment }
|
||||
: undefined;
|
||||
const result = await call(environmentTaskOperationSchema.parse({ kind: "resume", identity, bootstrapTicket,
|
||||
...(handoffCredential ? { handoffCredential } : {}),
|
||||
}));
|
||||
requireReleaseResume();
|
||||
if (result.kind !== "resume") throw new Error("Plugin Runner resume result unavailable");
|
||||
if (result.outcome === "unavailable") {
|
||||
|
||||
+215
-4
@@ -3,19 +3,23 @@ import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { environmentTaskOperationSchema } from "@paperclipai/plugin-sdk";
|
||||
import { environmentTaskOperationSchema, type PluginEnvironmentTaskResult } from "@paperclipai/plugin-sdk";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, completionContracts, createDb, environmentLeases, environments, heartbeatRuns, issues, nativeRunFinalizations,
|
||||
nativeRunResults, nativeRunnerCheckpoints, plugins } from "@paperclipai/db";
|
||||
import { parseNativeExecutionInput, runnerProviderLaunchRequirements, DurablePrpControlPlane, type DurablePrpCheckpoint, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { canonicalNativeRuntimeContextDigest, parseNativeExecutionInput, runnerProviderLaunchRequirements, DurablePrpControlPlane, type DurablePrpCheckpoint, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { recoveryPostgresSupport, startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js";
|
||||
import { createIsolatedTestHome } from "../../__tests__/helpers/isolated-test-home.js";
|
||||
import { executeEnvironmentTask, resolvePluginTaskResume } from "../environment-task-runtime.js";
|
||||
import type { PluginWorkerManager } from "../plugin-worker-manager.js";
|
||||
import { assertAttachedPortableTask, readyPortableTaskSource, reconcilePluginTaskOwnership } from "../plugin-task-ownership.js";
|
||||
import { remoteTerminationReceipt } from "../remote-execution-termination.js";
|
||||
import * as runtimeApi from "../../runtime-api.js";
|
||||
import { NativeExecutionContext } from "./native-execution-context.js";
|
||||
import { buildNativeExecutionInput } from "./native-execution-input.js";
|
||||
import { currentNativeControllerIdentity } from "./native-restart-recovery.js";
|
||||
import { createRunnerdBackend, nativeControllerMigrationDescriptor } from "./native-session-executor.js";
|
||||
import { buildNativeExecutionWithCheckpoint, nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
|
||||
import { loadNativeRunnerCheckpoint, nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js";
|
||||
import { claimPluginTaskSourceRecovery } from "./plugin-task-source-recovery.js";
|
||||
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
|
||||
@@ -83,7 +87,7 @@ describe.skipIf(!recoveryPostgresSupport.supported)("stopped source admission un
|
||||
leaseOwner: owner.leaseOwner, leaseExpiresAt: new Date(Date.now() + 60_000) });
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "source-fixture", version: "1.0.0", status: "ready",
|
||||
manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }] } as never });
|
||||
manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true, sessionHandoffVersion: 1 }] } as never });
|
||||
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "plugin", status: "active",
|
||||
config: { pluginKey: pluginId, driverKey: "tasks" } });
|
||||
const metadata = { driver: "plugin", pluginId, driverKey: "tasks", runnerTaskLease: true };
|
||||
@@ -98,7 +102,7 @@ describe.skipIf(!recoveryPostgresSupport.supported)("stopped source admission un
|
||||
const input = { companyId, leaseId, context, identity, resumeFrom: "source-task",
|
||||
...(provider === "codex" ? { codexSourceRecoveryVersion: 1 as const } : { acpxSourceRecoveryVersion: 1 as const }),
|
||||
accountIdentity: "current-selected-account", matchesExecution: (previous: typeof sourceExecution) => previous.provider.kind === execution.provider.kind && previous.workspace.cwd === execution.workspace.cwd };
|
||||
const workers = { getWorker: () => ({ supportedMethods: ["environmentTask"] }), call: vi.fn(async (_id: string, _method: string, p: any) => {
|
||||
const workers = { getWorker: () => ({ supportedMethods: ["environmentTask"] }), call: vi.fn(async (_id: string, _method: string, p: any): Promise<PluginEnvironmentTaskResult> => {
|
||||
if (p.operation.kind === "prepare") return { kind: "prepared", taskId: p.taskId,
|
||||
launch: { configurationId: "source-configuration", requirementsDigest: `sha256:${"a".repeat(64)}`, provider: {} } };
|
||||
if (p.operation.kind === "check_project_auth") return { kind: "project_auth", taskId: p.taskId, provider: p.operation.provider, configurationId: p.operation.configurationId, allowed: true };
|
||||
@@ -125,6 +129,213 @@ describe.skipIf(!recoveryPostgresSupport.supported)("stopped source admission un
|
||||
harness: provider === "claude" ? "claude" as const : "codex" as const, authProvider: provider === "claude" ? "anthropic" : "openai" };
|
||||
}
|
||||
|
||||
it.each([
|
||||
{ policy: "ordinary", scenario: "ordinary handoff" },
|
||||
{ policy: "reclaim_if_needed", scenario: "idle source reclaim" },
|
||||
{ policy: "ordinary", scenario: "fresh conversation after instructions change", freshSession: true },
|
||||
] as const)("reconciles ownership after a lost response: $scenario", async scenario => {
|
||||
const { policy } = scenario;
|
||||
const f = await fixture();
|
||||
await db.update(heartbeatRuns).set({ scopeKind: "issue", issueId: f.issueId }).where(eq(heartbeatRuns.id, f.runId));
|
||||
await db.update(environmentLeases).set({ status: "retained", releasedAt: null,
|
||||
metadata: sql`(${environmentLeases.metadata} - 'remoteExecutionTermination') || ${JSON.stringify({
|
||||
providerMetadata: { ownershipGeneration: "source-generation" }, runnerTaskAccountIdentity: f.accountIdentity,
|
||||
})}::jsonb`,
|
||||
}).where(eq(environmentLeases.id, f.sourceLeaseId));
|
||||
await db.update(environmentLeases).set({
|
||||
metadata: sql`${environmentLeases.metadata} || '{"providerMetadata":{"ownershipGeneration":"target-generation"}}'::jsonb`,
|
||||
}).where(eq(environmentLeases.id, f.leaseId));
|
||||
const request = { companyId: f.companyId, sourceLeaseId: f.sourceLeaseId, targetLeaseId: f.leaseId, policy };
|
||||
const send = (database: typeof db) => reconcilePluginTaskOwnership(database, request, operation =>
|
||||
executeEnvironmentTask(database, f.workers as unknown as PluginWorkerManager, { companyId: f.companyId, leaseId: f.leaseId, operation }));
|
||||
const describe = (database: typeof db, ownershipSignal?: AbortSignal) => executeEnvironmentTask(database, f.workers as unknown as PluginWorkerManager,
|
||||
{ companyId: f.companyId, leaseId: f.leaseId, ownershipSignal, operation: { kind: "describe" } });
|
||||
if (policy === "ordinary") await db.update(environmentLeases).set({
|
||||
metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({ portableTaskPreviousLeaseId: f.sourceLeaseId })}::jsonb`,
|
||||
}).where(eq(environmentLeases.id, f.leaseId));
|
||||
f.workers.call.mockRejectedValueOnce(new Error("worker transport lost"));
|
||||
await expect(policy === "ordinary" ? describe(db) : send(db)).rejects.toThrow();
|
||||
const operation = f.workers.call.mock.calls[0][2].operation;
|
||||
expect(operation).toMatchObject({ kind: "ensure_ownership", operationId: f.leaseId, identity: f.identity,
|
||||
sourceTaskId: "source-task", sourceGeneration: "source-generation", targetGeneration: "target-generation", policy });
|
||||
await expect(f.task({ ...operation, policy: policy === "ordinary" ? "reclaim_if_needed" : "ordinary" })).rejects.toThrow("ownership_unverified");
|
||||
await expect(f.task()).rejects.toThrow("session ownership unavailable");
|
||||
await expect(executeEnvironmentTask(db, f.workers as unknown as PluginWorkerManager, {
|
||||
companyId: f.companyId, leaseId: f.sourceLeaseId, operation: { kind: "resume", identity: f.identity, bootstrapTicket: "fixture-ticket" },
|
||||
})).rejects.toThrow("session ownership unavailable");
|
||||
expect(f.workers.call).toHaveBeenCalledTimes(1);
|
||||
const reply = { kind: "ownership", taskId: "replacement-task", operationId: f.leaseId,
|
||||
targetGeneration: "target-generation" } as const;
|
||||
f.workers.call.mockResolvedValueOnce({ ...reply, status: "pending" });
|
||||
await expect(describe(db)).rejects.toThrow("native_portable_task_ownership_pending");
|
||||
const targetWriter = nativeRunnerCheckpointWriter(db, { companyId: f.companyId, issueId: f.issueId,
|
||||
runId: f.sourceRunId, authorityRunId: f.runId, ...f.owner });
|
||||
await expect(targetWriter(f.checkpoint)).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
const restarted = createDb(database.connectionString);
|
||||
f.workers.call.mockResolvedValueOnce({ ...reply, status: "ready", targetGeneration: "another-generation" });
|
||||
await expect(describe(restarted)).rejects.toThrow("reconcile the same task");
|
||||
await expect(f.task()).rejects.toThrow("session ownership unavailable");
|
||||
const description = { kind: "description", taskId: "replacement-task",
|
||||
runner: { version: "test", digest: `sha256:${"a".repeat(64)}` } } as const;
|
||||
f.workers.call.mockRejectedValueOnce(new Error("worker transport lost again"));
|
||||
f.workers.call.mockResolvedValueOnce({ ...reply, status: "pending" });
|
||||
f.workers.call.mockResolvedValueOnce({ ...reply, status: "ready" });
|
||||
f.workers.call.mockResolvedValueOnce(description);
|
||||
await expect(describe(restarted, new AbortController().signal)).resolves.toEqual(description);
|
||||
expect(f.workers.call.mock.calls.map(([, , call]) => call.operation)).toEqual([...Array(6).fill(operation), { kind: "describe" }]);
|
||||
const [target] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId));
|
||||
expect(target.metadata?.portableTaskOwnershipReady).toBe(true);
|
||||
expect(target.metadata?.runnerTaskAccountIdentity).toBe(f.accountIdentity);
|
||||
const [source] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.sourceLeaseId));
|
||||
expect(source.metadata?.remoteExecutionTermination).toBeUndefined();
|
||||
await expect(f.oldWriter(f.checkpoint)).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
await expect(targetWriter(f.checkpoint)).resolves.toBeUndefined();
|
||||
|
||||
async function recoverAttachedRunner(execution: NativeExecutionInput, identity: typeof f.identity) {
|
||||
const { root: stateDirectory } = nativeControllerMigrationDescriptor(execution,
|
||||
nativeToolContractFingerprintForTarget("remote", execution.provider.kind));
|
||||
const durable = new DurablePrpControlPlane({ stateDirectory: join(stateDirectory, "control-plane"),
|
||||
identity: identity, expectedRunnerVersion: description.runner.version, expectedRunnerDigest: description.runner.digest });
|
||||
durable.persistRunAttachTemplate({ provider: { instructions: "Run using the admitted instructions.",
|
||||
runtimeContext: "runtimeContext" in execution ? execution.runtimeContext : null } });
|
||||
await durable.flushCheckpoint();
|
||||
await durable.stop();
|
||||
const recover = () => createRunnerdBackend({ db: restarted, execution,
|
||||
runnerInstanceId: identity.runnerInstanceId, runnerIngressAuthorized: true,
|
||||
runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: f.leaseId,
|
||||
sandboxLeaseAcquisition: { outcome: "created", providerLeaseId: "replacement-task" },
|
||||
runnerTask: (operation, options) => executeEnvironmentTask(restarted, f.workers as unknown as PluginWorkerManager, {
|
||||
companyId: f.companyId, leaseId: f.leaseId, operation: environmentTaskOperationSchema.parse(operation),
|
||||
expectedTaskId: options?.expectedTaskId,
|
||||
}),
|
||||
},
|
||||
restartRecovery: { kind: "reattach_remote_runner", remote: { kind: "plugin_task", leaseId: f.leaseId },
|
||||
runId: f.runId, leaseOwner: "successor", controllerGeneration: f.owner.generation + 1,
|
||||
providerAttempt: 1, restartKind: "hard", recoveryRequestId: null },
|
||||
});
|
||||
f.workers.call.mockClear();
|
||||
f.workers.call
|
||||
.mockResolvedValueOnce({ kind: "status", taskId: "replacement-task", phase: "running", executionStopped: false })
|
||||
.mockResolvedValueOnce({ kind: "state", taskId: "replacement-task",
|
||||
state: { schema: "paperclip.runner.durable.state.v1", ...identity } })
|
||||
.mockResolvedValueOnce({ ...description, launchPreparationVersion: 1, projectAuthCheckVersion: 1 });
|
||||
const api = vi.spyOn(runtimeApi, "resolveLocalRuntimeApiUrl").mockReturnValue("http://127.0.0.1:3100");
|
||||
try { await expect(recover()).resolves.toBeDefined(); }
|
||||
finally { api.mockRestore(); }
|
||||
expect(f.workers.call.mock.calls.map(([, , call]) => [call.taskId, call.operation.kind])).toEqual([
|
||||
["replacement-task", "status"], ["replacement-task", "read_state"], ["replacement-task", "describe"],
|
||||
]);
|
||||
return recover;
|
||||
}
|
||||
|
||||
if ("freshSession" in scenario) {
|
||||
const previousExecution = f.sourceExecution;
|
||||
const nativeToolContractFingerprint = nativeToolContractFingerprintForTarget("remote", f.execution.provider.kind);
|
||||
const normalizedSessionId = f.identity.normalizedSessionId;
|
||||
const previousRun = {
|
||||
id: f.sourceRunId, companyId: f.companyId, agentId: f.execution.binding.agentId, nativeSessionId: normalizedSessionId,
|
||||
runnerProfileJson: { nativeToolContractFingerprint, nativeExecutionInput: previousExecution,
|
||||
sessionCheckpoint: { backendKind: "runner", driverKind: previousExecution.session.driverKind,
|
||||
sessionId: "previous-provider-thread", providerSessionId: "previous-provider-thread",
|
||||
identity: { ...previousExecution.binding, sessionId: normalizedSessionId }, pendingRuntimeRequests: [] } },
|
||||
};
|
||||
const select = (current: NativeExecutionInput) => buildNativeExecutionWithCheckpoint({
|
||||
previousRun, normalizedSessionId, executionTargetKind: "remote", toolRefreshOnResume: true,
|
||||
buildExecution: ({ normalizedSessionId }) => ({ ...current, session: { ...current.session, normalizedSessionId } } as NativeExecutionInput),
|
||||
});
|
||||
expect(select(f.execution).checkpoint?.providerSessionId).toBe("previous-provider-thread");
|
||||
const changed = structuredClone(f.execution);
|
||||
if (!("runtimeContext" in changed)) throw new Error("fixture requires runtime context");
|
||||
changed.runtimeContext.instructions.bundle.digest = "1".repeat(64);
|
||||
changed.runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(changed.runtimeContext);
|
||||
const selected = select(changed);
|
||||
expect(selected.checkpoint).toBeNull();
|
||||
expect(selected.normalizedSessionId).not.toBe(normalizedSessionId);
|
||||
const scope = { attachedRunId: f.runId, accountIdentity: f.accountIdentity, selectedSessionId: selected.normalizedSessionId };
|
||||
const sourceFor = (identity: unknown) => readyPortableTaskSource(restarted, f.companyId, f.leaseId, identity, scope);
|
||||
await expect(sourceFor(null)).rejects.toThrow("ownership_unverified");
|
||||
await db.update(heartbeatRuns).set({ nativeSessionId: selected.normalizedSessionId }).where(eq(heartbeatRuns.id, f.runId));
|
||||
await expect(sourceFor(null)).rejects.toThrow("ownership_unverified");
|
||||
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: selected.execution } })
|
||||
.where(eq(heartbeatRuns.id, f.runId));
|
||||
await expect(sourceFor(null)).resolves.toBeUndefined();
|
||||
await expect(sourceFor(f.identity)).rejects.toThrow("ownership_unverified");
|
||||
const duplicate = randomUUID();
|
||||
await db.insert(environmentLeases).values({ ...target, id: duplicate, providerLeaseId: "ambiguous-task" });
|
||||
await expect(sourceFor(null)).rejects.toThrow("ownership_unverified");
|
||||
await db.delete(environmentLeases).where(eq(environmentLeases.id, duplicate));
|
||||
|
||||
const fresh = { ...f.identity, runId: f.runId, environmentLeaseId: f.leaseId, runnerInstanceId: randomUUID(),
|
||||
normalizedSessionId: selected.normalizedSessionId, turnId: "fresh-turn", itemId: "fresh-item" };
|
||||
const prepare = { ...f.operation, resumeFrom: undefined, requirements: { ...f.operation.requirements, identity: fresh } };
|
||||
const submit = { ...f.submit, resumeFrom: undefined, runner: { ...f.submit.runner,
|
||||
runnerId: fresh.runnerInstanceId, leaseId: fresh.environmentLeaseId, runId: fresh.runId,
|
||||
sessionId: fresh.normalizedSessionId, turnId: fresh.turnId, itemId: fresh.itemId } };
|
||||
f.workers.call.mockClear();
|
||||
await expect(f.task(prepare)).resolves.toMatchObject({ kind: "prepared" });
|
||||
await expect(f.task({ kind: "check_project_auth", provider: "openai", projectIds: [],
|
||||
configurationId: submit.preparedLaunchId })).resolves.toMatchObject({ kind: "project_auth", allowed: true });
|
||||
await expect(f.task(submit)).resolves.toMatchObject({ kind: "accepted" });
|
||||
expect(f.workers.call.mock.calls.map(([, , call]) => call.operation.kind)).toEqual(["prepare", "check_project_auth", "submit"]);
|
||||
expect(f.workers.call.mock.calls.every(([, , call]) => call.taskId === "replacement-task" &&
|
||||
call.operation.resumeFrom === undefined && call.operation.priorIdentity === undefined)).toBe(true);
|
||||
await expect(sourceFor(null)).rejects.toThrow("ownership_unverified");
|
||||
await expect(sourceFor({ ...fresh, turnId: "wrong-turn" })).rejects.toThrow("ownership_unverified");
|
||||
await expect(sourceFor(fresh)).resolves.toBeUndefined();
|
||||
await recoverAttachedRunner(selected.execution, fresh);
|
||||
return;
|
||||
}
|
||||
|
||||
const resume = { kind: "resume", identity: f.identity, bootstrapTicket: "fixture-ticket" } as const;
|
||||
f.workers.call.mockResolvedValueOnce({ kind: "resume", taskId: "replacement-task", outcome: "resumed" });
|
||||
await expect(f.task(resume)).resolves.toMatchObject({ kind: "resume", outcome: "resumed" });
|
||||
const [dispatched] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId));
|
||||
expect(dispatched.metadata?.runnerTaskDispatched).toBe(true);
|
||||
|
||||
const readState = { kind: "read_state", identity: f.identity } as const;
|
||||
await expect(f.task({ ...readState, identity: { ...f.identity, itemId: "wrong-item" } }))
|
||||
.rejects.toThrow("ownership_unverified");
|
||||
f.workers.call.mockResolvedValueOnce({ kind: "state", taskId: "replacement-task", state: { ...f.identity } });
|
||||
await expect(f.task(readState)).resolves.toMatchObject({ kind: "state", state: f.identity });
|
||||
const nextIdentity = { ...f.identity, runId: f.runId, turnId: "target-turn", itemId: "target-item" };
|
||||
const attach = { ...f.operation, resumeFrom: undefined, priorIdentity: f.identity,
|
||||
requirements: { ...f.operation.requirements, identity: nextIdentity } };
|
||||
await expect(f.task({ ...attach, requirements: { ...attach.requirements,
|
||||
identity: { ...nextIdentity, normalizedSessionId: randomUUID() } } })).rejects.toThrow("prior identity mismatch");
|
||||
await expect(f.task(attach)).resolves.toMatchObject({ kind: "prepared" });
|
||||
await expect(f.task(attach)).resolves.toMatchObject({ kind: "prepared" });
|
||||
const [attached] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId));
|
||||
expect(attached.metadata?.runnerTaskIdentity).toMatchObject({ runId: f.runId, sessionId: f.identity.normalizedSessionId });
|
||||
expect(attached.metadata?.runnerTaskPriorIdentity).toMatchObject({ runId: f.sourceRunId, itemId: f.identity.itemId });
|
||||
const scope = { attachedRunId: f.runId, accountIdentity: f.accountIdentity };
|
||||
await expect(readyPortableTaskSource(db, f.companyId, f.leaseId, nextIdentity, scope)).resolves.toBeUndefined();
|
||||
await expect(readyPortableTaskSource(db, f.companyId, f.leaseId, { ...nextIdentity, turnId: "wrong-turn" }, scope))
|
||||
.rejects.toThrow("ownership_unverified");
|
||||
await expect(readyPortableTaskSource(db, f.companyId, f.leaseId, f.identity, scope))
|
||||
.resolves.toEqual({ taskId: "source-task", identity: f.identity });
|
||||
await expect(readyPortableTaskSource(db, f.companyId, f.leaseId, f.identity, { ...scope, accountIdentity: "another-account" }))
|
||||
.rejects.toThrow("ownership_unverified");
|
||||
|
||||
const binding = { companyId: f.companyId, leaseId: f.leaseId, taskId: "replacement-task", runId: f.runId, identity: nextIdentity };
|
||||
await expect(assertAttachedPortableTask(restarted, binding)).resolves.toBeUndefined();
|
||||
for (const invalid of [
|
||||
{ ...binding, leaseId: f.sourceLeaseId },
|
||||
{ ...binding, taskId: "source-task" },
|
||||
{ ...binding, identity: f.identity },
|
||||
{ ...binding, identity: { ...nextIdentity, environmentLeaseId: f.leaseId } },
|
||||
]) await expect(assertAttachedPortableTask(restarted, invalid)).rejects.toThrow("ownership_unverified");
|
||||
|
||||
if (policy === "ordinary") {
|
||||
const recover = await recoverAttachedRunner(f.execution, nextIdentity);
|
||||
await db.update(environmentLeases).set({
|
||||
metadata: sql`${environmentLeases.metadata} - 'portableTaskSuccessor'`,
|
||||
}).where(eq(environmentLeases.id, f.sourceLeaseId));
|
||||
f.workers.call.mockClear();
|
||||
await expect(recover()).rejects.toThrow("ownership_unverified");
|
||||
expect(f.workers.call).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["codex", "claude"] as const)("authorizes the claimed %s source while preserving A's accepted outcome", async provider => {
|
||||
const f = await fixture(provider);
|
||||
const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceRunId));
|
||||
|
||||
@@ -5,6 +5,7 @@ import { parseNativeExecutionInput, type NativeExecutionInput, type PersistedNat
|
||||
import { currentNativeControllerIdentity, evaluateNativeControllerTakeover, recordLegacyHostFallbackProof } from "./native-restart-recovery.js";
|
||||
import { NativeControllerRecoveryWaitingError, readNativeControllerRecovery } from "./native-controller-recovery.js";
|
||||
import { NativePredecessorRetirementUnprovenError } from "./predecessor-retirement.js";
|
||||
import { readyPortableTaskSource } from "../plugin-task-ownership.js";
|
||||
|
||||
export type RemoteWarmSessionRecovery = {
|
||||
identity: Record<string, string>;
|
||||
@@ -12,6 +13,7 @@ export type RemoteWarmSessionRecovery = {
|
||||
previousExecution: NativeExecutionInput;
|
||||
reuseProcess: boolean;
|
||||
releasedSource?: DurableRecoveryIdentity;
|
||||
portableSourceTaskId?: string;
|
||||
remote: { providerLeaseId: string; remoteCwd: string };
|
||||
revalidate: (leaseOwner: string) => Promise<void>;
|
||||
};
|
||||
@@ -128,6 +130,7 @@ export async function inspectRemoteWarmSessionRecovery(input: {
|
||||
matchesExecution: (previous: NativeExecutionInput) => boolean;
|
||||
loadCheckpoint: (previous: NativeExecutionInput) => PersistedNativeSession | null;
|
||||
canReuseProcess: (previous: NativeExecutionInput) => boolean;
|
||||
portableSourceTaskId?: string;
|
||||
}): Promise<RemoteWarmSessionRecovery | null> {
|
||||
const { binding } = input.execution;
|
||||
const { target } = input;
|
||||
@@ -152,13 +155,15 @@ export async function inspectRemoteWarmSessionRecovery(input: {
|
||||
// sandbox (for example after a restart or deploy replaced the controller)
|
||||
// holds no Runner to adopt, so live adoption steps aside. Ordinary admission
|
||||
// then retires the finished owner or keeps it held with a named reason.
|
||||
if (target.transport === "sandbox" && ["created", "replacement"].includes(target.sandboxLeaseAcquisition?.outcome ?? "")) {
|
||||
if (!input.portableSourceTaskId && target.transport === "sandbox" && ["created", "replacement"].includes(target.sandboxLeaseAcquisition?.outcome ?? "")) {
|
||||
return null;
|
||||
}
|
||||
if (target.transport !== "sandbox" || !target.leaseId || !target.environmentId ||
|
||||
!target.providerKey || !target.sandboxLeaseAcquisition || target.sandboxLeaseAcquisition.outcome !== "resumed" ||
|
||||
!target.providerKey || !target.sandboxLeaseAcquisition ||
|
||||
(!input.portableSourceTaskId && target.sandboxLeaseAcquisition.outcome !== "resumed") ||
|
||||
identity.runId === binding.runId) return deny("target_not_resumed_sandbox");
|
||||
const providerLeaseId = target.sandboxLeaseAcquisition.providerLeaseId;
|
||||
const sourceProviderLeaseId = input.portableSourceTaskId ?? providerLeaseId;
|
||||
const [prior] = await input.db.select({ run: heartbeatRuns, owner: nativeRunFinalizations })
|
||||
.from(heartbeatRuns).innerJoin(nativeRunFinalizations, eq(nativeRunFinalizations.runId, heartbeatRuns.id))
|
||||
.where(and(eq(heartbeatRuns.id, identity.runId), eq(heartbeatRuns.companyId, binding.companyId),
|
||||
@@ -171,7 +176,7 @@ export async function inspectRemoteWarmSessionRecovery(input: {
|
||||
throw new NativeControllerRecoveryWaitingError(prior.owner.leaseExpiresAt);
|
||||
}
|
||||
if (prior.owner.phase !== "committed" || prior.owner.leaseOwner) return deny("owner_unsettled");
|
||||
settledPredecessor = { runId: identity.runId, providerLeaseId };
|
||||
if (sourceProviderLeaseId === providerLeaseId) settledPredecessor = { runId: identity.runId, providerLeaseId };
|
||||
const checkpoint = input.loadCheckpoint(previous);
|
||||
if (!checkpoint || checkpoint.identity.runId !== identity.runId ||
|
||||
checkpoint.identity.companyId !== binding.companyId || checkpoint.identity.issueId !== binding.issueId ||
|
||||
@@ -194,15 +199,22 @@ export async function inspectRemoteWarmSessionRecovery(input: {
|
||||
const priorLeases = await input.db.select().from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, binding.companyId), eq(environmentLeases.heartbeatRunId, identity.runId),
|
||||
eq(environmentLeases.issueId, binding.issueId), eq(environmentLeases.environmentId, target.environmentId),
|
||||
eq(environmentLeases.provider, target.providerKey), eq(environmentLeases.providerLeaseId, providerLeaseId),
|
||||
eq(environmentLeases.provider, target.providerKey), eq(environmentLeases.providerLeaseId, sourceProviderLeaseId),
|
||||
));
|
||||
if (priorLeases.length !== 1 || priorLeases[0].metadata?.remoteCwd !== target.remoteCwd ||
|
||||
!["released", "expired", "active"].includes(priorLeases[0].status)) return deny("prior_lease_mismatch");
|
||||
!["released", "expired", "active", ...(input.portableSourceTaskId ? ["retained"] : [])].includes(priorLeases[0].status)) {
|
||||
return deny("prior_lease_mismatch");
|
||||
}
|
||||
return {
|
||||
identity, checkpoint, previousExecution: previous, reuseProcess: input.canReuseProcess(previous),
|
||||
portableSourceTaskId: input.portableSourceTaskId,
|
||||
remote: { providerLeaseId, remoteCwd: target.remoteCwd },
|
||||
revalidate: async leaseOwner => {
|
||||
await assertPriorStopped();
|
||||
if (input.portableSourceTaskId &&
|
||||
(await readyPortableTaskSource(input.db, binding.companyId, target.leaseId!, identity))?.taskId !== input.portableSourceTaskId) {
|
||||
return deny("prior_lease_mismatch");
|
||||
}
|
||||
const controller = await currentNativeControllerIdentity();
|
||||
const [current] = await input.db.select({ run: heartbeatRuns, owner: nativeRunFinalizations, issue: issues, agent: agents, company: companies })
|
||||
.from(heartbeatRuns).innerJoin(nativeRunFinalizations, eq(nativeRunFinalizations.runId, heartbeatRuns.id))
|
||||
|
||||
Reference in new issue
Block a user