Skip to content

fix: strip model-emitted bili internal artifacts from output streams (#1634) - #1649

Merged
ranxianglei merged 1 commit into
masterfrom
2026-09-29_bili-artifact-output-strip
Sep 29, 2026
Merged

ranxianglei merged 1 commit into
masterfrom
2026-09-29_bili-artifact-output-strip

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Fixes #1634

Problem

Long sessions stall because the model's answer consists of compression metadata instead of a reply to the user. Three artifact families that the proxy itself injects into model-visible payloads get restated verbatim by models under sustained context pressure:

  1. <bili-chain v="1" processor="…" …/> checkpoint carrier (outbound stamping, src/chain-checkpoint.ts)
  2. [bili] context summary after compaction: handoff user message (src/codex-compact.ts, responses wire)
  3. [Compressed conversation section] — topic forged-summary blocks (src/codex-compact.ts, re-injected into the developer message every turn)

plus a fourth observed shape: model prose imitating the summary structure.

The existing output sanitizer (src/loop/tag-echo-filter.ts) only knew ACP render tags (<acp tokens="…" type="…">mNNNNN</acp>) and [ACP] marker lines, so all of these shapes passed through verbatim into the client transcript → the next turn answered the metadata instead of the user → stall.

Fix

New third streaming filter stage createBiliArtifactFilter plus whole-text support folded into stripAcpTags, composed into every wire's filter stack (openai/anthropic/responses/google adapters, plugin pipes incl. the reasoning-summary arg stream) and guarded at every hadEcho/rewrite site:

Degenerate-turn retry integration preserved (load-bearing per the issue thread): a fully-forged turn yields zero visible text and fires the existing one-time continuation nudge.

Debug observability (issue fix 5): [stamp] debug log at the outbound chain-stamping site, [inject] debug logs at the ephemeral-nudge / image-note / forged-summary developer re-injection sites. ACP_DUMP_REQ remains the byte-level forensic.

Behavior change (flagged)

Model output only, all wires: the four shapes above previously passed through to the client verbatim; they are now stripped. Request-side payloads are unchanged. No config-surface change (N/A — no new fields, env vars, or CLI flags; no config schema or persistence-format touch).

Verification (rebased head on master = v0.1.171)

  • npm run typecheck clean; full suite 3205 tests / 3189 pass / 0 fail / 16 skip; npm run build clean
  • New regression suite tests/bili-artifact-strip.test.ts (15 tests): whole-text well-formedness matrix (full strip / missing-digest keep / attr-reorder strip / truncated keep), escaped form, header blocks (position 0 / after \n / mid-line mention kept), streaming splits across every boundary class, over-cap release, pure-prose byte-exact passthrough, shared-constants pin, passthrough-pin (request-side stamped carriers survive untouched), degenerate-retry parity (fully-forged turn → zero visible text → retry gate fires)
  • Known pre-existing flake (unrelated, on both trees): tests/fix-437-idle-timeout.test.ts fails under high machine load (it drives fetchWithTimeout directly against a raw HTTP server; no code path my diff touches) and passes consistently when idle.

一句话:修复了压缩元数据(链检查点标签、伪造摘要头)泄漏进模型输出导致长会话卡死的问题——全部 wire 输出侧新增统一的内部产物剥离层(流式+非流式),注入侧与请求侧载体保持不变。

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-29_bili-artifact-output-strip (fc00bf6)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.1597-pr.1649.b0d1a1f

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Option B — Download artifact

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

Install instructions are refreshed on each push.

…1634)

The proxy injects three artifact families into model-visible payloads
(outbound checkpoint carriers, forged-compaction handoff user messages,
captured summary blocks). Under sustained context pressure models restate
these verbatim as their answer; the existing sanitizer only knew ACP render
tags and [ACP] marker lines, so all four observed shapes passed through to
the client transcript and the next turn answered metadata instead of the
user (long sessions stall).

