mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
fix: recover settled Dot checkpoints after runner exit
Use provider-owned exact settled checkpoint eligibility after proven daemon death; retain all Runner identity, authority, unknown-effect and original-deadline fences. Cover actual accept receipts, real daemon replay and normal authority with the qualified host fixture binding. Co-Authored-By: Codex <codex@users.noreply.github.com>
This commit is contained in:
1 parent
e4386f0b8e
commit
9997765052
4 files changed
+152
-20
No files matched your search
@@ -133,7 +133,7 @@ it.each([
|
||||
}
|
||||
}, 45000);
|
||||
|
||||
it.each(["local", "local pending finish", "custom local directory", "external launcher", "grok external launcher", "external launcher empty controller"])("reattaches the %s Rust bridge without duplicate operations and refuses lost checkpoints", async launch => {
|
||||
it.each(["local", "local pending finish", "custom local directory", "external launcher", "grok external launcher", "external launcher empty controller", "external launcher dead daemon"])("reattaches the %s Rust bridge without duplicate operations and refuses lost checkpoints", async launch => {
|
||||
const root = await mkdtemp(join(tmpdir(), "dot-driver-recovery-"));
|
||||
await writeFile(join(root, "AGENTS.md"), "Use only the synthetic counter.");
|
||||
const input = execution(root, launch === "grok external launcher" ? "grok_bot" : "openai_dot");
|
||||
@@ -143,6 +143,9 @@ it.each(["local", "local pending finish", "custom local directory", "external la
|
||||
const settlements = new Map<string, unknown>();
|
||||
const dispatches: unknown[] = [];
|
||||
let controllerPort = 0;
|
||||
const deadDaemon = launch === "external launcher dead daemon";
|
||||
let ownedChild: ReturnType<typeof spawn> | undefined;
|
||||
let ownedCompletion: Promise<unknown> | undefined;
|
||||
const emptyController = launch === "external launcher empty controller";
|
||||
const pendingFinish = launch === "local pending finish";
|
||||
const firstCompletion = vi.fn(() => new Promise<string>(() => {}));
|
||||
@@ -152,7 +155,7 @@ it.each(["local", "local pending finish", "custom local directory", "external la
|
||||
execution: input, stateDirectory: join(root, "state"),
|
||||
identity: { runnerInstanceId: randomUUID(), environmentLeaseId: randomUUID(), runId: input.binding.runId,
|
||||
normalizedSessionId: input.session.normalizedSessionId!, turnId: "turn-" + input.binding.runId, itemId: "item-" + input.binding.runId },
|
||||
runnerBinary: resolve("runner/target/debug/paperclip-runnerd"),
|
||||
runnerBinary: deadDaemon ? process.env.PAPERCLIP_ATTACH_TRANSITION_RUNNER ?? defaultCapabilityRunnerdBinary() : resolve("runner/target/debug/paperclip-runnerd"),
|
||||
onSpawn: async process => { spawned = process; },
|
||||
controlPlaneRegistration: async authority => {
|
||||
if (emptyController) {
|
||||
@@ -185,19 +188,23 @@ it.each(["local", "local pending finish", "custom local directory", "external la
|
||||
const child = spawn(spec.command, [...spec.args], { cwd: runnerState, env: spec.environment, stdio: "ignore" });
|
||||
const startedAt = new Date().toISOString();
|
||||
spawned = { pid: child.pid!, processGroupId: null, startedAt };
|
||||
return { child, startedAt, completion: new Promise((resolve, reject) => {
|
||||
child.once("error", reject); child.once("exit", (code, signal) => resolve({ code, signal, stdout: "", stderr: "" }));
|
||||
}) };
|
||||
const completion = new Promise<{ code: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string }>((resolve, reject) => {
|
||||
child.once("error", reject); child.once("close", (code, signal) => resolve({ code, signal, stdout: "", stderr: "" }));
|
||||
});
|
||||
ownedChild = child; ownedCompletion = completion;
|
||||
return { child, startedAt, completion };
|
||||
};
|
||||
}
|
||||
let firstFailure: unknown;
|
||||
const driver = new RunnerdDotDriver(options);
|
||||
let session = await driver.openSession({ runId: input.binding.runId, normalizedSessionId: input.session.normalizedSessionId!, workingDirectory: root });
|
||||
let session: Awaited<ReturnType<typeof driver.openSession>> | undefined;
|
||||
const operation = (action: ExternalProviderOperation["action"], args: Record<string, unknown>): ExternalProviderOperation => ({
|
||||
requestId: randomUUID(), bindingId: input.provider.binding.bindingId, bindingGeneration: 1, runId: input.binding.runId,
|
||||
normalizedSessionId: input.session.normalizedSessionId!, turnId: options.identity.turnId, assignmentRevision: 1,
|
||||
action, input: args, digest: externalOperationDigest(action, args),
|
||||
});
|
||||
try {
|
||||
session = await driver.openSession({ runId: input.binding.runId, normalizedSessionId: input.session.normalizedSessionId!, workingDirectory: root });
|
||||
await session.startTurn({ message: { role: "user", text: "Read the synthetic counter." } });
|
||||
await send!(operation("accept", {}));
|
||||
const call = operation("tool", { name: "synthetic_counter", arguments: {} });
|
||||
@@ -221,6 +228,13 @@ it.each(["local", "local pending finish", "custom local directory", "external la
|
||||
const snapshot = await session.snapshot();
|
||||
expect(snapshot).toMatchObject({ providerSessionId: null, activeTurnId: options.identity.turnId, providerRecoveryPolicy: "same_session_only" });
|
||||
await session.detachControllerForRestart!();
|
||||
const priorDaemonPid = spawned!.pid;
|
||||
if (deadDaemon) {
|
||||
expect(ownedChild?.pid).toBe(priorDaemonPid);
|
||||
expect(ownedChild!.kill("SIGTERM")).toBe(true);
|
||||
await ownedCompletion;
|
||||
expect(ownedChild!.exitCode !== null || ownedChild!.signalCode !== null).toBe(true);
|
||||
}
|
||||
if (emptyController) {
|
||||
await rm(options.stateDirectory, { recursive: true });
|
||||
checkpoint!.restoreSessionDirectory(options.stateDirectory);
|
||||
@@ -229,10 +243,11 @@ it.each(["local", "local pending finish", "custom local directory", "external la
|
||||
...(pendingFinish ? { completionFeedback: recoveredCompletion } : {}),
|
||||
...(emptyController ? { runnerBinary: join(root, "unavailable-old-runner"),
|
||||
runnerArtifact: { version: checkpoint!.runnerVersion, digest: checkpoint!.runnerDigest } } : {}),
|
||||
adoptExistingRunner: { ...spawned!, isAlive: () => true } });
|
||||
...(!deadDaemon ? { adoptExistingRunner: { ...spawned!, isAlive: () => true } } : {}) });
|
||||
const recovered = await recoveredDriver.recoverSession(snapshot, { signal: new AbortController().signal });
|
||||
expect(recovered.recovered).toBe(true);
|
||||
session = recovered.session!;
|
||||
if (deadDaemon) expect(spawned!.pid).not.toBe(priorDaemonPid);
|
||||
if (pendingFinish) {
|
||||
expect(options.recoverSemanticToolInput).toBeUndefined();
|
||||
await vi.waitFor(() => expect(settlements.get(finish.requestId)).toMatchObject({ status: "completed", isError: false }), { timeout: 10000 });
|
||||
@@ -246,10 +261,26 @@ it.each(["local", "local pending finish", "custom local directory", "external la
|
||||
await session.close({ reason: "Synthetic test complete" });
|
||||
await rm(join(runnerState, "dot-provider-state.json"));
|
||||
expect(await recoveredDriver.recoverSession(snapshot, { signal: new AbortController().signal })).toMatchObject({ recovered: false });
|
||||
} catch (error) {
|
||||
firstFailure = error; throw error;
|
||||
} finally {
|
||||
await session.close({ reason: "Test cleanup", force: true }).catch(() => {});
|
||||
if (spawned) { try { process.kill(spawned.pid, "SIGTERM"); } catch {} }
|
||||
await rm(root, { recursive: true, force: true });
|
||||
if (deadDaemon) {
|
||||
const cleanupFailures: unknown[] = [];
|
||||
try { await session?.close({ reason: "Test cleanup", force: true }); } catch (error) { cleanupFailures.push(error); }
|
||||
try {
|
||||
if (ownedChild && ownedChild.exitCode === null && ownedChild.signalCode === null) ownedChild.kill("SIGTERM");
|
||||
await ownedCompletion;
|
||||
} catch (error) { cleanupFailures.push(error); }
|
||||
try { await rm(root, { recursive: true, force: true }); } catch (error) { cleanupFailures.push(error); }
|
||||
if (cleanupFailures.length) throw new AggregateError(firstFailure === undefined ? cleanupFailures : [firstFailure, ...cleanupFailures],
|
||||
"Dead external daemon recovery cleanup failed", { cause: firstFailure ?? cleanupFailures[0] });
|
||||
} else {
|
||||
await session?.close({ reason: "Test cleanup", force: true }).catch(() => {});
|
||||
if (ownedChild && ownedChild.exitCode === null && ownedChild.signalCode === null) ownedChild.kill("SIGTERM");
|
||||
await ownedCompletion;
|
||||
if (!ownedChild && spawned) { try { process.kill(spawned.pid, "SIGTERM"); } catch {} }
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}, 45000);
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import express, { type Request } from "express";
|
||||
import request from "supertest";
|
||||
@@ -58,13 +58,15 @@ describe("durable Dot Runner integration", () => {
|
||||
let root: string;
|
||||
beforeAll(async () => {
|
||||
const runnerRoot = fileURLToPath(new URL("../../../packages/paperclip-runner/", import.meta.url));
|
||||
execFileSync("cargo", ["build", "--release", "--locked", "--manifest-path", join(runnerRoot, "runner/Cargo.toml"), "-p", "paperclip-runner-core", "--bin", "paperclip-runnerd"], { cwd: runnerRoot, stdio: "inherit", timeout: 300000 });
|
||||
const prebuiltRunner = process.env.PAPERCLIP_ATTACH_TRANSITION_RUNNER;
|
||||
if (prebuiltRunner && !isAbsolute(prebuiltRunner)) throw new Error("Explicit prebuilt Runner path must be absolute");
|
||||
if (!prebuiltRunner) execFileSync("cargo", ["build", "--release", "--locked", "--manifest-path", join(runnerRoot, "runner/Cargo.toml"), "-p", "paperclip-runner-core", "--bin", "paperclip-runnerd"], { cwd: runnerRoot, stdio: "inherit", timeout: 300000 });
|
||||
if (externalUrl) await applyPendingMigrations(externalUrl);
|
||||
else temporary = await startEmbeddedPostgresTestDatabase("paperclip-dot-runner-");
|
||||
db = createDb(externalUrl ?? temporary.connectionString);
|
||||
root = await mkdtemp(join(tmpdir(), "paperclip-dot-state-"));
|
||||
vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false");
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_BINARY", join(runnerRoot, "runner/target/release", process.platform === "win32" ? "paperclip-runnerd.exe" : "paperclip-runnerd"));
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_BINARY", prebuiltRunner ?? join(runnerRoot, "runner/target/release", process.platform === "win32" ? "paperclip-runnerd.exe" : "paperclip-runnerd"));
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", join(root, "runner-state"));
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", randomBytes(32).toString("base64"));
|
||||
await instanceSettingsService(db).updateExperimental({ enablePublicMcp: true, enableOpenAiDot: true, enableNativeRunner: false });
|
||||
|
||||
@@ -13,7 +13,7 @@ import * as ownerProof from "../owner-proof.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 { DurablePrpControlPlane, externalOperationDigest } 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";
|
||||
@@ -485,6 +485,7 @@ import {
|
||||
verifyRemoteRunnerReattachment,
|
||||
stopStaleRemoteRunnerBeforeBootstrap,
|
||||
verifyRemoteRunnerOrSettledExit,
|
||||
canRestartExternalRunnerCheckpoint,
|
||||
nativeRecoveryCommandUnanswered,
|
||||
nativeUnansweredRunnerReplacementDisposition,
|
||||
nativeAdmittedProviderAttemptLimit,
|
||||
@@ -1171,6 +1172,50 @@ describe("remote controller restart adoption", () => {
|
||||
target: exitedRunner({ ...externalReady, pendingProviderCleanup: { pid: 7 } }) as never })).rejects.toMatchObject({ code: "runner_remote_process_identity_unavailable" });
|
||||
expect(input.checkpointRecoveryEligible).not.toHaveBeenCalled();
|
||||
});
|
||||
const admittedExternal = () => {
|
||||
const expected = { provider: "openai_dot" as const, companyId: "company", agentId: "agent", bindingId: "binding",
|
||||
bindingGeneration: 1, expiresAtUnixMs: Date.now() + 60000, runId: "run", sessionId: "session", turnId: "turn" };
|
||||
const saved = { schema: "paperclip.runner.dot-provider-state.v1", runId: "run", sessionId: "session", turnId: "turn",
|
||||
lifecycle: "running", completion: null, completionInput: null,
|
||||
descriptor: { kind: expected.provider, companyId: expected.companyId, agentId: expected.agentId,
|
||||
bindingId: expected.bindingId, bindingGeneration: expected.bindingGeneration, expiresAtUnixMs: expected.expiresAtUnixMs },
|
||||
tools: { pending: {} }, operations: { stable: { outcome: { status: "completed" } } } };
|
||||
return { expected, saved };
|
||||
};
|
||||
it("the external checkpoint owner accepts only its current settled replay tuple", () => {
|
||||
const { expected, saved } = admittedExternal();
|
||||
expect(canRestartExternalRunnerCheckpoint(saved, expected)).toBe(true);
|
||||
expect(canRestartExternalRunnerCheckpoint(null, expected)).toBe(false);
|
||||
for (const field of ["runId", "sessionId", "turnId", "schema"])
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...saved, [field]: "foreign" }, expected)).toBe(false);
|
||||
for (const field of Object.keys(saved.descriptor))
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...saved, descriptor: { ...saved.descriptor, [field]: "foreign" } }, expected)).toBe(false);
|
||||
expect(canRestartExternalRunnerCheckpoint(saved, { ...expected, expiresAtUnixMs: 1 })).toBe(false);
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...saved, tools: { pending: { effect: {} } } }, expected)).toBe(false);
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...saved, operations: { effect: { outcome: { status: "unknown" } } } }, expected)).toBe(false);
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...saved, completionInput: {} }, expected)).toBe(false);
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...saved, descriptor: { ...saved.descriptor, kind: "muse" } }, expected)).toBe(false);
|
||||
});
|
||||
it("recovers the actual settled accept acknowledgement without treating pending work as settled", () => {
|
||||
const { expected, saved } = admittedExternal();
|
||||
const requestId = "75920c98-56cb-45d3-a299-3e5c6503307d";
|
||||
const operation = { requestId, bindingId: expected.bindingId, bindingGeneration: expected.bindingGeneration,
|
||||
runId: expected.runId, normalizedSessionId: expected.sessionId, turnId: expected.turnId,
|
||||
assignmentRevision: 1, action: "accept", input: {}, digest: externalOperationDigest("accept", {}) };
|
||||
const accepted = { ...saved, assignmentRevision: 1,
|
||||
operations: { [requestId]: { operation, outcome: { status: "accepted" } } } };
|
||||
expect(canRestartExternalRunnerCheckpoint(accepted, expected)).toBe(true);
|
||||
for (const field of ["requestId", "bindingId", "bindingGeneration", "runId", "normalizedSessionId", "turnId", "assignmentRevision", "action", "digest"])
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...accepted,
|
||||
operations: { [requestId]: { operation: { ...operation, [field]: "foreign" }, outcome: { status: "accepted" } } } }, expected)).toBe(false);
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...accepted,
|
||||
operations: { [requestId]: { operation: { ...operation, input: { unexpected: true },
|
||||
digest: externalOperationDigest("accept", { unexpected: true }) }, outcome: { status: "accepted" } } } }, expected)).toBe(false);
|
||||
for (const status of ["pending", "unknown"])
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...accepted,
|
||||
operations: { [requestId]: { operation, outcome: { status } } } }, expected)).toBe(false);
|
||||
expect(canRestartExternalRunnerCheckpoint({ ...accepted, tools: { pending: { effect: {} } } }, expected)).toBe(false);
|
||||
});
|
||||
const exitedBeforeOpen = { lifecycle: "ready", outbox: [{ id: 127 }], pendingTerminalDelivery: null, pendingProviderCleanup: null };
|
||||
it("starts a new runner when the previous attempt's runner exited before answering session.open", async () => {
|
||||
const error = await verifyRemoteRunnerOrSettledExit({ claim, target: exitedRunner(exitedBeforeOpen) as never, identity,
|
||||
|
||||
@@ -218,6 +218,7 @@ import {
|
||||
inspectRetainedRunInstructions,
|
||||
inspectWarmRunTransition,
|
||||
parseNativeExecutionInput,
|
||||
externalOperationDigest,
|
||||
parsePaperclipQuestionSet,
|
||||
resolveSourceCodexHome,
|
||||
readRunnerdArtifactBinding,
|
||||
@@ -15559,7 +15560,8 @@ async function observeUnansweredRunnerProgress(input: {
|
||||
export async function verifyRemoteRunnerOrSettledExit(
|
||||
input: Parameters<typeof verifyRemoteRunnerReattachment>[0] & { providerAttempt: number;
|
||||
claim: { exitedBeforeSessionOpen?: true; replaceUnansweredRunner?: true };
|
||||
unansweredRunnerProgress?: UnansweredRunnerProgressProbe; admittedAttemptLimit?: number },
|
||||
unansweredRunnerProgress?: UnansweredRunnerProgressProbe; admittedAttemptLimit?: number;
|
||||
checkpointRecoveryEligible?: () => Promise<boolean> },
|
||||
): Promise<Awaited<ReturnType<typeof verifyRemoteRunnerReattachment>> | undefined> {
|
||||
const recoveryDeadline = Math.min(input.recoveryDeadline ?? Number.POSITIVE_INFINITY,
|
||||
Date.now() + REMOTE_RUNNER_RECOVERY_PROBE_BUDGET_MS);
|
||||
@@ -15577,15 +15579,21 @@ export async function verifyRemoteRunnerOrSettledExit(
|
||||
const freshBootstrap = diagnostic !== null && exitedRunnerRequestedFreshBootstrap(diagnostic);
|
||||
const attemptLimit = Math.max(input.admittedAttemptLimit ?? 0, freshBootstrap && input.claim.replaceUnansweredRunner === true
|
||||
? NATIVE_PROVIDER_RECOVERY_ATTEMPT_LIMIT + 1 : NATIVE_PROVIDER_RECOVERY_ATTEMPT_LIMIT);
|
||||
const checkpointedRestart = input.checkpointRecoveryEligible !== undefined &&
|
||||
input.providerAttempt <= NATIVE_PROVIDER_RECOVERY_ATTEMPT_LIMIT &&
|
||||
diagnostic?.stage === "process_verification" && diagnostic.reason === "process_not_running" &&
|
||||
diagnostic.runnerLifecycle === "ready" && diagnostic.runnerSettled === true &&
|
||||
await input.checkpointRecoveryEligible().catch(() => false) === true;
|
||||
if (input.providerAttempt > attemptLimit || diagnostic?.stage !== "process_verification" ||
|
||||
diagnostic.reason !== "process_not_running" ||
|
||||
(!exitedBeforeSessionOpen && !freshBootstrap &&
|
||||
(!exitedBeforeSessionOpen && !freshBootstrap && !checkpointedRestart &&
|
||||
(diagnostic.runnerLifecycle !== "suspended" || diagnostic.runnerSettled !== true)) ||
|
||||
target?.kind !== "remote" || target.transport !== "sandbox" || !target.runner) throw error;
|
||||
const state = await readRemoteRunnerState({ runner: target.runner,
|
||||
stateDirectory: remoteRunnerStateDirectory(target.remoteCwd, input.normalizedSessionId), recoveryDeadline, stall });
|
||||
if (REMOTE_RUNNER_IDENTITY_FIELDS.some(field => state[field] !== input.identity[field])) throw error;
|
||||
if (freshBootstrap ? !runnerStateRequestsFreshBootstrap(state) : exitedBeforeSessionOpen ? !runnerStateAllowsFreshStart(state)
|
||||
if (checkpointedRestart ? state.lifecycle !== "ready" || !describeExitedRemoteRunner(state).runnerSettled || state.warmTransition != null
|
||||
: freshBootstrap ? !runnerStateRequestsFreshBootstrap(state) : exitedBeforeSessionOpen ? !runnerStateAllowsFreshStart(state)
|
||||
: state.lifecycle !== "suspended" || !describeExitedRemoteRunner(state).runnerSettled) throw error;
|
||||
return undefined;
|
||||
}
|
||||
@@ -16252,6 +16260,39 @@ export async function createRunnerdBackend(input: {
|
||||
}
|
||||
}
|
||||
|
||||
export function canRestartExternalRunnerCheckpoint(saved: Record<string, unknown> | null, expected: {
|
||||
provider: "openai_dot" | "grok_bot"; companyId: string; agentId: string;
|
||||
bindingId: string; bindingGeneration: number; expiresAtUnixMs: number;
|
||||
runId: string; sessionId: string; turnId: string;
|
||||
}): boolean {
|
||||
const descriptor = record(saved?.descriptor);
|
||||
const tools = record(saved?.tools);
|
||||
const operations = record(saved?.operations);
|
||||
return ["openai_dot", "grok_bot"].includes(expected.provider) && expected.expiresAtUnixMs > Date.now() &&
|
||||
saved?.schema === "paperclip.runner.dot-provider-state.v1" &&
|
||||
saved.runId === expected.runId && saved.sessionId === expected.sessionId && saved.turnId === expected.turnId &&
|
||||
saved.lifecycle === "running" && saved.completion === null && saved.completionInput === null &&
|
||||
descriptor.kind === expected.provider && descriptor.companyId === expected.companyId &&
|
||||
descriptor.agentId === expected.agentId && descriptor.bindingId === expected.bindingId &&
|
||||
descriptor.bindingGeneration === expected.bindingGeneration && descriptor.expiresAtUnixMs === expected.expiresAtUnixMs &&
|
||||
tools.pending != null && typeof tools.pending === "object" && !Array.isArray(tools.pending) &&
|
||||
Object.keys(record(tools.pending)).length === 0 && saved.operations != null &&
|
||||
typeof saved.operations === "object" && !Array.isArray(saved.operations) &&
|
||||
Object.entries(operations).every(([requestId, receipt]) => {
|
||||
const status = record(record(receipt).outcome).status;
|
||||
if (status === "completed" || status === "rejected") return true;
|
||||
const operation = record(record(receipt).operation);
|
||||
return status === "accepted" && operation.action === "accept" && operation.requestId === requestId &&
|
||||
operation.runId === expected.runId && operation.normalizedSessionId === expected.sessionId &&
|
||||
operation.turnId === expected.turnId && operation.bindingId === expected.bindingId &&
|
||||
operation.bindingGeneration === expected.bindingGeneration &&
|
||||
Number.isSafeInteger(saved.assignmentRevision) && Number(saved.assignmentRevision) > 0 &&
|
||||
operation.assignmentRevision === saved.assignmentRevision && operation.input != null &&
|
||||
typeof operation.input === "object" && !Array.isArray(operation.input) && Object.keys(operation.input).length === 0 &&
|
||||
operation.digest === externalOperationDigest("accept", record(operation.input));
|
||||
});
|
||||
}
|
||||
|
||||
/** Dot uses the same managed process launcher and authenticated PRP transports.
|
||||
* Its execution contract still exposes no workspace, shell, or provider secrets. */
|
||||
async function prepareRemoteExternalRunner({ input, target, runner, root, identity }: {
|
||||
@@ -16294,10 +16335,12 @@ async function prepareRemoteExternalRunner({ input, target, runner, root, identi
|
||||
throw new Error("runner_remote_artifact_verification_failed");
|
||||
}
|
||||
};
|
||||
const readProviderState = async () => {
|
||||
const readProviderState = async (deadline?: number) => {
|
||||
const timeoutMs = deadline === undefined ? 10000 : Math.min(10000, deadline - Date.now());
|
||||
if (timeoutMs <= 0) throw new Error("dot_provider_checkpoint_unavailable");
|
||||
const result = await runner.execute({ command: "sh", args: ["-c",
|
||||
'set -eu; if test ! -e "$1" && test ! -L "$1"; then exit 3; fi; test -f "$1" && test ! -L "$1"; test "$(wc -c < "$1")" -le 33554432; base64 < "$1"',
|
||||
"paperclip-dot-checkpoint", posix.join(runnerStateDirectory, checkpointFile)], bypassSession: true, timeoutMs: 10000 });
|
||||
"paperclip-dot-checkpoint", posix.join(runnerStateDirectory, checkpointFile)], bypassSession: true, timeoutMs });
|
||||
if (result.exitCode === 3 && !result.timedOut) return null;
|
||||
if (result.exitCode !== 0 || result.timedOut) throw new Error("dot_provider_checkpoint_unavailable");
|
||||
const state = record(JSON.parse(Buffer.from(result.stdout.replace(/\s+/g, ""), "base64").toString("utf8")));
|
||||
@@ -16320,10 +16363,21 @@ async function prepareRemoteExternalRunner({ input, target, runner, root, identi
|
||||
let identityFailed: (error: unknown) => void = () => {};
|
||||
const processIdentityReady = new Promise<void>((resolve, reject) => { identityReady = resolve; identityFailed = reject; });
|
||||
void processIdentityReady.catch(() => {});
|
||||
const provider = input.execution.provider;
|
||||
const externalCheckpoint = provider.kind === "openai_dot" || provider.kind === "grok_bot" ? {
|
||||
provider: provider.kind, companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId,
|
||||
bindingId: provider.binding.bindingId, bindingGeneration: provider.binding.bindingGeneration,
|
||||
expiresAtUnixMs: provider.binding.expiresAtUnixMs,
|
||||
runId: identity.runId, sessionId: identity.normalizedSessionId, turnId: identity.turnId,
|
||||
} : null;
|
||||
const reattachmentDeadline = Date.now() + REMOTE_RUNNER_RECOVERY_PROBE_BUDGET_MS;
|
||||
const adoptExistingRunner = input.restartRecovery?.kind === "reattach_remote_runner"
|
||||
? await verifyRemoteRunnerOrSettledExit({ claim: input.restartRecovery, target, identity: { ...identity },
|
||||
runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution),
|
||||
providerAttempt: input.restartRecovery.providerAttempt }) : undefined;
|
||||
providerAttempt: input.restartRecovery.providerAttempt, recoveryDeadline: reattachmentDeadline,
|
||||
...(externalCheckpoint ? { checkpointRecoveryEligible: async () =>
|
||||
canRestartExternalRunnerCheckpoint(await readProviderState(reattachmentDeadline), externalCheckpoint) } : {}),
|
||||
}) : undefined;
|
||||
if (adoptExistingRunner) { spawned(); identityReady(); }
|
||||
const launch = createRemoteRunnerProcessLauncher({ target, runner, remoteBinary,
|
||||
processIdentityPath: posix.join(runnerStateDirectory, "runner-process.identity"), stateDirectory: runnerStateDirectory,
|
||||
|
||||
Reference in new issue
Block a user