Skip to content

[PR] fix: filter long message histories without argument overflow - #6670

Merged
ranxianglei merged 1 commit into
ranxianglei:masterfrom
Afloat16:2026-11-14_bounded-history-filter
Nov 14, 2026
Merged

ranxianglei merged 1 commit into
ranxianglei:masterfrom
Afloat16:2026-11-14_bounded-history-filter

Conversation

@Afloat16

Copy link
Copy Markdown
Contributor

Closes #6669

Problem

Long histories are expanded into function arguments when filtering generated OpenCode reports or removing a failed compress round's temporary frames. With 250,000 retained messages, both splice(...history) sites throw RangeError before the normal hook or recovery request can complete.

Changes

Compact retained entries into the existing arrays, then truncate their tails. This avoids the argument-count ceiling and the temporary filtered array while keeping insertion order, object identity, sparse-array filtering behavior and the current filtering predicates. The same patch covers the OpenCode V2 context/compaction/title/generate hooks and the proxy loop's failed-compress recovery path.

The existing predicates and recovery receipt bytes are unchanged. Both native plugin hooks and proxy mode retain their current protocol behavior. No configuration, persistence, kernel or dependency changes.

Validation

  • All five new regressions fail on unchanged master 1ff89e878522f3e4d4147067973e2dc26e648923 with RangeError at the affected production splice call.
  • All 45 tests pass in opencode-v2.test.ts and issue5220-failed-compress-receipt.test.ts. The new hook cases verify stable order and array/object identities across 250,000 retained messages; the real compression loop reaches one recovery re-request, strips its failed tool frames, retains the history and receipt, and forwards the model's natural completion.
  • Another 17 related tests pass across issue4812-armed-breaker-short-receipt, issue2360-compress-receipt, issue847-compress-failure-guards and fix-1124-compress-receipt.
  • Full npm run typecheck, npm run build and git diff --check: pass.
  • Local checks use the production plugin registration and compression loop with controlled host/HTTP fixtures. The real OpenCode binary E2E and the full hosted matrix were not run locally.

@ranxianglei ranxianglei changed the title fix: filter long message histories without argument overflow [PR] fix: filter long message histories without argument overflow Nov 14, 2026
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(bot: opencode/qwen3.8-27b)

查重: 不重复 — searched open+closed issues/PRs for "splice RangeError", "argument overflow", "long history filter", "Maximum call stack" — no prior fix for this mechanism.

Review: PR #6670 — filter long message histories without argument overflow

The PR's 2-site fix: correct and well-tested ✅

The diagnosis is right: arr.splice(0, arr.length, ...kept) spreads the entire filtered array into splice's variadic args. V8's call-argument ceiling (~65K) is exceeded at 250K retained messages → RangeError: Maximum call stack size exceeded. I reproduced this empirically on the merge base (1ff89e8): a 250K-element splice throws; the in-place compaction pattern the PR introduces does not.

The replacement (forEach + kept++ + arr.length = kept) is the right shape:

  • Preserves insertion order, object identity, and sparse-hole semantics (both forEach and filter skip holes).
  • Mutates the same array reference (no temp array) — the PR's tests assert strictEqual(event.messages, messages) and first/last object identity, which is the correct invariant.
  • The predicate is logically equivalent (De Morgan of the drop condition).

Both affected sites are covered:

  • src/agent/opencode-v2.ts:574 — the V2 context/compaction/title/generate hook filter.
  • src/loop/core.ts:1753 — the failed-compress recovery path (operates on a copy, so the original ctx.messages is untouched — verified by the test asserting messages.length === 250_000).

The 5 new regression tests are real: all 5 fail on unpatched master with RangeError at the exact production call, and pass on the PR head. 45/45 targeted tests green; typecheck + build clean. CI on the PR head is fully green (30 checks, 0 failed).

Finding: 3 more sites with the same mechanism, not covered by this PR ⚠️

The same spread-argument overflow lives in three push(...history) rewrites in src/loop/core.ts, all operating on the full ~250K coreMessages array:

Line (PR head) Path Trigger
core.ts:1639-1640 coreMessages.push(...hidden.messages) hide-consumed-compress-calls rewrite (!textProtocol && !anyCompressFailed && hidden.hidden > 0)
core.ts:1659-1660 coreMessages.push(...refreshed) post-compress fold refresh (ctx.refreshFolded returns a non-empty view)
core.ts:1846-1847 coreMessages.push(...stripped) degraded-retry thinking strip (re-request rejected → retry without thinking)

I verified a.push(...src) at 250K throws the identical RangeError. So a 250K session that takes a successful compress (fold-refresh path) or a degraded retry (thinking-strip path) still bricks after this PR's splice fix. Per 连贯修复不拆片 (one mechanism = one closed loop), these belong in this PR.

