Repository navigation
fix(ai): replace streamed function name on same-id continuation - #130537
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
10eba8e to
ff49b54
Compare
|
Codex review: needs maintainer review before merge. Reviewed August 27, 2026, 1:24 AM ET / 05:24 UTC. ClawSweeper reviewWhat this changesThe branch updates shared OpenAI-compatible tool-call stream assembly so later nonempty function names replace earlier fragments unless a continuation supplies a conflicting tool-call ID. Merge readinessKeep open for maintainer review: current main still freezes the direct provider’s name at its first nonempty fragment, while this focused patch fixes that path and preserves explicitly conflicting-ID handling. Priority: P1 Review scores
Verification
Live VerificationCommand: Result: PASS (completed) Assertions:
How this fits togetherOpenAI-compatible completion chunks are assembled into assistant tool calls before OpenClaw dispatches them. The shared assembler serves both the standalone direct provider and the managed transport. flowchart LR
A[OpenAI-compatible SSE chunks] --> B[Shared stream assembler]
B --> C[Resolve tool-call identity]
C --> D[Update name and arguments]
D --> E[Assistant tool-call output]
E --> F[Tool dispatch]
Decision needed
Why: The patch is technically focused and source-proven, but it intentionally changes observable standalone-provider output from the previously preserved first snapshot. Before merge
Agent review detailsSecurityNone. PR surfaceSource +9, Tests +167. Total +176 across 3 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Adopt the latest-nonempty-name rule for an already resolved direct tool call while retaining first identity only for an explicitly conflicting supplied ID. Do we have a high-confidence way to reproduce the issue? Yes: current main’s direct-mode guard at packages/ai/src/transports/openai-completions-stream.ts:613 retains the first nonempty name; the supplied two-frame same-index stream is a high-confidence source reproduction. Is this the best way to solve the issue? Yes, subject to maintainer acceptance of the corrected direct-stream contract: the shared owner distinguishes absent identity evidence from an explicitly conflicting ID without changing argument assembly or managed-mode behavior. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 95c318669520. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
ff49b54 to
5edebe0
Compare
|
@clawsweeper re-review. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
The direct OpenAI Chat Completions provider froze a streamed tool-call function name on the first nonempty fragment. processCompletionsStream now replaces the stored name whenever the delta is not an explicitly conflicting id: a continuation that re-uses the established index but omits its id is treated as a continuation (the block was already resolved by index or id above), matching the pinned OpenAI SDK accumulator, while a present-and-differing id keeps the first name to preserve the first-tool-identity contract. Fixes openclaw#127601
5edebe0 to
b1a73fd
Compare
|
Maintainer dependency check: I inspected the installed pinned |
|
Thanks @SunnyShu0925! |
|
@obviyus My pleasure! |
) Use the latest nonempty function-name snapshot for a resolved tool call so fragmented direct OpenAI-compatible streams do not publish stale tool names. Preserve the first tool identity when a later fragment supplies an explicitly conflicting ID. Co-authored-by: SunnyShu0925 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
Fixes #127601
What Problem This Solves
A tool call streamed in fragments (e.g. the function name arriving as
get_thenweather) was published by the direct OpenAI Chat Completions provider under the stale first fragment, so the call could fail as an unknown tool or dispatch to the wrong one. The direct provider now takes the latest nonempty function-name snapshot, matching the pinned OpenAI SDK and the managed transport.openai-completionsprovider recorded only the first nonempty streamedfunction.nameand refused to replace it on later deltas, while the pinned OpenAI SDK (ChatCompletionStream) and the managedprocessCompletionsStreamtransport both replace the stored name on every nonempty snapshot.packages/ai/src/transports/openai-completions-stream.ts— the name-assignment guard inprocessCompletionsStream(shared by the direct provider viamode: "direct"and the managed transport);packages/ai/src/providers/openai-completions.test.ts— four regression tests covering same-id fragmented names, idless index-resolved continuations, conflicting-id continuations, and the existing first-tool-identity contract.mistral/responses/anthropicproviders (independent accumulators), argument accumulation, tool-call id handling, and the direct provider's first-tool-identity contract for explicitly conflicting ids.Why This Change Was Made
processCompletionsStreamis the single stream processor shared by both the direct provider and the managed transport. After #129962 unified the two implementations, the name-assignment guard(!directMode || !block.name)carried forward the direct path's original "first nonempty name wins" semantics, while the managed path (where!directModeis true) already used latest-snapshot semantics — so the divergence reported in #127601 survived the unification.The guard is now
conflictingId = directMode && block.id && toolCall.id && block.id !== toolCall.id; if (toolCall.function?.name && !conflictingId). A nonempty name replaces the stored name on the managed path (unchanged, sincedirectModeis false there) and on the direct path whenever the delta is not an explicitly conflicting id. Crucially, a continuation that re-uses the establishedindexbut omits its id is treated as a continuation rather than a conflict: the block has already been resolved byindex(or by id) at the top of the loop, so an absent id is not identity evidence either way — only an id that is present and differs from the establishedblock.idkeeps the first name. This matches how the pinned OpenAI SDK accumulator accepts a later name-only frame on the same index, while still preserving direct mode'spreserves-the-first-tool-identitycontract for an explicitly conflicting id (locked by the existing test added in #129962).!directMode || !block.id || block.id === toolCall.id) conflated an omitted continuation id with an explicitly conflicting id, so a fragmented stream that sent the id only on its first frame still froze on the first fragment. Distinguishing the two — absent id = continuation, present-and-differing id = conflict — is required to fix the reported stale-name failure without breaking the first-tool-identity contract.if (toolCall.function?.name)). Rejected — it regresses the different-id same-index case (the existingpreserves the first tool identitytest); see the newkeeps the first name when a continuation carries a conflicting idtest.User Impact
When a model streams a tool-call name across multiple fragments (or corrects the name mid-stream), the direct OpenAI-compatible provider now publishes the complete, final name instead of the first fragment. Calls that previously failed as "unknown tool" or silently dispatched to a wrong-but-valid tool now resolve correctly. No configuration changes; managed Chat Completions and Responses paths were already correct and are unaffected.
Evidence
Real-behavior proof via an unmocked local OpenAI-compatible SSE endpoint — a local HTTP server streams real
ChatCompletionChunkbytes over SSE (novi.mock, no synthetic chunk injection), and the realstreamOpenAICompletionsdirect provider consumes them via realfetch:The local SSE server emits three frames on the wire: (1)
tool_calls[0]withid="call_proof",function.name="get_",function.arguments='{"city":'; (2)tool_calls[0]with the id omitted (index-resolved continuation),function.name="weather",function.arguments='"Paris"}'; (3)finish_reason="tool_calls". The direct provider (mode: "direct") resolves the block by index, then replaces the stored name on the nonemptyweathersnapshot — matching the pinned OpenAI SDK accumulator and the managed transport.Pre-fix (prior
!directMode || !block.id || block.id === toolCall.idguard), same unmocked SSE stream — name froze on the first fragment:Bidirectional guard: pre-fix FAIL (
name: "get_", frozen on first fragment) → post-fix PASS (name: "weather", latest nonempty snapshot). The prior guard treated the absent continuation id as a conflict; the fix distinguishes absent id (continuation) from present-and-differing id (conflict).Pinned SDK accumulator confirmation (
[email protected],client.chat.completions.stream→ChatCompletionStream._accumulateChatCompletion):The same unmocked local SSE stream is fed to the pinned SDK's own accumulator to independently confirm the idless-continuation contract:
The pinned SDK resolves the block by
indexand replaces the stored name on every nonemptyfn.namewithout consultingid(ChatCompletionStream.js:455resolves by index,:474replaces name unconditionally). The fix'sconflictingIdguard aligns: an idless continuation replaces the name (matching the SDK), and only an explicitly conflicting id preserves the first name (the direct-mode contract the SDK does not carry).Post-fix regression tests (direct provider,
node/vitestruntime, in-process SSE chunks mirroring the issue's two-chunk fixture and the pinned OpenAI SDK accumulator semantics):Before/after divergence matrix — same in-process chunks fed to
streamOpenAICompletions(direct,mode: "direct") andcreateOpenAICompletionsTransportStreamFn(managed):Pre-fix (HEAD~1, the prior
!directMode || !block.id || block.id === toolCall.idguard), scenarios A and C:Pre-fix the direct provider froze on the first fragment (
get_for A,firstfor C); post-fix it matches the managed transport (weather/second). Scenario B is unchanged from pre-fix — thepreserves-the-first-tool-identitycontract for an explicitly conflicting id is preserved.Bidirectional guard verification (each new/changed test confirmed to fail pre-fix for the expected reason, then pass post-fix):
replaces the stored function name on a same-id fragmented continuation: pre-fixExpected "weather", Received "get_"; post-fix pass.replaces the stored name when an index-resolved continuation omits the id: pre-fixExpected "second", Received "first"(the prior guard treated the absent id as a conflict); post-fix pass.keeps the first name when a continuation carries a conflicting id: pass pre- and post-fix — the first-tool-identity contract is preserved by both guards.Full
openai-completions.test.tssuite (68 tests) andopenai-completions-stream.tool-assembly.test.ts(3 tests) green;oxlint -c .oxlintrc.jsonandoxfmt --checkclean on both changed files.Pinned SDK accumulator source (
[email protected], the package pin inpackages/ai/package.json):The direct provider's name-assignment guard mirrors the pinned OpenAI SDK's own
ChatCompletionStreamaccumulator (node_modules/openai/lib/ChatCompletionStream.js,_accumulateChatCompletion):The SDK resolves the snapshot by
indexand replaces the stored name on every nonemptyfn.namewithout consultingidat all. The fix'sconflictingId = directMode && block.id && toolCall.id && block.id !== toolCall.idaligns with this: an idless index-resolved continuation replaces the name (matchingif (fn.name)), and the guard only diverges from the SDK by additionally preserving the first name for an explicitly conflicting id — the direct-modepreserves-the-first-tool-identitycontract (#129962), which the SDK does not carry because it has no direct/managed split. The prior guard (block.id === toolCall.id) violated the SDK semantics by treating an absent id as a conflict, freezing the name on the first fragment.What was not tested: No live external model-provider traffic captured (the local unmocked SSE endpoint above reproduces the fragmented-name stream shape from the issue's fixture, but no real hosted model was queried). The
mistralprovider's analogous fragmented-name handling (#127603) is a separate issue and intentionally not touched here.Managed-parity assertion:
openai-completions-stream.tool-calls.test.tsdrivesprocessCompletionsStreamwithoutmode: "direct"(the managed path) with the same fragmented-name chunks (nameget_→weather, same index, id omitted on 2nd frame) and asserts the published name isweather— confirming the managed path resolves fragmented names identically to the direct provider.Empty-name continuation:
openai-completions.test.tsfeeds a continuation withfunction.name: ""on the second frame and asserts the stored name is not erased (get_weatherpreserved) — the guard's truthiness check skips empty snapshots.AI Assistance
await-of-non-Promise lint errors in the new tests. Pre-fix/post-fix bidirectional verification re-run. Round 2 proof pass: added pinned[email protected]SDK accumulator source (ChatCompletionStream.js:451-475) showing the SDK resolves byindexand replaces the name on every nonemptyfn.namewith no id check, cross-checking the guard against the exact pinned version. Full session log available on request.block.id !== toolCall.idnarrowing, and all four regression tests are explained above.oxlint+oxfmt+ full openai-completions vitest shard run instead).Re-review round (2026-08-27)
ClawSweeper flagged the prior Evidence as mock-only (
vi.mock("openai")chunk injection). Added an unmocked local OpenAI-compatible SSE endpoint proof: a local HTTP server streams realChatCompletionChunkbytes over SSE, andstreamOpenAICompletions(direct provider) consumes them via realfetch— no module mock. Pre-fix the name froze onget_; post-fix it resolves toweather. The proof script lives outside the repo (/home/code/github/contributions/pr-130537-evidence/). No production code changes this round — the patch was already approved at 🐚 platinum hermit (4/6) patch quality with zero findings. Added two regression tests closing issue acceptance criteria gaps identified by adversarial self-review: (1) empty-name continuation does not erase the stored name (openai-completions.test.ts), and (2) managed-path parity assertion for fragmented names (openai-completions-stream.tool-calls.test.ts). Both tests satisfy the issue's explicit "empty-name continuation" and "managed-parity assertions" requirements. Also added a pinned SDK accumulator proof (node --import tsxdriving[email protected]'s ownChatCompletionStreamagainst the same local SSE stream) to independently confirm the idless-continuation contract.Maintainer landing proof (2026-08-27)
b1a73fdda482ffa2b2ba58a2537b5369abf57c52.42ce03e72e34adeb34a79c91f534a906df46f882publishedget_instead ofweather, andfirstinstead ofsecond, in the two owner-boundary regression cases.[email protected]resolves by tool-call index and replaces every later nonempty function name (ChatCompletionStream.js:451-475).checks-node-compact-small-45andopenclaw/ci-gate.Telegram real-user proof used only the canonical
telegram-e2e-userbotrunner with a fresh gateway and dedicated QA user lease. Secrets are omitted:call_stable_weather; namesget_thenweather; arguments{"city":then"Paris"}.name: "weather"and complete arguments{"city":"Paris"}.14; four SUT typing events; progress message2403showedWeather blocked; final message2404wasSTREAM_NAME_E2E_OK; progress message2403was then deleted.events.ndjson,summary.json,gateway.log, andmock-openai-requests.ndjsonretained locally.