Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(core): 离开模型流时取消上游请求(上游 #1354 移植)

lmliheng735538e15f54
diff --git a/changelog/unreleased/2026-10-28-llm-stream-cleanup.md b/changelog/unreleased/2026-10-28-llm-stream-cleanup.md
new file mode 100644
index 00000000..f8d3d038
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-llm-stream-cleanup.md
@@ -0,0 +1,48 @@
+# Leaving a model stream cancels the upstream request
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `core`
+- **Breaking:** no
+
+[中文](2026-10-28-llm-stream-cleanup.zh.md)
+
+Ported from PenguinHarness `aff7ee37` (`#1354`).
+
+`GenerativeModel.streamGenerate()` turns one request into an iterator of messages. A caller that
+stops reading before the response ends — the engine abandoning a turn, a consumer that breaks out
+of its loop, a request that threw or timed out — used to leave two things behind: the request's
+own `AbortController` stayed un-aborted, and the upstream iterator was never closed. The provider
+kept generating into a stream nobody read (and kept billing for it), and the connection stayed
+open until the provider finished on its own.
+
+Every exit that happens **before** the response's stop event now cancels the request and asks the
+iterator to close. A response that already reported its stop is left untouched: the turn is
+committed and billed, and the transport may still be reading the end of the stream. Cleanup is
+best effort — an upstream whose `return()` throws, rejects or never settles cannot replace the
+outcome or hold the caller open. This is the same aborted request the engine's own interruption
+path expected; it just no longer waits for somebody else to do it.
+
+## Details
+
+- `packages/core/src/llm/generative-model.ts`: the upstream iterator is hoisted out of the `try`
+ (`let it: AsyncIterator<UniEvent> | undefined`), and the `finally` — after clearing the idle
+ timer and removing the abort listener — calls `ac.abort()` and
+ `void Promise.resolve(it?.return?.()).catch(() => undefined)` **only when the translator has not
+ seen a finish reason**. The never-settling branch (`res === STOPPED`) no longer closes the
+ iterator on its own; the `finally` does it once, for every exit. This fork's translator has no
+ `stopped` getter (that arrived with a later upstream commit), so the guard uses the equivalent
+ `sawFinishReason()`.
+- `packages/core/test/llm.test.ts`: three lifecycle cases — a consumer leaving early, a user abort
+ while the generator is suspended at a `yield`, and a received stop that must stay untouched —
+ plus the three cleanup-failure cases (`throw` / `reject` / `hang`) that must still let the caller
+ leave. Locally adapted: this tree's `UniEvent` vocabulary is `{ type: "text" }` items with an
+ explicit `stop` event, and its loop pulls until `done` instead of breaking at the stop, so the
+ "left untouched" case asserts that no `return()` is requested and the signal stays un-aborted
+ rather than that the producer's `finally` never runs.
+
+## Compatibility
+
+- No dependency, API, on-disk or protocol change: the same request made to the same endpoint; when
+ a caller leaves, the connection is now closed instead of being left streaming. A completed
+ request behaves exactly as before, usage included.
diff --git a/changelog/unreleased/2026-10-28-llm-stream-cleanup.zh.md b/changelog/unreleased/2026-10-28-llm-stream-cleanup.zh.md
new file mode 100644
index 00000000..7162cc81
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-llm-stream-cleanup.zh.md
@@ -0,0 +1,38 @@
+# 离开模型流时取消上游请求
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `core`
+- **Breaking:** no
+
+[English](2026-10-28-llm-stream-cleanup.md)
+
+移植自 PenguinHarness `aff7ee37`(`#1354`)。
+
+`GenerativeModel.streamGenerate()` 把一次请求变成一条消息流。调用方在响应结束之前就不再读的(引擎放弃这一轮、
+消费者从循环里跳出、请求抛错或超时),过去会留下两样东西:这次请求自己的 `AbortController` 没有被 abort,
+上游的迭代器也从没关过。于是厂商继续往一个没人读的流里生成(也继续计费),连接一直挂到厂商自己写完为止。
+
+现在**在响应的 stop 事件之前**离开的每一条路径都会取消请求、并让迭代器关掉。已经报过 stop 的响应不动:
+那一轮已经提交并入账,传输层可能还在读流的结尾。清理是尽力而为 —— 上游的 `return()` 抛错、被拒或永不落地,
+都不能改变这次的结果、也不能把调用方挂住。这正是引擎自己的中断路径本来就期望的「已 abort 的请求」,
+只是现在不必再等别人替它做。
+
+## 细节
+
+- `packages/core/src/llm/generative-model.ts`:把上游迭代器提到 `try` 之外
+ (`let it: AsyncIterator<UniEvent> | undefined`),`finally` 在清掉空闲计时器、摘掉 abort 监听之后,
+ **只在翻译器没有见到结束原因时**调用 `ac.abort()` 与
+ `void Promise.resolve(it?.return?.()).catch(() => undefined)`。「上游永不落地」那一支(`res === STOPPED`)
+ 不再自己关迭代器,统一交给 `finally` 处理,于是每一条出口都只关一次。本树的翻译器没有 `stopped`
+ 这个读取口(那是上游更晚的一笔带来的),守卫用等价的 `sawFinishReason()`。
+- `packages/core/test/llm.test.ts`:三条生命周期用例 —— 消费者提前离开、用户在生成器挂在 `yield` 时中断、
+ 以及「已经收到 stop 的请求不许动」—— 外加三条清理失败(`throw` / `reject` / `hang`)仍要让调用方走得掉。
+ 本地化:本树的 `UniEvent` 词汇是 `{ type: "text" }` 条目加一个显式 `stop` 事件,而且本树的循环会一直拉到
+ `done`(上游是在 stop 处 break),所以「不许动」那条改成断言「没有发出 `return()`、信号没被 abort」,
+ 而不是「生产者的 `finally` 从来不跑」。
+
+## 兼容性
+
+- 不改依赖、不改接口、不改磁盘格式与协议:仍是同一个端点上的同一个请求;调用方离开时,连接现在会被关掉,
+ 而不是留在那里继续流。正常读完的请求与以前完全一致,用量也不变。
diff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.ts
index 5296df49..33e8827a 100644
--- a/packages/core/src/llm/generative-model.ts
+++ b/packages/core/src/llm/generative-model.ts
@@ -1403,13 +1403,16 @@ export class GenerativeModel implements LLMInterface {
// Terminal-state classification: retryable (transport/parse failures) / fatal (definitive
// rejections) / aborted (user). null means it ended normally.
let outcome: LLMOutcome | null = null;
+ // The upstream iterator, kept outside the try so the finally below can close it: a consumer
+ // that leaves before the stop would otherwise leave generation running.
+ let it: AsyncIterator<UniEvent> | undefined;
try {
await this.refreshApiKey();
// The seller counts images per request, not per message: a conversation that read five
// pictures would fail every later turn with 400 media_count_exceeded, so the oldest
// replayed ones — and, when the input alone overflows, the input's own oldest ones — are
// dropped from THIS request (the history and Trace keep them).
- const it = this.openStream(
+ it = this.openStream(
this.fitReplayedVideos(this.fitReplayedImages(uniMessage)),
ac.signal,
this.requestConfig(params.thinkingLevel, params.newMessages),
@@ -1440,10 +1443,8 @@ export class GenerativeModel implements LLMInterface {
clearTimer();
}
if (res === STOPPED) {
- // Upstream never settled after the abort. Abandon it rather than await it: ask it to
- // close (best effort — a stream that ignored the signal may ignore this too, so the
- // rejection is swallowed and the promise is not awaited) and classify by trigger.
- void Promise.resolve(it.return?.(undefined)).catch(() => undefined);
+ // Upstream never settled after the abort. Cleanup below is best effort and does
+ // not wait on a stream that may also ignore return(). Classify by trigger.
outcome = userSignal?.aborted
? { status: "aborted" }
: { status: "retryable", errorCode: "timeout" };
@@ -1518,6 +1519,20 @@ export class GenerativeModel implements LLMInterface {
} finally {
clearTimer();
userSignal?.removeEventListener("abort", onUserAbort);
+ // Leaving before the stop (at a yield, on an error, or abandoning an upstream that never
+ // settled) must cancel generation, even without a caller-owned signal, and close the
+ // upstream iterator to release it. Once the stop arrived nothing is cancelled: the turn
+ // is committed and billed, and the transport may still be reading the stream's end
+ // (MMSP yields the stop before `[DONE]`); closing it here would drop the connection.
+ if (!translator.sawFinishReason()) {
+ ac.abort();
+ // Do not let a broken or unresponsive cleanup replace the outcome or hold it open.
+ try {
+ void Promise.resolve(it?.return?.()).catch(() => undefined);
+ } catch {
+ // A synchronous cleanup failure is no more authoritative than a rejected promise.
+ }
+ }
}
// Defensive: when the underlying stream responds to an abort with a **graceful end (done)**
diff --git a/packages/core/test/llm.test.ts b/packages/core/test/llm.test.ts
index 7b3d159d..064a1bc2 100644
--- a/packages/core/test/llm.test.ts
+++ b/packages/core/test/llm.test.ts
@@ -7,7 +7,7 @@
* 2. Translating/aggregating UniEvent[] into OmniMessage[] (partial_* ordering, complete
* messages, token_usage accumulation, tool_call_id passthrough).
* As well as helper functions for token conversion, UniConfig construction, and retry
- * determination.
+ * determination, and how streamGenerate releases the upstream when it is left before the stop.
*/
import { describe, expect, it } from "vitest";
import {
@@ -1699,6 +1699,133 @@ describe("GenerativeModel.streamGenerate outcome classification (PRN-013)", () =
const abortError = (): Error => Object.assign(new Error("aborted"), { name: "AbortError" });
+ // UniEvent helpers for the lifecycle cases (upstream's suite has these beside its own fakes;
+ // this tree's vocabulary is `{ type: "text" }` items and an explicit `stop` event).
+ const NO_USAGE: UsageMetadata = {
+ cached_tokens: 0,
+ prompt_tokens: 0,
+ thoughts_tokens: 0,
+ response_tokens: 0,
+ };
+ const delta = (text: string): UniEvent => ev({ content_items: [{ type: "text", text }] });
+ const text = (chunks: readonly string[]): UniEvent[] => chunks.map(delta);
+ const stop = (reason: NonNullable<UniEvent["finish_reason"]>, usage: UsageMetadata): UniEvent =>
+ ev({
+ content_items: [],
+ event_type: "stop",
+ finish_reason: reason,
+ usage_metadata: usage,
+ });
+
+ it("aborts and closes the upstream request when the consumer leaves early", async () => {
+ let upstreamSignal: AbortSignal | undefined;
+ let released = false;
+ const model = new SeamModel(async function* (signal) {
+ upstreamSignal = signal;
+ try {
+ yield delta("first");
+ yield delta("unwanted");
+ } finally {
+ released = true;
+ }
+ });
+ for await (const _record of model.streamGenerate({ newMessages: [userText("go")] })) break;
+ expect(upstreamSignal?.aborted).toBe(true);
+ expect(released).toBe(true);
+ });
+
+ it("closes upstream after a user abort while suspended at output", async () => {
+ const controller = new AbortController();
+ let released = false;
+ const model = new SeamModel(async function* () {
+ try {
+ yield delta("first");
+ } finally {
+ released = true;
+ }
+ });
+ const gen = model.streamGenerate({ newMessages: [userText("go")], signal: controller.signal });
+ expect((await gen.next()).done).toBe(false);
+ controller.abort();
+ expect((await drain(gen)).outcome.status).toBe("aborted");
+ expect(released).toBe(true);
+ });
+
+ it("leaves the upstream open after a received stop, preserving billed usage", async () => {
+ let upstreamSignal: AbortSignal | undefined;
+ let returns = 0;
+ // A hand-written iterator: this tree's loop pulls until `done` (upstream's breaks at the
+ // stop event), so the producer's own `finally` runs either way — what must not happen is
+ // the consumer-side cleanup aborting the signal or asking the transport to close.
+ const model = new SeamModel((signal) => {
+ upstreamSignal = signal;
+ return {
+ [Symbol.asyncIterator]() {
+ let step = 0;
+ return {
+ next: async (): Promise<IteratorResult<UniEvent>> => {
+ step += 1;
+ if (step === 1) return { done: false as const, value: delta("done") };
+ if (step === 2)
+ return {
+ done: false as const,
+ value: stop("stop", { ...NO_USAGE, response_tokens: 7 }),
+ };
+ return { done: true as const, value: undefined };
+ },
+ return: () => {
+ returns += 1;
+ return Promise.resolve({ done: true as const, value: undefined });
+ },
+ };
+ },
+ };
+ });
+ const { messages, outcome } = await drain(
+ model.streamGenerate({ newMessages: [userText("go")] }),
+ );
+ expect(outcome.status).toBe("completed");
+ expect(messages.find((m) => typeOf(m) === "token_usage")?.payload).toMatchObject({
+ request: { output: 7 },
+ });
+ expect(upstreamSignal?.aborted).toBe(false);
+ // Nothing is cancelled or closed once the stop arrived: the turn is committed and billed.
+ expect(returns).toBe(0);
+ });
+
+ it.each(["throw", "reject", "hang"])(
+ "does not let %s during cleanup prevent leaving the stream",
+ async (mode) => {
+ let upstreamSignal: AbortSignal | undefined;
+ let returns = 0;
+ const model = new SeamModel((signal) => {
+ upstreamSignal = signal;
+ return {
+ [Symbol.asyncIterator]() {
+ return {
+ next: async () => ({
+ done: false as const,
+ value: delta("first"),
+ }),
+ return: () => {
+ returns += 1;
+ if (mode === "throw") throw new Error("cleanup failed");
+ if (mode === "reject") return Promise.reject(new Error("cleanup failed"));
+ return new Promise<IteratorResult<UniEvent>>(() => {});
+ },
+ };
+ },
+ };
+ });
+ const gen = model.streamGenerate({ newMessages: [userText("go")] });
+ expect((await gen.next()).done).toBe(false);
+ expect(await gen.return({ status: "aborted" })).toMatchObject({ done: true });
+ expect(upstreamSignal?.aborted).toBe(true);
+ expect(returns).toBe(1);
+ },
+ 1000,
+ );
+
/**
* An upstream that IGNORES its AbortSignal: it never yields and never rejects, whatever
* happens to the signal. This is the shape that wedged real Sessions (observed with Kimi):