Skip to content

Commit f145fd5

Browse files
committed
fix(cursor): surface a cancel we did not request instead of dropping the turn
An unexpected NGHTTP2_CANCEL produced a turn with zero adapter events. The transport already got this right - both failure exits check `this.expectedClose` before swallowing a cancel - but the adapter re-decided the same question one layer up from the error CODE alone (cursor.ts:181 via isCursorBenignCancelError), with no provenance in scope. A cancel Cursor sent us was therefore indistinguishable from one we sent, and the turn vanished: streaming degraded to adapter_eof, non-streaming returned "completed". The transport now raises a typed CursorUnexpectedCancelError when the cancel is not ours and no terminal has been emitted yet. Two details the audit forced: - The guard includes !emittedTerminal. Tagging on !expectedClose alone would fire after a done/error was already queued, and buffered JSON processes both - flipping a completed turn to failed. - The error carries its own message rather than the raw NGHTTP2_CANCEL text. Left raw, it is re-matched by classifyCursorError and reported as "Cursor stream suspended", so a turn that failed unexpectedly would claim an intentional suspension. Untagged cancels keep their existing benign classification, so nothing that returns silently today starts erroring without evidence. Verified red-before-green.
1 parent dfb6fb8 commit f145fd5

4 files changed

Lines changed: 279 additions & 3 deletions

File tree

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# 040 — Phase 4: a server-side cancel must not vanish
2+
3+
Discovered by the round-6 audit of `010` and recorded there as a follow-up.
4+
Its own work-phase (LOOP-UNIT-CHAIN-01). **Revised after an audit returned FAIL**
5+
with two blockers; the original plan is corrected below.
6+
7+
## The defect
8+
9+
An unexpected `NGHTTP2_CANCEL` produces a turn with **zero adapter events**.
10+
11+
The transport already gets this right. Both failure exits
12+
(`live-transport.ts:629`, `:638`) check provenance before swallowing:
13+
14+
```ts
15+
if (this.expectedClose && isCursorBenignCancelError(failure)) return;
16+
throw attachPartialUsage(summarizeFailure(failure), state);
17+
```
18+
19+
So an unexpected cancel is thrown, correctly. It is the **adapter** that loses it
20+
(`cursor.ts:181`):
21+
22+
```ts
23+
if (isCursorBenignCancelError(err)) return;
24+
```
25+
26+
No `expectedClose` in scope, so it re-decides from the error **code** alone
27+
(`cursor-errors.ts:49`) and returns silently. The transport's provenance check is
28+
overruled one layer up by a weaker test of the same question.
29+
30+
Downstream: streaming synthesizes `response.incomplete` / `adapter_eof`
31+
(`bridge.ts:1283`); non-streaming defaults to `"completed"` (`:1829`) — the same
32+
silent-success shape `010` closed for EOF.
33+
34+
## Audit corrections
35+
36+
**Blocker 1 — do not re-emit after a terminal.** Tagging on `!expectedClose`
37+
alone would fire even when a `done`/`error` was already queued, adding a second
38+
terminal (`emittedTerminal` is set at `live-transport.ts:540`). Buffered JSON
39+
processes both and flips a completed turn to failed. **Tag only when
40+
`!expectedClose && !emittedTerminal`**, at both exits.
41+
42+
**Blocker 2 — a marker alone produces a lying message.** Making
43+
`isCursorBenignCancelError` false is not enough: `safeCursorTransportError`
44+
(`cursor.ts:50`) passes only `err.message` to `safeCursorErrorMessage`, and
45+
`classifyCursorError:105` re-matches the untagged string and labels it
46+
`"Cursor stream suspended"`. The turn would fail with a message claiming an
47+
intentional suspension — worse than the silent drop, because it misdirects
48+
diagnosis. **The tagged error must carry its own message**, not be reclassified
49+
from the raw text.
50+
51+
**Blocker 3 — the fixture cannot do a literal server RST.** A server-side
52+
`stream.close(NGHTTP2_CANCEL)` surfaces as a clean `end` in the local h2 fixture.
53+
Test 1 uses the existing fault-injection seam
54+
(`tests/cursor-live-transport.test.ts:207`) and is named for a **cancel-shaped
55+
transport failure**, not a literal RST reproduction. It is genuinely red today
56+
under that seam.
57+
58+
## Contract
59+
60+
| Situation | Behavior |
61+
|-----------|----------|
62+
| We cancelled (`expectedClose`) | silent — unchanged |
63+
| Cancel with a terminal already emitted | silent — no duplicate |
64+
| Cancel we did not request, no terminal yet | one `error`, with an honest message |
65+
66+
## Diff-level plan
67+
68+
**`src/adapters/cursor/cursor-errors.ts`**
69+
70+
- Add `CursorUnexpectedCancelError` carrying a message that names what happened
71+
("Cursor cancelled the stream before the turn completed"), so the adapter's
72+
existing `safeCursorTransportError` path renders it correctly instead of
73+
matching `"nghttp2_cancel"` and calling it a suspension.
74+
- `isCursorBenignCancelError` returns **false** for this class. Untagged errors
75+
keep the current code/message matching, so nothing that returns silently today
76+
starts erroring without evidence.
77+
- Verify `classifyCursorError` maps the new message to a connection failure, not
78+
`"Cursor stream suspended"`.
79+
80+
**`src/adapters/cursor/live-transport.ts`**
81+
82+
- At both failure exits, when `!this.expectedClose && !this.emittedTerminal` and
83+
the failure is cancel-shaped, throw `CursorUnexpectedCancelError` (preserving
84+
`attachPartialUsage`) instead of the raw failure.
85+
- `cancelCursorRun` is unchanged; its `expectedClose` write is the provenance.
86+
87+
**`src/adapters/cursor.ts`** — unchanged.
88+
89+
## Tests (`tests/cursor-cancel-provenance.test.ts`)
90+
91+
1. Cancel-shaped transport failure, no `expectedClose`, no prior terminal ->
92+
exactly one `error` event, **and** its message does not say "suspended".
93+
Red today. Uses the fault-injection seam.
94+
2. Client-tool suspend (`expectedClose`) -> still silent. The regression that
95+
matters: every working multi-turn tool cycle takes this path.
96+
3. Cancel after a terminal was already emitted -> still silent, no duplicate.
97+
4. Unit: `isCursorBenignCancelError` false for the new class, still true for an
98+
untagged `NGHTTP2_CANCEL` and for `"cursor stream suspended"`;
99+
`classifyCursorError` does not label the new message as a suspension.
100+
101+
## Scope
102+
103+
Not in scope: the non-streaming `completed` default (`bridge.ts:1829`), still the
104+
open follow-up in `000_index.md`. This removes one route to it, not the default.
105+
106+
## Done when
107+
108+
All four pass, `bun run typecheck` clean, cursor suite green on `ssh lidge`,
109+
pushed. Test 1 demonstrated red on the pre-fix tree.
110+

