Merge commit '54f8068df4c16f3916669550b44cc22dd683a6d8' into codex/private-dot-15b-source-union

* commit '54f8068df4c16f3916669550b44cc22dd683a6d8':
  fix(chaos): confirm a task that rests just before its deadline (#21979)
  fix(native): finish a failed warm session's cleanup by itself and continue the task (#21977)
  fix(native): continue a run that reports a system environment blocker (#21959)
This commit is contained in:
Dotta committed 2026-11-17 02:35:04 -06:00
commit ca4764599c
30 files changed
+719 -31

No files matched your search

@@ -2,6 +2,10 @@ import { normalizeLegacyPrpStructuredRunResult } from "../protocol/result-normal
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import {
PRP_BLOCKER_ALREADY_REPORTED_MESSAGE,
PRP_ENVIRONMENT_BLOCKER_ALREADY_REPORTED_MESSAGE,
PRP_SEMANTIC_RESULT_CONFLICT_MESSAGE,
prpSemanticResultConflictMessage,
PRP_BLOCK_RESULT_OUTPUT_SCHEMA,
PRP_BLOCK_RESULT_PROVIDER_INPUT_SCHEMA,
PRP_BLOCK_TOOL_DESCRIPTION,
@@ -291,3 +295,15 @@ describe("provider-neutral completion result schema", () => {
expect(validate(result)).toBe(false);
});
});
describe("semantic result conflict feedback", () => {
it("promises an automatic continuation only for a system environment or tool blocker", () => {
const blocked = (kind: string, reasonCode: string) => ({ reportedWorkDisposition: "blocked", blocker: { owner: { kind }, reasonCode } });
expect(prpSemanticResultConflictMessage(blocked("system", "environment_unavailable"))).toBe(PRP_ENVIRONMENT_BLOCKER_ALREADY_REPORTED_MESSAGE);
expect(prpSemanticResultConflictMessage(blocked("system", "tool_unavailable"))).toBe(PRP_ENVIRONMENT_BLOCKER_ALREADY_REPORTED_MESSAGE);
expect(prpSemanticResultConflictMessage(blocked("user", "credential_missing"))).toBe(PRP_BLOCKER_ALREADY_REPORTED_MESSAGE);
expect(prpSemanticResultConflictMessage(blocked("system", "credential_missing"))).toBe(PRP_BLOCKER_ALREADY_REPORTED_MESSAGE);
expect(prpSemanticResultConflictMessage({ reportedWorkDisposition: "done" })).toBe(PRP_SEMANTIC_RESULT_CONFLICT_MESSAGE);
expect(PRP_BLOCKER_ALREADY_REPORTED_MESSAGE).not.toContain("automatically");
});
});
@@ -6,6 +6,24 @@ export const PRP_COMPLETION_TOOL_DESCRIPTION =
"Report completed work (done), work requiring review (needs_review), or an explicit wait (yielded with response_wake for a response, monitor after set_task_monitor confirms a schedule on this task, or omit continuation to use this run's authorized published-review wait or saved repository-preparation continuation). Use the current completion contract and supporting evidence. If rejected, correct the report and retry. After acceptance, read the returned outcome; do not claim completion while gated. Explain any required approval with its supplied link and action, then write the final response and end the turn without further tool calls.";
export const PRP_BLOCK_TOOL_DESCRIPTION =
"Report work that cannot continue because of a concrete blocker. Routine repository preparation is not a blocker: use paperclip_finish with yielded and omit continuation to resume through the saved workspace continuation. Identify the blocker, its owner, and the action needed to unblock it; use the current completion contract and supporting evidence. If rejected, correct the report and retry. After acceptance, read the returned outcome, explain the blocker and any required action in the final response, and end the turn without further tool calls.";
export const PRP_SEMANTIC_RESULT_CONFLICT_MESSAGE = "A different semantic result was already committed";
export const PRP_BLOCKER_ALREADY_REPORTED_MESSAGE =
"This turn already reported a blocker, and a turn's first accepted report is final, so this report was not recorded. Do not report again in this turn. " +
"In your final response, list the steps that are complete and say whether the blocker still applies, then end the turn.";
export const PRP_ENVIRONMENT_BLOCKER_ALREADY_REPORTED_MESSAGE = PRP_BLOCKER_ALREADY_REPORTED_MESSAGE +
" Paperclip continues this environment or tool blocker automatically in a fresh session that checks the saved work.";
const PRP_ENVIRONMENT_BLOCKER_REASON_CODES: ReadonlySet<string> = new Set(["environment_unavailable", "tool_unavailable"]);
/** Feedback for a later report in a turn that already committed a different one. */
export function prpSemanticResultConflictMessage(committed: {
reportedWorkDisposition: string;
blocker?: { owner?: { kind?: string } | null; reasonCode?: string } | null;
} | null | undefined): string {
if (committed?.reportedWorkDisposition !== "blocked") return PRP_SEMANTIC_RESULT_CONFLICT_MESSAGE;
return committed.blocker?.owner?.kind === "system" && PRP_ENVIRONMENT_BLOCKER_REASON_CODES.has(committed.blocker.reasonCode ?? "")
? PRP_ENVIRONMENT_BLOCKER_ALREADY_REPORTED_MESSAGE : PRP_BLOCKER_ALREADY_REPORTED_MESSAGE;
}
export const PRP_SEMANTIC_TOOL_NAMES = [
PRP_COMPLETION_TOOL_NAME,
PRP_BLOCK_TOOL_NAME,
@@ -23,6 +23,7 @@ import type {
import {
PRP_BLOCK_TOOL_NAME,
PRP_COMPLETION_TOOL_NAME,
prpSemanticResultConflictMessage,
} from "../../contracts/completion-result.js";
import {
HarnessCapabilityUnavailableError,
@@ -1199,7 +1200,7 @@ class CodexAcpxSession implements HarnessSession {
this.#semanticFingerprint !== null &&
this.#semanticFingerprint !== fingerprint
) {
throw new Error("A different semantic result is already committed");
throw new Error(prpSemanticResultConflictMessage(this.#semanticResult));
}
const claimsLaterTurn =
this.#semanticFingerprint === fingerprint &&
@@ -6,6 +6,7 @@ import {
CODEX_BLOCK_TOOL_NAME,
} from "../../contracts/codex.js";
import { validatePrpStructuredRunResult } from "../../protocol/replay-contract.js";
import { prpSemanticResultConflictMessage } from "../../contracts/completion-result.js";
import type { CodexRpcServerRequest } from "./app-server-transport.js";
import {
boundedCodexValue,
@@ -235,9 +236,7 @@ async function handleServerRequestBody(
}
const admission = admitResult(state, validation.result, callId, turnId);
if (admission === "conflict") {
return rejectedToolCall(
"A different semantic result was already committed.",
);
return rejectedToolCall(prpSemanticResultConflictMessage(state.result));
}
return {
success: true,
@@ -30,6 +30,7 @@ import {
type NativeRuntimeContextSnapshot,
} from "../../contracts/runtime-context.js";
import { createCodexTaskEnvelope } from "../../contracts/codex.js";
import { PRP_BLOCKER_ALREADY_REPORTED_MESSAGE } from "../../contracts/completion-result.js";
import { CONFIGURED_ENVIRONMENT_KEYS, configuredEnvironmentProjection } from "../../configured-environment.js";
import { localIntegrityBoundaryGolden } from "../../../test-support/local-integrity-boundary-golden.js";
import type { PrpEvent } from "../../protocol/replay-contract.js";
@@ -2867,6 +2868,27 @@ describe("OpenCodeServerDriver", () => {
await session.close({ reason: "test" });
});
it("tells a provider that a turn's accepted blocker is final when it later tries to finish", async () => {
await chmod(fixture, 0o755);
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-block-finish-"));
const workspace = await mkdtemp(join(tmpdir(), "paperclip-opencode-workspace-"));
roots.push(root, workspace);
const driver = new OpenCodeServerDriver({ model: "openrouter/deepseek/deepseek-v4-flash-0731", runtimeDirectory: root, command: fixture, environment: { PATH: process.env.PATH, OPENROUTER_API_KEY: "fixture-key" } });
const session = await driver.openSession({ runId: "block-then-finish", normalizedSessionId: "block-then-finish", workingDirectory: workspace });
await session.startTurn({ message: { role: "user", text: "block-result finish-after-block" } });
const events = await collectTurnEvents(session.events());
const results = events.filter((event) => event.eventType === "run.result.proposed");
expect(results).toHaveLength(1);
expect(results[0].payload).toMatchObject({ reportedWorkDisposition: "blocked" });
const files = await readdir(root, { recursive: true });
const evidence = files.find((name) => name.endsWith("fake-finish-after-block.json"));
expect(evidence).toBeDefined();
expect(JSON.parse(await readFile(join(root, evidence!), "utf8"))).toMatchObject({ result: { isError: true,
content: [{ text: expect.stringContaining(PRP_BLOCKER_ALREADY_REPORTED_MESSAGE) }] } });
expect(JSON.stringify(JSON.parse(await readFile(join(root, evidence!), "utf8")))).not.toContain("continues this environment or tool blocker");
await session.close({ reason: "test" });
});
it.each(["monitor", "response_wake"] as const)("resolves an omitted %s through the real OpenCode MCP boundary only from current server state", async kind => {
for (const eligible of [true, false]) {
await chmod(fixture, 0o755);
@@ -44,6 +44,7 @@ import {
import {
PRP_BLOCK_TOOL_NAME,
PRP_COMPLETION_TOOL_NAME,
prpSemanticResultConflictMessage,
} from "../../contracts/completion-result.js";
import type {
HarnessDriver,
@@ -1325,7 +1326,7 @@ class OpenCodeHarnessSession implements HarnessSession {
}
const fingerprint = canonicalJson(validation.result);
if (this.#resultFingerprint && this.#resultFingerprint !== fingerprint)
throw new Error("A different semantic result was already committed");
throw new Error(prpSemanticResultConflictMessage(this.#result));
// Wait for the bound controller before committing or resolving the
// provider call. A rejection remains repairable in this same turn.
const feedback = this.#completionFeedback
@@ -1337,7 +1338,7 @@ class OpenCodeHarnessSession implements HarnessSession {
if (typeof feedback !== "string" || !feedback.trim())
throw new Error("Completion feedback omitted its response text");
if (this.#resultFingerprint && this.#resultFingerprint !== fingerprint)
throw new Error("A different semantic result was already committed");
throw new Error(prpSemanticResultConflictMessage(this.#result));
if (!this.#resultFingerprint) {
this.#result = structuredClone(validation.result);
this.#resultFingerprint = fingerprint;
@@ -275,6 +275,47 @@ export function completeTerminatedRemoteNativeSessionCleanup(binding: {
return true;
}
function quarantinedRemoteCleanupScope(
entry: QuarantinedSessionCleanup,
input: { companyId: string; issueId: string },
): string | null {
const [companyId, , , remoteCleanupScope] = JSON.parse(entry.domain.key) as string[];
return companyId === input.companyId && remoteCleanupScope &&
entry.domain.resources.includes(JSON.stringify(["issue", input.issueId]))
? remoteCleanupScope : null;
}
export function nativeSessionCleanupRemoteScopes(input: {
companyId: string;
issueId: string;
}): string[] {
const scopes = new Set<string>();
for (const entry of quarantinedSessionCleanups) {
const scope = quarantinedRemoteCleanupScope(entry, input);
if (scope) scopes.add(scope);
}
return [...scopes];
}
export function completeTerminatedRemoteNativeSessionCleanupForTask(input: {
companyId: string;
issueId: string;
remoteCleanupScope: string;
}): number {
if (!input.remoteCleanupScope) return 0;
let retired = 0;
for (const entry of [...quarantinedSessionCleanups]) {
if (quarantinedRemoteCleanupScope(entry, input) !== input.remoteCleanupScope) continue;
if (entry.attempt || entry.recovery) continue;
if (entry.timer) clearTimeout(entry.timer);
entry.timer = null;
quarantinedSessionCleanups.delete(entry);
announceCleanupSettled(entry.domain);
retired += 1;
}
return retired;
}
/** Host-only counterpart of remote resource termination. The caller has verified
* both exact local process identities and durably fenced their run. This removes
* only cleanup ownership; the retained checkpoint is never made resumable.
@@ -311,6 +311,18 @@ async function callTerminalTool(promptBody, signal) {
arguments: result,
}, signal);
const first = await call();
if (blocked && String(prompt.message ?? "").includes("finish-after-block")) {
const done = structuredClone(result);
done.reportedWorkDisposition = "done";
done.summary = "Fake provider recovered and completed the task.";
done.completionClaim.objectiveSatisfied = true;
done.completionClaim.criteria = done.completionClaim.criteria.map(criterion => ({ ...criterion, status: "satisfied" }));
done.completionClaim.remainingWork = [];
done.attentionRequests = [];
delete done.blocker;
const rejected = await mcpRequest("tools/call", { name: "paperclip_finish", arguments: done });
await writeFile(join(process.env.XDG_DATA_HOME, "fake-finish-after-block.json"), JSON.stringify(rejected));
}
if (String(prompt.message ?? prompt.task?.prompt ?? "").includes("completion-feedback")) {
const outcomes = [first];
if (first.result?.isError && String(prompt.message ?? prompt.task?.prompt ?? "").includes("current-wake-completion-feedback")) {
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { hostname } from "node:os";
import { agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db";
import { agents, companies, createDb, environmentLeases, heartbeatRuns, issues } from "@paperclipai/db";
import {
executeNativeSession,
NativeSessionCloseUnrecoverableError,
@@ -55,7 +55,8 @@ describeEmbeddedPostgres("queued native run behind the task's previous session c
}
async function retainPreviousSessionClose(f: Awaited<ReturnType<typeof seed>>, close: () => Promise<void>,
owner: { runId: string; runnerInstanceId: string } = { runId: randomUUID(), runnerInstanceId: randomUUID() }) {
owner: { runId: string; runnerInstanceId: string } = { runId: randomUUID(), runnerInstanceId: randomUUID() },
remoteCleanupScope?: string) {
const runId = owner.runId;
const identity = { runId, sessionId: `closing-${runId}`, companyId: f.companyId, issueId: f.issueId, agentId: f.previousId };
const capabilities = { resume: true, typedEvents: true, steering: false, interruption: false, structuredResult: true };
@@ -83,6 +84,7 @@ describeEmbeddedPostgres("queued native run behind the task's previous session c
appendEvent: async () => ({ cursor: 0, highestContiguousSourceSeq: 0, disposition: "committed" }),
replayEvents: async () => ({ events: [], highestContiguousSourceSeq: 0 }), completeRun: async () => {} },
runnerInstanceId: owner.runnerInstanceId, controlPlaneInstanceId: "control",
...(remoteCleanupScope ? { remoteCleanupScope } : {}),
})).rejects.toThrow("stopped for reassignment");
}
@@ -167,6 +169,63 @@ describeEmbeddedPostgres("queued native run behind the task's previous session c
expect(await readRun(run.id)).toMatchObject({ status: "queued", startedAt: null, errorCode: null });
});
async function recordSandboxLease(f: Awaited<ReturnType<typeof seed>>, providerLeaseId: string, terminated: boolean) {
const [failed] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.nextId,
invocationSource: "automation", status: "failed", errorCode: "provider_transport_failed", runtimeMode: "native",
nativeIssueId: f.issueId, startedAt: new Date(Date.now() - 60_000), finishedAt: new Date(),
contextSnapshot: { issueId: f.issueId } }).returning();
const leaseId = randomUUID();
await db.insert(environmentLeases).values({ id: leaseId, companyId: f.companyId, issueId: f.issueId,
heartbeatRunId: failed!.id, provider: "fake-sandbox", providerLeaseId, leasePolicy: "ephemeral",
status: terminated ? "released" : "active", releasedAt: terminated ? new Date() : null,
cleanupStatus: terminated ? "success" : null,
metadata: terminated ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId: f.companyId,
runId: failed!.id, leaseId, provider: "fake-sandbox", providerLeaseId, state: "stopped",
confirmedAt: new Date().toISOString() } } : {} });
return { leaseId, runId: failed!.id };
}
it("starts a queued run once the previous session's sandbox is confirmed terminated, whichever run released it", async () => {
const worker = dispatchWorker();
try {
const f = await seed();
const providerLeaseId = `sandbox-${randomUUID()}`;
await retainPreviousSessionClose(f, async () => {
throw new NativeSessionCloseUnrecoverableError({ runnerSuspended: false, providerDrained: false });
}, undefined, JSON.stringify(["fake-sandbox", providerLeaseId]));
expect(nativeSessionCleanupBlock({ companyId: f.companyId, issueId: f.issueId })).toBe("operator_required");
const held = await recordSandboxLease(f, providerLeaseId, false);
const run = await queueNextAssigneeRun(f);
await heartbeatService(db).resumeQueuedRuns();
expect(await readRun(run.id)).toMatchObject({ status: "queued", startedAt: null });
expect(nativeSessionCleanupBlock({ companyId: f.companyId, issueId: f.issueId })).toBe("operator_required");
await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success",
metadata: { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId: f.companyId,
runId: held.runId, leaseId: held.leaseId, provider: "fake-sandbox", providerLeaseId, state: "stopped",
confirmedAt: new Date().toISOString() } } }).where(eq(environmentLeases.id, held.leaseId));
await heartbeatService(db).resumeQueuedRuns();
await expect.poll(async () => (await readRun(run.id)).status, { timeout: 15_000 }).not.toBe("queued");
expect((await readRun(run.id)).errorCode).not.toBe("native_session_cleanup_quarantined");
expect(nativeSessionCleanupBlock({ companyId: f.companyId, issueId: f.issueId })).toBeNull();
} finally {
worker.stop();
}
});
it("keeps the run queued while a different sandbox of the task is terminated", async () => {
const f = await seed();
const providerLeaseId = `sandbox-${randomUUID()}`;
await retainPreviousSessionClose(f, async () => {
throw new NativeSessionCloseUnrecoverableError({ runnerSuspended: false, providerDrained: false });
}, undefined, JSON.stringify(["fake-sandbox", providerLeaseId]));
await recordSandboxLease(f, `other-${providerLeaseId}`, true);
const run = await queueNextAssigneeRun(f);
await heartbeatService(db).resumeQueuedRuns();
expect(await readRun(run.id)).toMatchObject({ status: "queued", startedAt: null });
expect(nativeSessionCleanupBlock({ companyId: f.companyId, issueId: f.issueId })).toBe("operator_required");
});
it("does not hold a run for a different task", async () => {
const f = await seed();
await retainPreviousSessionClose(f, () => new Promise<void>(() => {}));
@@ -901,6 +901,34 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {
},
);
it("cancels an environment-blocker fresh-session retry whose task is reassigned before adapter dispatch", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const replacementAgentId = randomUUID();
await db.insert(agents).values({ id: replacementAgentId, companyId, name: "ReplacementCoder", role: "engineer", status: "active",
adapterType: "codex_local", adapterConfig: {}, runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } }, permissions: {} });
const issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Environment blocker retry reassigned at final dispatch",
status: "in_progress", priority: "medium", assigneeAgentId: agentId });
const { runId } = await seedQueuedRun({ companyId, agentId, issueId, wakeReason: "native_environment_blocker",
invocationSource: "automation", scheduledRetryReason: "native_environment_blocker",
contextExtras: { retryReason: "native_environment_blocker", forceFreshSession: true } });
let guarded = false;
beforeContinuationDispatchCheck = async ({ runId: guardedRunId }) => {
if (guardedRunId !== runId) return;
guarded = true;
await db.update(issues).set({ assigneeAgentId: replacementAgentId, updatedAt: new Date() }).where(eq(issues.id, issueId));
};
await heartbeat.resumeQueuedRuns();
await heartbeat.drainActiveRunExecutions();
const [run] = await db.select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
.from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(guarded).toBe(true);
expect(run).toMatchObject({ status: "cancelled", errorCode: "issue_assignee_changed" });
expect(countExecuteCallsForRun(runId)).toBe(0);
});
it("rejects ownership changes immediately before the final continuation handoff", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
@@ -358,7 +358,7 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, competingId)))[0]?.status).toBe("running");
});
it.each(["native_safe_replacement", "native_provider_overloaded", "interrupted_preparation"])("does not dispatch %s when the task becomes blocked after scheduling", async retryReason => {
it.each(["native_safe_replacement", "native_provider_overloaded", "native_environment_blocker", "interrupted_preparation"])("does not dispatch %s when the task becomes blocked after scheduling", async retryReason => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "in_progress" });
@@ -180,7 +180,7 @@ function classifyRetryReasonKind(retryReason: string | null): RetryReasonKind {
if (retryReason === MAX_TURN_CONTINUATION_RETRY_REASON) return "max_turn_continuation";
if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) return "disposition_repair";
if ((retryReason === "ai_connection_busy" || retryReason === "ai_connection_pool_wait")) return "ai_connection_wait";
if (["native_safe_replacement", "native_provider_overloaded", "interrupted_preparation"].includes(retryReason ?? "")) return "native_safe_replacement";
if (["native_safe_replacement", "native_provider_overloaded", "native_environment_blocker", "interrupted_preparation"].includes(retryReason ?? "")) return "native_safe_replacement";
return "other";
}
@@ -593,7 +593,9 @@ export async function continueFreshInTransaction(tx: Db, input: Input): Promise<
const isolation: FreshContinuationIsolation = fenced || remoteSource ? "remote_epoch"
: writer === "ended" && !pastBound() && !refused ? "writer_ended" : "fresh_isolated_workspace";
if (isolation === "fresh_isolated_workspace" && delivery === "saved_input") delivery = "recorded";
const unverified = await unverifiedActions(tx, run);
const unconfirmed = object(coordinator?.failureDetail).unconfirmedActions;
const unverified = [...new Set([...await unverifiedActions(tx, run),
...(Array.isArray(unconfirmed) ? unconfirmed.filter((name): name is string => typeof name === "string") : [])])].slice(0, 20);
const created = await createdObjects(tx, run);
const note = freshContinuationNote({ runId: run.id, unverified, created,
workspace: isolation === "writer_ended" ? "kept" : "restored_last_save" });
+1 -1
View File
@@ -3135,7 +3135,7 @@ export function heartbeatService(
}
const enforceContinuationOwnership = Boolean(issueId && (isFailedChatRunRetry || isResolvedInteractionContinuationWakeContext(context) ||
typeof context.workspaceReconstructionActionId === "string" ||
["native_safe_replacement", "native_provider_overloaded"].includes(run.scheduledRetryReason ?? "")));
["native_safe_replacement", "native_provider_overloaded", "native_environment_blocker"].includes(run.scheduledRetryReason ?? "")));
if (issueId && enforceContinuationOwnership) {
await options.beforeResolvedInteractionContinuationDispatchCheck?.({ runId: run.id, issueId });
await options.afterResolvedInteractionContinuationDispatchCheck?.({ runId: run.id, issueId });
@@ -1,11 +1,46 @@
import type { Db } from "@paperclipai/db";
import { nativeSessionCleanupBlock } from "../../vendor/paperclip-runner/index.js";
import { and, eq } from "drizzle-orm";
import { heartbeatRuns, type Db } from "@paperclipai/db";
import {
completeTerminatedRemoteNativeSessionCleanupForTask,
nativeSessionCleanupBlock,
nativeSessionCleanupRemoteScopes,
} from "../../vendor/paperclip-runner/index.js";
import { logger } from "../../middleware/logger.js";
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
import { terminatedRemoteCleanupScope } from "../remote-execution-termination.js";
async function retireTerminatedRemoteCleanup(db: Db, input: { companyId: string; issueId: string }) {
for (const remoteCleanupScope of nativeSessionCleanupRemoteScopes(input)) {
const lease = await terminatedRemoteCleanupScope(db, input.companyId, remoteCleanupScope).catch(() => null);
if (!lease) continue;
const retired = completeTerminatedRemoteNativeSessionCleanupForTask({ ...input, remoteCleanupScope });
if (retired === 0) continue;
logger.warn({ companyId: input.companyId, issueId: input.issueId, leaseId: lease.id, runId: lease.heartbeatRunId,
provider: lease.provider, providerLeaseId: lease.providerLeaseId, retired },
"native session cleanup retired because its sandbox is confirmed terminated");
if (!lease.heartbeatRunId) continue;
const [run] = await db.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, lease.heartbeatRunId)))
.limit(1).catch(() => []);
if (!run) continue;
await appendHeartbeatRunEvent(db, {
companyId: input.companyId, runId: lease.heartbeatRunId, agentId: run.agentId,
eventType: "native.session_cleanup_gate_retired", stream: "system", level: "info",
message: "The task's previous sandbox is confirmed terminated, so its session cleanup gate was retired.",
payload: { leaseId: lease.id, provider: lease.provider, providerLeaseId: lease.providerLeaseId,
termination: lease.metadata?.remoteExecutionTermination ?? null, retired },
}).catch(() => undefined);
}
}
export async function nativeCleanupHoldsAdmission(
db: Db,
input: { companyId: string; issueId: string },
): Promise<"pending" | "operator_required" | null> {
let block = nativeSessionCleanupBlock(input);
if (block === null) return null;
await retireTerminatedRemoteCleanup(db, input);
block = nativeSessionCleanupBlock(input);
if (block === "operator_required") {
const { retireStoppedSessionCleanupGates } = await import("./native-session-executor.js");
await retireStoppedSessionCleanupGates(db, input).catch(() => false);
@@ -0,0 +1,125 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, companies, completionContracts, createDb, heartbeatRuns, issues, issueTreeHoldMembers, issueTreeHolds, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db";
import type { ControlPlanePort, NativeExecutionInputV1, PrpStructuredRunResult, PrpTerminalState } from "@paperclipai/paperclip-runner";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js";
const provider = vi.hoisted(() => ({ execute: vi.fn() }));
vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../../vendor/paperclip-runner/index.js")>()), executeNativeSession: provider.execute,
}));
import { executePaperclipNativeSession } from "./native-session-executor.js";
import { buildNativeCompletionContract } from "./completion-contracts.js";
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
import { finalizeNativeRun } from "./native-run-finalizer.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
NATIVE_ENVIRONMENT_BLOCKER_HINT, NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js";
import { taskInterruptionPresentation } from "../task-interruption-presentation.js";
type Blocker = NonNullable<PrpStructuredRunResult["blocker"]>;
const environmentBlocker: Blocker = {
owner: { kind: "system", name: "execution-environment" }, scope: "task_wide", reasonCode: "environment_unavailable",
unblockAction: "Resume/retry the run so the tool-result channel is healthy; then finish the remaining steps.",
};
describe("native run that reports a system environment blocker", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
const companyId = randomUUID(), agentId = randomUUID();
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("native-environment-blocker-");
db = createDb(temporary.connectionString);
await db.insert(companies).values({ id: companyId, name: "Environment blocker regression", issuePrefix: "ENV" });
await db.insert(agents).values({ id: agentId, companyId, name: "Environment worker", status: "active", adapterType: "paperclip_runner", adapterConfig: { provider: "opencode", model: "test-model" } });
});
afterAll(async () => { await temporary?.cleanup(); });
async function reportBlocked(blocker: Blocker, contextSnapshot: Record<string, unknown> = {}, beforeFinalize?: (issueId: string) => Promise<unknown>) {
const issueId = randomUUID(), runId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Ledger task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "env-owner" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "env-owner", contextSnapshot: { issueId, ...contextSnapshot } });
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
const [run] = await db.update(heartbeatRuns).set({ status: "running", runtimeMode: "native", nativeIssueId: issueId }).where(eq(heartbeatRuns.id, runId)).returning();
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() });
const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId));
const contractInput = buildNativeCompletionContract(issue, { revision: contract.revision });
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" });
const execution: NativeExecutionInputV1 = {
schema: "paperclip.native-execution-input.v1", binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId },
provider: { kind: "codex", model: "test-model" },
task: { identifier: issueId, title: issue.title, description: null, prompt: "Continue the task using its history.", workMode: "standard" },
workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null },
session: { normalizedSessionId: native.normalizedSessionId, driverKind: "codex_app_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", contract: contractInput },
interactionResponses: [], credentialBindings: [],
};
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId));
const terminal: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "completed", runTerminalState: "succeeded", reportedWorkDisposition: "blocked" };
const result: PrpStructuredRunResult = { ...CONTROL_PLANE_CONFORMANCE_RESULT, reportedWorkDisposition: "blocked",
summary: "Tool results looked corrupted, so the run stopped.",
completionClaim: { contractRevision: contractInput.revision, objectiveSatisfied: false,
criteria: contractInput.criteria.map(criterion => ({ criterionId: criterion.id, status: "unknown" as const, evidenceRefs: [] })),
remainingWork: [{ description: "Finish the ledger", blocksCompletion: true }] },
evidence: [], verification: [], attentionRequests: [], blocker };
provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => {
await options.controlPlane.openRun({ identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, backendKind: "mock", sourceInstanceId: native.runnerInstanceId });
await options.controlPlane.completeRun({ result, terminal, turnId: native.turnId });
return { result, terminal, turnId: native.turnId, normalizedSessionId: native.normalizedSessionId, providerSessionId: "fixture-session", driverKind: "codex_app_server", driverVersion: "fixture", nativeEventCount: 0, highestContiguousSourceSeq: 0, usage: null };
});
const unexpected = async () => { throw new Error("Unexpected provider call"); };
await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { descriptor: unexpected, openSession: unexpected } });
await beforeFinalize?.(issueId);
for (let replay = 0; replay < 2; replay++) await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId));
const retries = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId)));
const [settled] = await db.select().from(issues).where(eq(issues.id, issueId));
return { runId, issueId, decision: decision!, retries, issue: settled! };
}
it("continues the task automatically in a fresh session instead of resting it blocked", async () => {
const { runId, decision, retries, issue } = await reportBlocked(environmentBlocker);
expect(decision).toMatchObject({ reasonCode: NATIVE_ENVIRONMENT_BLOCKER_CODE });
expect(retries).toHaveLength(1);
expect(retries[0]).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: NATIVE_ENVIRONMENT_BLOCKER_CODE, scheduledRetryAttempt: 1,
contextSnapshot: { forceFreshSession: true, livenessContinuationSourceRunId: runId,
livenessContinuationReason: NATIVE_ENVIRONMENT_BLOCKER_CODE, livenessContinuationInstruction: NATIVE_ENVIRONMENT_BLOCKER_HINT } });
expect(await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.decisionId, decision.id)))
.toEqual(expect.arrayContaining([expect.objectContaining({ effectKind: "schedule_retry", targetType: "heartbeat_run", targetId: retries[0]!.id })]));
expect(issue).toMatchObject({ status: "in_progress", unblockDescriptor: null });
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "retry_scheduled", canRetry: false, userAction: null });
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retries[0]!.id));
});
it("hands the task to the board once the automatic retries are spent", async () => {
const { decision, retries, issue } = await reportBlocked(environmentBlocker, {
executionRetryAccounting: { version: 1, failureRetries: NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES, maxTurnContinuations: 0 },
});
expect(decision).toMatchObject({ reasonCode: NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE });
expect(retries).toHaveLength(0);
expect(issue).toMatchObject({ status: "blocked",
unblockDescriptor: { owner: "board", action: NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION } });
expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: false });
});
it("does not continue a paused task automatically", async () => {
const { decision, retries } = await reportBlocked(environmentBlocker, {}, async issueId => {
const holdId = randomUUID();
await db.insert(issueTreeHolds).values({ id: holdId, companyId, rootIssueId: issueId, mode: "pause", status: "active" });
await db.insert(issueTreeHoldMembers).values({ companyId, holdId, issueId, depth: 0, issueTitle: "Ledger task", issueStatus: "in_progress" });
});
expect(decision.reasonCode).not.toBe(NATIVE_ENVIRONMENT_BLOCKER_CODE);
expect(retries).toHaveLength(0);
});
it("keeps a blocker that only its owner can resolve", async () => {
const { decision, retries, issue } = await reportBlocked({ ...environmentBlocker, owner: { kind: "user", name: "board" },
reasonCode: "credential_missing", unblockAction: "Add the deploy key." });
expect(decision.reasonCode).toBe("task_wide_blocker_bound");
expect(retries).toHaveLength(0);
expect(issue.status).toBe("blocked");
});
});
@@ -0,0 +1,22 @@
export const NATIVE_ENVIRONMENT_BLOCKER_CODE = "native_environment_blocker";
export const NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE = "native_environment_blocker_exhausted";
export const NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES = 2;
export const NATIVE_ENVIRONMENT_BLOCKER_RETRY_DELAY_MS = 30_000;
export const NATIVE_ENVIRONMENT_BLOCKER_MESSAGE =
"The agent reported its execution environment unavailable. Paperclip continues the task in a fresh session.";
export const NATIVE_ENVIRONMENT_BLOCKER_HINT = "The previous run stopped because it reported its execution environment or tools unavailable. "
+ "Paperclip started this fresh session to continue. Earlier attempts may already have completed some steps: "
+ "check the workspace files, this task's documents and its comments before repeating a step, and never post a comment or save a document that already exists. "
+ "Then finish the remaining work and report the real outcome. If a tool result looks wrong, retry that step once before reporting a blocker.";
export const NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION =
"The agent still reported its execution environment unavailable after Paperclip continued the task in fresh sessions. The saved work is kept. Comment on the task when the agent should continue.";
const ENVIRONMENT_BLOCKER_REASON_CODES: ReadonlySet<string> = new Set(["environment_unavailable", "tool_unavailable"]);
export function isNativeEnvironmentBlocker(result: {
reportedWorkDisposition?: unknown;
blocker?: { owner?: { kind?: unknown } | null; reasonCode?: unknown } | null;
}) {
return result.reportedWorkDisposition === "blocked" && result.blocker?.owner?.kind === "system"
&& typeof result.blocker.reasonCode === "string" && ENVIRONMENT_BLOCKER_REASON_CODES.has(result.blocker.reasonCode);
}
@@ -7,6 +7,8 @@ import { accountingForScheduledRetry, executionFailureRetryCount } from "../exec
import { NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, NATIVE_TOOL_RECEIPT_LIMIT_HINT,
NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS, NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE, nativeRunHasStopRequest } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_HINT, NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES, NATIVE_ENVIRONMENT_BLOCKER_MESSAGE,
NATIVE_ENVIRONMENT_BLOCKER_RETRY_DELAY_MS } from "./native-environment-blocker.js";
import { NativeStatusRaceError } from "./status-decision-committer.js";
type NativeRetryTarget = {
@@ -57,6 +59,23 @@ export async function materializeNativeToolReceiptLimitContinuation(input: Nativ
});
}
export async function materializeNativeEnvironmentBlockerRetry(input: NativeRetryTarget) {
return materializeNativeFreshSessionRetry(input, {
reason: NATIVE_ENVIRONMENT_BLOCKER_CODE,
maxRetries: NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES,
delayMs: attempt => NATIVE_ENVIRONMENT_BLOCKER_RETRY_DELAY_MS * 2 ** (attempt - 1),
message: NATIVE_ENVIRONMENT_BLOCKER_MESSAGE,
idempotencyPrefix: "native-environment-blocker",
exhaustedError: "native_environment_blocker_retry_exhausted",
refuseStopped: true,
context: run => ({
livenessContinuationSourceRunId: run.id,
livenessContinuationReason: NATIVE_ENVIRONMENT_BLOCKER_CODE,
livenessContinuationInstruction: NATIVE_ENVIRONMENT_BLOCKER_HINT,
}),
});
}
async function materializeNativeFreshSessionRetry(input: NativeRetryTarget, lane: NativeRetryLane) {
const [run] = await input.tx.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId),
@@ -33,6 +33,7 @@ import { executionFailureRetryCount } from "../execution-recovery-attempt.js";
import { isFailedTurnContinuationRun } from "./native-failed-turn-continuation.js";
import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js";
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, cancelStoppedRunContinuation, nativeRunHasStopRequest, readPersistedNativeToolReceiptLimitStop } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE, isNativeEnvironmentBlocker } from "./native-environment-blocker.js";
import { explainFailedRun, explainNativeTurnFailure, NATIVE_RUN_FAILED_UNEXPLAINED } from "./native-run-failure-explanation.js";
import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js";
import { findSupersededExternalReviewRequests } from "./superseded-external-review-requests.js";
@@ -1700,7 +1701,8 @@ export async function finalizeNativeRun(input: {
issueId: authoritativeIssue.id,
runId: run.id,
}),
(terminalState === "failed" || (assessment.reportedDisposition === "yielded" &&
(terminalState === "failed" || (terminalState === "succeeded" && isNativeEnvironmentBlocker(result)) ||
(assessment.reportedDisposition === "yielded" &&
assessment.continuation?.kind === "response_wake" &&
assessment.hasBlockingRemainingWork))
? issueTreeControlService(input.db).getActivePauseHoldGate(
@@ -1769,6 +1771,8 @@ export async function finalizeNativeRun(input: {
providerFailureSuperseded: providerFailure?.errorCode === "native_provider_overloaded" && !ownsProviderFailureDecision,
toolReceiptLimitStopped: terminalState !== "succeeded" && ownsProviderFailureDecision && !reviewContext
&& !stopRequested && await readPersistedNativeToolReceiptLimitStop(input.db, run, resultRow.turnId),
environmentBlocker: terminalState === "succeeded" && ownsProviderFailureDecision && !reviewContext && !stopRequested
&& isNativeEnvironmentBlocker(result),
failureRetryCount: executionFailureRetryCount(run),
// Only the task's current owner may turn its own failed continuation
// into a blocker; the committer rechecks that under the issue lock.
@@ -1932,6 +1936,8 @@ export async function finalizeNativeRun(input: {
requireProviderFailureOwner: decision.reasonCode?.startsWith("native_provider_overloaded")
|| decision.reasonCode === "native_run_failed_continuation_exhausted"
|| decision.reasonCode === NATIVE_TOOL_RECEIPT_LIMIT_CODE
|| decision.reasonCode === NATIVE_ENVIRONMENT_BLOCKER_CODE
|| decision.reasonCode === NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE
? { agentId: run.agentId, reviewContext } : undefined,
requireBoardResponseWaitSource:
decision.reasonCode === "board_response_waiting" || repairBoardResponseWait
@@ -226,6 +226,74 @@ const support = externalDatabaseUrl
}
},
);
it.each(["remote_sandbox", "remote_unconfirmed_action", "remote_completed_action", "remote_started_only_action",
"remote_failed_exit_action", "local_codex", "unknown_provider"] as const)(
"continues a transport failure whose stop can never be proven locally without waiting for a person (%s)",
async (mode) => {
const source = await seed();
const workspace = await mkdtemp(join(tmpdir(), "paperclip-remote-transport-"));
const remote = mode.startsWith("remote_");
try {
await db.update(heartbeatRuns).set({ finishedAt: new Date(), errorCode: "provider_transport_failed",
runnerProfileJson: mode === "unknown_provider" ? {} : { nativeExecutionInput: {
provider: { kind: remote ? "opencode" : "codex" }, workspace: { cwd: workspace } } } })
.where(eq(heartbeatRuns.id, source.runId));
await db.update(nativeRunFinalizations).set({ failureCode: "provider_transport_failed", failureDetail: {} })
.where(eq(nativeRunFinalizations.runId, source.runId));
if (remote) await db.insert(environmentLeases).values({ companyId: source.companyId,
issueId: source.issueId, heartbeatRunId: source.runId, provider: "fake-sandbox", providerLeaseId: "sandbox-1",
status: "released", releasedAt: new Date(), cleanupStatus: "success" });
if (mode === "remote_unconfirmed_action") await appendHeartbeatRunEvent(db, {
companyId: source.companyId, runId: source.runId, agentId: source.agentId,
eventType: "tool.execution.started", stream: "system",
payload: { name: "send_email", executionId: "unconfirmed-send", transport: "mcp" },
});
if (mode === "remote_completed_action" || mode === "remote_started_only_action" || mode === "remote_failed_exit_action") {
const execution = { schema: "paperclip.tool.execution.v1", executionId: "prt_1e7c7089f001EN3I04Bfmz",
transport: "mcp", name: "send_email" };
await appendHeartbeatRunEvent(db, { companyId: source.companyId, runId: source.runId, agentId: source.agentId,
eventType: "tool.execution.started", stream: "system",
payload: { prpEvent: { payload: { ...execution, status: "running" } } } });
if (mode !== "remote_started_only_action") await appendHeartbeatRunEvent(db, { companyId: source.companyId,
runId: source.runId, agentId: source.agentId, eventType: "tool.execution.completed", stream: "system",
payload: { prpEvent: { payload: { ...execution, status: "completed",
exitCode: mode === "remote_failed_exit_action" ? 1 : 0 } } } });
}
const verifyStoppedSession = vi.fn(async () => null);
invalidateNativeReplacementDiscovery(db);
await reconcileSafeNativeReplacements(db, new Date(), { verifyStoppedSession });
const [decision] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, source.runId));
const holds = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, source.issueId));
if (!remote) {
expect(verifyStoppedSession).toHaveBeenCalled();
expect(decision!.failureDetail?.replacementDenied).toBeUndefined();
expect(holds).toHaveLength(0);
return;
}
if (mode === "remote_unconfirmed_action" || mode === "remote_started_only_action" || mode === "remote_failed_exit_action") {
expect(decision!.failureDetail?.replacementDenied).toBe("uncertain_external_action");
expect(holds).toMatchObject([{ status: "active", cause: "uncertain_external_action",
nextAction: expect.stringContaining("send_email") }]);
expect(decision!.failureDetail?.unconfirmedActions).toEqual(["send_email"]);
await settleUnrecoverableExecutions(db);
const [continued] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, source.issueId));
expect(continued!.evidence).toMatchObject({ freshContinuation: { unverifiedActions: ["send_email"] },
executionReconciliation: { outcomeEvidence: expect.stringContaining("unverified outcomes: send_email") } });
return;
}
expect(decision!.failureDetail?.replacementDenied).toBe("provider_failure_meaning_unverified");
expect(decision!.failureDetail?.unconfirmedActions).toBeUndefined();
expect(holds).toMatchObject([{ status: "active", cause: "provider_failure_meaning_unverified" }]);
await settleUnrecoverableExecutions(db);
const [settled] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, source.issueId));
expect(settled).toMatchObject({ status: "resolved", outcome: "restored",
evidence: { freshContinuation: { trigger: "recovery_refused", sourceRunId: source.runId, unverifiedActions: [] },
continuationDelivery: "pending" } });
} finally {
await rm(workspace, { recursive: true, force: true });
}
},
);
it("wakes a completed replacement scan after actual local stop proof commits", async () => {
const source = await seed(2);
const workspace = await mkdtemp(join(tmpdir(), "paperclip-late-stop-"));
@@ -21,7 +21,7 @@ import {
type Db,
} from "@paperclipai/db";
import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema } from "@paperclipai/shared";
import { decideNativeReplacement } from "./native-replacement-evidence.js";
import { decideNativeReplacement, type NativeReplacementDecision } from "./native-replacement-evidence.js";
import { issueService } from "../issues.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { buildExecutionContinuation } from "../execution-continuation.js";
@@ -435,11 +435,15 @@ export async function reconcileSafeNativeReplacements(
if (historicalListener && !await historicalListenerGuardEvidence(db, run)) continue;
const preClaim = coordinator.failureCode === NATIVE_PRE_CLAIM_FAILURE_CODE;
if (preClaim && !await preClaimFailureEvidence(db, run)) continue;
const stoppedSession = coordinator.failureCode !== "native_provider_terminal_failed" && !historicalListener && !preClaim
? await options.verifyStoppedSession?.(run) ?? null : null;
const needsStopProof = coordinator.failureCode !== "native_provider_terminal_failed" && !historicalListener && !preClaim;
const stoppedSession = needsStopProof ? await options.verifyStoppedSession?.(run) ?? null : null;
// A transport label alone is not evidence. Keep inspecting these candidates
// as process cleanup and the final transcript become durable.
if (coordinator.failureCode !== "native_provider_terminal_failed" && !historicalListener && !preClaim && !stoppedSession) continue;
const providerKind = record(execution.provider).kind;
const stopProofUnavailable = needsStopProof && !stoppedSession
&& ((typeof providerKind === "string" && providerKind !== "codex")
|| leases.some(lease => lease.provider !== null && lease.provider !== "local"));
if (needsStopProof && !stoppedSession && !stopProofUnavailable) continue;
const invocations = await db
.select()
.from(toolInvocations)
@@ -540,7 +544,40 @@ export async function reconcileSafeNativeReplacements(
&& run.runnerProfileJson?.nativeWorkspaceSync == null && nativeRunHasNoWorkspaceAccess(run);
if (preClaim && (invocations.length || !noWorkspaceToSave
&& (!remoteWorkspace?.workspacePreserved || !remoteWorkspace.providerStopped))) continue;
const decision = decideNativeReplacement({
const completedInvocation = (row: typeof invocations[number]) =>
row.status === "succeeded" && Boolean(row.completedAt) && Boolean(row.resultHash);
const executions = stopProofUnavailable ? (await db
.select({ seq: heartbeatRunEvents.seq, eventType: heartbeatRunEvents.eventType, payload: heartbeatRunEvents.payload })
.from(heartbeatRunEvents)
.where(and(eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
inArray(heartbeatRunEvents.eventType, ["tool.execution.started", "tool.execution.completed"]))))
.map(event => {
const envelope = record(event.payload);
return { seq: event.seq, eventType: event.eventType,
payload: envelope.prpEvent ? record(record(envelope.prpEvent).payload) : envelope };
}) : [];
const unconfirmedActions = stopProofUnavailable ? [...new Set([
...invocations.filter(row => row.riskLevel !== "read" && !completedInvocation(row)).map(row => row.toolName),
...uncertainProviderActions.flatMap(action => {
const started = executions.find(event => event.eventType === "tool.execution.started"
&& String(event.payload.executionId ?? event.payload.name) === action);
const executionId = started?.payload.executionId;
if (started && executionId != null && executions.some(event => event.eventType === "tool.execution.completed"
&& event.seq > started.seq && event.payload.executionId === executionId && event.payload.status === "completed"
&& (event.payload.exitCode == null || event.payload.exitCode === 0) && event.payload.error == null))
return [];
if (started && started.payload.transport !== "process" && invocations.some(row => completedInvocation(row)
&& (row.id === executionId || row.correlationId === executionId))) return [];
return [typeof started?.payload.name === "string" ? started.payload.name : action];
}),
])] : [];
const unprovenAction = unconfirmedActions[0];
const decision: NativeReplacementDecision = stopProofUnavailable ? unprovenAction ? { allowed: false,
cause: "uncertain_external_action",
nextAction: `Reconcile ${unprovenAction} and preserve its result before continuing. Do not repeat it automatically.` }
: { allowed: false, cause: "provider_failure_meaning_unverified",
nextAction: "The previous session could not be confirmed stopped and recorded no unconfirmed action, so the task continues in a fresh run from its saved work." }
: decideNativeReplacement({
failedSession: true,
// A facade transport failure can conceal an authoritative protocol
// rejection. A stopped process and read receipts do not resolve that.
@@ -618,6 +655,7 @@ export async function reconcileSafeNativeReplacements(
...current.failureDetail,
replacementDenied: decision.cause,
nextAction,
...(unconfirmedActions.length ? { unconfirmedActions } : {}),
},
updatedAt: now,
})
@@ -22625,6 +22625,68 @@ describe("runnerd provider runtime wiring", () => {
leaseOwner: "provider-owner", bootId: "backup-boot", generation: 1 }));
});
it("saves a closing session's backup under its own owner after a failed follow-up released the scope authority", async () => {
const current = { ...execution, binding: { ...execution.binding, runId: randomUUID(), issueId: randomUUID(),
executionWorkspaceId: randomUUID() }, session: { ...execution.session, normalizedSessionId: randomUUID() } };
const coordinator = { phase: "observed", resultId: null as string | null, leaseOwner: "provider-owner" as string | null,
controllerGeneration: 1, controllerBootId: "backup-boot" };
const db = leaseDb(current), select = db.select.bind(db);
db.select = ((fields?: Record<string, unknown>) => ({ from: (table: unknown) => {
if (table !== nativeRunFinalizations) return select(fields as never).from(table as never);
const promise = Promise.resolve([coordinator]);
const query = { then: promise.then.bind(promise), where: () => query, limit: () => query, for: () => query };
return query;
} })) as unknown as Db["select"];
const storage = vi.spyOn(harnessStorage, "durableNativeHarnessStorage").mockReturnValue({ provider: "s3" } as never);
const validateOwner = vi.spyOn(harnessStorage, "assertNativeHarnessBackupOwner").mockResolvedValue(undefined);
const checkpointRegistration = vi.spyOn(runnerCheckpoint, "nativeRunnerCheckpointRegistration")
.mockReturnValue(async () => undefined);
onTestFinished(() => { storage.mockRestore(); validateOwner.mockRestore(); checkpointRegistration.mockRestore(); });
let savingWorkspace = false;
const remoteExecute = vi.fn(async (command: { args?: string[] }) => {
if (savingWorkspace && command.args?.[1]?.includes("base64 <")) throw new Error("stopped-provider-inspection-reached");
return { exitCode: command.args?.[1]?.includes("base64") ? 1 : 0, timedOut: false, stderr: "", stdout:
command.args?.[0] === "--build-metadata" ? JSON.stringify({
schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", packageName: "@paperclipai/paperclip-runner",
binaryContractVersion: 2, durableSessionCapabilities: ["unlimited_runtime", "connection_lease_renewal"], prpTransportModes: ["listen_ws"],
}) : command.args?.[0] === "--version" ? "codex-cli 0.160.0" : "" };
});
const controllerArtifact = join(isolatedStateDirectory, "backup-fixture-runnerd");
await writeFile(controllerArtifact, "fixture bootstrap artifact");
await createRunnerdBackend({ db, execution: current, runnerInstanceId: "released-scope-backup-runner",
runnerRemoteBinaryPath: controllerArtifact, runnerRemoteCodexPath: controllerArtifact,
controllerPersistence: { bootId: "backup-boot" }, runnerIngressAuthorized: true, runnerExecutionTarget: {
kind: "remote", transport: "sandbox", remoteCwd: "/workspace", environmentId: "environment", leaseId: "released-scope-backup-lease",
providerKey: "daytona", sandboxLeaseAcquisition: { outcome: "created", providerLeaseId: "released-scope-backup-sandbox" },
effectiveCapabilities: { runnerWebSocketIngress: true }, runner: { execute: remoteExecute, syncIn: vi.fn(async () => undefined) },
getRunnerIngressEndpoint: async () => ({ kind: "authenticated_websocket", websocketUrl: "wss://sandbox.invalid/runner",
secretHeaders: [{ name: "Authorization", value: "fixture-ingress" }], generation: "1", refresh: vi.fn(), close: vi.fn(async () => undefined) }),
} as never });
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
const options = state.createTransport.mock.calls.at(-1)![0] as RunnerTransportOptions & {
controlPlaneRegistration: NonNullable<import("../../vendor/paperclip-runner/index.js").RunnerExecutionDriver["controlPlaneRegistration"]>;
};
const controller = new DurablePrpControlPlane({ stateDirectory: join(options.stateDirectory!, "control-plane"),
identity: options.prpIdentity! as ConstructorParameters<typeof DurablePrpControlPlane>[0]["identity"],
expectedRunnerVersion: "backup-fixture", expectedRunnerDigest: `sha256:${"a".repeat(64)}` });
controller.queueCommand("run.prepare", {});
controller.queueCommand("session.open", { reuse: "same_session" });
let registration: Awaited<ReturnType<typeof options.controlPlaneRegistration>> | undefined;
onTestFinished(async () => { await registration?.release(); await controller.stop(); });
registration = await options.controlPlaneRegistration(controller);
coordinator.phase = "workspace_finalizing";
coordinator.resultId = "accepted-result";
coordinator.leaseOwner = null;
savingWorkspace = true;
const authorities = sessionToolAuthorityCount();
await expect(createRunnerdBackend({ db, execution: current, runnerInstanceId: "released-scope-backup-runner",
executionContext: { signal: AbortSignal.abort() } as never })).rejects.toThrow();
expect(sessionToolAuthorityCount()).toBe(authorities - 1);
await expect(registration.checkpoint!("settled")).rejects.toThrow("stopped-provider-inspection-reached");
expect(validateOwner).toHaveBeenCalledWith(db, expect.objectContaining({ runId: current.binding.runId,
leaseOwner: "provider-owner", bootId: "backup-boot", generation: 1 }));
});
it.each([true, false])("restores a migrated warm backup into a created lease only for its exact session (matching: %s)", async matching => {
const remoteCwd = join(isolatedStateDirectory, "remote");
const current: NativeExecutionInputV1 = { ...execution,
@@ -18189,8 +18189,10 @@ async function createRunnerdBackendWithinSessionClaim(
)
return false;
const durableStorage = durableNativeHarnessStorage();
const currentAuthority = sessionToolAuthorityEpochs.get(sessionScopeId);
const backupOwner = durableStorage && currentAuthority ? sessionHarnessBackupOwners.get(currentAuthority) : null;
const currentAuthority = sessionToolAuthorityEpochs.get(sessionScopeId) ?? authorityEpoch;
const backupOwner = durableStorage
? sessionHarnessBackupOwners.get(currentAuthority) ?? sessionHarnessBackupOwners.get(authorityEpoch) ?? null
: null;
if (durableStorage && !backupOwner) throw new Error("native_harness_storage_owner_missing");
if (backupOwner) await assertNativeHarnessBackupOwner(input.db, backupOwner);
// Transport release also runs when provider bootstrap failed. In that case
@@ -18988,9 +18990,7 @@ async function createRunnerdBackendWithinSessionClaim(
target,
controllerPersistence: input.controllerPersistence ? nativeRunnerCheckpointPersistence(
input.db, input.controllerPersistence.bootId, () => {
const current = sessionToolAuthorityEpochs.get(sessionScopeId);
if (!current) throw new Error("native_session_tool_authority_unavailable");
return current.runId;
return (sessionToolAuthorityEpochs.get(sessionScopeId) ?? authorityEpoch).runId;
}, detachNativeSessionsForRestart) : undefined,
binding: input.remoteWarmRecovery
? { ...input.execution.binding, runId: input.remoteWarmRecovery.identity.runId }
@@ -757,4 +757,15 @@ describe("native status authority", () => {
]);
});
it("continues a system environment blocker in a fresh session, bounded, and never for a paused task or chat", () => {
const blocked = assessment({ reportedDisposition: "blocked", objectiveSatisfied: false, allCriteriaSatisfied: false,
blocker: { unblockAction: "Retry the run.", boardOwned: false, ownerKind: "system", scope: "task_wide" } });
expect(arbitrate({ assessment: blocked, environmentBlocker: true })).toMatchObject({ statusAction: "preserve",
reasonCode: "native_environment_blocker", effects: [{ kind: "schedule_retry", cause: "native_environment_blocker", agentId: "agent" }] });
expect(arbitrate({ assessment: blocked, environmentBlocker: true, failureRetryCount: 2 })).toMatchObject({ toStatus: "blocked",
reasonCode: "native_environment_blocker_exhausted", unblockDescriptor: { owner: "board" } });
for (const held of [{ hasActivePauseHold: true }, { isConversation: true }, { environmentBlocker: false }]) {
expect(arbitrate({ assessment: blocked, environmentBlocker: true, ...held })).toMatchObject({ reasonCode: "task_wide_blocker_bound" });
}
});
});
@@ -2,6 +2,8 @@ import { COMPLETION_REVIEW_STAGE_REASON, COMPLETION_REVIEW_STAGE_REJECTED_REASON
import type { NativeEvidenceAssessment } from "./evidence-classifier.js";
import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js";
export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v14";
@@ -258,6 +260,8 @@ export function arbitrateNativeStatus(input: {
providerOverloaded?: boolean;
providerFailureSuperseded?: boolean;
toolReceiptLimitStopped?: boolean;
/** The current owner's blocked report names a system-owned environment or tool outage. */
environmentBlocker?: boolean;
failureRetryCount?: number;
/**
* This run was itself the automatic continuation of an earlier failed turn.
@@ -624,6 +628,31 @@ export function arbitrateNativeStatus(input: {
})),
};
}
if (
input.assessment.reportedDisposition === "blocked" &&
input.assessment.blocker &&
input.environmentBlocker &&
!input.isConversation &&
!input.hasActivePauseHold
) {
if ((input.failureRetryCount ?? 0) < NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: NATIVE_ENVIRONMENT_BLOCKER_CODE, unblockDescriptor: null,
effects: [{ kind: "schedule_retry", cause: NATIVE_ENVIRONMENT_BLOCKER_CODE,
summary: "Continue the task in a fresh session.", agentId: input.agentId }],
};
}
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "blocked", toStatus: "blocked",
reasonCode: NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
blockerOwnerKind: input.assessment.blocker.ownerKind,
unblockDescriptor: { owner: "board", action: NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION },
effects: [{ kind: "bind_blocker", owner: "board", action: NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION }],
};
}
if (
input.assessment.reportedDisposition === "blocked" &&
input.assessment.blocker
@@ -87,7 +87,8 @@ import {
type ActivityPublication,
} from "../activity-log.js";
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
import { materializeNativeProviderCapacityRetry, materializeNativeToolReceiptLimitContinuation } from "./native-provider-capacity-retry.js";
import { materializeNativeEnvironmentBlockerRetry, materializeNativeProviderCapacityRetry, materializeNativeToolReceiptLimitContinuation } from "./native-provider-capacity-retry.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE } from "./native-environment-blocker.js";
import { NATIVE_PROVIDER_OVERLOADED_CODE } from "./native-provider-failure.js";
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE } from "./native-tool-receipt-limit.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js";
@@ -909,9 +910,11 @@ async function materializeDecisionEffect(input: {
}
if (effect.kind === "schedule_retry") {
failAt("continuation_materialization", input.failpoint);
if (effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE || effect.cause === NATIVE_TOOL_RECEIPT_LIMIT_CODE) {
const materialize = effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE
? materializeNativeProviderCapacityRetry : materializeNativeToolReceiptLimitContinuation;
if (effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE || effect.cause === NATIVE_TOOL_RECEIPT_LIMIT_CODE
|| effect.cause === NATIVE_ENVIRONMENT_BLOCKER_CODE) {
const materialize = effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE ? materializeNativeProviderCapacityRetry
: effect.cause === NATIVE_ENVIRONMENT_BLOCKER_CODE ? materializeNativeEnvironmentBlockerRetry
: materializeNativeToolReceiptLimitContinuation;
const retryId = await materialize({
tx: input.tx as unknown as Db, companyId: input.companyId,
issueId: input.issue.id, runId: input.runId, agentId: effect.agentId,
@@ -1716,7 +1719,8 @@ export async function commitNativeStatusDecision(input: {
throw new Error("native_model_rejection_owner_required");
}
if ((reasonCode.startsWith("native_provider_overloaded") || reasonCode === "native_run_failed_continuation_exhausted"
|| reasonCode === NATIVE_TOOL_RECEIPT_LIMIT_CODE) && !input.requireProviderFailureOwner) {
|| reasonCode === NATIVE_TOOL_RECEIPT_LIMIT_CODE || reasonCode === NATIVE_ENVIRONMENT_BLOCKER_CODE
|| reasonCode === NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE) && !input.requireProviderFailureOwner) {
throw new Error("native_provider_failure_owner_required");
}
const publications: ActivityPublication[] = [];
@@ -1,4 +1,4 @@
import { and, eq } from "drizzle-orm";
import { and, desc, eq } from "drizzle-orm";
import { environmentLeases, type Db } from "@paperclipai/db";
import { retiredReusableLeasePredecessors } from "./environment-lease-handoff.js";
@@ -129,3 +129,21 @@ export async function remoteExecutionHasReleased(db: Db, companyId: string, runI
const leases = await runRemoteLeases(db, companyId, runId);
return leases.length > 0 && leases.every(hasRemoteTerminationReceipt);
}
export async function terminatedRemoteCleanupScope(db: Db, companyId: string, remoteCleanupScope: string) {
let parsed: unknown;
try {
parsed = JSON.parse(remoteCleanupScope);
} catch {
return null;
}
if (!Array.isArray(parsed) || parsed.length !== 2 || typeof parsed[0] !== "string" || typeof parsed[1] !== "string"
|| parsed[0] === "local") return null;
const [provider, providerLeaseId] = parsed as [string, string];
const leases = await db.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, companyId),
eq(environmentLeases.provider, provider), eq(environmentLeases.providerLeaseId, providerLeaseId)))
.orderBy(desc(environmentLeases.createdAt), desc(environmentLeases.id));
if (leases.length === 0 || leases.some(lease => !lease.releasedAt)) return null;
const newest = await resolveRemoteTerminationLease(db, leases[0]!);
return hasRemoteTerminationReceipt(newest) ? newest : null;
}
+2
View File
@@ -213,6 +213,8 @@ export const nativeRestartContinuationInFlight = runner.nativeRestartContinuatio
export const completeTerminatedRemoteNativeSessionCleanup = runner.completeTerminatedRemoteNativeSessionCleanup;
export const completeTerminatedLocalNativeSessionCleanup = runner.completeTerminatedLocalNativeSessionCleanup;
export const completeTerminatedRemoteNativeSessionCleanupForTask = runner.completeTerminatedRemoteNativeSessionCleanupForTask;
export const nativeSessionCleanupRemoteScopes = runner.nativeSessionCleanupRemoteScopes;
export const nativeSessionCleanupBlock = runner.nativeSessionCleanupBlock;
export const onNativeSessionCleanupSettled = runner.onNativeSessionCleanupSettled;
export const onNativeSessionCleanupQuarantined = runner.onNativeSessionCleanupQuarantined;
+48
View File
@@ -123,6 +123,54 @@ describe("TaskObserver", () => {
expect(observer.record.restAt).toBe(start + 1_000);
});
describe("deadline versus rest confirmation", () => {
async function observe(statusAt: (now: number, start: number) => string) {
let start = 0;
let current = 0;
const { api } = fakeApi({ "/api/issues/i1": route => route.endsWith("/runs")
? [{ runId: "r1", status: "succeeded", createdAt: new Date(0).toISOString(), finishedAt: new Date(1).toISOString() }]
: { id: "i1", status: statusAt(current, start), interruption: null } });
const observer = new TaskObserver({ ...plan, workload: "A1", followUpAfterMs: null }, api, lab, new Timeline(null), ready);
await observer.launch();
start = observer.record.createdAt!;
observer.record.deadlineAt = start + 60_000;
const poll = (at: number) => { current = at; return observer.poll(at); };
return { observer, start, poll };
}
it("confirms a task that began resting just before its deadline instead of timing it out", async () => {
const { observer, start, poll } = await observe((now, begin) => now >= begin + 59_000 ? "done" : "in_progress");
await poll(start + 58_000);
await poll(start + 59_000);
await poll(start + 60_001);
expect(observer.done).toBe(false);
expect(observer.record.timedOut).toBe(false);
await poll(start + 59_000 + REST_CONFIRM_MS);
expect(observer.done).toBe(true);
expect(observer.record.timedOut).toBe(false);
expect(observer.record.finalStatus).toBe("done");
expect(observer.record.restAt).toBe(start + 59_000);
});
it("times out a task that is still running at its deadline", async () => {
const { observer, start, poll } = await observe(() => "in_progress");
await poll(start + 59_000);
await poll(start + 60_001);
expect(observer.done).toBe(true);
expect(observer.record.timedOut).toBe(true);
expect(observer.record.finalStatus).toBe("in_progress");
});
it("times out a task that only starts resting after its deadline", async () => {
const { observer, start, poll } = await observe((now, begin) => now > begin + 60_000 ? "done" : "in_progress");
await poll(start + 59_000);
await poll(start + 60_001);
expect(observer.done).toBe(true);
expect(observer.record.timedOut).toBe(true);
expect(observer.record.restAt).toBeNull();
});
});
it("reports a failed workspace-operation read as a sweep error, not a clean rest", async () => {
const { api } = fakeApi({ "/workspace-operations": () => { throw new Error("timeout"); } });
const observer = new TaskObserver(plan, api, lab, new Timeline(null), ready);
+2
View File
@@ -543,6 +543,8 @@ export class TaskObserver {
}
}
if (this.record.deadlineAt !== null && now > this.record.deadlineAt && !this.supervisor.faultInProgress) {
if (this.restCandidateSince !== null && this.restCandidateSince <= this.record.deadlineAt
&& now - this.restCandidateSince < REST_CONFIRM_MS) return;
this.record.timedOut = true;
this.record.finalStatus = sample.issueStatus ?? this.record.finalStatus;
this.done = true;