[GH-ISSUE #2745] [Issue]: Client SSE parser hardening — no reader cleanup, no final decoder flush, dead/uncancellable stream(), parse-failure-as-token, strict data: prefix #1384

Closed
opened 2026-10-21 05:32:45 +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/2745

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The two client SSE generators in api-client.ts (stream() and streamEvents()) share a hand-rolled parser copied from a provider-SSE context. They never release the reader / cancel the body on early exit, never flush the TextDecoder or drain the residual buffer at end-of-stream, require a literal data: (with trailing space) and split only on \n, treat [DONE] as a terminator the Marinara server never sends, and (in stream()) swallow error events and drop empty tokens. On any JSON-parse failure they synthesize a fake token from the raw line, which would inject garbage into the visible message. stream() additionally takes no AbortSignal and is currently dead code, but client/.instructions.md:248 documents it as the canonical token API.

Most of these are latent (the Marinara server always emits data: + \n\n + JSON, and stream() has zero callers), so they do not break the live pipeline today — but they are real robustness defects and a footgun for anyone following the documented pattern.

Sub-bug 1: No reader cleanup on early exit (LOW, leak)

  • How it breaks: Both generators acquire res.body.getReader() and read in a while(true) loop with no try/finally. On the type:'error' early-return (line 290) or any consumer break/throw, the generator's .return() runs no finally, so reader.cancel() never executes and the body stays locked. Reachable on routine server error frames (bad key/provider error/empty response).
  • Repro: Trigger repeated server error frames (e.g. bad API key) and observe abandoned locked readers.
  • Trace: api-client.ts:271-298 (streamEvents, return at 290), 212-239 (stream); no finally/reader.cancel() anywhere.

Sub-bug 2: No final decoder flush / trailing buffer discarded (LOW, truncation)

  • How it breaks: if (done) break; exits without a no-arg decoder.decode() flush and without processing residual buffer. On abrupt mid-frame close a final unterminated frame or a split multibyte tail is dropped. (Clean EOF ends on ASCII \n\n, so happy path is safe; the authoritative DB refetch reconciles the message.)
  • Repro: Simulate a mid-frame transport close; the trailing partial frame is not processed.
  • Trace: api-client.ts:275-281 (streamEvents), 216-222 (stream).

Sub-bug 3: stream() is uncancellable and dead, but documented (LOW, other)

  • How it breaks: stream(path, body?) takes no signal and its fetch omits signal, so the documented canonical token path cannot wire the stop button. Zero callers today; only client/.instructions.md:248 references it.
  • Trace: api-client.ts:192-198 (no signal) vs streamEvents 249/256 (forwards signal).

Sub-bug 4: stream() swallows error events (LOW, wrong-output)

  • How it breaks: throw new ApiError(...) for type:'error' (231) is inside the same try whose catch only yields for non-ApiError, so the ApiError is caught and dropped and the loop continues — a failed generation looks like a silently-empty success.
  • Trace: api-client.ts:228-236.

Sub-bug 5: stream() drops empty tokens (LOW, truncation)

  • How it breaks: if (parsed.type === 'token' && parsed.data) makes an empty-string token falsy and unyielded; streamEvents yields unconditionally, so the two parsers disagree.
  • Trace: api-client.ts:230 vs 289.

Sub-bug 6: strict 'data: ' prefix, [DONE] dead, CRLF/no-space mishandled (LOW, other/wrong-output)

  • How it breaks: line.startsWith('data: ') (space) + slice(6) drops spec-legal data: (no space); buffer.split('\n') leaves a trailing \r on CRLF frames; data === '[DONE]' is dead for this server (only {type:'done'} is sent). All latent — server emits data: + LF + \n\n.
  • Trace: api-client.ts:224-227 (stream), 283-286 (streamEvents).

Sub-bug 7: JSON-parse failure yielded as visible token (LOW, wrong-output)

  • How it breaks: On JSON.parse failure both generators do yield { type: 'token', data } with the raw line; use-generate.ts:1324-1335 appends it to the visible message. Unreachable today (every server frame is JSON.stringify-ed, newlines escaped), but any corrupted/garbled byte or future raw-string emit becomes visible garbage.
  • Trace: api-client.ts:287-294 (streamEvents), 228-236 (stream); consumer use-generate.ts:1300-1336.

Suggested Fix

  • Wrap each read loop in try { ... } finally { try { await reader.cancel(); } catch {} }.
  • After the loop: buffer += decoder.decode(); then process any remaining complete data: line.
  • Match SSE permissively: line.startsWith('data:') then strip one optional leading space and trimEnd(); split on /\r?\n/.
  • On JSON-parse failure, do NOT synthesize a token — console.warn and skip the frame (or buffer as a possible split fragment).
  • Either delete stream() and fix client/.instructions.md:248 to show streamEvents(), or add a signal?: AbortSignal param, forward empty-string tokens (typeof parsed.data === 'string'), and re-throw ApiError in its catch.

Root-cause throughline

The client parser is a single copied implementation that conflates provider-SSE conventions ([DONE], raw-token fallback) with Marinara's own {type:'done'} JSON framing, and was never given the standard SSE hygiene (reader cleanup, decoder flush, residual-buffer drain, permissive prefix). Because the live server contract is narrow and stream() is dead, the gaps are latent — but they are duplicated footguns waiting on the first proxy reframe or contributor who follows the docs.

Verification checklist (leave all UNCHECKED)

  • Manually verify: repeated bad-key/error generations do not accumulate dangling readers (DevTools / leak check)
  • Manually verify: normal streaming completion still renders the full final message
  • Manually verify: a forced non-JSON frame is skipped, not rendered as message text
  • Update client/.instructions.md:248 to document streamEvents() (or remove dead stream())
  • Run pnpm check

Affected files

  • packages/client/src/lib/api-client.ts
  • packages/client/.instructions.md

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: MEDIUM.

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/2745 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The two client SSE generators in `api-client.ts` (`stream()` and `streamEvents()`) share a hand-rolled parser copied from a provider-SSE context. They never release the reader / cancel the body on early exit, never flush the `TextDecoder` or drain the residual `buffer` at end-of-stream, require a literal `data: ` (with trailing space) and split only on `\n`, treat `[DONE]` as a terminator the Marinara server never sends, and (in `stream()`) swallow `error` events and drop empty tokens. On any JSON-parse failure they synthesize a fake `token` from the raw line, which would inject garbage into the visible message. `stream()` additionally takes no `AbortSignal` and is currently dead code, but `client/.instructions.md:248` documents it as the canonical token API. Most of these are latent (the Marinara server always emits `data: ` + `\n\n` + JSON, and `stream()` has zero callers), so they do not break the live pipeline today — but they are real robustness defects and a footgun for anyone following the documented pattern. ### Sub-bug 1: No reader cleanup on early exit (LOW, leak) - **How it breaks:** Both generators acquire `res.body.getReader()` and read in a `while(true)` loop with no try/finally. On the `type:'error'` early-return (line 290) or any consumer break/throw, the generator's `.return()` runs no finally, so `reader.cancel()` never executes and the body stays locked. Reachable on routine server `error` frames (bad key/provider error/empty response). - **Repro:** Trigger repeated server `error` frames (e.g. bad API key) and observe abandoned locked readers. - **Trace:** `api-client.ts:271-298` (streamEvents, return at 290), `212-239` (stream); no `finally`/`reader.cancel()` anywhere. ### Sub-bug 2: No final decoder flush / trailing buffer discarded (LOW, truncation) - **How it breaks:** `if (done) break;` exits without a no-arg `decoder.decode()` flush and without processing residual `buffer`. On abrupt mid-frame close a final unterminated frame or a split multibyte tail is dropped. (Clean EOF ends on ASCII `\n\n`, so happy path is safe; the authoritative DB refetch reconciles the message.) - **Repro:** Simulate a mid-frame transport close; the trailing partial frame is not processed. - **Trace:** `api-client.ts:275-281` (streamEvents), `216-222` (stream). ### Sub-bug 3: stream() is uncancellable and dead, but documented (LOW, other) - **How it breaks:** `stream(path, body?)` takes no `signal` and its fetch omits `signal`, so the documented canonical token path cannot wire the stop button. Zero callers today; only `client/.instructions.md:248` references it. - **Trace:** `api-client.ts:192-198` (no signal) vs `streamEvents` `249/256` (forwards signal). ### Sub-bug 4: stream() swallows error events (LOW, wrong-output) - **How it breaks:** `throw new ApiError(...)` for `type:'error'` (231) is inside the same `try` whose `catch` only `yield`s for non-ApiError, so the ApiError is caught and dropped and the loop continues — a failed generation looks like a silently-empty success. - **Trace:** `api-client.ts:228-236`. ### Sub-bug 5: stream() drops empty tokens (LOW, truncation) - **How it breaks:** `if (parsed.type === 'token' && parsed.data)` makes an empty-string token falsy and unyielded; `streamEvents` yields unconditionally, so the two parsers disagree. - **Trace:** `api-client.ts:230` vs `289`. ### Sub-bug 6: strict 'data: ' prefix, [DONE] dead, CRLF/no-space mishandled (LOW, other/wrong-output) - **How it breaks:** `line.startsWith('data: ')` (space) + `slice(6)` drops spec-legal `data:` (no space); `buffer.split('\n')` leaves a trailing `\r` on CRLF frames; `data === '[DONE]'` is dead for this server (only `{type:'done'}` is sent). All latent — server emits `data: ` + LF + `\n\n`. - **Trace:** `api-client.ts:224-227` (stream), `283-286` (streamEvents). ### Sub-bug 7: JSON-parse failure yielded as visible token (LOW, wrong-output) - **How it breaks:** On `JSON.parse` failure both generators do `yield { type: 'token', data }` with the raw line; `use-generate.ts:1324-1335` appends it to the visible message. Unreachable today (every server frame is `JSON.stringify`-ed, newlines escaped), but any corrupted/garbled byte or future raw-string emit becomes visible garbage. - **Trace:** `api-client.ts:287-294` (streamEvents), `228-236` (stream); consumer `use-generate.ts:1300-1336`. ## Suggested Fix - Wrap each read loop in `try { ... } finally { try { await reader.cancel(); } catch {} }`. - After the loop: `buffer += decoder.decode();` then process any remaining complete `data:` line. - Match SSE permissively: `line.startsWith('data:')` then strip one optional leading space and `trimEnd()`; split on `/\r?\n/`. - On JSON-parse failure, do NOT synthesize a token — `console.warn` and skip the frame (or buffer as a possible split fragment). - Either delete `stream()` and fix `client/.instructions.md:248` to show `streamEvents()`, or add a `signal?: AbortSignal` param, forward empty-string tokens (`typeof parsed.data === 'string'`), and re-throw ApiError in its catch. ## Root-cause throughline The client parser is a single copied implementation that conflates provider-SSE conventions (`[DONE]`, raw-token fallback) with Marinara's own `{type:'done'}` JSON framing, and was never given the standard SSE hygiene (reader cleanup, decoder flush, residual-buffer drain, permissive prefix). Because the live server contract is narrow and `stream()` is dead, the gaps are latent — but they are duplicated footguns waiting on the first proxy reframe or contributor who follows the docs. ## Verification checklist (leave all UNCHECKED) - [ ] Manually verify: repeated bad-key/error generations do not accumulate dangling readers (DevTools / leak check) - [ ] Manually verify: normal streaming completion still renders the full final message - [ ] Manually verify: a forced non-JSON frame is skipped, not rendered as message text - [ ] Update `client/.instructions.md:248` to document `streamEvents()` (or remove dead `stream()`) - [ ] Run `pnpm check` --- ### Affected files - `packages/client/src/lib/api-client.ts` - `packages/client/.instructions.md` ### 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: **MEDIUM**. > 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. Hardened the client SSE readers with reader cleanup, decoder flush/residual drain, permissive data: parsing, no raw malformed-frame token injection, optional AbortSignal for api.stream(), and updated the client instructions to prefer streamEvents() for generation.

<!-- gh-comment-id:4763179157 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on PR #2747. Hardened the client SSE readers with reader cleanup, decoder flush/residual drain, permissive data: parsing, no raw malformed-frame token injection, optional AbortSignal for api.stream(), and updated the client instructions to prefer streamEvents() for generation.
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#1384
No description provided.