fix(runner): repair approval and Stop races and eval infrastructure (#13750)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Runner tasks must continue after approval and stop when the user
presses Stop.
> - Live evals found races at approval delivery and provider startup.
> - Browser readiness and CI setup errors also hid the actual task
results.
> - This pull request fixes those races and the related test
infrastructure.
> - Regression tests and saved live reports show which cases now pass.

## Linked Issues or Issue Description

Companion eval definitions PR:
https://github.com/paperclipai/paperclip-evals/pull/25 (AgentCore paused
and provider/environment infrastructure).

Related: #13741 now supplies the late-startup Stop fence and
warm-attachment recovery; this PR retains that fence and extends startup
tracking and regression coverage to both native backend paths. #13539
introduced queued approvals during active runs. #13738 fixes child
assignment, task replies, and warm process continuity and is already in
the base. #13291 concerns automatic continuation of interrupted legacy
sandbox runs; this PR fixes native startup cancellation and does not
change that recovery policy.

**What happened?**
An accepted service approval could wait after its source run stopped.
Stop could return success before the provider handle existed. Work could
then start after Stop, or a cancelled run could be recorded as failed.
Some E2E tests also failed on unloaded browser content or irrelevant
reply wording. Runner CI could fail before model work because of
dependency or sandbox setup.

**Expected behavior**
Deliver each settled approval once after its source run stops. Do not
start work after an acknowledged Stop. Preserve the audited
cancellation. Test the intended product behavior with a ready browser
and verified runtime dependencies.

**Steps to reproduce**
1. Approve a service request while its source run is active. Let the run
finish. Check that its result starts one continuation.
2. Delay provider startup. Press Stop before its handle is available.
Check cancellation, then submit `/new`.
3. Run the browser, warm-workspace, and Stop-and-redirect cases from the
linked report.

**Paperclip version or commit**
The branch includes master at `9d19f98b5`. The report records the
original source for each focused attempt.

**Deployment mode**
Isolated local development instances and disposable Daytona sandboxes.

## What Changed

- Deliver settled tool-action results for the exact company and source
run during final cleanup. Keep the existing idempotent receipt and
periodic recovery sweep.
- Wait for startup to hand off its provider handle before acknowledging
Stop. Reject first-turn admission after cancellation. Preserve a
matching audited pending or acknowledged cancellation.
- Wait for mounted task history and connector controls in browser tests.
Record failure evidence. Grade workspace contents and process continuity
separately from exact reply wording. Require each warm-turn marker once
and in order, allowing surrounding prose.
- Stop-and-redirect now checks that the source file exists and work is
active before Stop.
- Resolve target dependency locks in an uncredentialed CI job. Verify
the lock artifact hash. Keep orchestration and publication on the
trusted workflow revision.
- Materialize the pinned OpenCode executable and configure the exact
Codex executable's user-namespace profile before provider credentials
are available.
- Compress Daytona directory uploads with gzip. Preserve files,
executable modes, symlinks, empty directories, and confinement checks.
- Classify file-transfer RPC deadlines as infrastructure. Keep unrelated
runner RPC failures visible.

## Verification

