Skip to content

fix: resolve finish_reason placement and chunk emission issues for v1/chat/completions endpoint - #55210

Closed
niuma996 wants to merge 6 commits into
openclaw:mainfrom
niuma996:fix/chatcompletion-streaming-finish-reason
Closed

niuma996 wants to merge 6 commits into
openclaw:mainfrom
niuma996:fix/chatcompletion-streaming-finish-reason

Conversation

@niuma996

Copy link
Copy Markdown
Contributor

Bug Description

The /v1/chat/completions streaming endpoint emits SSE chunks that violate the OpenAI Chat Completions streaming spec:

  • finish_reason is placed inside delta instead of at choices[0] level
  • finish_reason is emitted on every chunk, not just the final one

Root Cause

writeAssistantContentChunk placed finish_reason inside the delta object and always included it regardless of chunk position.

Fix

  • writeAssistantContentChunk: only attach finish_reason at choices[0] level when isLast = true
  • Emit a final stop chunk (delta: {}, finish_reason: "stop") when phase === "end" fires
  • In error path: send error content as a regular chunk first, then send stop chunk separately
  • Added wroteFinalChunk guard to prevent duplicate final chunk sends

Test

Updated openai-http.test.ts streaming tests to verify:

  • Middle chunks do NOT contain finish_reason
  • Final chunk has finish_reason: "stop" at choices[0] level with empty delta
  • Error path sends error content and stop chunk as separate chunks

Impact

Any client consuming OpenClaw's streaming response with a strict OpenAI-compatible parser now works correctly.


Built with AI assistance (Claude Code / Codex).

… 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
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Mar 26, 2026
@greptile-apps

greptile-apps Bot commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two real OpenAI streaming-spec violations in /v1/chat/completions: the error path was bundling error text and finish_reason: "stop" in the same SSE chunk (the stop chunk must have an empty delta), and no properly-formed terminal stop chunk was being emitted on normal completion. The implementation is clean and the core logic is correct.

  • writeAssistantContentChunk: correctly moves finish_reason from always-present in every chunk to only on the final chunk, and at the choices[0] level with an empty delta: {}. ✅
  • phase === "end" handler: now explicitly emits the final stop chunk before closing the stream. ✅
  • Error path: splits error content and the stop signal into two separate SSE chunks. ✅
  • wroteFinalChunk guard: prevents duplicate final-chunk emission across the catch/finally/lifecycle-event paths. ✅
  • Tests: updated to validate both the happy path and error path against the new spec-aligned behavior. The test's find (vs findLast) for the stop chunk means it doesn't confirm the stop is the last emitted choice — a weak but non-blocking coverage gap.
  • Non-final chunks now omit finish_reason entirely rather than including finish_reason: null; this is a minor deviation from the strict OpenAI spec and worth a deliberate comment/decision.

Confidence Score: 4/5

Safe 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 wroteFinalChunk guard that prevents double-sends across all concurrency paths. The two P2s (test uses find instead of findLast; intermediate chunks lack finish_reason: null) are non-blocking improvements, not defects in the delivered behavior.

No files require special attention; both changed files are straightforward and self-contained.

Important Files Changed

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

Comment thread src/gateway/openai-http.test.ts Resolved
Comment thread src/gateway/openai-http.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/gateway/openai-http.ts Resolved
niuma996 and others added 2 commits March 26, 2026 23:48
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>
@niuma996 niuma996 changed the title [Bug] /v1/chat/completions streaming: fix finish_reason position and chunk emissionfix(gateway): align /v1/chat/completions streaming output with OpenAI… fix: resolve finish_reason placement and chunk emission issues for v1/chat/completions endpoint Mar 26, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/gateway/openai-http.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +598 to +601
if (phase === "end") {
closed = true;
unsubscribe();
if (!wroteFinalChunk) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

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 details

Best 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 maybeFinalize() contract, not merging this stale direct-close implementation.

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:

  • Live stale PR state: gh pr view 55210 shows this PR is still open at head 68efa83, touches only src/gateway/openai-http.ts and src/gateway/openai-http.test.ts, and GitHub reports mergeable: CONFLICTING. (68efa839ee66)
  • Canonical replacement PR: gh pr view 83203 shows fix(gateway): separate finish_reason from content chunks in streaming #83203 is open from the same author, changes the same Gateway streaming files, and its body names this PR as the item it closes. (26e73fad14a7)
  • Canonical search pass: A GitHub PR search for the central finish_reason streaming terms found this stale PR and the newer replacement PR as the active same-author items; no separate canonical issue displaced the replacement PR.
  • Current main finalizer contract: Current main finalizes streaming Chat Completions through maybeFinalize(), which waits for result/usage state, stops disconnect watching, writes the terminal finish chunk, optionally writes usage, sends [DONE], and ends the response. (src/gateway/openai-http.ts:1072, 1f794d2816d1)
  • Current main remaining bug: Current main still writes generic streaming error content with finishReason: "stop" in the same content chunk, and the colocated test still expects that combined shape, so the central bug is real but belongs in the replacement PR. (src/gateway/openai-http.ts:1230, 1f794d2816d1)
  • Current documented behavior at risk: Gateway docs state that stream_options.include_usage=true emits a trailing usage chunk before [DONE], which depends on current main's usage-aware finalizer rather than the old branch's direct close path. Public docs: docs/gateway/openai-http-api.md. (docs/gateway/openai-http-api.md:250, 1f794d2816d1)

Likely related people:

  • @Lellansin: Recent merged work added real usage handling, usage-gated stream finalization, lifecycle flush behavior, and related Gateway tests in the same OpenAI-compatible streaming path. (role: recent adjacent streaming contributor; confidence: high; commits: 2ccd1839f212, e964469d973d, 51fba8cac2f4; files: src/gateway/openai-http.ts, src/gateway/openai-http.test.ts, docs/gateway/openai-http-api.md)
  • @steipete: History shows the OpenAI-compatible HTTP endpoint and later initial streaming chunk behavior were introduced or maintained through the affected Gateway files. (role: introduced affected gateway surface and recent gateway contributor; confidence: high; commits: 97bd183c1af0, 57fb65820aae, 3b1273cf8f5f; files: src/gateway/openai-http.ts, src/gateway/openai-http.test.ts, docs/gateway/openai-http-api.md)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 1f794d2816d1.

@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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels May 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 19, 2026
@clawsweeper

clawsweeper Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this May 19, 2026
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. 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-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.

1 participant