mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[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
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#1384
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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()andstreamEvents()) share a hand-rolled parser copied from a provider-SSE context. They never release the reader / cancel the body on early exit, never flush theTextDecoderor drain the residualbufferat end-of-stream, require a literaldata:(with trailing space) and split only on\n, treat[DONE]as a terminator the Marinara server never sends, and (instream()) swallowerrorevents and drop empty tokens. On any JSON-parse failure they synthesize a faketokenfrom the raw line, which would inject garbage into the visible message.stream()additionally takes noAbortSignaland is currently dead code, butclient/.instructions.md:248documents it as the canonical token API.Most of these are latent (the Marinara server always emits
data:+\n\n+ JSON, andstream()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)
res.body.getReader()and read in awhile(true)loop with no try/finally. On thetype:'error'early-return (line 290) or any consumer break/throw, the generator's.return()runs no finally, soreader.cancel()never executes and the body stays locked. Reachable on routine servererrorframes (bad key/provider error/empty response).errorframes (e.g. bad API key) and observe abandoned locked readers.api-client.ts:271-298(streamEvents, return at 290),212-239(stream); nofinally/reader.cancel()anywhere.Sub-bug 2: No final decoder flush / trailing buffer discarded (LOW, truncation)
if (done) break;exits without a no-argdecoder.decode()flush and without processing residualbuffer. 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.)api-client.ts:275-281(streamEvents),216-222(stream).Sub-bug 3: stream() is uncancellable and dead, but documented (LOW, other)
stream(path, body?)takes nosignaland its fetch omitssignal, so the documented canonical token path cannot wire the stop button. Zero callers today; onlyclient/.instructions.md:248references it.api-client.ts:192-198(no signal) vsstreamEvents249/256(forwards signal).Sub-bug 4: stream() swallows error events (LOW, wrong-output)
throw new ApiError(...)fortype:'error'(231) is inside the sametrywhosecatchonlyyields for non-ApiError, so the ApiError is caught and dropped and the loop continues — a failed generation looks like a silently-empty success.api-client.ts:228-236.Sub-bug 5: stream() drops empty tokens (LOW, truncation)
if (parsed.type === 'token' && parsed.data)makes an empty-string token falsy and unyielded;streamEventsyields unconditionally, so the two parsers disagree.api-client.ts:230vs289.Sub-bug 6: strict 'data: ' prefix, [DONE] dead, CRLF/no-space mishandled (LOW, other/wrong-output)
line.startsWith('data: ')(space) +slice(6)drops spec-legaldata:(no space);buffer.split('\n')leaves a trailing\ron CRLF frames;data === '[DONE]'is dead for this server (only{type:'done'}is sent). All latent — server emitsdata:+ LF +\n\n.api-client.ts:224-227(stream),283-286(streamEvents).Sub-bug 7: JSON-parse failure yielded as visible token (LOW, wrong-output)
JSON.parsefailure both generators doyield { type: 'token', data }with the raw line;use-generate.ts:1324-1335appends it to the visible message. Unreachable today (every server frame isJSON.stringify-ed, newlines escaped), but any corrupted/garbled byte or future raw-string emit becomes visible garbage.api-client.ts:287-294(streamEvents),228-236(stream); consumeruse-generate.ts:1300-1336.Suggested Fix
try { ... } finally { try { await reader.cancel(); } catch {} }.buffer += decoder.decode();then process any remaining completedata:line.line.startsWith('data:')then strip one optional leading space andtrimEnd(); split on/\r?\n/.console.warnand skip the frame (or buffer as a possible split fragment).stream()and fixclient/.instructions.md:248to showstreamEvents(), or add asignal?: AbortSignalparam, 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 andstream()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)
client/.instructions.md:248to documentstreamEvents()(or remove deadstream())pnpm checkAffected files
packages/client/src/lib/api-client.tspackages/client/.instructions.mdAudit 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
stagingtree. Severity: MEDIUM.@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.