Skip to content

fix(ai): report interrupted local-model streams instead of empty success - #129794

Merged
steipete merged 2 commits into
mainfrom
codex/r5-stream-terminal-refactor
Aug 26, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/r5-stream-terminal-refactor

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users running OpenAI-compatible local models through the managed Gateway could receive an empty successful answer, a silently truncated answer, or a dropped tool call when the provider disconnected before completing its response.

Why This Change Was Made

The OpenAI SDK treats both a real SSE [DONE] marker and an ordinary connection EOF as the end of its iterator. The managed transport already observes the raw SSE terminal, but its stream owner only used that fact when deciding whether a tool call was executable. Consequently, interrupted empty, text, and tool responses were finalized as successful stop outcomes.

Record the provider finish reason in the existing canonical stream owner and require either that explicit finish reason or the existing observed [DONE] marker before completing a managed response. The correction removes six production lines overall. Direct package streams, internal parser callers without terminal observers, malformed-tool safeguards, cancellation, request policy, and existing provider-specific behavior retain their contracts.

User Impact

Interrupted local-model responses now fail visibly instead of pretending that an empty, partial, or abandoned tool response succeeded. Compatible providers that omit [DONE] after an explicit finish reason still work, and providers that emit [DONE] without a finish reason still work.

Evidence

The existing real-localhost streaming regression originally accepted a dropped tool stream as a successful empty answer. Replacing it with a table covering real HTTP/SSE streams produced three failing regressions before the fix:

empty response without finish_reason or [DONE]       done -> error
partial text without finish_reason or [DONE]         done -> error
unfinished tool call without finish_reason or [DONE] done -> error
clean [DONE] without finish_reason                  done -> done
explicit finish_reason without [DONE]               done -> done

After the owner repair, all five cases pass. A separate real-localhost replay confirmed that each interrupted response ends with Stream ended without finish_reason and exposes no executable tool call, while both valid terminal formats remain successful.

Focused validation passed 413 tests across 21 suites, covering standalone and managed stream parity, encrypted and Google thought signatures, reasoning and usage contracts, DeepSeek recovery, legacy and modern tool calls, malformed arguments, provider response hooks, cancellation, request timeouts, and local HTTP streaming. Scoped formatting and lint checks passed; the final independent structured review reported no actionable findings.

Production: +7/-13 (net -6). Regression tests: +52/-30.

@clawsweeper

clawsweeper Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Aug 26, 2026
@steipete
steipete marked this pull request as ready for review August 26, 2026 02:53
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 26, 2026
@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 25, 2026, 11:17 PM ET / August 26, 2026, 03:17 UTC.

ClawSweeper review

What this changes

The PR makes managed OpenAI-compatible streams fail when neither a provider finish reason nor an SSE [DONE] terminal marker was observed, and expands localhost SSE regression coverage.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

No blocking patch defect found. Keep this maintainer-authored PR open for explicit compatibility approval: it intentionally changes managed OpenAI-compatible streams with bare EOF from apparent success to a visible error.

Priority: P1
Reviewed head: 7d0f7dbf10041849dbf77847371e9d975991fdb9
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The owner-boundary repair and regression matrix are strong, with merge readiness awaiting the explicit compatibility decision and exact-head CI.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the contributor proof gate; its described real-localhost HTTP/SSE replay remains useful supporting evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the contributor proof gate; its described real-localhost HTTP/SSE replay remains useful supporting evidence.
Evidence reviewed 7 items Terminal owner repair: The stream owner throws before finalization when its managed caller explicitly reports neither a finish reason nor an SSE terminal marker, preventing partial text or a silent tool call from becoming a successful outcome.
Managed caller boundary: The OpenAI-completions transport observes raw response bytes for [DONE] and passes the result into the owner; direct parser callers do not supply this option and retain their existing contract.
Boundary regression coverage: The table-driven localhost HTTP/SSE test covers empty, partial-text, and unfinished-tool bare EOF errors alongside valid [DONE] and explicit-finish-reason success cases through the public transport.
Findings None None.
Security None None.

Live Verification

Command: pnpm test packages/ai/src/transports/openai-completions-stream.tool-calls.test.ts

Result: PASS (completed)

$ node --import tsx scripts/test-projects.mts packages/ai/src/transports/openai-completions-stream.tool-calls.test.ts
[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-129794-5UupGL/target

 ✓  unit  packages/ai/src/transports/openai-completions-stream.tool-calls.test.ts (14 tests) 143ms

 Test Files  1 passed (1)
      Tests  14 passed (14)
   Start at  03:18:37
   Duration  1.67s (transform 1.17s, setup 759ms, import 494ms, tests 143ms, environment 0ms)

[test] passed 1 Vitest shard in 10.01s
$ node --import tsx scripts/test-projects.mts packages/ai/src/transports/openai-completions-stream.tool-calls.test.ts
[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-129794-5UupGL/target

 ✓  unit  packages/ai/src/transports/openai-completions-stream.tool-calls.test.ts (14 tests) 96ms

 Test Files  1 passed (1)
      Tests  14 passed (14)
   Start at  03:18:47
   Duration  865ms (transform 368ms, setup 329ms, import 280ms, tests 96ms, environment 0ms)

[test] passed 1 Vitest shard in 8.37s

Assertions:

  • NOT OBSERVED expect_output: openai completions stream — command exited successfully; expected output was not observed in the captured pane

How this fits together

The OpenAI-compatible transport consumes provider HTTP/SSE responses and normalizes text and tool calls into agent events. Its stream owner now decides whether the response has enough terminal evidence to expose a successful assistant outcome.

flowchart LR
  Provider[OpenAI-compatible provider]
  SSE[HTTP and SSE response]
  Detector[Raw terminal marker detector]
  Owner[Stream outcome owner]
  Decision{Terminal evidence present?}
  Result[Done event or error event]
  Provider --> SSE --> Detector --> Owner --> Decision
  Decision -->|Finish reason or DONE| Result
  Decision -->|Bare EOF| Result
Loading

Decision needed

Question Recommendation
Should managed OpenAI-compatible endpoints that provide neither a finish reason nor [DONE] be treated as interrupted rather than accepted as successful for backward compatibility? Adopt terminal evidence: Merge with the documented rule that bare EOF is an interrupted managed response and must produce a visible error.

Why: This is an intentional observable compatibility change for configured local and custom endpoints; source review can validate the implementation, but maintainers must choose the supported endpoint contract.

Before merge

  • Resolve merge risk (P1) - Existing OpenAI-compatible endpoints that historically end successful responses with neither finish_reason nor [DONE] will now receive a visible error; maintainers need to accept that compatibility boundary before merge.
  • Resolve merge risk (P1) - The direct OpenAI SDK source contract could not be inspected locally because the dependency source is absent and GitHub was unreachable; the included localhost transport test is the available behavioral evidence.
Agent review details

Security

None.

PR surface

Source -6, Tests +22. Total +16 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 7 13 -6
Tests 1 52 30 +22
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 59 43 +16

Review metrics

Metric Value Why it matters
Production versus regression LOC production +7/-13 (net -6); tests +52/-30 The repair reduces production logic while adding boundary coverage for five terminal-response cases.

Stored data model

Persistent data-model change detected: serialized state: packages/ai/src/transports/openai-completions-stream.tool-calls.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the terminal-evidence contract (recommended)
    Confirm that managed bare-EOF responses should fail visibly, then merge with the existing localhost regression matrix.
  2. Pause for endpoint compatibility
    Do not merge if supported OpenAI-compatible endpoints intentionally use bare EOF as successful completion; define their explicit compatibility contract first.

Technical review

Best possible solution:

Adopt one managed-stream terminal rule: only an explicit provider finish reason or observed SSE [DONE] may finalize success, while retaining direct parser behavior and the focused localhost boundary tests.

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

Yes. The checked-in localhost HTTP/SSE fixture terminates streams with and without finish_reason and [DONE], exercising the managed transport's terminal event and final result.

Is this the best way to solve the issue?

Yes, subject to the explicit compatibility decision. The terminal evidence is recorded at the managed transport boundary and enforced by its canonical stream owner rather than inferred downstream.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The patch addresses managed model streams that can silently report empty, partial, or abandoned responses as successful.
  • merge-risk: 🚨 compatibility: Merging changes existing configured OpenAI-compatible endpoints from bare-EOF apparent success to a visible error.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is exempt from the contributor proof gate; its described real-localhost HTTP/SSE replay remains useful supporting evidence.

Evidence

What I checked:

Likely related people:

  • steipete: Peter Steinberger has 19 commits in the central stream/transport history and authored the current implementation and follow-up test synchronization commit. (role: recent area contributor; confidence: high; commits: 7d0f7dbf1004; files: packages/ai/src/transports/openai-completions-stream.ts, packages/ai/src/transports/openai-completions-stream.tool-calls.test.ts)
  • osolmaz: Onur Solmaz has three commits in the central OpenAI-completions stream and transport history. (role: adjacent historical contributor; confidence: medium; files: packages/ai/src/transports/openai-completions-stream.ts, packages/ai/src/transports/openai-completions-transport.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Confirm the supported behavior for configured endpoints that finish with bare EOF and neither terminal signal.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-26T02:59:52.872Z sha 8cafa31 :: needs maintainer review before merge. :: none

@steipete

Copy link
Copy Markdown
Contributor Author

Maintainer compatibility decision: a managed OpenAI-compatible stream ending with neither an explicit finish_reason nor an SSE [DONE] marker is interrupted and must produce a visible error, not a successful empty, partial, or abandoned-tool response.

This restores the already-shipped boundary: v2026.7.1-2 rejects a stream without finish_reason, and the current direct OpenAI-compatible, Ollama, and Mistral owners likewise require authoritative terminal evidence. The installed upstream OpenAI SDK also rejects a completed choice missing finish_reason; its lower-level SSE iterator accepts ordinary EOF without distinguishing interruption, which is why the managed transport must own that decision.

This change is more permissive than the existing direct-provider contract: either a valid provider finish reason or an observed [DONE] marker completes successfully. No supported provider contract was found for successful bare EOF with neither signal. A malformed custom endpoint that supplies neither will now receive an explicit interruption error instead of silent apparent success; this compatibility boundary is intentional and approved.

The flagged .test.ts file is regression coverage, not serialized persistent state; there is no database, migration, or schema change. Exact-head hosted CI and all 413 focused streaming/provider tests are green.

@steipete
steipete merged commit 9b51019 into main Aug 26, 2026
115 checks passed
@steipete
steipete deleted the codex/r5-stream-terminal-refactor branch August 26, 2026 04:08
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 26, 2026
…ess (openclaw#129794)

* fix(ai): report interrupted local-model streams instead of empty success

* test(ai): await asynchronous managed stream fixtures
vincentkoc added a commit that referenced this pull request Aug 26, 2026
* origin/main: (24 commits)
  fix(gateway): reject rootless session permission modes (#128149)
  docs(memory): document shipped turn-taint propagation for network tool output (#129837)
  fix(ui): pool reply-less wake activity into one chat rollup (#128442)
  fix(package): prevent installs from deleting validated runtime assets (#129724)
  fix(nodes): approve silent initial node surfaces and name the pending surface approval (#129795)
  fix(backup): preserve configured agent state roots (#129773)
  fix(ui): own chat history issuance with a closed state machine (#129776)
  fix(cron): preserve cancellation reason after late finalization (#129331)
  fix(cron): prevent run waits from failing after clock changes (#129805)
  fix(telegram): route commentary through one frozen progress owner (#128259)
  fix(release): start approved VCR mirror recovery jobs (#129829)
  test: complete current-plugin-metadata-snapshot mock factories (#129791)
  test(telegram): remove duplicate reaction case (#129848)
  fix(channels): honor supported account reply-threading policies (#129679)
  refactor(cli): deduplicate lazy subcommand registration (#129351)
  fix(ai): report interrupted local-model streams instead of empty success (#129794)
  refactor(cli): consolidate Gateway fallback and hook ownership (#129802)
  fix(qa): reject token confidence lanes without executed evidence (#129830)
  fix(tui): fence session state and delayed actions (#129810)
  fix(control-ui): keep task progress full width on hover (#129832)
  ...
@VACInc

VACInc commented Sep 6, 2026

Copy link
Copy Markdown
Member

Follow-up merged: #140367 landed in main on September 6, 2026 (04081aa).

This PR established the transport-side distinction between a genuinely interrupted completions stream and valid terminal completion. #140367 handles the resulting Stream ended without finish_reason error in the agent recovery layer: it classifies the incomplete stream as a timeout and allows tool-free answer recovery after settled tools when only pre-tool commentary exists.

The changes are complementary. #140367 does not relax transport terminal validation or authorize replaying completed tools.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants