Skip to content

fix(gateway): separate finish_reason from content chunks in streaming - #83203

Closed
niuma996 wants to merge 1 commit into
openclaw:mainfrom
niuma996:fix/openai-streaming-finish-reason-v2
Closed

niuma996 wants to merge 1 commit into
openclaw:mainfrom
niuma996:fix/openai-streaming-finish-reason-v2

Conversation

@niuma996

Copy link
Copy Markdown
Contributor

Summary

  • Split writeAssistantContentChunk (always finish_reason: null) from a new writeAssistantFinishChunk (empty delta, finish_reason: stop)
  • Emit the finish chunk from the lifecycle end handler, the error path, and the finally fallback path
  • Updated streaming tests to assert spec-correct behavior

Test plan

  • pnpm test src/gateway/openai-http.test.ts — 7/7 passing
  • Normal streaming: content chunks have finish_reason: null, stop chunk has finish_reason: stop with empty delta
  • Error path: error content chunk is separate from stop chunk

Closes #55210

🤖 Generated with Claude Code

… responses

Per OpenAI streaming spec, finish_reason must appear only on the final
chunk at choices[0] level with an empty delta, not mixed into content
chunks. Split writeAssistantContentChunk (always finish_reason: null)
from a new writeAssistantFinishChunk (empty delta, finish_reason: stop).
Emit the finish chunk from the lifecycle end handler, the error path,
and the finally fallback path.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 17, 2026
@clawsweeper

clawsweeper Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 1, 2026, 5:38 AM ET / 09:38 UTC.

Summary
The PR changes /v1/chat/completions SSE streaming to make content chunks use finish_reason: null, add a separate empty-delta stop chunk, and update Gateway streaming tests.

PR surface: Source +18, Tests +24. Total +42 across 2 files.

Reproducibility: yes. source-reproducible: current main still sends generic streaming internal-error content in the same content choice as finishReason: "stop". I did not run a live HTTP SSE request because this is a read-only review.

Review metrics: 1 noteworthy metric.

  • Gateway SSE Terminal Writers: 3 direct finish/end paths added. The diff changes public OpenAI-compatible stream termination behavior, so ordering, usage chunks, and tool-call finish semantics need maintainer attention before merge.

Root-cause cluster
Relationship: canonical
Canonical: #83203
Summary: This PR is the current candidate for the Gateway finish_reason chunk-shape cleanup; the older same-author PR is closed as superseded, while nearby SSE finalization and provider finish_reason items cover distinct remaining behavior.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Rebase or replace the branch on current main and route terminal writes through maybeFinalize().
  • Preserve tool_calls terminal finish reasons and stream_options.include_usage ordering in focused assertions.
  • [P1] Add redacted real /v1/chat/completions SSE proof after the reworked patch; updating the PR body should trigger a fresh ClawSweeper review.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body lists local test checkboxes only; it still needs redacted after-fix Gateway SSE output, terminal capture, logs, recording, or a linked artifact before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Mantis proof suggestion
A redacted terminal capture of a real Gateway SSE request would materially prove the public streaming contract after rework. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis visual task: capture a redacted real `/v1/chat/completions` SSE request showing content chunks, terminal finish chunk, optional usage chunk, and `[DONE]` ordering.

Risk before merge

  • [P1] The PR is currently conflicting with current main, so the exact merge result is not reviewable without a rebase or replacement.
  • [P1] The added direct lifecycle-end finish path can close the SSE response before current main's result and usage gates run, risking lost usage chunks or terminal stream state.
  • [P1] The new finish helper hardcodes finish_reason: "stop", which can mislabel streaming tool-call responses that current main and docs expect to finish with tool_calls.
  • [P1] The external PR still lacks redacted real /v1/chat/completions SSE output, terminal logs, recording, or a linked artifact after the patch.

