Skip to content

fix: absorb same-frame tool_call deltas before the finish_reason settle (#1306) - #1311

Merged
ranxianglei merged 1 commit into
masterfrom
2026-09-25_openai-sameframe-toolcall-args
Sep 25, 2026
Merged

ranxianglei merged 1 commit into
masterfrom
2026-09-25_openai-sameframe-toolcall-args

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Fixes #1306

Root cause

src/loop/adapter-openai.ts handled finish_reason before absorbing the current chunk's delta.tool_calls fragments:

  1. settleToolCalls() flushed the proxy call with the arguments accumulated so far — missing this frame's fragment — then pending.clear();
  2. the proxy branch (no continue) fell through to the accumulation block, which re-buffered the fragment as a nameless orphan (id="", name="");
  3. the [DONE] settle dropped the orphan silently (guard requires name or id) → arguments permanently lost;
  4. compress received "" → JSON.parse fallback {} → kind=missing-content; canonicalArgs("") is stable across rounds → failedSignatures match → breaking early (#156) terminated the turn.

Real tools were unaffected on the wire (verbatim raw replay); only proxy tools (compress/decompress/…) depend on the accumulated arguments.

Fix

  • Accumulate first, settle second: pure fragment accumulation (absorbToolCallDeltas) now runs at the top of the frame loop, before the finish_reason settle. The settle always sees the complete pending state; the orphan-producing mechanism is gone. Wire output for real tools is unchanged — the same-frame chunk still replays exactly once (via the verbatim finish-chunk replay), verified by test 9.
  • Diagnostics (requested in the issue): flushPendingAsStructured now warns when dropping an arguments-carrying nameless buffer instead of losing data silently; core.ts logs the failing arguments shape (len + head) at the JSON.parse fallback so wire-level loss is separable from model-authored junk.

Tests (tests/openai-toolcall-finish-reason.test.ts)

  • test 8 (adapter, proxy): same-frame args fragment + finish_reason → structured compress call carries the complete arguments. Fails on master (args ""), passes with the fix.
  • test 9 (adapter, real): same-frame shape → passthrough bookkeeping sees complete args AND the same-frame raw chunk replays exactly once (no duplication from absorbing earlier).
  • test 10 (loop): full runCompressLoop round with the same-frame upstream → compress actually executes (Compressed m00001–…), no missing-content, exactly one re-request.

The existing 7 tests in the file (name-splitting, mixed rounds, verbatim replay) all still pass.

Pre-flight

  • npm run typecheck ✅
  • focused file node --import tsx --test tests/openai-toolcall-finish-reason.test.ts → 11/11 ✅
  • A/B: with src/loop stashed, the 3 new tests fail exactly as the issue describes; restored → 11/11 green
  • npm run build ✅
  • Full npm test locally stalls in tests/dsh-native.test.ts (5s-timeout failures) — reproduced on pristine master in this sandbox too (environmental, not from this diff); deferring the full suite to CI as agreed.

No wire/message-shape change for existing paths; comments reference the invariant docs already in the file. Kernel untouched (the diag.keys-in-error-text suggestion from the issue is kernel-side and stays out of scope).

…le (#1306)

When the last tool_call arguments fragment and finish_reason arrive in the
SAME SSE chunk, the openai adapter settled BEFORE absorbing that frame's
fragment: the proxy call flushed with truncated/empty arguments, pending
was cleared, and the post-finish fallthrough re-buffered the fragment as a
nameless orphan that the [DONE] settle silently dropped. compress then
executed with {} -> kind=missing-content -> canonicalArgs('') is stable ->
#156 repeated-identical-failure early break.

- move pure fragment accumulation ahead of the finish_reason settle so it
  always sees the complete pending state (wire output for real tools is
  unchanged: the same-frame chunk still replays exactly once via rawBuf)
- flushPendingAsStructured now warns when dropping an arguments-carrying
  orphan buffer instead of losing data silently
- core.ts logs the failing arguments shape at the JSON.parse fallback so
  wire-level loss is separable from model-authored junk in logs
@github-actions

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-25_openai-sameframe-toolcall-args (280af50)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-1311

Each push to this PR publishes a new version under the pr-1311 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr1311.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,开始按 PR Review 规范审查本 PR(原 issue #1306 → 回归审查 → 代码审查 → 测试有效性 → diff 整洁度)。稍后给出完整结论。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review complete — mergeable. All five gates walked; evidence below.

① Original issue (direction)

#1306's failure chain (same-frame finish_reason+fragment → truncated flush → nameless orphan → silent [DONE] drop → missing-content → stable canonicalArgs("") → #156 early break) matches the code path I traced in src/loop/adapter-openai.ts. The fix attacks the producer mechanism (settle-before-absorb ordering), not the symptom — no retry/special-case bandaid on the empty-args side. Root-cause fix, not a mask. ✓

② Regression review — existing behaviors on touched paths, item by item

Existing behavior Conclusion
Multi-frame tool-call accumulation (name split across frames) Preserved — absorbToolCallDeltas is a byte-identical extraction of the old inline loop; tests 6/7/8 pass
Real-tool verbatim raw replay (each chunk exactly once, original ids/order) Preserved — rawToolChunks.push position and the finish-chunk rawBuf replay are untouched; the real path continues before the fall-through push, so no double replay (test 3, 7 + new test 9 pin this)
Proxy-vs-real decision at settle Unchanged — settleToolCalls body untouched
[DONE] orphan drop (guard requires name||id) Semantics unchanged; now warns instead of silently dropping when the buffer carries args (log-only, honest-output improvement)
done.finishReason remap (stop→tool_calls when hadToolCalls) One edge-case behavior change — disclosed below
core.ts JSON.parse fallback ({} + execute) Behavior identical; only adds a diagnostic log
Both compression modes (§6) Adapter is mode-agnostic; real-tool wire output unchanged in plugin and proxy modes alike; proxy-tool arg completeness benefits both. Anthropic/Responses adapters correctly untouched (bug is OpenAI-wire-shaped)

Behavior change disclosure (old → new + why): for the degenerate shape entire tool call (id+name+args in one chunk) arriving with finish_reason="stop": old code's settle saw an empty pending at finish → emitted done("stop") without suppressCompletion, then absorbed the fragment in fall-through and flushed it late at the [DONE] settle (a confused double-settle/double-done path). New code settles once at finish: proxy path remaps to done("tool_calls"), real path gets the clean single settle + verbatim finish-chunk replay + suppressCompletion. Strictly more correct; the old path was broken-by-construction for that shape. In practice providers stream deltas (and would send finish_reason:"tool_calls" for a complete single chunk anyway), so this affects no known-good deployment — flagged per policy, not a regression concern.

③ Code review

  • Placement verified: absorb runs after the choice/error guards, before the settle; nothing reads pending mid-frame except the settle, so non-finish frames are order-insensitive. No interaction with tagFilter or rawToolChunks timing.
  • Diagnostics use the right channels: loggerLog (import pre-existing) in the adapter, ctx.log in core.ts (consistent with surrounding code at core.ts:606). No console.error, no as any, no @ts-ignore.
  • One noted, accepted trade-off: the new core.ts log prints up to 200 chars of user-authored tool arguments into bili.log (AGENTS.md asks for secret masking in logs). It fires only on the rare JSON.parse-failure path, goes to the local-only state log, and is exactly what the issue requested ("len + head" to separate wire-loss from model-junk). Not blocking; tighten later if it ever becomes an issue.

④ Test validity — teeth confirmed by A/B

Ran the new tests against master's src/loop with the PR's test file: tests 9–11 fail exactly as the issue describes (truncated "" args / no compression executed), existing 8 pass; restored the fix → 11/11 green. Test 9 asserts in both directions (complete args AND exactly-one replay — catches both loss and duplication-from-early-absorb). Test 10 pins the user-visible symptom end-to-end through runCompressLoop (real Compressed m00001… marker, no missing-content, exactly one re-request). Deterministic mocks, no port/env luck.

⑤ Diff cleanliness

Single linear commit on current master (parent = dc8bdea5, release v0.1.149 merge — no stale base). 3 files, every line serves the fix; no whitespace churn, no lockfile/generated churn. No other open PR touches src/loop/adapter-openai.ts or src/loop/core.ts (checked all 17 open PRs) — zero hot-file contention.

Verification evidence

  • Focused: 11/11 on branch; A/B 3-fail-on-master confirmed (above)
  • npm run typecheck ✅ · npm run build ✅
  • Full npm test on PR head in this sandbox: 2562 tests, 2552 pass, 0 fail, 10 skipped (~95 s) — the dsh-native stall you reported did not reproduce here
  • CI on head 280af507: all green — e2e, hermetic registry e2e, real-codex lane, real-pi native lane, codex CODEX_HOME overlay, test ubuntu 22/24 + windows 22/24, version-guard, build-artifact (includes the request-pipeline e2e suite required for src/loop/** changes)

中文摘要:修复了 OpenAI 流式适配中 finish_reason 与 tool_call 参数同帧到达时 proxy 工具(compress)参数被丢弃、导致 missing-content 并提前终止整轮的 bug——根因是 settle 先于同帧片段吸收执行,改为先吸收后 settle(settle 总见完整状态),真实工具的线上输出经测试验证逐字节不变;新增 3 个回归测试在 master 上精确复现失败、修复后全绿,CI(含 e2e)全过,可以合并。

@ranxianglei
ranxianglei merged commit 2b75eb6 into master Sep 25, 2026
11 checks passed
@ranxianglei
ranxianglei deleted the 2026-09-25_openai-sameframe-toolcall-args branch October 15, 2026 05:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant