[GH-ISSUE #2739] [Issue]: Streaming abort handling — Stop persists a truncated assistant message + aborts surface as errors + mid-stream partial discarded (non-tool path) #1379

Closed
opened 2026-10-21 05:32:39 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Jun 21, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2739

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The non-tool streaming path in generate.routes.ts is asymmetric with the tool path: the tool path returns null on abort before the shared save/emit block, but the streaming else branch has no abort guard between the stream loop and the DB save. As a result, pressing Stop (or a qualifying disconnect) mid-generation persists the truncated text as a real assistant message, and an abort that surfaces as a rejected reader.read() is reported to the client as a generic error SSE event. A related mid-stream failure path discards already-streamed content on both the client and in the base chatComplete() collector.

Sub-bug 1: Abort saves a truncated assistant message (HIGH, data-loss)

  • How it breaks: On abort the provider's reader.cancel() resolves the next read with {done:true}, so the stream loop ends with a partial-but-nonempty fullResponse. There is no if (abortController.signal.aborted) return null between the loop end and the save, so execution reaches content_replace, chats.createMessage({content: fullResponse}), and message_saved. On reload the user sees the reply they thought they cancelled. The empty-response guard if (!fullResponse.trim()) does not fire for a partial buffer.
  • Repro: Disable tools; send a message to a model; click Stop mid-stream (or trigger a qualifying disconnect); reload the chat — the truncated reply is persisted.
  • Trace: Tool path returns null on abort at generate.routes.ts:6066, 6113-6114, 6120-6121. Non-tool branch consumes the generator at 6325-6337 with no abort check; reaches content_replace (6364, 6609), chats.createMessage/addSwipe (6664-6672), message_saved (6751). Client Stop reaches abort via chat.store.ts:346-358 -> /api/generate/abort -> generate.routes.ts:10700-10709.

Sub-bug 2: Spurious error event on abort (LOW, wrong-output)

  • How it breaks: When abort makes reader.read() reject with AbortError, it propagates out of generateForCharacter (only finally at 6855, no catch) to the outer catch at 10667, which unconditionally calls sendSseEvent(reply, {type:"error", data: message}) at 10677 with no signal.aborted short-circuit. (Note: in practice the client aborts its own controller first and/or clientDisconnected suppresses the write, so the toast is usually not observed — this is primarily an asymmetry/code-smell vs the tool path.)
  • Repro: Code inspection; compare tool path (6111-6117 guards) vs outer catch (10667-10677 no guard).
  • Trace: generate.routes.ts:6290-6340 (no try/catch), 10667-10677 (unconditional error emit).

Sub-bug 3: Client drops visibly-streamed partial on mid-stream error (MEDIUM, data-loss)

  • How it breaks: On a {type:'error'} after some tokens streamed, the client error handler flushes the typewriter (still only in streamBuffers, not persisted), streamEvents returns, and the finally runs clearStreamBuffer then refreshMessagesAuthoritatively which overwrites the view from the DB. If the server saved no partial row, the streamed text disappears.
  • Repro: Force an upstream provider stream failure after a few tokens; observe the visible partial vanish on error.
  • Trace: use-generate.ts:2170-2178 (error handler), 2307-2323 (finally clearStreamBuffer + refresh); server emits error without partial save at generate.routes.ts:10667-10677.

Sub-bug 4: base chatComplete() discards partial on mid-stream throw (MEDIUM, data-loss)

  • How it breaks: The collector loop content += result.value; result = await gen.next() has no try/catch. When gen.next() rejects mid-stream (Anthropic/Google provider throwing on an error event, or undici body drop), the accumulated content is thrown away and the caller (summarizers, trackers, selectors with no onToken) gets an exception and empty result.
  • Repro: Trigger a transient mid-stream provider error during an Anthropic/Google non-tool chatComplete call (e.g. auto-summary); the salvageable partial is lost.
  • Trace: base-provider.ts:613-627 (no try/catch); Anthropic throws at anthropic.provider.ts:571-573 (try at 542 has only finally at 606); Google at google.provider.ts:741/764.

Suggested Fix

  • Add if (abortController.signal.aborted) return null; immediately after the non-tool stream loop (~generate.routes.ts:6340), and wrap gen.next() so an AbortError is treated as a silent cancel returning null (mirror the tool path at 6111-6117).
  • In the outer catch (10667), short-circuit aborts: if (abortController.signal.aborted || err?.name === 'AbortError') return; before emitting error.
  • On the client error terminal path, if receivedContent is true and no message_saved arrived, persist/keep the streamed fullBuffer as a local partial rather than clearing+refetching over it (or have the server persist the partial before emitting error).
  • Wrap the base chatComplete() consumption loop in try/catch and return the partial content (with finishReason: 'error'/'length') instead of discarding it.

Root-cause throughline

The tool-enabled path was hardened to treat abort and mid-stream failure as graceful, salvageable terminations, but the default non-tool streaming path and the base collector were never brought to parity — they assume a clean run-to-completion and fall straight through to save/emit, so an abort or mid-stream throw becomes either a persisted truncated message, a spurious error toast, or a discarded partial.

Verification checklist (leave all UNCHECKED)

  • Manually verify in browser: Stop mid-generation with tools disabled, reload — no truncated assistant message is persisted
  • Manually verify in browser: Stop mid-generation shows a clean cancel with no error toast
  • Manually verify: mid-stream provider error after partial tokens keeps/persists the visible partial instead of blanking it
  • Manually verify: an Anthropic/Google auto-summary that errors mid-stream returns/uses the partial rather than throwing empty
  • Run pnpm check
  • Confirm tool-path abort behavior is unchanged (regression check)

Affected files

  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/services/llm/base-provider.ts
  • packages/client/src/hooks/use-generate.ts

Audit provenance

Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged staging tree. Severity: HIGH.

AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2739 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The non-tool streaming path in `generate.routes.ts` is asymmetric with the tool path: the tool path returns `null` on abort before the shared save/emit block, but the streaming `else` branch has no abort guard between the stream loop and the DB save. As a result, pressing Stop (or a qualifying disconnect) mid-generation persists the truncated text as a real assistant message, and an abort that surfaces as a rejected `reader.read()` is reported to the client as a generic `error` SSE event. A related mid-stream failure path discards already-streamed content on both the client and in the base `chatComplete()` collector. ### Sub-bug 1: Abort saves a truncated assistant message (HIGH, data-loss) - **How it breaks:** On abort the provider's `reader.cancel()` resolves the next read with `{done:true}`, so the stream loop ends with a partial-but-nonempty `fullResponse`. There is no `if (abortController.signal.aborted) return null` between the loop end and the save, so execution reaches `content_replace`, `chats.createMessage({content: fullResponse})`, and `message_saved`. On reload the user sees the reply they thought they cancelled. The empty-response guard `if (!fullResponse.trim())` does not fire for a partial buffer. - **Repro:** Disable tools; send a message to a model; click Stop mid-stream (or trigger a qualifying disconnect); reload the chat — the truncated reply is persisted. - **Trace:** Tool path returns null on abort at `generate.routes.ts:6066`, `6113-6114`, `6120-6121`. Non-tool branch consumes the generator at `6325-6337` with no abort check; reaches `content_replace` (`6364`, `6609`), `chats.createMessage`/`addSwipe` (`6664-6672`), `message_saved` (`6751`). Client Stop reaches abort via `chat.store.ts:346-358` -> `/api/generate/abort` -> `generate.routes.ts:10700-10709`. ### Sub-bug 2: Spurious error event on abort (LOW, wrong-output) - **How it breaks:** When abort makes `reader.read()` reject with AbortError, it propagates out of `generateForCharacter` (only `finally` at `6855`, no catch) to the outer catch at `10667`, which unconditionally calls `sendSseEvent(reply, {type:"error", data: message})` at `10677` with no `signal.aborted` short-circuit. (Note: in practice the client aborts its own controller first and/or `clientDisconnected` suppresses the write, so the toast is usually not observed — this is primarily an asymmetry/code-smell vs the tool path.) - **Repro:** Code inspection; compare tool path (`6111-6117` guards) vs outer catch (`10667-10677` no guard). - **Trace:** `generate.routes.ts:6290-6340` (no try/catch), `10667-10677` (unconditional error emit). ### Sub-bug 3: Client drops visibly-streamed partial on mid-stream error (MEDIUM, data-loss) - **How it breaks:** On a `{type:'error'}` after some tokens streamed, the client error handler flushes the typewriter (still only in `streamBuffers`, not persisted), `streamEvents` returns, and the `finally` runs `clearStreamBuffer` then `refreshMessagesAuthoritatively` which overwrites the view from the DB. If the server saved no partial row, the streamed text disappears. - **Repro:** Force an upstream provider stream failure after a few tokens; observe the visible partial vanish on error. - **Trace:** `use-generate.ts:2170-2178` (error handler), `2307-2323` (finally clearStreamBuffer + refresh); server emits error without partial save at `generate.routes.ts:10667-10677`. ### Sub-bug 4: base chatComplete() discards partial on mid-stream throw (MEDIUM, data-loss) - **How it breaks:** The collector loop `content += result.value; result = await gen.next()` has no try/catch. When `gen.next()` rejects mid-stream (Anthropic/Google provider throwing on an error event, or undici body drop), the accumulated `content` is thrown away and the caller (summarizers, trackers, selectors with no `onToken`) gets an exception and empty result. - **Repro:** Trigger a transient mid-stream provider error during an Anthropic/Google non-tool `chatComplete` call (e.g. auto-summary); the salvageable partial is lost. - **Trace:** `base-provider.ts:613-627` (no try/catch); Anthropic throws at `anthropic.provider.ts:571-573` (try at 542 has only finally at 606); Google at `google.provider.ts:741/764`. ## Suggested Fix - Add `if (abortController.signal.aborted) return null;` immediately after the non-tool stream loop (~`generate.routes.ts:6340`), and wrap `gen.next()` so an AbortError is treated as a silent cancel returning null (mirror the tool path at 6111-6117). - In the outer catch (`10667`), short-circuit aborts: `if (abortController.signal.aborted || err?.name === 'AbortError') return;` before emitting `error`. - On the client error terminal path, if `receivedContent` is true and no `message_saved` arrived, persist/keep the streamed `fullBuffer` as a local partial rather than clearing+refetching over it (or have the server persist the partial before emitting error). - Wrap the base `chatComplete()` consumption loop in try/catch and return the partial `content` (with `finishReason: 'error'`/`'length'`) instead of discarding it. ## Root-cause throughline The tool-enabled path was hardened to treat abort and mid-stream failure as graceful, salvageable terminations, but the default non-tool streaming path and the base collector were never brought to parity — they assume a clean run-to-completion and fall straight through to save/emit, so an abort or mid-stream throw becomes either a persisted truncated message, a spurious error toast, or a discarded partial. ## Verification checklist (leave all UNCHECKED) - [ ] Manually verify in browser: Stop mid-generation with tools disabled, reload — no truncated assistant message is persisted - [ ] Manually verify in browser: Stop mid-generation shows a clean cancel with no error toast - [ ] Manually verify: mid-stream provider error after partial tokens keeps/persists the visible partial instead of blanking it - [ ] Manually verify: an Anthropic/Google auto-summary that errors mid-stream returns/uses the partial rather than throwing empty - [ ] Run `pnpm check` - [ ] Confirm tool-path abort behavior is unchanged (regression check) --- ### Affected files - `packages/server/src/routes/generate.routes.ts` - `packages/server/src/services/llm/base-provider.ts` - `packages/client/src/hooks/use-generate.ts` ### Audit provenance Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged `staging` tree. Severity: **HIGH**. > AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 21, 2026):

Addressed on PR #2747. Non-tool streaming now treats AbortError as silent cancellation, checks the abort signal before post-processing/saving, suppresses abort error SSEs in the outer catch, keeps visible client partials when an error arrives before message_saved, and the base chatComplete() collector returns partial content on mid-stream failure instead of discarding it.

<!-- gh-comment-id:4763188231 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on PR #2747. Non-tool streaming now treats AbortError as silent cancellation, checks the abort signal before post-processing/saving, suppresses abort error SSEs in the outer catch, keeps visible client partials when an error arrives before message_saved, and the base chatComplete() collector returns partial content on mid-stream failure instead of discarding it.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1379
No description provided.