Skip to content

feat: detect + retry fake completions (tool call written as text, #371) - #378

Merged
ranxianglei merged 3 commits into
masterfrom
2026-08-31_fake-completion-retry
Sep 2, 2026
Merged

ranxianglei merged 3 commits into
masterfrom
2026-08-31_fake-completion-retry

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

Fixes the "fake completion" from #371 (root-cause follow-up to #361): a small model (e.g. MiniMax-M3 via a gateway) can WRITE a tool call as plain text — echoing the tool-call XML template from the context — instead of emitting a real tool block. With no tool block the agent ends the turn early and shows success, but the tool never ran.

This adds a proxy-side detect + retry fallback:

  • Detect: a response carrying a complete tool-call structure (an opening <invoke>-style tag, or 2+ distinct closing tags like </invoke> + </tool_calls>) AND no real tool block for the wire protocol (Anthropic tool_use / OpenAI tool_calls / Responses function_call). Reuses PR fix: warn on tool-call XML fragments + close-side truncated acp echo (#361) #365's containsToolCallXmlFragment detector; the structural guard (opening tag OR 2+ distinct closers) avoids false-positives on legit prose that merely mentions a single closing tag.
  • Retry: re-request upstream with a corrective hint appended as a trailing user message ("you wrote the tool call as text; use the real tool-calling mechanism"). Bounded per turn (max retries) and per session (session.metadata.fakeCompletionStreak — consecutive fake-completion turns; resets on a clean turn).

Opt-in (disabled by default)

The fallback must buffer the whole response before the client sees it (a fake completion is only knowable at end-of-stream), which defeats incremental streaming. That cost is only worth paying for the low-frequency fake-completion case, so it is opt-in:

This matches the issue's "先收集数据…确认频率后再决定是否上重试(避免为低频问题加复杂逻辑)" guidance: detection is already observable (PR #365's warn), and the retry can be turned on for the models/scenarios where it is confirmed to help.

Trade-off (documented)

When enabled, streaming responses are buffered before being sent to the client (the client waits for the complete response before seeing tokens). This is the price of being able to retry before the client sees a fake completion.

Tests

tests/fake-completion.test.ts (21 tests):

  • Detection per protocol (anthropic/openai/responses): tool-XML + no tool block → fake; tool-XML + tool block → not fake.
  • hasToolCallStructure: opening tag / 2+ distinct closers → structure; single closer (legit prose) → not.
  • injectFakeCompletionHint per protocol (merge into last user msg / append).
  • Integration (full proxy vs scripted mock upstream):
    • fake → retry → real tool_use reaches the client (fake text discarded).
    • retry cap: always-fake upstream → 3 requests turn 1, 6 turn 2, 7 turn 3 (streak cap blocks the retry).
    • legit prose (single closing tag) → NO retry.

Pre-flight

  • npm run typecheck — green
  • npm test — 883 passing (all green)
  • npm run build — green

Rebased onto latest master (v0.1.66).

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-08-31_fake-completion-retry (892ffa2)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-378

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

Option B — Download artifact

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

This comment is automatically updated on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · vllm-qwen/qwen3.8-27b

[bot] Picked up #378. Reviewing the 2026-08-31_fake-completion-retry branch now: checking out the diff, re-running the pre-flight (typecheck / test / build), and reviewing the detect+retry logic for correctness. Will report findings here.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · vllm-qwen/qwen3.8-27b

[bot] Review complete — LGTM, no blocking issues. Reviewed the diff on 2026-08-31_fake-completion-retry (commit 5cccaa7, 3 files) and re-ran the pre-flight myself.

Pre-flight (re-run on the branch, all match your claims):

  • npm run typecheck — green
  • npm test — 883 pass / 0 fail
  • npm run build — green (dist/index.js 2.56 MB)
  • tests/fake-completion.test.ts — 21/21 pass

What I verified in the code:

  • Retry invariant holds: the retry re-sends exactly what the original request sent — same prepared.body (the body the original fetch uses at src/server.ts:2256), same upstreamUrl, same proxyDispatcher, same clientAbort.signal, same 10-min default timeout. Headers are rebuilt via buildForwardHeaders, which strips the stale host/content-length before the hinted body (different length) — correct.
  • Placement is right: the buffer+retry sits after the !upstream.ok early return (src/server.ts:2408), the empty-body return (2418), and the plugin-mode verbatim return (2435) — so it only touches 2xx, non-plugin, client-streaming responses, exactly as documented.
  • Detection logic checks out against the real gate: containsToolCallXmlFragment (src/loop/tag-echo-filter.ts:64) passes both opening and closing tags, so the structural guard (opening tag OR 2+ distinct closers) is precisely the narrowing that excludes legit single-closer prose. The hasToolBlock regexes match the actual wire shapes (Anthropic content_block_start "type":"tool_use", OpenAI first tool_calls delta, Responses function_call item).
  • Streak semantics match the tests (max=2 → 3/6/7 requests across turns 1–3); the read-modify-write of session.metadata.fakeCompletionStreak is serialized under withSessionLock (src/server.ts:1158) and persisted via markDirty.
  • Hint injection handles all three protocols, string/array content shapes, and Anthropic's user/assistant alternation (merge into last user msg vs. append after assistant).
  • Code quality per AGENTS.md: no as any/@ts-ignore, hex-escaped XML, opts.log (no console.error).

Minor findings (report-only, non-blocking):

  1. Silent truncation when a response exceeds BILI_FAKE_BUF_CAP (default 16 MiB) — confirmed by repro: readStreamToBuffer (src/server.ts:2623) does not throw on overflow; it retains the first maxBytes and drains the rest. With the feature enabled, an 8810-byte SSE response under a 1024-byte cap reached the client as exactly 1024 bytes, cut mid-event with no message_stop. At the default 16 MiB cap this needs a >100K-token-class response (SSE overhead ≈ 100 B/token), so it's rare — but it's a new failure mode introduced by the buffering (pre-PR the success path streamed directly), and it fails silently (corrupted stream) rather than loudly. Suggested fix: detect overflow and fail loudly (502) instead of serving truncated bytes, or raise the default cap well beyond any realistic LLM response.
  2. Non-streaming responses are out of scope: the prepared.stream gate (src/server.ts:2440) skips stream:false JSON responses. Buffering costs nothing there (the client already waits for the full body), so covering them would be nearly free. Small gap — agents stream by default.
  3. Retry fetch skips recordUpstreamConnection telemetry — the original fetch records it (src/server.ts:2270), the retry (src/server.ts:2683) doesn't, so retry traffic is invisible to connection-status telemetry.
  4. (Footnote) markDirty is called unconditionally even when the streak is unchanged (0→0) — an extra persist per streaming request when enabled; harmless since it's debounced.

E2E regression: per AGENTS.md, changes to the request pipeline (server.ts) should run tests/e2e/e2e-codex.test.ts before merge. I could not run it in this environment — no codex binary on PATH and the default upstream http://127.0.0.1:8199/v1 is unreachable (probe 000); the E2E_CHECK=1 preflight also needs the codex binary. Please run the 4-phase core locally (or via the manual-dispatch CI) before merging.

A small model (e.g. MiniMax-M3 via a gateway) can write a tool call as plain
text - echoing the tool-call XML template from the context - instead of
emitting a real tool block. With no tool block the agent ends the turn early
and shows success, but the tool never ran (the "fake completion" from #371,
root-cause follow-up to #361).

Add a proxy-side detect + retry fallback:
- Detect: a response carrying a complete tool-call structure (an opening
  invoke-style tag, or 2+ distinct closing tags) AND no real tool block for
  the wire protocol (Anthropic tool_use / OpenAI tool_calls / Responses
  function_call). Reuses PR #365's containsToolCallXmlFragment detector; the
  structural guard avoids false-positives on legit prose that merely mentions
  a single closing tag.
- Retry: re-request upstream with a corrective hint appended as a trailing
  user message. Bounded per turn (max retries) and per session
  (session.metadata.fakeCompletionStreak, resets on a clean turn).

Opt-in (disabled by default): the fallback must buffer the whole response
before the client sees it (a fake completion is only knowable at end-of-stream),
which defeats incremental streaming. That cost is only worth paying for the
low-frequency case, so it is opt-in via BILI_FAKE_COMPLETION_RETRIES (default
0 = pre-#371 passthrough).

Tests: tests/fake-completion.test.ts (21) - detection per protocol, the
structure guard, hint injection per protocol, and full-proxy integration
(fake -> retry -> real tool_use; retry cap via streak; legit prose no-retry).
@ranxianglei
ranxianglei force-pushed the 2026-08-31_fake-completion-retry branch from 5cccaa7 to 0dde055 Compare September 2, 2026 17:18
…letion resolution

Merging #378 with post-#466 master left the #460 strip branch reading
upstream.body, which resolveFakeCompletion has already consumed when
BILI_FAKE_COMPLETION_RETRIES > 0 — the client would hang on an empty
response. Read responseBody instead (identical to upstream.body when
retries are disabled).
@ranxianglei

Copy link
Copy Markdown
Owner Author

Pushed to this branch (merge master + one fix), same drill as #464:

  1. Merged post-fix(#460): strip render-tag echoes from non-injected proxy-mode chat SSE #466 master in — textual auto-merge was clean, but semantically broken: the proxy 模式 SSE 出站不 strip 模型 emit 的渲染标签(openai/anthropic wire)— #457 分析发现的同类遗漏 #460 non-inject SSE strip branch (forward()) read upstream.body directly, which resolveFakeCompletion has already consumed when BILI_FAKE_COMPLETION_RETRIES > 0 — that path would hand the client an exhausted stream (empty response / hang).
  2. Fixed in 892ffa2: the strip branch now reads responseBody (the buffered stream), identical to upstream.body when retries are disabled — zero behavior change at default 0.

Verified on the merged tree:

One design gap noted for follow-up (not blocking this PR): the fake-completion gate sits after the plugin-mode early return in forward(), so plugin-mode streams (omp/pi — the original reporters of #361/#371) are not covered. Tracking issue to follow.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · qwen3.8-27b

[bot] Verifying the new push (master merge + 892ffa2): checking out the branch, reviewing the strip-branch fix, and re-running the pre-flight (typecheck / targeted tests / full suite) plus confirming the 3 suite failures are pre-existing on master HEAD. Will report here.

@ranxianglei
ranxianglei merged commit 67285ae into master Sep 2, 2026
6 checks passed
@ranxianglei ranxianglei mentioned this pull request Sep 2, 2026
ranxianglei added a commit that referenced this pull request Sep 3, 2026
…tream.body

With BILI_FAKE_COMPLETION_RETRIES>0 and a streaming request, the #378
buffering block consumes upstream.body before the ladder. The new G3
application/json branch piped upstream.body — a drained stream — so the
client received an empty body. Read responseBody instead, matching the
SSE strip branch and the bare pipeThrough fallback.

Includes a red-then-green regression test driving the real proxy harness
(fake-completion enabled + stream:true + JSON answer).
@ranxianglei
ranxianglei deleted the 2026-08-31_fake-completion-retry 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

Development

Successfully merging this pull request may close these issues.

1 participant