fix(runner): keep the session of a stopped run (#23543)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The conversation an agent has on a task is called a session. Each
task saves a pointer to its session (the session link), and the next run
uses it to continue the conversation
> - A run's own record keeps its session id. The task gets its pointer
to that session only when the run's result is accepted
> - A stopped run has no accepted result, so it saves no pointer. If a
task's first run is stopped, the task has no pointer. The next run
starts a new session and the agent has forgotten the first run
> - A later run can also start a new session, for example after an
assignment, a retry or a configuration change. If that run is stopped,
the pointer still names the older session. The next message goes back to
the older session or starts another one
> - Saving the pointer on every stop would be unsafe. The agent's turn
might still be open, a request might still be waiting, or the provider
might not have kept the session
> - This pull request copies the session id from a stopped run to the
task only when the records show that the stop was acknowledged, the turn
started and then ended with nothing waiting, the provider kept the
session, and no newer run has taken over the task. Otherwise, the
pointer does not change
> - The benefit is that someone can stop a run, send a correction, and
continue the same conversation

## Linked Issues or Issue Description

No issue exists.

**What happened?**

A user stopped the first run of a task. The user then sent a message.
The agent started a new session and did not remember the first run. The
same loss happens when a user stops a later run that started a new
session.

**Expected behavior**

The agent continues the session of the stopped run.

**Steps to reproduce**

1. Use an agent whose environment provider runs Runner tasks and keeps
their session state.
2. Create a task and wait for the first run to start a turn.
3. Stop the run during the turn.
4. Send a message on the task.
5. See that the new run has a new session.

**Paperclip version or commit**

`4db307d53c`

**Deployment mode**

Self-hosted server with a sandbox environment plugin.

## What Changed

- A stopped run now links its session after its environment lease is
released.
- The link needs all of this evidence:
  - The Stop was delivered and acknowledged.
- The provider accepted a turn. The next prompt leaves out messages that
the linked run received, so a run whose turn did not start cannot be
linked.
  - The turn ended. No request, background work or goal is waiting.
  - The controller journal is settled.
- The provider reports that the task stopped and that it kept the
session state.
  - No newer run, reset or conversation owns the task.
- An existing link is replaced only if its run belongs to the same task
and agent and finished before the stopped run started. Accepted results
already use this rule. Both paths now share one function.
- If any evidence is missing, the link does not change, as before.
- If the provider later confirms that the kept state is gone, the next
run starts a new session. The acknowledged Stop replaces the committed
result in that proof. All other checks in that proof still apply.

## Verification

- `npx vitest run` on the publication tests for stopped runs, the
publication tests for accepted results, the runtime execution tests and
the terminal state reader test: 121 passed. The executor tests ran on an
earlier commit, and the executor code has not changed since.
- The publication tests use embedded Postgres. They test six saves and
37 refusals. Each refusal checks that the task session row did not
change.
- The executor tests check that a stopped run retires after a confirmed
state loss. They also check that an unacknowledged Stop and a different
failure stay refused.
- `npx tsc --noEmit` in `server` has no errors.
- Saved evidence from two real first-run stops during a turn shows ended
turns with no request waiting. The first has a released lease with kept
session state. The second failed its lease cleanup, so this change still
refuses it.
- Saved evidence from two real later-run stops: one kept its session,
and the next run resumed it. The other kept no session and had no
settled turn, and the next run failed. This change refuses to link the
second.
- Two of 104 real stops with a cancelled terminal had no accepted turn.
The turn check refuses them.
- Not done: a live test of this change. CI runs the Runner integration
suites.

## Risks

- A wrong link could resume an unsafe session. The link uses the same
evidence that the resume path checks again, so the resume path still
refuses an unsettled session.
- A link that turns out to be unusable now replaces an older link
instead of no link. The next run then usually fails, and the run after
it usually starts a new session, as it does for an unusable link from a
finished run.
- The change applies only to providers that run Runner tasks and report
kept session state. Local Runners and other sandboxes have no equal
evidence, so they keep the previous behavior.
- A stop while the agent waits for background work is not covered. The
Runner holds its terminal event in that state, so the evidence is
missing.
- The saved link keeps that run's Runner checkpoint, as any other link
does.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, tool use and code execution.

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Nicky LeachandClaude Opus 5.5 authored and GitHub committed 2026-12-03 08:17:44 -08:00
1 parent dc16c47362
commit 63d3354be7
10 files changed
+379 -15

No files matched your search

@@ -20083,6 +20083,9 @@ describe("runnerd provider runtime wiring", () => {
"stopped-availability-omitted",
"stop-unconfirmed",
"stopped-lease-unreleased",
"run-stopped-state-unavailable",
"run-stopped-unacknowledged",
"run-stopped-other-failure",
] as const)(
"handles unconfirmed plugin checkpoint status on replacement lease: %s",
async mode => {
@@ -20112,16 +20115,27 @@ describe("runnerd provider runtime wiring", () => {
const ordinarySelect = db.select.bind(db);
const { currentNativeControllerIdentity } = await import("./native-restart-recovery.js");
const controller = await currentNativeControllerIdentity();
const runStopped = mode.startsWith("run-stopped");
const committedPrior = {
run: {
id: first.binding.runId, companyId: first.binding.companyId, agentId: first.binding.agentId,
nativeIssueId: first.binding.issueId, runtimeMode: "native", status: "succeeded",
nativeIssueId: first.binding.issueId, runtimeMode: "native", status: runStopped ? "cancelled" : "succeeded",
resultJson: runStopped ? { nativeCancellation: {
schema: "paperclip.native-cancellation.v1", runId: first.binding.runId, companyId: first.binding.companyId,
issueId: first.binding.issueId, scope: "run", reasonCode: "cancellation_run_only", dispatched: true,
dispatchState: mode === "run-stopped-unacknowledged" ? "requested" : "acknowledged",
intentAuditId: "intent", acknowledgementAuditId: "acknowledgement",
} } : null,
runnerProfileJson: { nativeExecutionInput: first },
processPid: null, processGroupId: null, processStartedAt: null,
},
owner: {
runId: first.binding.runId, companyId: first.binding.companyId, issueId: first.binding.issueId,
phase: "committed", resultId: "result-1", leaseOwner: null, recoveryState: null,
...(runStopped
? { phase: "terminal_failure", resultId: null,
failureCode: mode === "run-stopped-other-failure" ? "provider_failed" : "native_retry_cancelled" }
: { phase: "committed", resultId: "result-1", failureCode: null }),
leaseOwner: null, recoveryState: null,
controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt,
controllerBootId: controller.bootId,
},
@@ -20150,7 +20164,7 @@ describe("runnerd provider runtime wiring", () => {
};
db.select = ((fields?: Record<string, unknown>) => {
if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) {
return priorNativeRunDb(first, "succeeded").select(fields as never);
return priorNativeRunDb(first, committedPrior.run.status).select(fields as never);
}
if (fields && "run" in fields && "owner" in fields) {
return {
@@ -20202,10 +20216,14 @@ describe("runnerd provider runtime wiring", () => {
sandboxLeaseAcquisition: { outcome: "replacement", providerLeaseId: "replacement-task" },
} as never,
};
if (mode === "stopped-state-unavailable") {
if (mode === "stopped-state-unavailable" || mode === "run-stopped-state-unavailable") {
await expect(createRunnerdBackend(launch)).resolves.toBeDefined();
expect(state.createBackend).toHaveBeenCalledOnce();
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(true);
} else if (runStopped) {
await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=owner_terminal_failure");
expect(state.createBackend).not.toHaveBeenCalled();
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false);
} else if (mode === "stopped-lease-unreleased") {
await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=prior_lease_active");
expect(state.createBackend).not.toHaveBeenCalled();