Skip to content

Commit a1dfe62

Browse files
committed
fix(claude-agent-sdk): review-r3 M1: only an idle query right after a result ends OK on close
The N1 shortcut keyed off resultSeen, which never resets, so an abort in a later streaming turn between model steps (turn span ended, next assistant message not yet out) was recorded as OK. Track idleAfterResult instead: a result sets it, any later assistant/user message clears it. close(), asyncDispose and AbortController aborts mid-turn are cancelled again. README names the residual gap (abort after a new prompt is sent, before the SDK yields anything for it). Comments in queryWrapper.ts refreshed. M2 (reset the in-query baseline on conversation_reset) not taken: whether the CLI's running totals restart there is unverified; the README keeps the documented /clear undercount. Test first: 3 new jest cases (close, asyncDispose, abort) failed on a8831d6. approved: Nikhil 2026-10-03 blanket Refs: TH-8235
1 parent a8831d6 commit a1dfe62

4 files changed

Lines changed: 59 additions & 7 deletions

File tree

‎typescript/packages/traceai_claude_agent_sdk/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ await shutdown(); // flush before a short script exits
5252
### What the wrapper does and does not do
5353

5454
- Calls the original `query()` with the same params object. Options (`resume`, `forkSession`, `sessionId`, `hooks`, `mcpServers`, `agents`, `abortController`, `allowedTools`, `permissionMode`, `maxTurns`, `env`, ...) are passed through untouched. The wrapper never sets `ANTHROPIC_BASE_URL`.
55-
- Yields the same message objects, in order. Control methods on the returned `Query` (`interrupt()`, `setModel()`, ...) go to the original. `close()` and `Symbol.asyncDispose` first end the query's open spans, then go to the original: as cancelled if a turn, tool or subagent was still running, or as a normal end if a result had arrived and nothing was running (the usual way to end a streaming-input session).
55+
- Yields the same message objects, in order. Control methods on the returned `Query` (`interrupt()`, `setModel()`, ...) go to the original. `close()` and `Symbol.asyncDispose` first end the query's open spans, then go to the original: as cancelled while the query is working, or as a normal end when it is idle right after a result (the usual way to end a streaming-input session).
5656
- A tracing error never fails the agent. An exporter or collector failure is logged and does not reject the iterator.
5757
- `startup()` is not wrapped in 0.1.0.
5858