Maintainer options:

  1. Rework On Current Finalizer (recommended)
    Preserve maybeFinalize() result and usage gates plus configurable terminal finish reasons while adding the error-content split this PR is trying to fix.
  2. Open A Narrow Replacement
    If the contributor branch remains hard to rebase, maintainers can carry the useful test intent into a small replacement PR and credit the source contribution.
  3. Pause Until Proof Arrives
    If no rebase and real SSE proof are added, keep the PR blocked rather than merging a public streaming-contract change without after-fix evidence.

Next step before merge

  • [P1] Human follow-up is needed because the external PR lacks real behavior proof, is conflicting, and needs maintainer-safe rework around the current finalizer before merge.

Security
Cleared: The diff only changes Gateway SSE response shaping and colocated tests, with no auth, secret, dependency, workflow, publishing, or supply-chain surface changed.

Review findings

  • [P1] Route finish writes through the finalizer — src/gateway/openai-http.ts:612-619
  • [P1] Preserve non-stop terminal finish reasons — src/gateway/openai-http.ts:166-177
Review details

Best possible solution:

Rebase or replace the branch around current main's maybeFinalize() flow, preserve stop versus tool_calls terminal reasons and usage ordering, and split generic error content into a null-finish content chunk followed by the terminal stop chunk.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: current main still sends generic streaming internal-error content in the same content choice as finishReason: "stop". I did not run a live HTTP SSE request because this is a read-only review.

Is this the best way to solve the issue?

No, not as written. The useful fix should be applied through current main's finalizer so usage chunks and tool_calls terminal reasons remain intact.

Full review comments:

  • [P1] Route finish writes through the finalizer — src/gateway/openai-http.ts:612-619
    The added lifecycle handler writes a finish chunk, [DONE], and ends the response as soon as lifecycle end arrives. Current main's finalizer waits for the command result and optional usage before closing, so this shape can drop terminal usage or stream state after rebase.
    Confidence: 0.92
  • [P1] Preserve non-stop terminal finish reasons — src/gateway/openai-http.ts:166-177
    The new finish helper hardcodes finish_reason: "stop". Current Gateway streaming tool-call responses document and test a terminal tool_calls finish reason, so this would mislabel those streams as ordinary stops.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.91

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against cf2efbe5d515.

Label changes

Label justifications:

  • P2: This is a bounded Gateway OpenAI-compatible streaming compatibility bug with client impact but no evidence of a core outage or security issue.
  • merge-risk: 🚨 compatibility: Merging as written could break existing OpenAI-compatible clients that rely on usage chunks or tool_calls finish reasons.
  • merge-risk: 🚨 message-delivery: The direct lifecycle-end close path can end the SSE response before current main's final result or terminal stream state has been emitted.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body lists local test checkboxes only; it still needs redacted after-fix Gateway SSE output, terminal capture, logs, recording, or a linked artifact before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +18, Tests +24. Total +42 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 23 5 +18
Tests 1 29 5 +24
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 52 10 +42

What I checked:

  • Repository policy read and applied: Root AGENTS.md and scoped src/gateway/AGENTS.md were read fully; their whole-path review, Gateway compatibility, and real-behavior-proof guidance apply to this public streaming API contract PR. (AGENTS.md:1, cf2efbe5d515)
  • Live PR state: Live GitHub data shows this external PR is open at head 26e73fad14a7c2f20b71ca8738d0467fee2ef454, maintainer-editable, and currently CONFLICTING/DIRTY; its body lists local test checkboxes but no redacted real Gateway SSE output or linked artifact. (26e73fad14a7)
  • PR head hardcodes terminal stop: The proposed writeAssistantFinishChunk() always emits finish_reason: "stop", so it cannot preserve current Gateway streaming tool-call completions that terminate with tool_calls. (src/gateway/openai-http.ts:166, 26e73fad14a7)
  • PR head bypasses current finalizer shape: The proposed lifecycle handler writes a finish chunk, [DONE], and ends the response directly on lifecycle end, which bypasses current main's result and optional usage gates. (src/gateway/openai-http.ts:612, 26e73fad14a7)
  • Current main finalizer contract: Current main finalizes streaming chat completions through maybeFinalize(), waits for result resolution and optional usage, writes a configurable terminal finish chunk, optionally writes usage, then sends [DONE]. (src/gateway/openai-http.ts:1195, cf2efbe5d515)
  • Current main tool-call contract: Current main supports finishReason: "stop" | "tool_calls" in the terminal SSE chunk, and the docs state streaming tool responses end with finish_reason: "tool_calls" before [DONE]. (src/gateway/openai-http.ts:305, cf2efbe5d515)