Adds a third streaming filter stage (createBiliArtifactFilter) plus whole-
text support folded into stripAcpTags, composed into every wire's filter
stack and guarded at every hadEcho/rewrite site:
- well-formed <bili-chain .../> spans (validated by the frozen parser,
  literal or \u003c-escaped form) are stripped anywhere in prose;
- line-start '[bili] context summary after compaction:' and
  '[Compressed conversation section]' blocks are cut to end of field;
- unterminated/over-cap openings release as prose byte-exact (#1039/#644);
- request-side stamped carriers are untouched; #1542 inbound backstop
  unchanged.

Behavior change (model output only): the four shapes above are now
stripped on all wires where they previously passed through verbatim.
Degenerate-turn retry integration preserved: a fully-forged turn yields
zero visible text and fires the existing one-time continuation nudge.

Debug observability: [stamp]/[inject] debug logs at every outbound
append site (chain stamping, ephemeral nudge, image note, forged-summary
developer re-injection). ACP_DUMP_REQ remains the byte-level forensic.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,开始 review。当前状态:head fc00bf6 CI 全绿(test/ubuntu+windows 22/24、e2e、hermetic registry、各 native lane、build-artifact、version-guard)。正在本地拉分支做代码级审查(方向核对 #1634、回归清点、代码与测试有效性、diff 整洁度),结论稍后补。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR Review — fix: strip model-emitted bili internal artifacts from output streams (fixes #1634)

Reviewed at head fc00bf6 (rebased on master v0.1.171). CI: all 13 checks green (test ubuntu/windows × node 22/24, e2e, real-client native lanes opencode/pi/dsh/codex vs zero-token fake upstreams, hermetic registry, build-artifact, version-guard). Local re-run on the head: new suite 16/16 pass, npm run typecheck clean, npm run build clean (dist-import-annotations OK).

① Direction (原 issue): root-cause layering is correct — bili injects internal bookkeeping into model-visible payloads, and under sustained pressure models restate it verbatim; the client history then perpetuates the stall loop. Fixing at the output side is the right layer: the injection side (stamped carriers, compaction handoff, forged-summary re-injection) must stay visible to the model for compression to work, and the request side must keep carrying checkpoints. Scope matches exactly what was settled in the #1634 thread (well-formed-only strip, header-block-to-end-of-field, mid-line mentions untouched, no config surface).

② Regression audit — existing behaviors on touched paths, item by item:

  1. Render-tag echo strip (偶尔重复输出 <acp tokens="177" type="text">m00155</acp> #206/[bug] #644 follow-up (post-#646, v0.1.97): typo'd render-tag echo (<acip …) bypasses the strip regex and passes through as a 43-char degenerate end_turn turn — agent stalls mid-orchestration until manual nudge #673) — createTagEchoFilter untouched, still first stage in every stack. Preserved.
  2. Marker-line strip (模型把 "📦 [ACP] Compressed" 确认标记伪造为普通 assistant 文本——17 次假压缩、0 次真实执行(自我回执幻觉) #717) — untouched, second stage. Preserved.
  3. Tool-call args byte-exact ([bug] 插件透传会剥掉工具调用参数里的 render tag(arguments 流挂了 tag-echo 过滤器) #1039) — verified at every site: plugin pipe argStreams only ever receives response.reasoning_summary_text.delta (src/plugin.ts:2410), function_call argument deltas fall through to the raw write; stripResponsesText/stripOpenaiChatText/stripAnthropicText/stripGoogleChunk all explicitly exclude .arguments. Preserved.
  4. Request-side stamped carriers + plugin-mode sessions: #1421 outbound chain stamps accumulate in the model-visible transcript (+1 user message per request) #1542 inbound backstop — enumerated every stripAcpTags caller (stream.ts, stream-openai.ts, stream-responses.ts, stream-google.ts, plugin.ts ×3, compress-loop-responses.ts:144, tag-echo-filter internals): all are model-output paths. replaceBiliCompactionItems changed only by constant extraction (byte-identical string). Request payloads untouched. Preserved.
  5. Degenerate-turn retry (load-bearing per Compression metadata reaches the transcript and the model answers it instead of the user (long sessions stall) #1634) — fully-forged turn → zero visible chars → existing one-time continuation nudge fires; pinned by the parity test. Preserved.
  6. Codex handoff/forged-summary wire bytes — literals replaced by exported constants, strings identical. No drift.
  7. Over-cap-release semantics ([bug] #361 residual, form 3: turn whose entire text is a render-tag echo strips to an EMPTY message — agent records a marker-only turn, stalls until manual nudge (v0.1.92, post-#365) #644 boundary) — unterminated openings held ≤640 chars then released byte-exact; over-cap released immediately. Same contract as the render-tag filter. Consistent.
  8. server.ts delta is debug-logging only ([stamp] at outbound stamping, [inject] ×4 at nudge/image-note/forged-summary re-injection) — zero behavior change. Preserved.

Regressions found: none (0).

③ Code: clean design — one shared module, stripper keys off the same constants its injectors emit (byte-match by construction), frozen parser parseChainCheckpoint as the well-formedness oracle, and the streaming filter and whole-text path share the same primitives (nextChainSpan/headBlockCut). Verified composeStreamFilters flush propagation through the nested triple composition (an upstream-held partial header tail pushed into the bili stage at flush correctly triggers swallow-and-drop). Fast-path mayStartBiliInternal pre-check keeps clean chunks regex-free; prefix-tail holds cover every chunk-boundary split (tested char-by-char).

One known limitation (non-blocking, probed and confirmed): left-to-right scanning means a closed-but-invalid chain opener (e.g. missing digest) shields any well-formed span that follows it in the same text/buffer — the good one leaks once. This is the conservative side of the agreed 宁漏剥不误伤 policy (real-world likelihood low: model would have to emit both an invalid and a valid carrier in one turn). Optional hardening if you care: when a terminator IS found but parsing fails, it's safe to resume scanning after that terminator (the span is bounded) — unterminated openers can't be skipped safely, which the 640-char cap already bounds. Happy to take that as a tiny follow-up if you want it pinned; otherwise leave as-is. Minor nit: PR body says 15 tests, the file has 16 test() blocks — cosmetic only.

④ Tests: high-quality, teeth everywhere — exact-equality assertions, deliberate false-positive traps ([Compressed data export done, [Code review notes]), a shared-constants pin that fails if injector and stripper ever drift apart, a directionality pin proving request-side stamped carriers survive byte-exact, streaming split matrices across every boundary class, and the degenerate-retry parity pin. Would catch a regression of each shape individually. Native-lane e2e covers the adapter integration end-to-end.

⑤ Diff: single linear commit, +526/−60 over 14 files, every line serves the stated purpose (filter module, composition sites, hadEcho/rewrite gates, debug logs, constant exports, tests). No whitespace churn, no unrelated files. Clean.

Flagged behavior change (as disclosed in the PR body, confirmed accurate): model output on all wires — well-formed <bili-chain …/> spans anywhere in prose (literal or \u003c-escaped), line-start [bili] context summary after compaction: blocks, and line-start [Compressed conversation section] blocks — previously passed through to the client verbatim; now stripped (plus their escaped forms). Request-side payloads unchanged. New observability: [bili-artifact] warn lines on strip, [stamp]/[inject] debug lines. No config-surface change.

Verdict: mergeable. ✅

一句话:修复了模型在长会话压力下把 bili 内部压缩元数据(链检查点标签、伪造摘要头块)原样复读进输出导致会话卡死的问题——全 wire 输出侧新增统一的内部产物剥离层(流式+非流式,与注入侧共享常量保证字节级一致),请求侧载体、工具参数逐字节保真、degenerate-retry 集成均验证无回归,测试有牙、diff 干净,可以合并。

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.

Compression metadata reaches the transcript and the model answers it instead of the user (long sessions stall)

1 participant