@@ -132,7 +132,7 @@ With 0.3.289 the CLI then calls `POST {ANTHROPIC_BASE_URL}/v1/messages?beta=true
132132
- **No traces.** `register()` needs `projectName` or `FI_PROJECT_NAME`.
133133
- **Zero spans from a short script.** `await shutdown()` before exit.
134134
- **Duplicate model spans.** Do not also run a provider instrumentor on the same calls.
135-
- **A span left open after abort.** Every span for the query is ended with status ERROR and `claude_agent.cancelled=true` when its `AbortController` aborts, when you call `close()` on the returned `Query` (the SDK's abort path), or when `await using` disposes it (`Symbol.asyncDispose`). Calling `close()` after the stream has completed changes nothing, and `close()` after a result with nothing still running ends the conversation OK. Anything else is a bug here.
135+
- **A span left open after abort.** Every span for the query is ended with status ERROR and `claude_agent.cancelled=true` when its `AbortController` aborts, when you call `close()` on the returned `Query` (the SDK's abort path), or when `await using` disposes it (`Symbol.asyncDispose`). Calling `close()` after the stream has completed changes nothing. Right after a result, before any further assistant or user message and with no background subagent running, `close()`, `Symbol.asyncDispose` and an abort end the conversation OK instead, because nothing was cancelled. One gap remains: an abort after the app sends a new streaming-input prompt but before the SDK yields any message for it is recorded as OK. Anything else is a bug here.
136136

137137
## Tests
138138

‎typescript/packages/traceai_claude_agent_sdk/src/__tests__/wrapper.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,18 @@ import {
2626
TOOL_INPUT_MARKER,
2727
TOOL_OUTPUT_MARKER,
2828
TOTAL_COST_USD,
29+
assistant,
2930
backgroundedSubagentJourney,
31+
init,
3032
mcpErrorJourney,
33+
resultSuccess,
3134
simpleToolJourney,
3235
streamingInputJourney,
3336
subagentJourney,
3437
taskNotification,
38+
text,
39+
toolResult,
40+
toolUse,
3541
} from "./fixtures/messages";
3642
import { StackContextManager, allAttributeText, byName, drain, memoryProvider, one, parentId } from "./helpers";
3743

@@ -674,6 +680,42 @@ describe("wrapQuery", () => {
674680
},
675681
);
676682

683+
/** Streaming input: turn 1 ends with a result, turn 2 is mid-tool-loop (its turn span already ended). */
684+
function secondTurnBetweenModelSteps(): SDKMessage[] {
685+
return [
686+
init(),
687+
assistant("msg_s1", [text("First answer.")]),
688+
resultSuccess("First answer.", { num_turns: 1 }),
689+
assistant("msg_s2", [toolUse("toolu_read_2", "Read", { file_path: "/tmp/b.md" })]),
690+
toolResult("toolu_read_2", "# b"),
691+
assistant("msg_s3", [text("Second answer.")]),
692+
resultSuccess("Second answer.", { num_turns: 2 }),
693+
];
694+
}
695+
696+
it.each(["close", "asyncDispose", "abort"] as const)(
697+
"M1: %s() in a later streaming turn, between model steps, stays cancelled",
698+
async (method) => {
699+
const { provider, exporter } = memoryProvider();
700+
const abortController = new AbortController();
701+
const fake = makeFakeQuery(secondTurnBetweenModelSteps());
702+
const q = wrapQuery(fake.query, { tracerProvider: provider })({ prompt: PROMPT, options: { abortController } });
703+
// Read through turn 2's tool_result: the turn span has ended, the next model step has no span yet.
704+
for (;;) {
705+
const step = await q.next();
706+
if (step.done) throw new Error("stream ended early");
707+
if (step.value.type === "user") break;
708+
}
709+
if (method === "close") q.close();
710+
else if (method === "asyncDispose") await (q as unknown as Record<symbol, () => Promise<void>>)[ASYNC_DISPOSE]();
711+
else abortController.abort();
712+
713+
const conversation = one(exporter.getFinishedSpans(), "claude_agent.conversation");
714+
expect(conversation.status.code).toBe(SpanStatusCode.ERROR);
715+
expect(conversation.attributes["claude_agent.cancelled"]).toBe(true);
716+
},
717+
);
718+
677719
it("N1: close() after a result while a background subagent still runs stays cancelled", async () => {
678720
const { provider, exporter } = memoryProvider();
679721
// The result arrives before the background subagent's task_notification.

‎typescript/packages/traceai_claude_agent_sdk/src/queryWrapper.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
* forwards every control method (`interrupt()`, `setModel()`, ...) to the
88
* original. `next`, `return`, `throw` and `Symbol.asyncIterator` are
99
* intercepted to drive the span model in `spans.ts`; `close()` and
10-
* `Symbol.asyncDispose` end the open spans as cancelled, then forward.
10+
* `Symbol.asyncDispose` end the open spans (as cancelled unless the query was
11+
* idle right after a result), then forward.
1112
*/
1213
import { Tracer, context as otelContext, diag } from "@opentelemetry/api";
1314
import { ContentPolicy, QueryTracer, clockMs } from "./spans";
@@ -128,7 +129,8 @@ function proxyQuery<G extends AsyncGenerator<unknown, unknown, unknown>>(
128129
if (typeof value !== "function") return value;
129130
// close() is the SDK's abort path (sdk.d.ts Query.close) and asyncDispose
130131
// runs on `await using`: neither goes through next/return/throw, so end
131-
// every open span as cancelled before forwarding.
132+
// every open span before forwarding (cancelled, unless the query was idle
133+
// right after a result: see QueryTracer.finish).
132134
if (property === "close") {
133135
return function close(this: unknown, ...args: unknown[]) {
134136
safe(() => queryTracer.finish({ kind: "aborted", reason: "close" }));

‎typescript/packages/traceai_claude_agent_sdk/src/spans.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,8 @@ export class QueryTracer {
287287
private conversationContext?: Context;
288288
private conversationIsError = false;
289289
private resultSeen = false;
290+
/** A result arrived and no assistant/user message has followed it yet. */
291+
private idleAfterResult = false;
290292
private sessionId?: string;
291293
private finished = false;
292294
private abortListener?: () => void;
@@ -378,6 +380,9 @@ export class QueryTracer {
378380
}
379381
try {
380382
const type = (message as { type?: unknown }).type;
383+
if (type === "assistant" || type === "user") {
384+
this.idleAfterResult = false;
385+
}
381386
if (type === "assistant") {
382387
this.onAssistant(message as AssistantMessageLike);
383388
} else if (type === "user") {
@@ -402,9 +407,11 @@ export class QueryTracer {
402407
if (!this.conversation) {
403408
return;
404409
}
405-
// close()/asyncDispose/abort after a result with nothing still running
406-
// (no open turn, tool or subagent) cancels nothing: end it as returned.
407-
if (outcome.kind === "aborted" && this.resultSeen && this.nothingInFlight()) {
410+
// close()/asyncDispose/abort right after a result, with nothing still
411+
// running (no open turn, tool or subagent), cancels nothing: end it as
412+
// returned. Any assistant/user message after the result means a new turn
413+
// is under way, even between model steps when no span is open.
414+
if (outcome.kind === "aborted" && this.idleAfterResult && this.nothingInFlight()) {
408415
outcome = { kind: "returned" };
409416
}
410417
try {
@@ -576,6 +583,7 @@ export class QueryTracer {
576583
this.setSessionId(message.session_id);
577584
}
578585

586+
this.idleAfterResult = true;
579587
this.recordUsage(cumulativeUsage(message));
580588
if (typeof message.duration_ms === "number") {
581589
conversation.setAttribute(A.DURATION_MS, message.duration_ms);

0 commit comments

Comments
 (0)