Likely related people:

  • Lellansin: Authored the merged usage-aware OpenAI-compatible chat completions work that current main's finalizer must preserve. (role: recent adjacent streaming contributor; confidence: high; commits: 2ccd1839f212, aad3bbebdd; files: src/gateway/openai-http.ts, src/gateway/openai-http.test.ts)
  • steipete: Shortlog and history show heavy prior ownership of the Gateway OpenAI HTTP path, including earlier stream and edge-handling refactors. (role: feature-history contributor; confidence: high; commits: 0f989d3109, a2ceadcc2a, 2863661bcc; files: src/gateway/openai-http.ts, src/gateway/agent-event-assistant-text.ts)
  • vincentkoc: Recent history includes OpenAI compatibility agent-first work and stream chunk normalization on the same endpoint. (role: recent Gateway OpenAI compatibility contributor; confidence: high; commits: d10669629d, eaad4ad1be, 9dab154519; files: src/gateway/openai-http.ts, src/gateway/openai-http.test.ts, docs/gateway/openai-http-api.md)
  • momothemage: Current blame for the finish helper and finalizer area points to commit 59df350f3c; the commit title is broader, so this is a recent-routing signal rather than sole ownership. (role: recent current-main line contributor; confidence: medium; commits: 59df350f3c18; files: src/gateway/openai-http.ts, src/gateway/openai-http.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added the P2 Normal backlog priority with limited blast radius. label May 17, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jun 15, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Jul 1, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 1, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 16, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

@niuma996 thanks for the PR. ClawSweeper is still waiting on real behavior proof before this can move forward.

Useful proof can be a screenshot, short video, terminal output, copied live output, linked artifact, or redacted logs that show the changed behavior after the fix. Please redact private tokens, phone numbers, private endpoints, customer data, and anything else sensitive.

Once proof is added to the PR body or a comment, ClawSweeper or a maintainer can re-check it.

@clawsweeper

clawsweeper Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix(gateway): separate finish_reason from content chunks in streaming This is item 1/1 in the current shard. Shard 0/22.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jul 19, 2026
steipete added a commit that referenced this pull request Jul 29, 2026
Emit every assistant content chunk with a null finish reason and rely on the canonical empty terminal choice for normal and error streams.

Refs: #83203

Co-authored-by: niuma996 <[email protected]>
@steipete

Copy link
Copy Markdown
Contributor

Thank you @niuma996 for correctly identifying that streamed assistant content must carry a null finish reason and be followed by a separate empty terminal stop chunk. This is now landed in #115718 at beca834, with your real Co-authored-by trailer preserved in the merged commit. We reproduced the defect against current main using the actual pinned official OpenAI SDK and the real Gateway SSE stream, verified all 112 relevant Gateway, Responses, and agent-filter tests plus the full changed gate, and confirmed green hosted CI and Workflow Sanity. Closing this superseded PR now that the contributor-credited fix has actually landed. Thank you again for the report and original patch.

@steipete steipete closed this Jul 29, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 30, 2026
…aw#115718)

Emit every assistant content chunk with a null finish reason and rely on the canonical empty terminal choice for normal and error streams.

Refs: openclaw#83203

Co-authored-by: niuma996 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants