[GH-ISSUE #2744] [Issue]: Provider upstream SSE parsing gaps — strict data: prefix, discarded buffer/no decoder flush, swallowed failures, lost event name, hardcoded finishReason #1383

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/2744

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The Anthropic and Google streaming parsers require a literal data: (with trailing space) and slice a fixed 6 chars, unlike the OpenAI provider's tolerant extractSseData (startsWith('data:') + slice(5).trimStart()). Against a non-canonical/compatible/proxy endpoint that emits data:{...}, Anthropic drops every event and returns an empty assistant message; Google hard-fails with "no candidates". Google also discards the residual buffer at stream end and none of the three parsers flush the TextDecoder. The OpenAI Responses parser swallows response.failed (no throw, unlike chat()/Anthropic), so a mid-stream failure can be saved as a truncated-but-complete message, and it resets currentEvent inside the read loop so a split event:/data: frame loses its type. Finally, the base chatComplete() collector hardcodes finishReason: 'stop', so streaming Anthropic/Google max_tokens truncation is reported as a clean completion.

Sub-bug 1: Anthropic strict 'data: ' prefix -> empty generation (MEDIUM, truncation)

  • How it breaks: if (!trimmed.startsWith('data: ')) continue; const data = trimmed.slice(6); drops every data:{...} (no-space) frame; no content_block_delta is parsed, no tokens yielded, no message_stop — the generation appears to hang then returns empty. baseUrl is user-configurable, so a proxy/compatible endpoint reaches this.
  • Repro: Point an Anthropic-type connection at a proxy that emits data: without the space; replies come back empty.
  • Trace: anthropic.provider.ts:552-554; contrast openai.provider.ts:146-149.

Sub-bug 2: Google strict 'data: ' prefix (LOW, truncation)

  • How it breaks: google.provider.ts:729-730 same startsWith('data: ') + slice(6); spaceless frames yield no parts and the post-loop guard throws "Gemini stream returned no candidates/content". Canonical ?alt=sse is fine; risk is proxy reframing (the file comments document proxy reshaping).
  • Trace: google.provider.ts:729-730, throw at 786-792.

Sub-bug 3: Google discards trailing buffer / no flush (LOW, truncation)

  • How it breaks: On done the loop breaks and the retained buffer = lines.pop() is never re-parsed; there is no decoder.decode() flush. Gemini SSE has no [DONE]/message_stop sentinel (termination depends on socket close), so the un-flushed final frame is the one carrying finishReason+usageMetadata+last text. Only bites if the final frame lacks its trailing newline (spec-violating), so latent.
  • Trace: google.provider.ts:716-804; decoder created 704, only decode(...,{stream:true}) at 720.

Sub-bug 4: No final decoder flush in any parser (LOW, truncation)

  • How it breaks: All six streaming-decode sites use only decode(value,{stream:true}) and never a no-arg flush. Cannot drop a content codepoint of a well-formed stream (last bytes are ASCII terminators), but a code smell.
  • Trace: anthropic.provider.ts:547, openai.provider.ts:1002/1250/1720/1921, google.provider.ts:720.

Sub-bug 5: Responses swallows response.failed (LOW, wrong-output)

  • How it breaks: case 'response.failed' only logs + breaks in both chatResponses and chatCompleteResponses; neither throws (unlike chat() 1027-1031 / Anthropic 571-573). A mid-stream failure after some tokens leaves a non-empty partial that is saved as a normal message with no error/retry. (Zero-token case is caught by the empty-response guard at 6617.)
  • Trace: openai.provider.ts:1789-1795 (chatResponses), 2047-2053 (chatCompleteResponses).

Sub-bug 6: Responses event name lost across chunk boundary (LOW, wrong-output)

  • How it breaks: let currentEvent = '' is declared inside the while(true) loop, so an event: line in read N is wiped before its split-off data: line is parsed in read N+1; typing then falls back to parsed.type. Real OpenAI always includes type, so only an atypical proxy that strips type triggers a dropped delta.
  • Trace: openai.provider.ts:1724 (chatResponses), 1925 (chatCompleteResponses).

Sub-bug 7: hardcoded finishReason:'stop' (LOW, wrong-output)

  • How it breaks: Base chatComplete() returns finishReason: 'stop' unconditionally; the chat() generator carries no finish reason out. For non-tool Anthropic/Google calls (which fall back to super.chatComplete), a real max_tokens truncation is reported as clean — Professor Mari's workspace agent never marks the turn length-truncated and offers no continue affordance.
  • Trace: base-provider.ts:613-627 (hardcoded 626); fallback anthropic.provider.ts:270-272, google.provider.ts:413-415; consumer workspace-agent.service.ts:1022-1025.

Suggested Fix

  • Replace the Anthropic and Google parsers' startsWith('data: ') + slice(6) with startsWith('data:') + slice(5).trimStart(), mirroring extractSseData.
  • After the Google read loop, buffer += decoder.decode(); and parse any residual complete data: line; add the no-arg flush to all parsers.
  • Throw on response.failed in both Responses parsers (mirror chat()/Anthropic); optionally throw at stream end if nothing yielded and no response.completed.
  • Hoist let currentEvent = '' above the while loop in both Responses parsers.
  • Plumb the real finish reason out of the streaming generators (Anthropic message_delta.delta.stop_reason, Google candidate.finishReason) so chatComplete reports actual truncation instead of hardcoding 'stop'.

Root-cause throughline

Each provider hand-rolls its own SSE parser instead of sharing the tolerant OpenAI extractSseData/finish-reason logic, so the same fixed-offset data: assumption, missing trailing-buffer/decoder flush, and dropped finish-reason/failure semantics are re-implemented inconsistently across Anthropic, Google, and the Responses path.

Verification checklist (leave all UNCHECKED)

  • Manually verify: Anthropic-compatible/proxy endpoint emitting 'data:' (no space) now streams tokens
  • Manually verify: Gemini behind a reframing proxy streams instead of throwing 'no candidates'
  • Manually verify: a mid-stream Responses failure surfaces an error/retry, not a silent truncated message
  • Manually verify: Anthropic/Google max_tokens truncation reports length finishReason (Professor Mari continue affordance)
  • Run pnpm check

Affected files

  • packages/server/src/services/llm/providers/anthropic.provider.ts
  • packages/server/src/services/llm/providers/google.provider.ts
  • packages/server/src/services/llm/providers/openai.provider.ts
  • packages/server/src/services/llm/base-provider.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: 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/2744 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The Anthropic and Google streaming parsers require a literal `data: ` (with trailing space) and slice a fixed 6 chars, unlike the OpenAI provider's tolerant `extractSseData` (`startsWith('data:')` + `slice(5).trimStart()`). Against a non-canonical/compatible/proxy endpoint that emits `data:{...}`, Anthropic drops every event and returns an empty assistant message; Google hard-fails with "no candidates". Google also discards the residual `buffer` at stream end and none of the three parsers flush the `TextDecoder`. The OpenAI Responses parser swallows `response.failed` (no throw, unlike `chat()`/Anthropic), so a mid-stream failure can be saved as a truncated-but-complete message, and it resets `currentEvent` inside the read loop so a split `event:`/`data:` frame loses its type. Finally, the base `chatComplete()` collector hardcodes `finishReason: 'stop'`, so streaming Anthropic/Google `max_tokens` truncation is reported as a clean completion. ### Sub-bug 1: Anthropic strict 'data: ' prefix -> empty generation (MEDIUM, truncation) - **How it breaks:** `if (!trimmed.startsWith('data: ')) continue; const data = trimmed.slice(6);` drops every `data:{...}` (no-space) frame; no `content_block_delta` is parsed, no tokens yielded, no `message_stop` — the generation appears to hang then returns empty. `baseUrl` is user-configurable, so a proxy/compatible endpoint reaches this. - **Repro:** Point an Anthropic-type connection at a proxy that emits `data:` without the space; replies come back empty. - **Trace:** `anthropic.provider.ts:552-554`; contrast `openai.provider.ts:146-149`. ### Sub-bug 2: Google strict 'data: ' prefix (LOW, truncation) - **How it breaks:** `google.provider.ts:729-730` same `startsWith('data: ')` + `slice(6)`; spaceless frames yield no parts and the post-loop guard throws "Gemini stream returned no candidates/content". Canonical `?alt=sse` is fine; risk is proxy reframing (the file comments document proxy reshaping). - **Trace:** `google.provider.ts:729-730`, throw at `786-792`. ### Sub-bug 3: Google discards trailing buffer / no flush (LOW, truncation) - **How it breaks:** On `done` the loop breaks and the retained `buffer = lines.pop()` is never re-parsed; there is no `decoder.decode()` flush. Gemini SSE has no `[DONE]`/`message_stop` sentinel (termination depends on socket close), so the un-flushed final frame is the one carrying finishReason+usageMetadata+last text. Only bites if the final frame lacks its trailing newline (spec-violating), so latent. - **Trace:** `google.provider.ts:716-804`; decoder created `704`, only `decode(...,{stream:true})` at `720`. ### Sub-bug 4: No final decoder flush in any parser (LOW, truncation) - **How it breaks:** All six streaming-decode sites use only `decode(value,{stream:true})` and never a no-arg flush. Cannot drop a content codepoint of a well-formed stream (last bytes are ASCII terminators), but a code smell. - **Trace:** `anthropic.provider.ts:547`, `openai.provider.ts:1002/1250/1720/1921`, `google.provider.ts:720`. ### Sub-bug 5: Responses swallows response.failed (LOW, wrong-output) - **How it breaks:** `case 'response.failed'` only logs + breaks in both `chatResponses` and `chatCompleteResponses`; neither throws (unlike `chat()` 1027-1031 / Anthropic 571-573). A mid-stream failure after some tokens leaves a non-empty partial that is saved as a normal message with no error/retry. (Zero-token case is caught by the empty-response guard at `6617`.) - **Trace:** `openai.provider.ts:1789-1795` (chatResponses), `2047-2053` (chatCompleteResponses). ### Sub-bug 6: Responses event name lost across chunk boundary (LOW, wrong-output) - **How it breaks:** `let currentEvent = ''` is declared inside the `while(true)` loop, so an `event:` line in read N is wiped before its split-off `data:` line is parsed in read N+1; typing then falls back to `parsed.type`. Real OpenAI always includes `type`, so only an atypical proxy that strips `type` triggers a dropped delta. - **Trace:** `openai.provider.ts:1724` (chatResponses), `1925` (chatCompleteResponses). ### Sub-bug 7: hardcoded finishReason:'stop' (LOW, wrong-output) - **How it breaks:** Base `chatComplete()` returns `finishReason: 'stop'` unconditionally; the `chat()` generator carries no finish reason out. For non-tool Anthropic/Google calls (which fall back to `super.chatComplete`), a real `max_tokens` truncation is reported as clean — Professor Mari's workspace agent never marks the turn length-truncated and offers no continue affordance. - **Trace:** `base-provider.ts:613-627` (hardcoded 626); fallback `anthropic.provider.ts:270-272`, `google.provider.ts:413-415`; consumer `workspace-agent.service.ts:1022-1025`. ## Suggested Fix - Replace the Anthropic and Google parsers' `startsWith('data: ')` + `slice(6)` with `startsWith('data:')` + `slice(5).trimStart()`, mirroring `extractSseData`. - After the Google read loop, `buffer += decoder.decode();` and parse any residual complete `data:` line; add the no-arg flush to all parsers. - Throw on `response.failed` in both Responses parsers (mirror `chat()`/Anthropic); optionally throw at stream end if nothing yielded and no `response.completed`. - Hoist `let currentEvent = ''` above the `while` loop in both Responses parsers. - Plumb the real finish reason out of the streaming generators (Anthropic `message_delta.delta.stop_reason`, Google `candidate.finishReason`) so `chatComplete` reports actual truncation instead of hardcoding `'stop'`. ## Root-cause throughline Each provider hand-rolls its own SSE parser instead of sharing the tolerant OpenAI `extractSseData`/finish-reason logic, so the same fixed-offset `data: ` assumption, missing trailing-buffer/decoder flush, and dropped finish-reason/failure semantics are re-implemented inconsistently across Anthropic, Google, and the Responses path. ## Verification checklist (leave all UNCHECKED) - [ ] Manually verify: Anthropic-compatible/proxy endpoint emitting 'data:' (no space) now streams tokens - [ ] Manually verify: Gemini behind a reframing proxy streams instead of throwing 'no candidates' - [ ] Manually verify: a mid-stream Responses failure surfaces an error/retry, not a silent truncated message - [ ] Manually verify: Anthropic/Google max_tokens truncation reports length finishReason (Professor Mari continue affordance) - [ ] Run `pnpm check` --- ### Affected files - `packages/server/src/services/llm/providers/anthropic.provider.ts` - `packages/server/src/services/llm/providers/google.provider.ts` - `packages/server/src/services/llm/providers/openai.provider.ts` - `packages/server/src/services/llm/base-provider.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: **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. Anthropic and Gemini SSE parsers now accept data: without a space and flush decoder/residual buffers at EOF; OpenAI Responses parsers preserve event names across chunks and throw on response.failed; streamed usage can carry normalized finishReason so Anthropic/Gemini max-token truncation reports length instead of stop. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.

<!-- gh-comment-id:4763204686 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on PR #2747. Anthropic and Gemini SSE parsers now accept data: without a space and flush decoder/residual buffers at EOF; OpenAI Responses parsers preserve event names across chunks and throw on response.failed; streamed usage can carry normalized finishReason so Anthropic/Gemini max-token truncation reports length instead of stop. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.
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#1383
No description provided.