Skip to content

feat(server): auto-truncate oversized history on /v1/chat/completions and /v1/messages - #10

Open
ihsieh31 wants to merge 1 commit into
2951461586:mainfrom
ihsieh31:feat/auto-truncate-chat-and-messages
Open

ihsieh31 wants to merge 1 commit into
2951461586:mainfrom
ihsieh31:feat/auto-truncate-chat-and-messages

Conversation

@ihsieh31

Copy link
Copy Markdown
Contributor

Problem

Upstream DeepAI silently truncates the beginning of oversized request bodies (issue #7: ~196 KB body limit, usage.prompt_tokens pegs near 40k). The /v1/responses endpoint already handles this correctly via previous_response_id replay + truncation: "auto". But the two stateless endpoints — /v1/chat/completions and /v1/messages — forwarded payloads unchanged, so long conversations quietly "forgot" their earliest turns.

What this does

New respstate.EnforceLimits — pulls the dual-gate (token + byte) truncation logic out of Replay into a standalone, reusable function:

  • Returns (items, OK) when within budget
  • Returns (items, TooLong, msg) when over budget and auto-truncation is off
  • Returns (truncated items, OK) when over budget and auto-truncation is on
  • Returns (items, TooLong, msg) when even after truncation it still overflows

Wire it into both stateless endpoints: chat.go and anthropic.go call EnforceLimits on the (already chat-shaped) messages array before forwarding. The semantics are identical to /v1/responses:

  • Keep system prefix + first user message + newest tail
  • Insert the same (中間的對話歷史因超過上下文長度已由網關自動省略) marker at the cut
  • dropOrphanToolOutputs cleans up split function_call / function_call_output pairs

Defaults

Auto-truncation is ON by default — silent upstream truncation is strictly worse than a marked mid-cut, and existing clients (Claude Code, Continue, etc.) get memory-loss protection with no changes needed.

Clients that prefer strict behavior can opt out per-request:

{ "model": "...", "messages": [...], "truncation": "disabled" }

which surfaces a 400 with the exact overflow numbers (mirroring the existing truncation: "auto" opt-in on /v1/responses).

Compatibility

  • /v1/responses flow unchanged — Replay still owns its own logic; EnforceLimits reuses the same helpers (truncateHistoryByCosts, historyTruncMarker, EffectiveContextWindow, ContextBodyBytes)
  • No new env vars; honors DEEPAI2API_CONTEXT_BODY_BYTES, DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW, DEEPAI2API_CONTEXT_WINDOWS overrides
  • Marker text identical to the one Replay uses

Tests

  • 5 new unit tests in internal/respstate/enforce_test.go:
    • under-budget passthrough
    • strict TooLong when allowAuto=false
    • auto-truncate path produces marker + preserves head/tail
    • byte-cap-only mode (token gate disabled)
    • max_output_tokens reserve edge case
  • go test ./... — all 23 packages pass
  • go vet ./... — clean
  • End-to-end: 250 KB body against claude-haiku-5-5 returns HTTP 200 with the codeword correctly recalled (vs. silent memory loss before); "truncation": "disabled" returns 400 as expected

Files

  • internal/respstate/enforce.go — new
  • internal/respstate/enforce_test.go — new
  • internal/server/chat.go — add EnforceLimits call before marshal
  • internal/server/anthropic.go — same, after AnthropicToChatPayload

🤖 Generated with Claude Code

… and /v1/messages

Problem
-------
The upstream DeepAI gateway silently truncates the *beginning* of oversized
request bodies (issue 2951461586#7). On /v1/responses we already handle this via the
previous_response_id replay path with explicit truncation:"auto". But the
two stateless endpoints — /v1/chat/completions and /v1/messages — forwarded
requests unchanged, so a long conversation silently "forgot" its early turns.

What this does
--------------
- New respstate.EnforceLimits: a standalone function that applies the same
  token + byte dual-gate logic Replay uses, but takes a flat item list. It
  returns the original items, the truncated items, or TooLong + reason.
- /v1/chat/completions and /v1/messages now run EnforceLimits on their
  (already chat-shaped) messages array before forwarding. The truncation
  semantics match /v1/responses: keep system prefix + first user msg +
  newest tail, insert a 「中間的對話歷史因超過上下文長度已由網關自動省略」
  marker at the cut, and drop orphan tool outputs via the same helper.

Defaults
--------
Auto-truncation is ON by default — silent upstream truncation is strictly
worse than a marked mid-cut. Clients that want strict behavior can send
  "truncation": "disabled"
which surfaces a 400 with the exact overflow numbers (mirroring the
existing truncation:"auto" opt-in on /v1/responses).

Compatibility
-------------
- /v1/responses flow unchanged; Replay still owns its own logic.
- The marker text is identical to the one Replay uses.
- No new env vars; honors the existing DEEPAI2API_CONTEXT_BODY_BYTES and
  DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW / DEEPAI2API_CONTEXT_WINDOWS
  overrides via EffectiveContextWindow + ContextBodyBytes.

Tests
-----
- 5 new unit tests in respstate/enforce_test.go cover: under-budget
  passthrough, strict TooLong, auto-truncate path, byte-cap-only mode,
  and the output-reserve edge case.
- go test ./... — all packages pass.
- End-to-end: 250 KB body against claude-haiku-5-5 returns HTTP 200 with
  the codeword still recalled; "disabled" returns 400 as expected.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@ihsieh31
ihsieh31 force-pushed the feat/auto-truncate-chat-and-messages branch from 1897122 to 84464c5 Compare November 30, 2026 14:06

@2951461586 2951461586 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

必改 4 项,改完后合入。分支已拉下来实测:go build / go vet / gofmt -l 干净,22 包 go test ./... 全绿,覆盖率门禁 respstate 86.6% / server 79.3% 通过。方向认同,问题在工具配对。

P1 ① chat 形状:裁完会留下孤立的 role:"tool"

dropOrphanToolOutputs 只识别 Responses 的 function_call / function_call_output,不识别 chat 的 role:"tool"。裁剪点落在 assistant(tool_calls) 与 tool 之间时,输出变成:

[system user MARKER tool assistant user]

marker 是 user 角色,紧跟一条 tool → OpenAI 兼容上游必然 400(messages with role 'tool' must be a response to a preceding message with 'tool_calls')。

复现:EnforceLimits(items, "m", 320000, "", nil, 0, true),扫 DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW 150–500,15 个窗口值命中。

P1 ② Anthropic 形状:tool_result 失去 tool_use

[user MARKER user:tool_result assistant user]

tool_result 块保留、配对的 tool_use 被裁掉 → Anthropic 侧 400。11 个窗口值命中。

①② 的修法:让 dropOrphanToolOutputs 同时识别 role:"tool"(chat)与 content 数组里的 tool_use / tool_result(Anthropic),或者让裁剪点避开工具对边界。这两条正好是 PR 描述里声称已覆盖的场景("dropOrphanToolOutputs cleans up split function_call / function_call_output pairs"),不能留到后续。

P2 ③ truncation 被转发到上游

chat.go / anthropic.go 判完 allowAuto 后没把它从 payload 里删掉,紧接着 json.Marshal(payload) 直接发上游。客户端按文档写 "truncation":"disabled" 就会把这个上游不认识的字段带出去(400 This request cannot be accepted 的风险)。Marshal 前删掉即可,或者改成走请求头。

P2 ④ 默认值与已写死的契约冲突

README.md 第十节写的是「/v1/chat/completions 与 /v1/messages 保持透明代理,超限只记日志」,本 PR 把默认改成自动截断却没改文档。方向可以接受(静默砍头确实更糟),请同批更新 README.md / README.en.md / docs/changes.md。

顺带

  • msgs, _ := payload["messages"].([]any) 吞掉类型断言失败;失败时会把 messages 写成 null 发上游;
  • Anthropic 顶层 system 没计入固定开销(instructions=""),tooLongMessage 里的 token 数会偏低,只影响错误信息准不准;
  • 建议补两个 handler 级测试:超限 400 路径、truncation:"disabled" 退出路径——目前 5 个单测只覆盖了纯函数。

已核对,不是问题

  • sessionAffinity 的 prefixDigest 只看 model + system + tools,截断不会造成会话粘性漂移;
  • perModelContextWindow 里没有 40k 条目(40k 是字节闸的表现),max_tokens 预扣不会造成过度截断。

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.

2 participants