Recognize exact stopped environment resources during read-only runner monitoring

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-11-11 06:55:51 -06:00
1 parent a5a7e27c0a
commit ce9dde250b
11 files changed
+435 -28

No files matched your search

@@ -759,6 +759,38 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device
}catch{process.stderr.write("owned_checkpoint_frontier_witness_unwritten\n");}
throw primary;
}
const preFaultAssignments=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,failedRunId));
expect(preFaultAssignments).toHaveLength(1);
let assignment=preFaultAssignments[0];
expect(assignment).toMatchObject({bindingId:pairing.body.bindingId,agentId,companyId,runId:failedRunId,status:"offered"});
const preFaultRead=await tool(raw,"paperclip_dot_read",{assignmentId:assignment.id});
expect(preFaultRead.status).toBe(200);expect(preFaultRead.body.result.isError).toBe(false);
const operation=async(name:"paperclip_dot_accept"|"paperclip_dot_tool"|"paperclip_dot_finish",input:Record<string,unknown>,requestId=randomUUID(),expectedStatus:"completed"|"rejected"="completed")=>{
const action=({paperclip_dot_accept:"accept",paperclip_dot_tool:"tool",paperclip_dot_finish:"finish"} as const)[name];
const expectedOutcome=expectedStatus==="rejected"?"rejected":action==="accept"?"accepted":"completed";
const sent=await tool(raw,name,{assignmentId:assignment.id,requestId,...input});expect(sent.status,JSON.stringify(sent.body)).toBe(200);expect(sent.body.result.isError,JSON.stringify(sent.body)).toBe(false);
let receipt:Record<string,unknown>|undefined;
await vi.waitFor(async()=>{
const polled=await tool(raw,"paperclip_dot_operation_status",{assignmentId:assignment.id,requestId});expect(polled.status,JSON.stringify(polled.body)).toBe(200);expect(polled.body.result.isError,JSON.stringify(polled.body)).toBe(false);
receipt=polled.body.result.structuredContent.result;expect(receipt?.status,JSON.stringify({name,requestId,receipt})).toBe(expectedOutcome);
const rows=await db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId,requestId));expect(rows).toHaveLength(1);const journal=rows[0];
expect(journal).toMatchObject({companyId,assignmentId:assignment.id,requestId,status:expectedStatus,digest:externalOperationDigest(action,input)});
expect(journal.command).toEqual({bindingId:assignment.bindingId,bindingGeneration:assignment.bindingGeneration,runId,normalizedSessionId:assignment.normalizedSessionId,turnId:assignment.turnId,assignmentRevision:assignment.revision,requestId,action,input,digest:externalOperationDigest(action,input)});
expect(journal.outcome).toEqual(receipt);if(expectedStatus==="completed")expect(journal.sourceEventId).not.toBeNull();
if(action==="accept"&&expectedStatus==="completed"){
const [accepted]=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.id,assignment.id));
expect(accepted).toMatchObject({companyId,agentId,bindingId:assignment.bindingId,bindingGeneration:assignment.bindingGeneration,runId,status:"accepted"});expect(accepted.acceptedAt).toBeInstanceOf(Date);
}
},{timeout:10_000,interval:50});return{requestId,receipt:receipt!};
};
// Exercise the original permission rejection at the actual pre-accept
// frontier. No useful operation is admitted before the owned fault.
const deniedId=randomUUID();const denied=await operation("paperclip_dot_tool",{name:"write_document",arguments:{key:"before-accept",title:"Forbidden",body:"must not exist",baseRevisionId:null,idempotencyKey:deniedId}},deniedId,"rejected");expect(denied.receipt).toMatchObject({status:"rejected"});expect(await documentService(db).getIssueDocumentByKey(task.id,"before-accept")).toBeNull();
const preFaultAcceptId=randomUUID();
const preFaultAccept=await operation("paperclip_dot_accept",{},preFaultAcceptId);
const preFaultAcceptReplay=await operation("paperclip_dot_accept",{},preFaultAcceptId);
expect(preFaultAcceptReplay.receipt).toEqual(preFaultAccept.receipt);
expect(await documentService(db).getIssueDocumentByKey(task.id,"report")).toBeNull();
if(!childControl)throw new Error("Missing actual installed child provider owner");
const fault=z.object({status:z.literal("stopped"),runId:z.literal(failedRunId),providerLeaseId:z.string(),containerId:z.string(),
kernel:z.object({pid:z.number().int().positive(),fingerprint:z.string()}).passthrough(),checkpoint:z.object({recoveryMode:z.literal("exact_checkpoint_resume")}).passthrough(),
@@ -766,9 +798,13 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device
.parse((await childControl.request({command:"stop-checkpointed",runId:failedRunId,environmentId:environment.body.id},childDeadline())).result);
expect(fault.termination).toEqual({providerLeaseId:fault.providerLeaseId,state:"stopped"});
let failureEpisode:Record<string,unknown>|undefined;
const historyObservationStartedAt=Date.now();
let lastHistoryObservation:{observedAt:number;historyCount:number;retryableCount:number}|undefined;
try {
await vi.waitFor(async()=>{
const [owner]=await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId,failedRunId));
const episodes=owner?.recoveryHistory.filter(row=>row.disposition==="retryable_failure")??[];
lastHistoryObservation={observedAt:Date.now(),historyCount:Math.min(owner?.recoveryHistory.length??0,21),retryableCount:Math.min(episodes.length,21)};
expect(episodes).toHaveLength(1);failureEpisode=episodes[0];
expect(failureEpisode).toMatchObject({checkpointExists:true,providerSessionEstablished:true});
// Observe the actual native settlement category; never substitute the
@@ -777,6 +813,18 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device
"provider_stdout_closed","provider_process_output_closed"]).toContain(failureEpisode.reason);
expect(Date.parse(String(failureEpisode.at))).toBeGreaterThan(0);
},{timeout:30_000,interval:50});
} catch(primary) {
// Failure-only timestamps/counts from the SAME existing wait callback.
// No extra SQL, child request, retry, identity or provider observation.
try {
const destination=process.env.PAPERCLIP_DOT_ACCEPTANCE_RECEIPT;
if(!destination||!path.isAbsolute(destination))throw new Error("private_witness_destination_required");
await writeFile(destination+".recovery-history-frontier.json",JSON.stringify({version:1,
historyObservationStartedAt,caughtAt:Date.now(),lastHistoryObservation,
noAdditionalCalls:true,originalFailureRethrown:true})+"\n",{flag:"wx",mode:0o600});
}catch{process.stderr.write("owned_recovery_history_witness_unwritten\n");}
throw primary;
}
expect(await documentService(db).getIssueDocumentByKey(task.id,"report")).toBeNull();
const failedAssignments=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,failedRunId));
expect(failedAssignments).toHaveLength(1);
@@ -805,28 +853,9 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device
expect(await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,runId))).toHaveLength(1);
},{timeout:30_000,interval:50});
const successorAssignments=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId,runId));
const assignment=successorAssignments[0];expect(assignment).toMatchObject({bindingId:pairing.body.bindingId,agentId,companyId});
assignment=successorAssignments[0];expect(assignment).toMatchObject({bindingId:pairing.body.bindingId,agentId,companyId});
expect(["offered","accepted"]).toContain(assignment.status);
const assigned=await tool(raw,"paperclip_dot_read",{assignmentId:assignment.id});expect(assigned.body.result.isError,JSON.stringify(assigned.body)).toBe(false);
const operation=async(name:"paperclip_dot_accept"|"paperclip_dot_tool"|"paperclip_dot_finish",input:Record<string,unknown>,requestId=randomUUID(),expectedStatus:"completed"|"rejected"="completed")=>{
const action=({paperclip_dot_accept:"accept",paperclip_dot_tool:"tool",paperclip_dot_finish:"finish"} as const)[name];
const expectedOutcome=expectedStatus==="rejected"?"rejected":action==="accept"?"accepted":"completed";
const sent=await tool(raw,name,{assignmentId:assignment.id,requestId,...input});expect(sent.status,JSON.stringify(sent.body)).toBe(200);expect(sent.body.result.isError,JSON.stringify(sent.body)).toBe(false);
let receipt:Record<string,unknown>|undefined;
await vi.waitFor(async()=>{
const polled=await tool(raw,"paperclip_dot_operation_status",{assignmentId:assignment.id,requestId});expect(polled.status,JSON.stringify(polled.body)).toBe(200);expect(polled.body.result.isError,JSON.stringify(polled.body)).toBe(false);
receipt=polled.body.result.structuredContent.result;expect(receipt?.status,JSON.stringify({name,requestId,receipt})).toBe(expectedOutcome);
const rows=await db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId,requestId));expect(rows).toHaveLength(1);const journal=rows[0];
expect(journal).toMatchObject({companyId,assignmentId:assignment.id,requestId,status:expectedStatus,digest:externalOperationDigest(action,input)});
expect(journal.command).toEqual({bindingId:assignment.bindingId,bindingGeneration:assignment.bindingGeneration,runId,normalizedSessionId:assignment.normalizedSessionId,turnId:assignment.turnId,assignmentRevision:assignment.revision,requestId,action,input,digest:externalOperationDigest(action,input)});
expect(journal.outcome).toEqual(receipt);if(expectedStatus==="completed")expect(journal.sourceEventId).not.toBeNull();
if(action==="accept"&&expectedStatus==="completed"){
const [accepted]=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.id,assignment.id));
expect(accepted).toMatchObject({companyId,agentId,bindingId:assignment.bindingId,bindingGeneration:assignment.bindingGeneration,runId,status:"accepted"});expect(accepted.acceptedAt).toBeInstanceOf(Date);
}
},{timeout:10_000,interval:50});return{requestId,receipt:receipt!};
};
const deniedId=randomUUID();const denied=await operation("paperclip_dot_tool",{name:"write_document",arguments:{key:"before-accept",title:"Forbidden",body:"must not exist",baseRevisionId:null,idempotencyKey:deniedId}},deniedId,"rejected");expect(denied.receipt).toMatchObject({status:"rejected"});expect(await documentService(db).getIssueDocumentByKey(task.id,"before-accept")).toBeNull();
await operation("paperclip_dot_accept",{});expect((await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.id,assignment.id)))[0].status).toBe("accepted");
const writeId=randomUUID(),writeArgs={name:"write_document",arguments:{key:"report",title:"Arithmetic",body:"17 + 25 = 42.",baseRevisionId:null,idempotencyKey:writeId}};
const written=await operation("paperclip_dot_tool",writeArgs,writeId);expect(written.receipt).toMatchObject({status:"completed",isError:false});expect((await documentService(db).getIssueDocumentByKey(task.id,"report"))?.body).toBe("17 + 25 = 42.");
@@ -220,7 +220,7 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
beforeEach(async () => {
orphanCleanupSpoolDir = await mkdtemp(path.join(os.tmpdir(), "orphan-cleanup-spool-"));
process.env.SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR = orphanCleanupSpoolDir;
db = createDb(connectionString);
db = createDb(connectionString, { maxConnections: 4 });
runtime = environmentRuntimeService(db);
});
@@ -2919,6 +2919,69 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
return { companyId, environment, runId, pluginId };
}
it("observes exact stopped plugin resources without converting unknown transport failures", async () => {
const { companyId, environment, runId, pluginId } = await seedFakePluginSandbox();
const transportError = new Error("controlled_provider_transport_failed");
let inspection: { providerLeaseId: string; state: "active" | "stopped" | "destroyed" | "unknown" } | undefined;
let inspectionFails = false;
let executeCalls = 0;
let inspectionCalls = 0;
const workerManager = {
isRunning: vi.fn((id: string) => id === pluginId),
getWorker: vi.fn(() => ({ supportedMethods: [
"environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease", "environmentInspectLease",
] })),
call: vi.fn(async (id: string, method: string, params: unknown, timeoutMs: number) => {
expect(id).toBe(pluginId);
if (method === "environmentAcquireLease") return {
providerLeaseId: "controlled-resource",
metadata: { provider: "fake-plugin", image: "fake:test", timeoutMs: 1234, reuseLease: false, remoteCwd: "/workspace" },
};
if (method === "environmentExecute") { executeCalls += 1; throw transportError; }
if (method === "environmentInspectLease") {
inspectionCalls += 1;
expect(params).toMatchObject({
driverKey: "fake-plugin", companyId, environmentId: environment.id,
providerLeaseId: "controlled-resource", config: { image: "fake:test", timeoutMs: 1234, reuseLease: false },
});
expect(timeoutMs).toBeGreaterThan(0);
expect(timeoutMs).toBeLessThanOrEqual(1000);
if (inspectionFails) throw new Error("controlled_inspection_failed");
return inspection;
}
throw new Error("unexpected_controlled_plugin_method");
}),
} as unknown as PluginWorkerManager;
const controlled = environmentRuntimeService(db, { pluginWorkerManager: workerManager });
const acquired = await controlled.acquireRunLease({
companyId, environment, issueId: null, heartbeatRunId: runId, persistedExecutionWorkspace: null,
});
const command = () => controlled.execute({
environment, lease: acquired.lease, command: "controlled-no-process", cwd: "/workspace", env: {}, timeoutMs: 1000,
}).catch((error: unknown) => error);
for (const state of ["active", "unknown"] as const) {
inspection = { providerLeaseId: "controlled-resource", state };
expect(await command()).toBe(transportError);
}
inspection = { providerLeaseId: "foreign-resource", state: "stopped" };
expect(await command()).toBe(transportError);
inspection = undefined;
expect(await command()).toBe(transportError);
inspectionFails = true;
expect(await command()).toBe(transportError);
inspectionFails = false;
for (const state of ["stopped", "destroyed"] as const) {
inspection = { providerLeaseId: "controlled-resource", state };
const failed = await command();
// These guards run before the old-runtime causal RED oracle.
expect(executeCalls).toBe(state === "stopped" ? 6 : 7);
expect(acquired.lease.providerLeaseId).toBe("controlled-resource");
expect(failed).toMatchObject({ code: "environment_resource_stopped", state, cause: transportError });
}
expect(inspectionCalls).toBe(7);
expect((await environmentService(db).getLeaseById(acquired.lease.id))?.status).toBe("active");
});
it("runs a plugin-backed lease release under the run-time exec parent, so the teardown span keeps a valid traceparent", async () => {
const { companyId, environment, runId, pluginId } = await seedFakePluginSandbox();
@@ -3,6 +3,8 @@
import assert from "node:assert/strict";
import { mock } from "node:test";
import { request } from "node:http";
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { eq } from "drizzle-orm";
export async function installDotChildPorts(input: {
@@ -10,6 +12,7 @@ export async function installDotChildPorts(input: {
callbackPublicOrigin: string; callbackLoopback: string;
deviceStage: () => "first-select"|"retry-select"|undefined;
emit: (event: Record<string,unknown>) => void;
probeWitnessRoot: string;
}) {
const actual=await import("@paperclipai/db");
const database={queries:0,clients:0,opened:0,closed:0,dedicated:0,listeners:0};
@@ -32,6 +35,37 @@ export async function installDotChildPorts(input: {
return{listen:listener.listen,async close(){await listener.close();if(!closed){closed=true;database.listeners--;}}};},
}});
assert.equal((await import("@paperclipai/db")).createDb,createDb,"Child DB observer did not bind actual module graph");
// Observe the same normal read-only probe promise. No input, runner,
// request, timeout, retry, return value or rejection is changed.
assert(path.isAbsolute(input.probeWitnessRoot));
const probeModule=await import("../../../services/native-runtime/remote-runner-recovery-probe.js");
const {readRemoteRunnerRecoveryError}=await import("../../../services/native-runtime/remote-runner-recovery-diagnostics.js");
const probeCounts={started:0,settled:0,pending:0,rejected:0,overflow:0,witnessWriteFailures:0};
const probeStages={runner_state:0,identity_marker:0,process_verification:0};
const readProbe:typeof probeModule.readRemoteRunnerRecoveryProbe=probe=>{
const startedAt=Date.now(),startedMonotonic=performance.now();
probeCounts.started++;probeCounts.pending++;probeStages[probe.stage]++;
const promise=probeModule.readRemoteRunnerRecoveryProbe(probe);
void promise.then(()=>{probeCounts.settled++;},async error=>{
probeCounts.settled++;probeCounts.rejected++;
const diagnostic=readRemoteRunnerRecoveryError(error);
if(probeCounts.rejected>32){probeCounts.overflow++;return;}
const fixedMessages=new Set(["owned_resource_retiring","owned_execution_resource_inactive","owned_provider_closing"]);
const fixedMessage=error instanceof Error&&fixedMessages.has(error.message)?error.message:"unclassified";
try {
await writeFile(path.join(input.probeWitnessRoot,"first-native-probe-failure.json"),JSON.stringify({version:1,
stage:probe.stage,readOnly:probe.readOnly,startedAt,failedAt:Date.now(),elapsedMs:Math.max(0,performance.now()-startedMonotonic),
reason:diagnostic?.reason??"unclassified",fixedMessage,counts:{...probeCounts},stageCounts:{...probeStages},
noRawPayload:true,noAdditionalCalls:true,originalPromiseReturned:true})+"\n",{flag:"wx",mode:0o600});
}catch(witnessError){
if(!(witnessError instanceof Error&&"code" in witnessError&&witnessError.code==="EEXIST"))probeCounts.witnessWriteFailures++;
}
}).catch(()=>{probeCounts.witnessWriteFailures++;}).finally(()=>{probeCounts.pending--;});
return promise;
};
mock.module(new URL("../../../services/native-runtime/remote-runner-recovery-probe.ts",import.meta.url).href,
{namedExports:{...probeModule,readRemoteRunnerRecoveryProbe:readProbe}});
assert.equal((await import("../../../services/native-runtime/remote-runner-recovery-probe.js")).readRemoteRunnerRecoveryProbe,readProbe);
let authorityRequests=0,callbackRequests=0,unexpectedEventRequests=0,eventFactoryOwners=0,deviceRegistrations=0,authenticateCalls=0,observerPending=0,observerFailures=0,overflow=0,events=0;
const emit=(event:Record<string,unknown>)=>{if(events++>=32){overflow++;return;}input.emit(event);};
const originalFetch=globalThis.fetch;
@@ -90,6 +124,6 @@ export async function installDotChildPorts(input: {
eventFactoryOwners++;return eventModule.createPublicMcpEvents(db,oauth,dispatch,{...options,fetch:eventFetch});}
return eventModule.createPublicMcpEvents(...args);
}}});
return{snapshot:()=>({...database,connections:connections.size,eventFactoryOwners,authorityRequests,callbackRequests,unexpectedEventRequests,deviceRegistrations,authenticateCalls,observerPending,observerFailures,overflow}),
return{snapshot:()=>({...database,connections:connections.size,eventFactoryOwners,authorityRequests,callbackRequests,unexpectedEventRequests,deviceRegistrations,authenticateCalls,observerPending,observerFailures,overflow,probeObservation:{...probeCounts,stages:{...probeStages}}}),
restore(){globalThis.fetch=originalFetch;mock.restoreAll();}};
}
@@ -20,7 +20,7 @@ let stage:"first-select"|"retry-select"|undefined;
const send=(event:Record<string,unknown>)=>{if(!process.connected)throw new Error("owned_child_ipc_disconnected");process.send!(event);};
const restoreCA=beginOwnedPrivateCA({pem:await readFile(input.linuxInput.caBundle,"utf8"),SHA256:input.linuxInput.caSHA256});
let ports:Awaited<ReturnType<typeof installDotChildPorts>>;
try{ports=await installDotChildPorts({...input,deviceStage:()=>stage,emit:send});}
try{ports=await installDotChildPorts({...input,deviceStage:()=>stage,emit:send,probeWitnessRoot:input.linuxInput.providerRoot});}
catch(primary){try{restoreCA();}catch(cleanup){throw new AggregateError([primary,cleanup],"owned_dot_child_port_setup_failed");}throw primary;}
let owner:Awaited<ReturnType<typeof import("./normal-app-generation.js")["startNormalDotAppGeneration"]>>|undefined;
let shutting:Promise<void>|undefined;
@@ -0,0 +1,102 @@
import { afterEach, expect, it, vi } from "vitest";
import type { EnvironmentLease } from "@paperclipai/shared";
import type { PluginEnvironmentLeaseObservation } from "@paperclipai/plugin-sdk";
import { observeStoppedExecutionResource, readEnvironmentResourceObservationFailure } from "./environment-resource-observation.js";
afterEach(() => vi.restoreAllMocks());
const lease: Pick<EnvironmentLease, "id" | "companyId" | "environmentId" | "heartbeatRunId" | "provider" | "providerLeaseId" | "status" | "releasedAt"> = {
id: "lease", companyId: "company", environmentId: "environment", heartbeatRunId: "run",
provider: "controlled-provider", providerLeaseId: "resource", status: "active", releasedAt: null,
};
it.each(["stopped", "destroyed"] as const)("accepts only an exact positive %s observation and retains the original cause", async state => {
const cause = new Error("controlled_transport_failure");
const inspect = vi.fn(async () => ({ providerLeaseId: "resource", state }));
const result = await observeStoppedExecutionResource({
expected: lease, originalError: cause, deadline: performance.now() + 1000,
readCurrentLease: async () => lease, inspect,
});
expect(inspect).toHaveBeenCalledOnce();
expect(result).toMatchObject({ code: "environment_resource_stopped", state, cause });
expect(result?.matches({ leaseId: "lease", environmentId: "environment", providerLeaseId: "resource" })).toBe(true);
expect(result?.matches({ leaseId: "foreign", environmentId: "environment", providerLeaseId: "resource" })).toBe(false);
});
it("can inspect the same retained lease without requiring an active allocation", async () => {
const retained = { ...lease, status: "retained" as const, releasedAt: new Date(1) };
const result = await observeStoppedExecutionResource({
expected: retained, originalError: new Error("transport"), deadline: performance.now() + 1000,
readCurrentLease: async () => retained,
inspect: async () => ({ providerLeaseId: "resource", state: "stopped" }),
});
expect(result?.state).toBe("stopped");
});
it.each([
{ id: "foreign" }, { companyId: "foreign" }, { environmentId: "foreign" },
{ heartbeatRunId: "foreign" }, { provider: "foreign" }, { providerLeaseId: "foreign" },
{ status: "retained" as const }, { releasedAt: new Date(1) },
])("refuses a changed current lease before provider inspection (%j)", async change => {
const original = new Error("transport");
const inspect = vi.fn();
expect(await observeStoppedExecutionResource({
expected: lease, originalError: original, deadline: performance.now() + 1000,
readCurrentLease: async () => ({ ...lease, ...change }), inspect,
})).toBeNull();
expect(inspect).not.toHaveBeenCalled();
expect(readEnvironmentResourceObservationFailure(original)).toBe("lease_changed");
});
it.each([
{ observation: { providerLeaseId: "resource", state: "active" }, reason: "resource_active" },
{ observation: { providerLeaseId: "resource", state: "unknown" }, reason: "resource_unknown" },
{ observation: { providerLeaseId: "foreign", state: "stopped" }, reason: "foreign_observation" },
{ observation: undefined, reason: "inspection_unavailable" },
] satisfies Array<{ observation: PluginEnvironmentLeaseObservation | undefined; reason: string }>)("retains unknown/foreign observation (%s)", async ({ observation, reason }) => {
const original = new Error("transport");
expect(await observeStoppedExecutionResource({
expected: lease, originalError: original, deadline: performance.now() + 1000,
readCurrentLease: async () => lease, inspect: async () => observation,
})).toBeNull();
expect(readEnvironmentResourceObservationFailure(original)).toBe(reason);
});
it.each(["read", "inspect"] as const)("retains a fixed diagnostic for %s failure", async stage => {
const original = new Error("transport");
expect(await observeStoppedExecutionResource({
expected: lease, originalError: original, deadline: performance.now() + 1000,
readCurrentLease: async () => { if (stage === "read") throw new Error("private detail"); return lease; },
inspect: async () => { throw new Error("private detail"); },
})).toBeNull();
expect(readEnvironmentResourceObservationFailure(original)).toBe(stage === "read" ? "lease_read_failed" : "inspection_failed");
});
it.each(["before_read", "after_read", "after_inspect"] as const)("never accepts proof outside the original budget (%s)", async boundary => {
let now = boundary === "before_read" ? 1000 : 0;
vi.spyOn(performance, "now").mockImplementation(() => now);
const original = new Error("transport");
const readCurrentLease = vi.fn(async () => { if (boundary === "after_read") now = 1000; return lease; });
const inspect = vi.fn(async () => { if (boundary === "after_inspect") now = 1000; return { providerLeaseId: "resource", state: "stopped" as const }; });
expect(await observeStoppedExecutionResource({ expected: lease, originalError: original, deadline: 1000, readCurrentLease, inspect })).toBeNull();
if (boundary === "before_read") expect(readCurrentLease).not.toHaveBeenCalled();
if (boundary !== "after_inspect") expect(inspect).not.toHaveBeenCalled();
expect(readEnvironmentResourceObservationFailure(original)).toBe("budget_exhausted");
});
it.each([
{ id: "foreign" }, { companyId: "foreign" }, { environmentId: "foreign" },
{ heartbeatRunId: "foreign" }, { provider: "foreign" }, { providerLeaseId: "rotated" },
{ status: "released" as const }, { releasedAt: new Date(1) },
])("refuses a stale positive when the exact lease changes during inspection (%j)", async change => {
const original = new Error("transport");
let reads = 0;
let inspectionSettled = false;
const result = await observeStoppedExecutionResource({
expected: lease, originalError: original, deadline: performance.now() + 1000,
readCurrentLease: async () => { reads += 1; return inspectionSettled ? { ...lease, ...change } : lease; },
inspect: async () => { inspectionSettled = true; return { providerLeaseId: "resource", state: "stopped" }; },
});
expect(reads).toBe(2);
expect(result).toBeNull();
expect(readEnvironmentResourceObservationFailure(original)).toBe("lease_changed");
});
@@ -0,0 +1,69 @@
import type { EnvironmentLease } from "@paperclipai/shared";
import type { PluginEnvironmentLeaseObservation } from "@paperclipai/plugin-sdk";
type LeaseBinding = Pick<EnvironmentLease, "id" | "companyId" | "environmentId" | "heartbeatRunId" |
"provider" | "providerLeaseId" | "status" | "releasedAt">;
export type ObservedResourceBinding = { leaseId: string; environmentId: string; providerLeaseId: string };
type ObservationFailure = "budget_exhausted" | "lease_read_failed" | "lease_changed" |
"inspection_failed" | "inspection_unavailable" | "foreign_observation" | "resource_active" | "resource_unknown";
const failures = new WeakMap<object, ObservationFailure>();
/** Read-only evidence; never execution, replacement, or cleanup authority. */
export class EnvironmentResourceStoppedError extends Error {
readonly code = "environment_resource_stopped";
constructor(readonly binding: ObservedResourceBinding, readonly state: "stopped" | "destroyed", cause: unknown) {
super("The exact environment resource is positively stopped.", { cause });
this.name = "EnvironmentResourceStoppedError";
}
matches(binding: ObservedResourceBinding | undefined): boolean {
return binding !== undefined && binding.leaseId === this.binding.leaseId &&
binding.environmentId === this.binding.environmentId && binding.providerLeaseId === this.binding.providerLeaseId;
}
}
export function readEnvironmentResourceObservationFailure(error: unknown): ObservationFailure | null {
return error && typeof error === "object" ? failures.get(error) ?? null : null;
}
/** A failed command may hide a stopped namespace. Observe only that SAME lease,
* through its normal provider port, inside the command's original budget. */
export async function observeStoppedExecutionResource<T extends LeaseBinding>(input: {
expected: T; originalError: unknown; deadline: number;
readCurrentLease: () => Promise<T | null>;
inspect: (lease: T, timeoutMs: number) => Promise<PluginEnvironmentLeaseObservation | undefined>;
}): Promise<EnvironmentResourceStoppedError | null> {
const fail = (reason: ObservationFailure) => {
if (input.originalError && typeof input.originalError === "object") failures.set(input.originalError, reason);
return null;
};
const remaining = () => Math.min(15_000, Math.floor(input.deadline - performance.now()));
if (!Number.isFinite(input.deadline) || remaining() < 1) return fail("budget_exhausted");
const expected = { ...input.expected };
let current: T | null;
try { current = await input.readCurrentLease(); } catch { return fail("lease_read_failed"); }
if (!current || !expected.environmentId || !expected.heartbeatRunId || !expected.provider || !expected.providerLeaseId ||
current.id !== expected.id || current.companyId !== expected.companyId || current.environmentId !== expected.environmentId ||
current.heartbeatRunId !== expected.heartbeatRunId || current.provider !== expected.provider ||
current.providerLeaseId !== expected.providerLeaseId || current.status !== expected.status ||
current.releasedAt?.getTime() !== expected.releasedAt?.getTime()) return fail("lease_changed");
const timeoutMs = remaining();
if (timeoutMs < 1) return fail("budget_exhausted");
let observation: PluginEnvironmentLeaseObservation | undefined;
try { observation = await input.inspect(current, timeoutMs); } catch { return fail("inspection_failed"); }
if (remaining() < 1) return fail("budget_exhausted");
if (!observation) return fail("inspection_unavailable");
if (observation.providerLeaseId !== current.providerLeaseId) return fail("foreign_observation");
if (observation.state === "active") return fail("resource_active");
if (observation.state !== "stopped" && observation.state !== "destroyed") return fail("resource_unknown");
// Provider inspection awaited outside the database. A concurrent resume,
// release, or resource rotation must not turn a stale positive into evidence.
let after: T | null;
try { after = await input.readCurrentLease(); } catch { return fail("lease_read_failed"); }
if (!after || after.id !== expected.id || after.companyId !== expected.companyId ||
after.environmentId !== expected.environmentId || after.heartbeatRunId !== expected.heartbeatRunId ||
after.provider !== expected.provider || after.providerLeaseId !== expected.providerLeaseId ||
after.status !== expected.status || after.releasedAt?.getTime() !== expected.releasedAt?.getTime()) return fail("lease_changed");
if (remaining() < 1) return fail("budget_exhausted");
return new EnvironmentResourceStoppedError({ leaseId: current.id, environmentId: expected.environmentId,
providerLeaseId: expected.providerLeaseId }, observation.state, input.originalError);
}
+22 -4
View File
@@ -1,3 +1,4 @@
import { observeStoppedExecutionResource } from "./environment-resource-observation.js";
import { readPluginLoginCredential } from "./plugin-login-credential.js";
import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "./environment-lease-controller.js";
import { RetainedSandboxAbsentError, resumeReplyConfirmsAbsence } from "./retained-sandbox-absent-error.js";
@@ -649,7 +650,7 @@ export interface EnvironmentDriverRunnerIngressInput
export interface EnvironmentRuntimeDriver {
readonly driver: string;
inspectLeaseResource?(input: { environment: Environment | null; lease: EnvironmentLease }): Promise<PluginEnvironmentLeaseObservation | undefined>;
inspectLeaseResource?(input: { environment: Environment | null; lease: EnvironmentLease; deadline?: number }): Promise<PluginEnvironmentLeaseObservation | undefined>;
acquireRunLease(input: EnvironmentDriverAcquireInput): Promise<EnvironmentLease>;
releaseRunLease(input: EnvironmentDriverReleaseInput): Promise<EnvironmentLease | null>;
resumeRunLease?(input: EnvironmentDriverResumeInput): Promise<PluginEnvironmentLease | EnvironmentLease | null>;
@@ -2338,7 +2339,7 @@ function createSandboxEnvironmentDriver(
});
},
async inspectLeaseResource({ lease }) {
async inspectLeaseResource({ lease, deadline }) {
const provider = lease.provider;
const config = sandboxConfigFromLeaseMetadataLoose(lease);
if (!provider || isBuiltinSandboxProvider(provider) || !config || config.provider !== provider ||
@@ -2353,11 +2354,13 @@ function createSandboxEnvironmentDriver(
resolved.resolved.driver.configSchema as Record<string, unknown> | undefined,
{ issueId: lease.issueId, heartbeatRunId: lease.heartbeatRunId });
if (!resolvedConfig) return undefined;
const timeoutMs = deadline === undefined ? 15_000 : Math.min(15_000, Math.floor(deadline - performance.now()));
if (!Number.isFinite(timeoutMs) || timeoutMs < 1) return undefined;
return await pluginWorkerManager.call(pluginId, "environmentInspectLease", {
driverKey: provider, companyId: lease.companyId, environmentId: lease.environmentId,
issueId: lease.issueId, config: stripSandboxProviderEnvelope(resolvedConfig as SandboxEnvironmentConfig),
providerLeaseId: lease.providerLeaseId, leaseMetadata: lease.metadata ?? {},
}, 15_000);
}, timeoutMs);
},
async retryPendingSandboxTeardown(input) {
@@ -4532,7 +4535,22 @@ export function environmentRuntimeService(
if (!driver.execute) {
throw new Error(`Environment driver "${driver.driver}" does not support command execution.`);
}
return await driver.execute(input);
const deadline = typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
? performance.now() + input.timeoutMs : null;
try {
return await driver.execute(input);
} catch (originalError) {
if (deadline !== null && driver.inspectLeaseResource) {
const stopped = await observeStoppedExecutionResource({ expected: input.lease, originalError, deadline,
readCurrentLease: () => environmentsSvc.getLeaseById(input.lease.id),
// Use the driver's existing historical-credential observation port,
// not the failed-ephemeral-cleanup-only public dispatcher.
inspect: (lease, timeoutMs) => driver.inspectLeaseResource!({ environment: input.environment, lease, deadline: Math.min(deadline, performance.now() + timeoutMs) }),
});
if (stopped) throw stopped;
}
throw originalError;
}
},
supportsSync(input: EnvironmentDriverLeaseInput): boolean {
@@ -1,3 +1,5 @@
import { EnvironmentResourceStoppedError } from "../environment-resource-observation.js";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import type { NativeSession } from "../../vendor/paperclip-runner/index.js";
import { currentControllerProcess } from "../controller-process-identity.js";
import { activeNativeExecutionRunIds } from "./native-active-runs.js";
@@ -1229,6 +1231,44 @@ describe("remote runner launch fingerprint compatibility", () => {
});
describe("remote runner process supervision", () => {
it.each(["exact", "foreign"] as const)("joins only exact positively stopped remote resource evidence (%s)", async binding => {
vi.useFakeTimers();
try {
const resource = { leaseId: "lease", environmentId: "environment", providerLeaseId: "resource" };
const stopped = new EnvironmentResourceStoppedError({ ...resource, leaseId: binding === "exact" ? "lease" : "foreign" }, "stopped", new Error("transport"));
let nonce = "";
const ok = { exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "", pid: null, startedAt: "2026-09-06T00:00:00.000Z" };
const execute = vi.fn<CommandManagedRuntimeRunner["execute"]>(async request => {
const label = request.args?.[2];
if (label === "paperclip-runner-launch") { nonce = request.args?.[4] ?? ""; return ok; }
if (label === "paperclip-runner-process-identity") return { ...ok, stdout: `${nonce}\n4321\n2026-09-06T00:00:00.000Z\nrunner-remote\n` };
if (label === "paperclip-runner-monitor") throw stopped;
throw new Error("unexpected_controlled_command");
});
const handle = createRemoteRunnerProcessLauncher({
target: { kind: "remote", transport: "sandbox", environmentId: "environment", leaseId: "lease", remoteCwd: "/workspace",
sandboxLeaseAcquisition: { outcome: "created", providerLeaseId: "resource" } },
runner: { execute }, remoteBinary: "/runtime/runnerd", processIdentityPath: "/runtime/identity",
stateDirectory: "/runtime", diagnosticsDirectory: "/runtime/diagnostics", runnerInstanceId: "runner-remote",
})({ command: "/controller/runnerd", args: [], cwd: "/controller", environment: {} });
const settled = handle.completion.then(result => ({ result }), error => ({ error }));
await vi.runAllTimersAsync();
const outcome = await settled;
const monitors = execute.mock.calls.filter(([request]) => request.args?.[2] === "paperclip-runner-monitor");
if (binding === "exact") {
expect(outcome).toEqual({ result: { code: null, signal: null, stdout: "", stderr: "runner_remote_resource_stopped" } });
expect(handle.isExitConfirmed?.()).toBe(true);
expect(handle.child.exitCode).toBeNull();
expect(monitors).toHaveLength(1);
} else {
expect(outcome).toEqual({ error: stopped });
expect(handle.isExitConfirmed?.()).toBe(false);
expect(monitors.length).toBeGreaterThan(1);
}
expect(execute.mock.calls.every(([request]) => ["paperclip-runner-launch", "paperclip-runner-process-identity", "paperclip-runner-monitor"].includes(request.args?.[2] ?? ""))).toBe(true);
} finally { vi.useRealTimers(); }
});
it.each(["staging", "dispatch trace"])("retains cancellation during %s without a launch RPC", async (boundary) => {
let enter!: () => void;
let release!: () => void;
@@ -1,3 +1,4 @@
import { EnvironmentResourceStoppedError } from "../environment-resource-observation.js";
import { currentControllerProcess } from "../controller-process-identity.js";
import { remoteRecoveryLeaseMismatch } from "./remote-recovery-lease-mismatch.js";
import { isGovernancePauseStop } from "../governance-pause-stop.js";
@@ -14633,8 +14634,15 @@ export function createRemoteRunnerProcessLauncher(input: {
});
while (true) {
const observed = await readRemoteRunnerRecoveryProbe({
const resource = input.target.transport === "sandbox" && input.target.leaseId && input.target.environmentId &&
input.target.sandboxLeaseAcquisition?.providerLeaseId
? { leaseId: input.target.leaseId, environmentId: input.target.environmentId,
providerLeaseId: input.target.sandboxLeaseAcquisition.providerLeaseId } : undefined;
let observed: Awaited<ReturnType<typeof readRemoteRunnerRecoveryProbe>>;
try {
observed = await readRemoteRunnerRecoveryProbe({
runner,
resource,
stage: "process_verification",
deadline: Date.now() + REMOTE_RUNNER_RECOVERY_PROBE_BUDGET_MS,
readOnly: true,
@@ -14653,6 +14661,14 @@ export function createRemoteRunnerProcessLauncher(input: {
bypassSession: true,
},
});
} catch (error) {
if (!(error instanceof EnvironmentResourceStoppedError) || !error.matches(resource)) throw error;
// The verified provider observed the whole owned namespace stopped.
// The individual exit code/signal remain unknown; do not invent 45.
exitConfirmed = true;
child.exitCode = null;
return { code: null, signal: null, stdout: "", stderr: "runner_remote_resource_stopped" };
}
if (observed.exitCode === 0 && !observed.timedOut) {
await new Promise<void>((resolve) =>
setTimeout(resolve, REMOTE_RUNNER_PROCESS_POLL_MS),
@@ -1,3 +1,4 @@
import { EnvironmentResourceStoppedError } from "../environment-resource-observation.js";
import { afterEach, expect, it, vi } from "vitest";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import { readRemoteRunnerRecoveryError } from "./remote-runner-recovery-diagnostics.js";
@@ -88,3 +89,32 @@ it("returns a definitive ownership conflict without retrying it", async () => {
})).toBe(conflict);
expect(execute).toHaveBeenCalledTimes(1);
});
const resource = { leaseId: "lease", environmentId: "environment", providerLeaseId: "resource" };
it("does not retry positive exact stopped-namespace evidence on a read-only process probe", async () => {
const stopped = new EnvironmentResourceStoppedError(resource, "stopped", new Error("transport"));
const execute = vi.fn().mockRejectedValue(stopped);
const result = await readRemoteRunnerRecoveryProbe({
runner: { execute }, request: { command: "sh" }, stage: "process_verification",
readOnly: true, deadline: Date.now() + 30_000, resource,
}).catch(error => error);
expect(result).toBe(stopped);
expect(execute).toHaveBeenCalledOnce();
});
it.each(["foreign", "missing", "other_stage"] as const)("keeps ordinary bounded retries for %s proof", async negative => {
vi.useFakeTimers();
const stopped = new EnvironmentResourceStoppedError(resource, "stopped", new Error("transport"));
const execute = vi.fn().mockRejectedValue(stopped);
const startedAt = Date.now();
const result = readRemoteRunnerRecoveryProbe({
runner: { execute }, request: { command: "sh" },
stage: negative === "other_stage" ? "identity_marker" : "process_verification",
readOnly: true, deadline: startedAt + 1000,
resource: negative === "missing" ? undefined : { ...resource, leaseId: negative === "foreign" ? "foreign" : "lease" },
}).catch(error => error);
await vi.runAllTimersAsync();
expect(await result).toBe(stopped);
expect(execute.mock.calls.length).toBeGreaterThan(1);
expect(Date.now() - startedAt).toBeLessThanOrEqual(1000);
});
@@ -1,3 +1,4 @@
import { EnvironmentResourceStoppedError, type ObservedResourceBinding } from "../environment-resource-observation.js";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import {
attachRemoteRunnerRecoveryDiagnostic,
@@ -13,6 +14,7 @@ export async function readRemoteRunnerRecoveryProbe(input: {
stage: RemoteRunnerRecoveryDiagnostic["stage"];
deadline: number;
readOnly: boolean;
resource?: ObservedResourceBinding;
}) {
let lastError: unknown = new RemoteRunnerRecoveryError({
stage: input.stage, reason: "probe_timeout",
@@ -31,6 +33,10 @@ export async function readRemoteRunnerRecoveryProbe(input: {
if (!result.timedOut) return result;
lastError = new RemoteRunnerRecoveryError({ stage: input.stage, reason: "probe_timeout" });
} catch (error) {
// A positive observation of this exact namespace is not a transient
// transport outage. Never infer this from a message or an unknown state.
if (input.readOnly && input.stage === "process_verification" &&
error instanceof EnvironmentResourceStoppedError && error.matches(input.resource)) throw error;
lastError = attachRemoteRunnerRecoveryDiagnostic(error, {
stage: input.stage, reason: "probe_transport_failed",
});