Files
PaperClipAI/server/src/services/native-runtime/native-stopped-session-publication.test.ts
Nicky LeachandClaude Opus 5.5 63d3354be7 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>
2026-12-03 08:17:44 -08:00

214 lines
15 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import { agents, agentTaskSessions, companies, createDb, environmentLeases, environments, heartbeatRunEvents,
heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js";
const journal = vi.hoisted(() => ({ load: vi.fn() }));
vi.mock("./native-runner-checkpoint.js", async original => ({
...await original<typeof import("./native-runner-checkpoint.js")>(), loadNativeRunnerCheckpoint: journal.load,
}));
const { publishStoppedNativeSession } = await import("./native-stopped-session-publication.js");
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("stopped run's task session", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("paperclip-stopped-session-");
db = createDb(temporary.connectionString);
}, 60_000);
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await temporary?.cleanup();
});
beforeEach(() => { journal.load.mockReset(); });
async function fixture() {
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
const sessionId = randomUUID(), runner = randomUUID(), environmentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Stopped session", issuePrefix: uniqueIssuePrefix("SS") });
await db.insert(agents).values({ id: agentId, companyId, name: "Agent", adapterType: "paperclip_runner" });
await db.insert(issues).values({ id: issueId, companyId, title: "Task", status: "in_progress", assigneeAgentId: agentId });
const nativeCancellation = { schema: "paperclip.native-cancellation.v1", intentId: "intent", intentAuditId: "intent-audit",
acknowledgementAuditId: "acknowledgement-audit", companyId, runId, issueId, scope: "run",
reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true };
const sessionCheckpoint = { backendKind: "test", sessionId, providerSessionId: "provider-thread", activeTurnId: null,
identity: { companyId, agentId, issueId, runId, sessionId }, pendingRuntimeRequests: [], goal: null, semanticResult: null,
terminal: { schema: "paperclip.prp.terminal.v1", turnTerminalState: "cancelled", runTerminalState: "cancelled",
reportedWorkDisposition: "yielded" } };
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "cancelled", runtimeMode: "native",
nativeIssueId: issueId, issueId, nativeSessionId: sessionId, runnerInstanceId: runner,
startedAt: new Date("2026-01-01T00:10:00Z"), finishedAt: new Date("2026-01-01T00:20:00Z"), resultJson: { nativeCancellation }, runnerProfileJson: { sessionCheckpoint } });
await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId, seq: 1, eventType: "turn.accepted" });
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "terminal_failure",
failureCode: "native_retry_cancelled", attempt: 1 });
await db.insert(environments).values({ id: environmentId, name: `Environment ${environmentId}`, driver: "plugin" });
const metadata = { runnerTaskLease: true, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true,
runnerTaskIdentity: { runnerId: runner, leaseId: "lease", runId, sessionId } };
const [lease] = await db.insert(environmentLeases).values({ companyId, environmentId, issueId, heartbeatRunId: runId,
status: "released", cleanupStatus: "success", provider: "plugin", providerLeaseId: "task", metadata }).returning();
await db.insert(agentTaskSessions).values({ companyId, agentId, adapterType: "paperclip_runner", taskKey: issueId,
goalSourceId: `${runner}:${runId}`, goalSourceCursor: 4 });
const envelope = { runId, normalizedSessionId: sessionId };
const control: Record<string, unknown> = { identity: { runId, normalizedSessionId: sessionId, runnerInstanceId: runner },
commands: [{ type: "turn.start", status: "completed", controllerSeq: 1 }, { type: "runner.suspend", status: "completed", controllerSeq: 2 }],
committedEvents: [{ eventType: "turn.cancelled", envelope }, { eventType: "run.terminal", envelope }] };
journal.load.mockImplementation(async () => ({ records: new Map([
["header", JSON.stringify({ state: { identity: control.identity } })],
["cursor", "{}"],
...(control.commands as unknown[]).map((command, index) => [`command:${index + 1}`, JSON.stringify(command)] as const),
...(control.committedEvents as unknown[]).map((event, index) => [`event:${index + 1}`, JSON.stringify(event)] as const),
]) }));
const context = { taskKey: issueId, adapterType: "paperclip_runner",
sessionParamsJson: { cwd: "/workspace", paperclipSessionConfigFingerprint: "prepared" } };
const read = async () => (await db.select().from(agentTaskSessions).where(eq(agentTaskSessions.taskKey, issueId)))[0];
const setRun = (values: Partial<typeof heartbeatRuns.$inferInsert>) =>
db.update(heartbeatRuns).set(values).where(eq(heartbeatRuns.id, runId));
const setLease = (values: Partial<typeof environmentLeases.$inferInsert>) =>
db.update(environmentLeases).set(values).where(eq(environmentLeases.id, lease!.id));
return { companyId, agentId, issueId, runId, sessionId, runner, environmentId, nativeCancellation, sessionCheckpoint,
metadata, control, context, read, setRun, setLease, publish: () => publishStoppedNativeSession(db, runId, context) };
}
type Fixture = Awaited<ReturnType<typeof fixture>>;
const linkEarlierRun = async (f: Fixture, sessionId: string, run: Partial<typeof heartbeatRuns.$inferInsert> = {}) => {
const id = randomUUID();
await db.insert(heartbeatRuns).values({ id, companyId: f.companyId, agentId: f.agentId, status: "succeeded", issueId: f.issueId,
startedAt: new Date("2026-01-01T00:00:00Z"), finishedAt: new Date("2026-01-01T00:05:00Z"), ...run });
await db.update(agentTaskSessions).set({ lastRunId: id, sessionDisplayId: "earlier-thread",
sessionParamsJson: { sessionId, paperclipSessionConfigFingerprint: "earlier" } }).where(eq(agentTaskSessions.taskKey, f.issueId));
};
const newerRun = async (f: Fixture) => {
const id = randomUUID();
await db.insert(heartbeatRuns).values({ id, companyId: f.companyId, agentId: f.agentId, status: "queued", issueId: f.issueId });
return id;
};
it("links the session with the prepared metadata, so the next run can resume it", async () => {
const f = await fixture();
expect(await f.publish()).toBe("published");
expect(await f.read()).toMatchObject({ lastRunId: f.runId, sessionDisplayId: "provider-thread", lastError: null,
sessionParamsJson: { ...f.context.sessionParamsJson, sessionId: f.sessionId } });
expect(await f.publish()).toBe("published");
});
it.each([
["the same session", (f: Fixture) => f.sessionId],
["another session", () => randomUUID()],
])("replaces an earlier run's link to %s", async (_name, linkedSession) => {
const f = await fixture();
await linkEarlierRun(f, linkedSession(f));
expect(await f.publish()).toBe("published");
expect(await f.read()).toMatchObject({ lastRunId: f.runId, sessionDisplayId: "provider-thread",
sessionParamsJson: { ...f.context.sessionParamsJson, sessionId: f.sessionId } });
});
it("replaces an earlier run that finished when this run started", async () => {
const f = await fixture();
await linkEarlierRun(f, randomUUID(), { finishedAt: new Date("2026-01-01T00:10:00Z") });
expect(await f.publish()).toBe("published");
});
it("accepts the provider's own turn start", async () => {
const f = await fixture();
await db.update(heartbeatRunEvents).set({ eventType: "turn.started" }).where(eq(heartbeatRunEvents.runId, f.runId));
expect(await f.publish()).toBe("published");
});
it("accepts the issue's execution lock when this run still holds it", async () => {
const f = await fixture();
await db.update(issues).set({ executionRunId: f.runId }).where(eq(issues.id, f.issueId));
expect(await f.publish()).toBe("published");
});
const refusals: Array<[string, string, (f: Fixture) => Promise<unknown> | void]> = [
["the Stop was never acknowledged", "stop_unproven", f =>
f.setRun({ resultJson: { nativeCancellation: { ...f.nativeCancellation, dispatchState: "pending" } } })],
["the Stop did not reach the provider", "stop_unproven", f =>
f.setRun({ resultJson: { nativeCancellation: { ...f.nativeCancellation, dispatched: false } } })],
["the run failed instead of stopping", "stop_unproven", f => f.setRun({ status: "failed" })],
["the coordinator did not settle as a Stop", "stop_unproven", f => db.update(nativeRunFinalizations)
.set({ phase: "retryable_failure", failureCode: "native_session_interrupted" }).where(eq(nativeRunFinalizations.runId, f.runId))],
["recovery still owns the run", "stop_unproven", f => db.update(nativeRunFinalizations)
.set({ leaseOwner: "owner", leaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(nativeRunFinalizations.runId, f.runId))],
["no checkpoint was saved", "turn_unsettled", f => f.setRun({ runnerProfileJson: {} })],
["the checkpoint belongs to another session", "turn_unsettled", f => f.setRun({ nativeSessionId: randomUUID() })],
["the turn never ended", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, activeTurnId: "turn", terminal: null } } })],
["the turn waits for background work", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, awaitingProviderTurn: true, terminal: null } } })],
["the turn failed", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, terminal: { ...f.sessionCheckpoint.terminal, runTerminalState: "failed" } } } })],
["a request is still waiting for an answer", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, pendingRuntimeRequests: [{ requestId: "request" }] } } })],
["a goal is recorded", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, goal: { status: "active" } } } })],
["the provider never accepted a turn", "turn_not_started", f => db.update(heartbeatRunEvents)
.set({ eventType: "turn.submitted" }).where(eq(heartbeatRunEvents.runId, f.runId))],
["only another run's turn was accepted", "turn_not_started", async f => {
const runId = await newerRun(f);
await db.update(heartbeatRunEvents).set({ runId }).where(eq(heartbeatRunEvents.runId, f.runId));
}],
["the journal is missing", "journal_unsettled", () => { journal.load.mockResolvedValue(null); }],
["the journal cannot be read", "journal_unsettled", () => { journal.load.mockRejectedValue(new Error("retired")); }],
["the journal names another run", "journal_unsettled", f => { (f.control.identity as Record<string, unknown>).runId = randomUUID(); }],
["the journal has no terminal", "journal_unsettled", f => { (f.control.committedEvents as unknown[]).pop(); }],
["a command is still pending", "journal_unsettled", f => { (f.control.commands as Array<Record<string, unknown>>)[1]!.status = "pending"; }],
["a command's outcome is unknown", "journal_unsettled", f => {
(f.control.commands as Array<Record<string, unknown>>)[0]!.status = "indeterminate"; }],
["a tool call started after the terminal", "journal_unsettled", f => {
(f.control.committedEvents as unknown[]).push({ eventType: "tool.execution.started",
envelope: { runId: f.runId, normalizedSessionId: f.sessionId } }); }],
["the provider kept no session state", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskSessionRetained: false } })],
["the task is not known to have stopped", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskExecutionStopped: false } })],
["the retained state names another session", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskIdentity: { ...f.metadata.runnerTaskIdentity, sessionId: randomUUID() } } })],
["the lease is not a Runner task", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskLease: false } })],
["lease cleanup is still pending", "session_not_retained", f =>
f.setLease({ status: "pending_cleanup", cleanupStatus: "failed" })],
["the run used a second lease", "session_not_retained", f => db.insert(environmentLeases).values({ companyId: f.companyId,
environmentId: f.environmentId, issueId: f.issueId, heartbeatRunId: f.runId, status: "released", cleanupStatus: "success",
provider: "plugin", providerLeaseId: "other-task", metadata: f.metadata })],
["a newer run holds the task", "superseded", async f => db.update(issues).set({ executionRunId: await newerRun(f) })
.where(eq(issues.id, f.issueId))],
["a newer run wrote the session row", "superseded", async f => db.update(agentTaskSessions)
.set({ goalSourceId: `${f.runner}:${await newerRun(f)}` }).where(eq(agentTaskSessions.taskKey, f.issueId))],
["the session was reset", "session_row_missing", f => db.delete(agentTaskSessions).where(eq(agentTaskSessions.taskKey, f.issueId))],
["a later run wrote the link", "superseded", f => linkEarlierRun(f, randomUUID(), {
startedAt: new Date("2026-01-01T00:21:00Z"), finishedAt: new Date("2026-01-01T00:22:00Z") })],
["the linked run has not finished", "superseded", f => linkEarlierRun(f, randomUUID(), { status: "running", finishedAt: null })],
["the linked run belongs to another task", "superseded", async f => {
const issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Other task", status: "todo" });
await linkEarlierRun(f, randomUUID(), { issueId });
}],
["the linked run belongs to another agent", "superseded", async f => {
const agentId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId: f.companyId, name: "Other agent", adapterType: "paperclip_runner" });
await linkEarlierRun(f, randomUUID(), { agentId });
}],
["this run has no start time", "superseded", async f => {
await linkEarlierRun(f, randomUUID());
await f.setRun({ startedAt: null });
}],
["the task is a conversation", "unsupported_task", f => db.update(issues).set({ conversationAgentId: f.agentId,
conversationUserId: "stopped-session-user", conversationState: "active" }).where(eq(issues.id, f.issueId))],
["the run's content was deleted", "unsupported_task", f => f.setRun({
resultJson: { nativeCancellation: f.nativeCancellation, contentDeletedAt: new Date(0).toISOString() } })],
];
it.each(refusals)("leaves the task session unchanged when %s", async (_name, outcome, change) => {
const f = await fixture();
await change(f);
const before = await f.read();
expect(await f.publish()).toBe(outcome);
expect(await f.read()).toEqual(before);
});
});