- [Focused live report with screenshots and original
attempts](https://pages.paperclip.ing/runner-reliability-20260921/): 14
of 15 selected Product E2E cases pass across the recorded revisions.
Claude and Codex Stop → `/new`, Claude service approval, delegation,
both hiring/reuse cases, and native Daytona warm continuity pass.
- Two credentialed Runner smoke cases pass. These are not full protocol
coverage.
- E2E harness after the master merge: 429 tests pass. E2E and server
TypeScript checks pass.
- Daytona plugin: 239 tests pass, 6 skipped. Plugin TypeScript build
passes. The compression test fails against the old code and passes with
the change.
- Runner backend/runtime regression group: 161 tests pass.
Cancellation/startup selection: 26 tests pass. Approval delivery: 34
real-database tests pass.
- Workflow security: 7 tests pass. Both edited workflows pass
actionlint. Runner TypeScript and Rust builds pass.
- After merging master, all 389 native executor tests pass, including
both native backend paths and late startup after the Stop deadline.
- Post-merge `pnpm -r typecheck` and `pnpm build` pass. The monolithic
local `pnpm test:run` was interrupted to integrate master and is
inconclusive. The [hosted CI test
partitions](https://github.com/paperclipai/paperclip/actions/runs/35620461738)
pass on `50a3e43822bcba1e0d07b1b45b0be91cbf9312da`. An unchanged sandbox
callback schema test initially received HTTP 503. It passed five
isolated local runs, its full local test file, and one failed-job CI
retry. No assertion was weakened.

## Risks

- Stop can wait for the bounded startup handoff. If it cannot settle,
the existing pending-recovery state remains instead of a false
acknowledgement.
- Immediate approval delivery must remain idempotent across cleanup and
recovery sweeps. Tests cover duplicate delivery and company/run
boundaries.
- The workflow changes still need hosted Linux verification. They retain
the trusted workflow and credential boundaries.
- Gzip reduces the observed provider upload from about 1.8 GB to 663 MB.
It does not yet fix the remaining Claude Daytona transfer timeout. That
recovery test never reached Claude, so recovery remains unverified. Use
a matching image with the verified provider package preinstalled for the
next recovery test; retain cold-upload coverage separately.
- The report preserves diagnostic runs with missing source metadata and
marks them as such. It does not claim a new full-suite pass.
- This PR adds no new prompt policy or historical status reconciliation.

## Model Used

OpenAI GPT-6 through Codex performed the primary implementation and
review. The exact primary backend model ID is not exposed in this
session. OpenAI `gpt-5.6-luna` assisted with bounded infrastructure work
and verification. The agents used repository tools, code execution, and
browser tests. The exact backend revision and context-window size are
not exposed in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: OpenAI GPT-6 <noreply@openai.com>
This commit is contained in:
authored and GitHub committed 2026-09-21 12:50:50 -05:00
1 parent 0103cb2292
commit 3790ca2f13
23 files changed
+644 -93

No files matched your search

@@ -381,8 +381,17 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(nativeResponses).toMatchObject([{ interactionId: interaction.id, response: { status: "accepted", result: { toolAction: { status: "executed", resultSummary: expect.stringContaining("bodyLength") } } } }]);
expect(wakeup).not.toHaveBeenCalled();
expect((await db.select().from(toolActionDeliveries))[0].deliveredAt).toBeNull();
await deliveries.deliverForRun({ companyId: company.id, runId: run.id });
expect(wakeup).not.toHaveBeenCalled();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run.id));
const restarted = toolActionDeliveryService(db, { wakeup });
await deliveries.deliverForRun({ companyId: randomUUID(), runId: run.id });
await deliveries.deliverForRun({ companyId: company.id, runId: randomUUID() });
expect(wakeup).not.toHaveBeenCalled();
// The original executor's terminal cleanup must deliver a review that was
// approved while it was running, without waiting for the scheduler sweep.
await deliveries.deliverForRun({ companyId: company.id, runId: run.id });
expect(wakeup).toHaveBeenCalledTimes(1);
await Promise.all([restarted.sweepPending(), deliveries.sweepPending()]);
await gateway.approveActionRequest({ companyId: company.id, actionRequestId: request.id, actor: { userId: "second-reviewer" } });
await restarted.sweepPending();
+8
View File
@@ -1,4 +1,5 @@
import { publicChatTaskUrl } from "./chat-task-url.js";
import { toolActionDeliveryService } from "./tool-action-delivery.js";
import { readQueuedInteractionResponse } from "./queued-interaction-response.js";
import { AGENT_CHAT_DIRECTIVE, conversationReplay, isConversation, isConversationExecutionWake, isWaitingConversation, prepareConversationTurn, settleConversationTurn } from "./agent-conversations.js";
import { PROCESS_IDENTITY_RECORDED, recordNativeLocalProcessStop } from "./native-local-process-stop.js";
@@ -26011,6 +26012,13 @@ export function heartbeatService(
if (latestRun) await resumeRemoteStopComments(latestRun).catch(err => {
logger.warn({ err, runId: run.id }, "failed to resume user messages after remote Stop");
});
if (latestRun && isHeartbeatRunTerminalStatus(latestRun.status)) {
await toolActionDeliveryService(db, { wakeup: trackWakeup })
.deliverForRun({ companyId: run.companyId, runId: run.id })
.catch(err => {
logger.warn({ err, runId: run.id }, "failed to deliver settled tool reviews after execution cleanup");
});
}
await startNextQueuedRunForAgent(run.agentId);
}
}
@@ -4903,7 +4903,7 @@ describe("native session cancellation", () => {
});
});
it("waits for an in-flight startup handle before acknowledging Stop", async () => {
it.each([true, false])("waits for an in-flight startup handle before acknowledging Stop (runnerd=%s)", async (useRunnerd) => {
const root = await mkdtemp(join(tmpdir(), "native-startup-stop-"));
const previous = process.env.PAPERCLIP_RUNNER_STATE_DIR;
process.env.PAPERCLIP_RUNNER_STATE_DIR = root;
@@ -4927,7 +4927,7 @@ describe("native session cancellation", () => {
};
});
const running = executePaperclipNativeSession({
db: leaseDb(), execution, runnerInstanceId: "runner", useRunnerd: true,
db: leaseDb(), execution, runnerInstanceId: "runner", useRunnerd,
});
const outcome = running.catch(error => error);
const persistence = cancellationDb();
@@ -4935,6 +4935,9 @@ describe("native session cancellation", () => {
let acknowledged = false;
try {
await admitted;
await expect(executePaperclipNativeSession({
db: leaseDb(), execution, runnerInstanceId: "duplicate-runner", useRunnerd,
})).rejects.toThrow("native_session_supervisor_busy");
stopping = cancelNativeSession(execution.binding.runId, "operator Stop during startup", {
db: persistence.db, scope: "run",
});
@@ -4961,7 +4964,7 @@ describe("native session cancellation", () => {
}
});
it("fences a late startup even when Stop reaches its acknowledgement deadline", async () => {
it.each([true, false])("fences a late startup even when Stop reaches its acknowledgement deadline (runnerd=%s)", async (useRunnerd) => {
const root = await mkdtemp(join(tmpdir(), "native-late-startup-stop-"));
const previous = process.env.PAPERCLIP_RUNNER_STATE_DIR;
process.env.PAPERCLIP_RUNNER_STATE_DIR = root;
@@ -4975,7 +4978,7 @@ describe("native session cancellation", () => {
submitTurn();
throw new Error("a stopped startup must not reach prompt submission");
});
const outcome = executePaperclipNativeSession({ db: leaseDb(), execution, runnerInstanceId: "runner", useRunnerd: true }).catch(error => error);
const outcome = executePaperclipNativeSession({ db: leaseDb(), execution, runnerInstanceId: "runner", useRunnerd }).catch(error => error);
const persistence = cancellationDb();
try {
await admitted;
@@ -6593,6 +6596,25 @@ describe("native session bounded recovery", () => {
expect(state.upsertRecoveryAction).not.toHaveBeenCalled();
});
it.each(["pending", "acknowledged"])("preserves a %s Stop when cancellation wins before the first turn", async (dispatchState) => {
const updates: Array<{ table: unknown; values: Record<string, unknown> }> = [];
const stop: Record<string, unknown> = {};
state.execute.mockReset().mockImplementationOnce(async () => {
Object.assign(stop, { nativeCancellation: {
schema: "paperclip.native-cancellation.v1", ...execution.binding,
scope: "run", reasonCode: "cancellation_run_only", dispatchState,
dispatched: true, intentAuditId: "intent", acknowledgementAuditId: "ack",
} });
throw new Error("native_session_cancelled");
});
state.upsertRecoveryAction.mockClear();
await expect(executePaperclipNativeSession({
db: leaseDb(execution, {}, stop, updates), execution, runnerInstanceId: "stop-before-first-turn",
})).rejects.toThrow("native_cancellation_pending_recovery");
expect(updates.some(update => update.table === heartbeatRuns && update.values.status === "failed")).toBe(false);
expect(state.upsertRecoveryAction).not.toHaveBeenCalled();
});
it("keeps typed integrity failure permanent even if a wrapper changes its message", () => {
const failure = new NativeSessionProtocolIntegrityError(
"semantic_input_digest_mismatch",
@@ -6980,16 +6980,27 @@ export async function executePaperclipNativeSession(input: {
},
) => Promise<unknown>;
}): Promise<AdapterExecutionResult> {
if (!input.useRunnerd) {
return executePaperclipNativeSessionWithinScope(input);
const runId = input.execution.binding.runId;
if (nativeSessionStartups.has(runId)) {
throw new Error("native_session_supervisor_busy");
}
// Register before the first asynchronous operation on either backend path.
// A duplicate execution must not replace the original startup handoff.
let resolveStartup!: (session: ActiveNativeSession | null) => void;
const startup: NativeSessionStartup = {
promise: new Promise<ActiveNativeSession | null>(resolve => { resolveStartup = resolve; }),
resolve: session => resolveStartup(session),
};
nativeSessionStartups.set(runId, startup);
let preparedInput: typeof input = input;
let cleanupStagedAttachments: () => Promise<void> = async () => undefined;
let sessionScopeId: string | null = null;
let ownsSessionScope = false;
let executionFailure: unknown;
let startup: NativeSessionStartup | undefined;
try {
if (!input.useRunnerd) {
return await executePaperclipNativeSessionWithinScope(input);
}
// The session scope is unaffected by appending server-staged attachment
// descriptors. Claim it before any workspace scrub/write so a duplicate
// execution cannot truncate or replace the active turn's staging inode.
@@ -7002,11 +7013,6 @@ export async function executePaperclipNativeSession(input: {
input.execution.binding.runId,
);
ownsSessionScope = true;
let resolveStartup!: (session: ActiveNativeSession | null) => void;
const startupPromise = new Promise<ActiveNativeSession | null>(resolve => { resolveStartup = resolve; });
startup = { promise: startupPromise, resolve: resolveStartup };
nativeSessionStartups.set(input.execution.binding.runId, startup);
// The shutdown sweep can have removed an idle owner while its remote
// checkpoint is still being saved. The scope reservation also prevents
// a later sweep from closing an owner this turn is about to acquire.
@@ -7061,9 +7067,9 @@ export async function executePaperclipNativeSession(input: {
executionFailure = error;
throw error;
} finally {
startup?.resolve(null);
if (startup && nativeSessionStartups.get(input.execution.binding.runId) === startup) {
nativeSessionStartups.delete(input.execution.binding.runId);
startup.resolve(null);
if (nativeSessionStartups.get(runId) === startup) {
nativeSessionStartups.delete(runId);
}
if (
ownsSessionScope &&
@@ -8303,14 +8309,28 @@ async function executePaperclipNativeSessionWithinScope(
// Stop before paperclip_finish is normal. Bounded provider teardown has
// finished; a missing result must not overwrite cancellation or trigger
// another turn to perform completion bookkeeping.
if (protocolIntegrityFailure === null && error instanceof Error && error.message === "native_finalization_missing: session returned no semantic result") {
const stoppedBeforeFirstTurn = error instanceof Error && error.message === "native_session_cancelled";
if (protocolIntegrityFailure === null && error instanceof Error &&
(stoppedBeforeFirstTurn || error.message === "native_finalization_missing: session returned no semantic result")) {
const [stoppedRun] = await input.db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, input.execution.binding.runId),
eq(heartbeatRuns.companyId, input.execution.binding.companyId),
eq(heartbeatRuns.agentId, input.execution.binding.agentId),
eq(heartbeatRuns.nativeIssueId, input.execution.binding.issueId),
)).limit(1);
if (stoppedRun && (hasAcknowledgedNativeStopIntent(stoppedRun) || hasAcknowledgedNativeReassignmentStopIntent(stoppedRun))) {
const stopIntent = record(stoppedRun?.resultJson?.nativeCancellation);
// The backend can reject the first turn while the Stop API is still
// recording its acknowledgement. Preserve that audited, exactly bound
// cancellation instead of racing it with a generic provider failure.
const pendingStartupStop = stoppedBeforeFirstTurn &&
stopIntent.schema === "paperclip.native-cancellation.v1" &&
stopIntent.companyId === input.execution.binding.companyId &&
stopIntent.runId === input.execution.binding.runId &&
stopIntent.issueId === input.execution.binding.issueId &&
stopIntent.scope === "run" &&
typeof stopIntent.intentAuditId === "string" && stopIntent.intentAuditId.length > 0 &&
["pending", "acknowledged"].includes(String(stopIntent.dispatchState));
if (stoppedRun && (pendingStartupStop || hasAcknowledgedNativeStopIntent(stoppedRun) || hasAcknowledgedNativeReassignmentStopIntent(stoppedRun))) {
const [settled] = await input.db.update(nativeRunFinalizations).set({
phase: "terminal_failure", failureCode: "native_retry_cancelled", nextAttemptAt: null,
leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null, recoveryState: null,
@@ -337,6 +337,29 @@ export function toolActionDeliveryService(
}
return {
deliver,
async deliverForRun(input: { companyId: string; runId: string }) {
// A review can settle before its source run yields. Retry that run's
// receipts as soon as execution cleanup finishes; the periodic sweep
// remains the recovery path if this callback is interrupted.
const pending = await db
.select({ id: toolActionDeliveries.actionRequestId })
.from(toolActionDeliveries)
.innerJoin(toolActionRequests, and(
eq(toolActionRequests.id, toolActionDeliveries.actionRequestId),
eq(toolActionRequests.companyId, input.companyId),
))
.innerJoin(toolInvocations, and(
eq(toolInvocations.id, toolActionRequests.invocationId),
eq(toolInvocations.companyId, input.companyId),
eq(toolInvocations.runId, input.runId),
))
.where(and(
eq(toolActionDeliveries.companyId, input.companyId),
isNull(toolActionDeliveries.deliveredAt),
inArray(toolActionRequests.status, terminalStatuses),
));
for (const row of pending) await deliver(row.id);
},
async sweepPending() {
let cursor: string | undefined;
let scanned = 0;