‎src/adapters/cursor/cursor-errors.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,28 @@ export class CursorStreamTruncatedError extends Error {
4646
}
4747
}
4848

49+
/**
50+
* A cancel-shaped stream failure that WE did not request. `cancelCursorRun` is the only place
51+
* that cancels our own stream, and it sets `expectedClose` first, so a cancel arriving without it
52+
* came from Cursor or the network and is a real transport failure.
53+
*
54+
* It carries its own message on purpose. Left as a raw `NGHTTP2_CANCEL` error, the text is
55+
* re-matched downstream (`classifyCursorError`) and labelled "Cursor stream suspended" — a turn
56+
* that failed unexpectedly would report an intentional suspension and misdirect diagnosis.
57+
*/
58+
export class CursorUnexpectedCancelError extends Error {
59+
constructor(public readonly cause?: unknown) {
60+
super("Cursor connection was cancelled by the server before the turn completed");
61+
this.name = "CursorUnexpectedCancelError";
62+
}
63+
}
64+
4965
export function isCursorBenignCancelError(value: unknown): boolean {
66+
// An unexpected cancel is never benign, however it is spelled. This class is raised only when
67+
// the transport knows WE did not request the cancel, so its provenance outranks the code match
68+
// below — otherwise the adapter would re-decide the same question from the error code alone
69+
// and swallow a real transport failure (cursor.ts:181).
70+
if (value instanceof CursorUnexpectedCancelError) return false;
5071
const message = errorMessage(value).toLowerCase();
5172
const code = errorCode(value).toUpperCase();
5273
if (code === "NGHTTP2_CANCEL") return true;

‎src/adapters/cursor/live-transport.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import {
4848
type InteractionResponse,
4949
} from "./gen/agent_pb";
5050
import { debugProviderDiagnostic } from "../../lib/debug";
51-
import { classifyCursorError, CursorStreamTruncatedError, isCursorBenignCancelError, safeCursorErrorMessage } from "./cursor-errors";
51+
import { classifyCursorError, CursorStreamTruncatedError, CursorUnexpectedCancelError, isCursorBenignCancelError, safeCursorErrorMessage } from "./cursor-errors";
5252
import { mcpArgsFromToolCall } from "./protobuf-events";
5353
import { OCX_RESPONSES_TOOL_PROVIDER } from "./tool-definitions";
5454
import {
@@ -528,6 +528,22 @@ class LiveCursorTransport implements CursorTransport {
528528
}
529529
return err;
530530
};
531+
/**
532+
* A cancel we did not request is a real transport failure, but as a raw `NGHTTP2_CANCEL` it
533+
* gets swallowed twice over: the adapter re-decides "benign" from the error code alone
534+
* (`cursor.ts:181`) and drops the turn, and any message that survives is re-matched
535+
* downstream and labelled an intentional "Cursor stream suspended". Raising a typed error
536+
* carries the provenance this class already holds.
537+
*
538+
* Suppressed once a terminal was emitted: the turn already ended, and a second terminal flips
539+
* a completed buffered response to failed.
540+
*/
541+
const classifyTurnFailure = (err: Error): Error => {
542+
if (!this.expectedClose && !this.emittedTerminal && isCursorBenignCancelError(err)) {
543+
return summarizeFailure(new CursorUnexpectedCancelError(err));
544+
}
545+
return summarizeFailure(err);
546+
};
531547
const wake = () => {
532548
const fn = notify;
533549
notify = undefined;
@@ -627,7 +643,7 @@ class LiveCursorTransport implements CursorTransport {
627643
// A CANCEL is benign only on the client-tool suspend path (expectedClose); an
628644
// unexpected server-side NGHTTP2_CANCEL must surface as a real transport error.
629645
if (this.expectedClose && isCursorBenignCancelError(failure)) return;
630-
throw attachPartialUsage(summarizeFailure(failure), state);
646+
throw attachPartialUsage(classifyTurnFailure(failure), state);
631647
}
632648
if (done) break;
633649
await new Promise<void>(resolve => {
@@ -636,7 +652,7 @@ class LiveCursorTransport implements CursorTransport {
636652
}
637653
if (failure) {
638654
if (this.expectedClose && isCursorBenignCancelError(failure)) return;
639-
throw attachPartialUsage(summarizeFailure(failure), state);
655+
throw attachPartialUsage(classifyTurnFailure(failure), state);
640656
}
641657
}
642658

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { createLiveCursorTransport } from "../src/adapters/cursor/live-transport";
3+
import {
4+
classifyCursorError,
5+
CursorUnexpectedCancelError,
6+
isCursorBenignCancelError,
7+
} from "../src/adapters/cursor/cursor-errors";
8+
import { resetCursorBlobStateForTests } from "../src/adapters/cursor/native-exec";
9+
import { createTestTranslatorBudget } from "./helpers/translator-budget";
10+
import type { CursorServerMessage } from "../src/adapters/cursor/types";
11+
12+
type OpenFn = (
13+
encoded: Uint8Array,
14+
signal: AbortSignal | undefined,
15+
state: unknown,
16+
push: (message: CursorServerMessage) => void,
17+
fail: (error: Error) => void,
18+
finish: () => void,
19+
) => void;
20+
21+
function cancelError(): Error {
22+
const err = new Error("stream closed with NGHTTP2_CANCEL");
23+
(err as { code?: string }).code = "NGHTTP2_CANCEL";
24+
return err;
25+
}
26+
27+
/**
28+
* Drive a turn through the transport's fault-injection seam. A literal server-side
29+
* `stream.close(NGHTTP2_CANCEL)` surfaces as a clean HTTP/2 `end` in a local fixture, so the
30+
* cancel-shaped FAILURE is injected directly — that is the state the production socket handler
31+
* reaches when Cursor resets the stream.
32+
*/
33+
async function runCancelTurn(opts: {
34+
emitTerminalFirst?: boolean;
35+
suspendFirst?: boolean;
36+
}): Promise<{ messages: CursorServerMessage[]; failure?: Error }> {
37+
resetCursorBlobStateForTests();
38+
const transport = createLiveCursorTransport({
39+
provider: { adapter: "cursor", baseUrl: "https://api2.cursor.sh", apiKey: "test-token" },
40+
translatorBudget: createTestTranslatorBudget(),
41+
headers: new Headers(),
42+
});
43+
let onOpened!: () => void;
44+
const opened = new Promise<void>(resolve => { onOpened = resolve; });
45+
let failTurn!: (error: Error) => void;
46+
let pushEvent!: (message: CursorServerMessage) => void;
47+
(transport as unknown as { open: OpenFn }).open = (_encoded, _signal, _state, push, fail) => {
48+
failTurn = fail;
49+
pushEvent = push;
50+
onOpened();
51+
};
52+
53+
const messages: CursorServerMessage[] = [];
54+
let failure: Error | undefined;
55+
const iterator = transport.run({
56+
modelId: "composer-2.5",
57+
conversationId: "cursor_cancel_provenance",
58+
system: ["system"],
59+
messages: [{ role: "user", content: "hi" }],
60+
})[Symbol.asyncIterator]();
61+
62+
const drain = (async () => {
63+
try {
64+
for (let next = await iterator.next(); !next.done; next = await iterator.next()) {
65+
messages.push(next.value);
66+
}
67+
} catch (err) {
68+
failure = err instanceof Error ? err : new Error(String(err));
69+
}
70+
})();
71+
72+
await opened;
73+
if (opts.emitTerminalFirst) pushEvent({ type: "done", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 } });
74+
// The client-tool suspend path cancels our own stream, which sets expectedClose.
75+
if (opts.suspendFirst) (transport as unknown as { cancelCursorRun(): void }).cancelCursorRun();
76+
failTurn(cancelError());
77+
await drain;
78+
transport.close?.();
79+
return { messages, failure };
80+
}
81+
82+
describe("Cursor cancel provenance", () => {
83+
test("a cancel we did not request surfaces as a real transport failure", async () => {
84+
const { failure } = await runCancelTurn({});
85+
86+
// Before this change the adapter treated ANY NGHTTP2_CANCEL as benign and returned silently,
87+
// leaving the turn with zero adapter events — reported as `completed` on the non-streaming path.
88+
expect(failure).toBeDefined();
89+
expect(failure).toBeInstanceOf(CursorUnexpectedCancelError);
90+
// The message must not claim an intentional suspension: that would misdirect diagnosis of a
91+
// turn that actually failed.
92+
expect(failure?.message.toLowerCase()).not.toContain("suspend");
93+
expect(classifyCursorError(failure!.message)).not.toBe("Cursor stream suspended");
94+
});
95+
96+
test("a cancel from our own client-tool suspend stays silent", async () => {
97+
const { failure } = await runCancelTurn({ suspendFirst: true });
98+
99+
// The regression that matters: every working multi-turn tool cycle ends this way.
100+
expect(failure).toBeUndefined();
101+
});
102+
103+
test("a cancel after a terminal was already emitted does not add a second one", async () => {
104+
const { messages, failure } = await runCancelTurn({ emitTerminalFirst: true });
105+
106+
expect(messages.some(m => m.type === "done")).toBe(true);
107+
// The transport still throws, but as the RAW cancel rather than the typed unexpected-cancel.
108+
// That distinction is the whole contract: the adapter's benign check (cursor.ts:181) swallows
109+
// a raw cancel, so no second terminal reaches the bridge and an already-completed buffered
110+
// response is not flipped to failed.
111+
expect(failure).toBeDefined();
112+
expect(failure).not.toBeInstanceOf(CursorUnexpectedCancelError);
113+
expect(isCursorBenignCancelError(failure)).toBe(true);
114+
});
115+
});
116+
117+
describe("isCursorBenignCancelError provenance", () => {
118+
test("an unexpected-cancel error is never benign, but an untagged one still is", () => {
119+
expect(isCursorBenignCancelError(new CursorUnexpectedCancelError())).toBe(false);
120+
// Fallback preserved: nothing that returns silently today starts erroring without evidence.
121+
expect(isCursorBenignCancelError(cancelError())).toBe(true);
122+
expect(isCursorBenignCancelError(new Error("Cursor stream suspended"))).toBe(true);
123+
});
124+
125+
test("the unexpected-cancel message is not classified as a suspension", () => {
126+
const classified = classifyCursorError(new CursorUnexpectedCancelError().message);
127+
expect(classified).not.toBe("Cursor stream suspended");
128+
});
129+
});

0 commit comments

Comments
 (0)