fix(opencode): bound cooperative abort before governed shutdown (#23399)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native Runner saves a question before it stops the provider turn.
> - The wait must retain usage and prove shutdown before the run can
finish.
> - OpenCode's abort HTTP request can hold the command loop for twenty
seconds.
> - The transport close budget is ten seconds. A late abort can delay
definitive stop and suspension beyond that budget.
> - This pull request limits the cooperative abort request to five
seconds.
> - The benefit is time for definitive shutdown, with the same
accounting and suspension checks.

## Linked Issues or Issue Description

**What happened?**

A saved question can be followed by a failed native run. OpenCode's
cooperative abort can wait longer than the transport's shutdown budget.
The shutdown commands then lack time to prove provider drain and durable
suspension. A saved interaction alone cannot prove that the previous
executor stopped.

**Expected behavior**

A stalled cooperative abort must release the command loop in time for
definitive process stop. A timeout must still reject interruption. It
must not create a terminal event or count as successful accounting.

**Steps to reproduce**

Start a controlled OpenCode session. Keep its abort HTTP request pending
until its signal aborts. Request interruption. Advance the controlled
clock by five seconds. On the base code, the request is still pending.
With this change, the request rejects and the active turn remains
recorded without a terminal event or a new model request.

Related prior repairs: #20494, #20519, #20838. They address saved wait
recovery. This change addresses the pending cooperative abort before
definitive shutdown.

## What Changed

- Give only OpenCode's session abort a five-second HTTP deadline through
the API helper. Other API requests keep their existing deadline.
- Keep timeout errors visible. Keep physical stop, retained usage, and
durable suspension proof unchanged.
- Add a controlled-clock regression to the existing interruption tests.
- Document the deadline and proof requirements in the durable transport
contract.
- Keep session state and identity formats unchanged. Previous releases'
saved state needs no migration.

## Verification

- Red: the new regression fails on the base code because the request
signal remains active after five seconds.
- Green: both interruption test files pass, 13 tests. These include
idle, silent, busy-tool, provider-question handoff, pending MCP tool,
and the new stalled abort case.
- The eight `settles only verified governed shutdown` cases pass. They
cover success, restart, foreign turn, missing proof, stop failure,
timeout, provider failure, and terminal write failure.
- The broader driver run has 99 passes and eight failures. The same
driver file with this production change removed has 86 passes and the
same eight failures. Those failures concern final-answer retention. They
remain a verification gap; this PR does not change their assertions.
- No hosted acceptance claim yet. After merge and automatic staging
deployment, run only the question-answer-resume journey.
- Required CI passed on final commit
`45e39805efffbd648bfeca9697c9898593487805`:
https://github.com/paperclipai/paperclip/actions/runs/46726627054. This
includes typecheck, build, Runner tests, general tests, and E2E suites.
- Greptile gives final commit `45e39805e` 5/5, Medium impact. All three
review threads are resolved.
- After review corrections, both interruption files pass again: 13
tests. The test always restores timers and attempts resource cleanup.
The API helper owns the single request deadline.

## Risks

- An abort response that needs more than five seconds now fails earlier.
Definitive process stop must still prove shutdown. A timeout alone does
not authorize session reuse or completion.
- The regression uses the real driver and a controlled HTTP boundary. It
does not prove hosted suspension timing. The targeted staging journey
remains required.
- The owning driver file already exceeds 1,000 lines. The change adds
only the request deadline and its rationale at the existing abort call.
A separate module would add no useful boundary.
- There is no schema, saved identity, provider selection, accounting
policy, or journey grading change.

## Model Used

- OpenAI GPT-6, through Codex with reasoning and tools for source
inspection, code editing, and test 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
- [ ] 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-01 19:55:53 +00:00
1 parent 11d5b06864
commit 7585830b9c
3 files changed
+81 -1

No files matched your search

@@ -51,6 +51,13 @@ Recovery uses the same entry point. The Runner rejects `--source-reconcile`.
## Recovery contract
OpenCode's cooperative session abort has a five-second HTTP deadline. The
ordinary API deadline is twenty seconds, which can keep the command loop busy
beyond the governed wait's accounting drain and the transport's close budget.
An abort timeout still fails the interruption. It does not establish a provider
terminal or successful accounting. Definitive `turn.stop`, retained event drain,
and exact durable suspension proof remain required before a saved wait settles.
Events enter the outbox before delivery. A cumulative ACK may advance only to a
source sequence the runner has produced; acknowledged prefixes are removed
atomically from durable state. After disconnect, every remaining event is sent
@@ -122,3 +122,74 @@ it.each(["idle", "status", "silent", "correcting-idle", "correcting-silent", "bu
await rm(root, { recursive: true, force: true });
}
}, 15_000);
it("releases a stalled cooperative abort before governed shutdown without inventing a terminal", async () => {
const root = await mkdtemp(join(tmpdir(), "opencode-abort-deadline-"));
const command = join(root, "fake-opencode.mjs");
await copyFile(resolve("test/fixtures/fake-opencode-server.mjs"), command);
await chmod(command, 0o755);
let streamOpened!: () => void;
const opened = new Promise<void>(done => { streamOpened = done; });
let abortStarted!: () => void;
const aborting = new Promise<void>(done => { abortStarted = done; });
let abortSignal: AbortSignal | undefined;
const observed: PrpEvent[] = [];
let prompts = 0;
const driver = new OpenCodeServerDriver({
model: "openrouter/controlled-model", runtimeDirectory: root, command,
environment: { PATH: process.env.PATH, OPENROUTER_API_KEY: "controlled-fixture-key" },
fetch: async (input, init) => {
const url = new URL(String(input));
if (url.pathname === "/event") return new Response(new ReadableStream<Uint8Array>({
start() { streamOpened(); },
}), { headers: { "Content-Type": "text/event-stream" } });
if (url.pathname.endsWith("/prompt_async")) {
prompts += 1;
return new Response(null, { status: 204 });
}
if (url.pathname.endsWith("/abort")) {
abortSignal = init!.signal!;
abortStarted();
return new Promise<Response>((_resolve, reject) => {
abortSignal!.addEventListener("abort", () => reject(abortSignal!.reason), { once: true });
});
}
return fetch(input, init);
},
});
const session = await driver.openSession({ runId: "owned-run", normalizedSessionId: "owned-session", workingDirectory: root });
let collecting: Promise<void> | undefined;
try {
await opened;
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
vi.spyOn(AbortSignal, "timeout").mockImplementation(ms => {
const controller = new AbortController();
setTimeout(() => controller.abort(new DOMException("Deadline exceeded", "TimeoutError")), ms);
return controller.signal;
});
collecting = (async () => { for await (const event of session.events()) observed.push(event); })();
const turn = await session.startTurn({ message: { role: "user", text: "Save a question and wait." } });
const interruption = session.interrupt!({ turnId: turn.turnId });
void interruption.catch(() => undefined);
await aborting;
await vi.advanceTimersByTimeAsync(5_001);
expect(abortSignal?.aborted).toBe(true);
await expect(interruption).rejects.toThrow(/abort request failed: TimeoutError/);
expect(observed.filter(event => ["turn.completed", "turn.cancelled", "turn.failed"].includes(event.eventType))).toEqual([]);
expect(prompts).toBe(1);
expect((await session.snapshot()).activeTurnId).toBe(turn.turnId);
} finally {
try {
if (vi.isFakeTimers()) await vi.advanceTimersByTimeAsync(20_001);
} finally {
vi.restoreAllMocks();
vi.useRealTimers();
try {
await session.close({ reason: "controlled test complete" });
await collecting;
} finally {
await rm(root, { recursive: true, force: true });
}
}
}
}, 15_000);
@@ -987,6 +987,7 @@ class OpenCodeHarnessSession implements HarnessSession {
this.#runtime,
`/session/${encodeURIComponent(this.#providerSessionId)}/abort`,
{ method: "POST" },
5_000,
);
}
@@ -3176,8 +3177,9 @@ async function api(
runtime: OpenCodeRuntime,
path: string,
init: RequestInit = {},
timeoutMs = 20_000,
): Promise<unknown> {
const timeout = AbortSignal.timeout(20_000);
const timeout = AbortSignal.timeout(timeoutMs);
const signal = init.signal
? AbortSignal.any([init.signal, timeout])
: timeout;