I've prepared the fix + a 250K regression test for the fold-refresh path (the other two share the identical one-line pattern). I don't have push access to the fork, so the patch is below for the author to apply:

diff --git a/src/loop/core.ts b/src/loop/core.ts
--- a/src/loop/core.ts
+++ b/src/loop/core.ts
@@ -1637,7 +1637,7 @@
                     if (hidden.hidden > 0) {
                         ctx.log(`[acp-loop] round ${round} hideConsumed hid ${hidden.hidden} compress record(s)`);
                         coreMessages.length = 0;
-                        coreMessages.push(...hidden.messages);
+                        for (const m of hidden.messages) coreMessages.push(m);
                     }
                 }
                 // #422: a successful compress changed the session state — refresh
@@ -1657,7 +1657,7 @@
                         const refreshed = await ctx.refreshFolded(coreMessages);
                         if (refreshed.length > 0) {
                             coreMessages.length = 0;
-                            coreMessages.push(...refreshed);
+                            for (const m of refreshed) coreMessages.push(m);
                             // The fold has now materialized in a request the
                             // model actually sees — the next usage report is
                             // post-fold reality; keeping the credit would net
@@ -1844,7 +1844,7 @@
                     degradedRetried = true;
                     const stripped = stripLoopThinking(coreMessages);
                     coreMessages.length = 0;
-                    coreMessages.push(...stripped);
+                    for (const m of stripped) coreMessages.push(m);
                     ctx.log(`[acp-loop] round ${round}: re-request rejected (${e.status}: ${e.body.slice(0, 200)}); retrying without replayed thinking blocks`);

Plus a 250K regression test in tests/issue5220-failed-compress-receipt.test.ts (successful compress → refreshFolded returns a 250K view → asserts the re-request reaches the client with head+tail intact). Verified: fails on unpatched master with RangeError, passes with the fix. Full patch (commit + test) is 37 insertions / 3 deletions across 2 files.

Scope note: I audited every other spread-arg site in src/ (persist.ts, dsh-ledger.ts, fold-reconcile.ts, diagnostics, CA pems, etc.) — they all operate on bounded data (lockfile lines, single fold-block ids, diagnostic lines), not 250K message histories. Out of scope for this PR.


结构化八问

  1. 是什么问题:长会话(>65K 条消息)在过滤/重写历史时,splice(0, len, ...arr) 和 push(...arr) 把整个数组展开成函数参数,超出 V8 调用参数上限(~65K),抛 RangeError: Maximum call stack size exceeded,会话直接卡死。
  2. 什么原因导致的:V8 引擎对函数调用参数数量有硬性上限(约 65K)。arr.splice(0, arr.length, ...kept) 和 arr.push(...src) 把整个过滤后/重写后的数组(250K 元素)展开为变长参数,触发上限。根因是「用 spread 传整个数组」这个写法本身,不是某个特定过滤条件。
  3. 影响范围与严重程度:任何保留消息数 >65K 的会话,一旦走到以下任一路径即触发:OpenCode V2 的 context/compaction/title/generate hook 过滤、失败压缩恢复、成功压缩后的 fold 刷新、hide-consumed 重写、降级重试 thinking 剥离。严重程度 p1——会话完全不可用(RangeError 中断请求循环)。
  4. 怎么修复的:PR 对两个 splice 站点用原地紧凑(forEach + kept++ + arr.length = kept)替代 spread-splice;我补充的三个 push 站点用逐元素拷贝(for (const m of X) arr.push(m))替代 spread-push。两种写法都不产生临时数组、不改变插入顺序/对象引用/稀疏孔语义。
  5. 是否有回归问题:无。过滤谓词逻辑等价(De Morgan);原地紧凑和逐元素拷贝都保持顺序、对象身份、稀疏孔行为。PR 的 5 个新回归测试 + 我补的 1 个共 6 个,全部在未打补丁的 master 上以 RangeError 失败、在修复后通过。既有 45 个定向测试全绿;typecheck + build 干净;CI 30 项检查 0 失败。
  6. 是否破坏缓存:不涉及。修复只改数组重写方式,不触碰缓存、重试、去重、增量游标等任何失效策略。
  7. 是否改了设计方向:不涉及。过滤谓词、协议行为、恢复收据字节均不变;plugin/proxy 两种压缩模式的协议行为保持原样。纯机械修复,无架构/边界/数据流转向。
  8. 是否引入了新的配置:不涉及。无新 env、config、默认值。

判定

PR 的两个 splice 站点修复正确、测试充分、CI 全绿,可合。但同一机制还有三个 push 站点未覆盖(fold 刷新 / hide-consumed / thinking 剥离),250K 会话在成功压缩或降级重试路径上仍会卡死。建议作者将上述补丁并入本 PR(一个闭环),补上后整体可合。

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.

Long message histories overflow call arguments during report and recovery filtering

2 participants