Repository navigation
fix: resolve finish_reason placement and chunk emission issues for v1/chat/completions endpoint - #55210
fix: resolve finish_reason placement and chunk emission issues for v1/chat/completions endpoint#55210niuma996 wants to merge 6 commits into
Conversation
… spec - Move finish_reason out of delta, into choices[0] level (per spec) - Only emit finish_reason on the final chunk (not every chunk) - Send empty final chunk with finish_reason: "stop" on stream end - Separate error content chunk from stop chunk in error path - Add wroteFinalChunk guard to prevent duplicate final chunk sends - Update tests to verify spec compliance for middle/stop chunks
Greptile SummaryThis PR fixes two real OpenAI streaming-spec violations in
Confidence Score: 4/5Safe to merge; the fix is correct and well-guarded, with only minor test-coverage and spec-compliance edge cases remaining. The implementation correctly addresses all described bugs with a clear No files require special attention; both changed files are straightforward and self-contained.
|
| Filename | Overview |
|---|---|
| src/gateway/openai-http.ts | Core fix: writeAssistantContentChunk now emits finish_reason only on the final stop chunk at choices[0] level with empty delta; wroteFinalChunk guard prevents duplicate stop chunks across all async paths. |
| src/gateway/openai-http.test.ts | Tests updated to validate spec-aligned streaming behavior for both happy path and error path; minor coverage gap where find is used instead of findLast for the stop chunk assertion. |
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/gateway/openai-http.test.ts
Line: 769
Comment:
**`find` doesn't verify the stop chunk is last**
`allChoices.find(...)` returns the *first* choice with `finish_reason === "stop"`. If a middle chunk accidentally acquired `finish_reason: "stop"` while later chunks continued streaming, the test would still pass. Consider using `findLast` (or checking the index) to assert the stop chunk is actually the terminal entry:
```suggestion
const lastChunk = allChoices.findLast((choice) => choice.finish_reason === "stop");
```
Same pattern applies to the `stopChoice` lookup in the error path (line 842).
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/gateway/openai-http.ts
Line: 149-151
Comment:
**Non-final chunks omit `finish_reason: null`**
The [OpenAI streaming spec](https://platform.openai.com/docs/api-reference/chat/streaming) includes `"finish_reason": null` on every intermediate chunk (at the `choices[0]` level). The new code omits the property entirely on non-final chunks. Most client libraries handle both cases gracefully, but strict spec consumers may behave differently. Consider whether explicit `null` should be preserved:
```suggestion
delta: isLast ? {} : { content: params.content },
...(isLast ? { finish_reason: params.finishReason } : { finish_reason: null }),
```
If the intentional goal is to omit it (simpler output), that's fine — just worth a comment documenting the deliberate deviation.
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(gateway): align /v1/chat/completions..." | Re-trigger Greptile
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 597ac69c23
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 80d348ba46
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 68efa839ee
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (phase === "end") { | ||
| closed = true; | ||
| unsubscribe(); | ||
| if (!wroteFinalChunk) { |
There was a problem hiding this comment.
Remove disconnect watcher when stream ends normally
In the phase === "end" branch, the code closes the SSE response without calling stopWatchingDisconnect(). On the normal success path this branch sets closed = true, so the finally cleanup is skipped and the socket close listener installed by watchClientDisconnect remains attached until the socket is destroyed; with keep-alive reuse this can accumulate listeners and retained abort-controller closures across requests, eventually triggering listener warnings and avoidable memory growth.
Useful? React with 👍 / 👎.
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. Close as superseded: the stale, conflicting branch is replaced by a newer same-author PR that carries the remaining Gateway SSE finish_reason work, while current main now uses a finalizer flow this branch bypasses. Canonical path: Close this stale branch and continue the fix in #83203 after it is rebased around current main's finalizer and includes real Gateway SSE proof. So I’m closing this here and keeping the remaining discussion on #83203. Review detailsBest possible solution: Close this stale branch and continue the fix in #83203 after it is rebased around current main's finalizer and includes real Gateway SSE proof. Do we have a high-confidence way to reproduce the issue? Yes, source-level. Current main still combines generic streaming error content with a stop-marked choice, and the current test suite still expects that shape; I did not run a live Gateway request in this read-only review. Is this the best way to solve the issue? No for this branch. The maintainable path is the newer replacement PR reworked around current main's Security review: Security review cleared: The diff only changes Gateway SSE response shaping and colocated tests, with no auth, secret, dependency, workflow, publishing, or supply-chain surface changed. What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against 1f794d2816d1. |
|
ClawSweeper applied the proposed close for this PR.
|
Bug Description
The
/v1/chat/completionsstreaming endpoint emits SSE chunks that violate the OpenAI Chat Completions streaming spec:finish_reasonis placed insidedeltainstead of atchoices[0]levelfinish_reasonis emitted on every chunk, not just the final oneRoot Cause
writeAssistantContentChunkplacedfinish_reasoninside thedeltaobject and always included it regardless of chunk position.Fix
writeAssistantContentChunk: only attachfinish_reasonatchoices[0]level whenisLast = truedelta: {},finish_reason: "stop") whenphase === "end"fireswroteFinalChunkguard to prevent duplicate final chunk sendsTest
Updated
openai-http.test.tsstreaming tests to verify:finish_reasonfinish_reason: "stop"atchoices[0]level with emptydeltaImpact
Any client consuming OpenClaw's streaming response with a strict OpenAI-compatible parser now works correctly.
Built with AI assistance (Claude Code / Codex).