Skip to content

fix(#325): floor meter at provider anchor minus tokens reclaimed since it - #328

Merged
ranxianglei merged 1 commit into
masterfrom
2026-09-08_post-compress-token-floor
Sep 26, 2026
Merged

ranxianglei merged 1 commit into
masterfrom
2026-09-08_post-compress-token-floor

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Sep 7, 2026 •

Copy link
Copy Markdown
Owner

Fixes #325.

Problem

After a successful compress, ACP's own token accounting dropped ~70–80K below the provider-reported prompt size, so the nudge meter flipped to idle. On the next turn the host-floor anchor (#257) snapped tokenCount back up to the real prompt size (~84–95% of the effective limit) and re-injected an EMERGENCY "compress now" nudge. The model compressed again → loop. The agent stopped working every few turns just to compress.

Root cause

src/index.ts sets tokenCount = estimateTokens(coreMessages, coveredIds, imageTokens) + systemPromptTokens, then floors it at the provider-reported prompt size — unless usageAnchorPredatesCompression() is true (a successful compress landed after the last valid assistant usage), in which case the floor was skipped entirely.

  • estimateTokens (src/tokens.ts) sums message text only. It structurally omits tool-definition schemas, ref-tag overhead, and the injected nudge — a fixed ~70–80K on this host. So the raw sent-view is always that far below the real request.
  • Pre-compression, the current-anchor floor lifted tokenCount to the provider number — which is why pre-compression estimates "matched the provider exactly."
  • Post-compression, the stale-anchor skip dropped tokenCount back to the undercounting raw estimate → false idle. Next turn, fresh provider usage re-engaged the floor at full real size → spurious EMERGENCY.

The #289 view-recount inherited the same blind spot because it compares against the post-processTurn view.

Fix

When the anchor predates a successful compress, floor at (lastProviderUsage − netReclaimedSinceAnchor) instead of skipping. netReclaimedSinceAnchor = Σ over active blocks whose creating compress toolResult lands after the last valid usage anchor of max(0, compressedTokens − summaryTokens).

The provider's real number already counts all fixed overhead (tool schemas, etc.) accurately; subtracting only the genuinely-freed tokens yields an exact post-compression size with no need to measure tool schemas — which are unmeasurable/unstable inside the extension (no API enumerates Pi's full tool set). This is why the issue's suggested direction ("add the fixed component to the estimate") was not taken: it would need an unstable magic constant.

New work added after the compress still grows tokenCount through sentTokens as before; the non-stale path is unchanged; a stale-anchor compress that reclaimed little still correctly trips the nudge.

Tests

  • tests/floor-stale.test.ts: unit tests for compressionAnchorStaleness (fresh / stale / pre-anchor exclusion / inactive+unattributable skip / negative-savings clamp / multi-block sum).
  • tests/sent-view-arbitration.test.ts: rewrote the stale test to seed a real reclaiming block (no false emergency), plus a guard test asserting a tiny-reclaim + near-limit context still fires.
  • Full suite: 472 tests, 469 pass, 0 fail (3 pre-existing skips). Typecheck + tsup build green.

Notes

  • No version bump (release-branch territory per AGENTS.md).

Rebase onto v0.1.74 (acp-kernel 0.0.81)

Rebased onto current master; the single commit is preserved. src/floor-stale.ts and tests/floor-stale.test.ts applied cleanly (unchanged upstream). Two regions had moved upstream and were merged by hand:

Meter integration

The provider floor is now continuous instead of a binary skip:

hostFloor = max(0, realPrompt − (predates ? netReclaimed : 0))

Fresh turns floor at the full provider number; stale turns floor at anchor − netReclaimed. It feeds the same applyFloors as the #455 calibration cap and the #289 view-recount, and the #455 calibration stays fresh-only (gated on !predates).

Growth-scale flip signal (#267)

The baseline re-anchor trigger changes from the binary stale flag to estScaleWins = hostFloor <= sentTokens — i.e. it fires when the effective ruler actually switches between estimate-dominated and provider-floor-dominated. Under the adjusted floor a stale turn can still floor near the full anchor (small reclaim); treating "stale ⇒ estimate scale" would spuriously reset the growth baseline. Keying off which value actually wins avoids that while still catching genuine switches.

Test adaptations forced by the new base

Verification on the rebased head

tsc --noEmit ✅ · tsup build ✅ (acp-kernel inlined, zero runtime deps). All three affected test files pass locally (floor-stale 14, sent-view-arbitration 5, growth-scale-flip 2). No version bump (release-branch territory per AGENTS.md).

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Reviewing now — pulling the PR diff, re-verifying the root-cause chain independently, and running the full suite locally before giving a verdict. Will report back shortly.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

Reviewed end-to-end — the fix logic is correct (root cause independently verified, floor math proven in both quadrants), but the PR cannot land as-is: it is dirty against current master, because master refactored exactly the floor region after your branch point. Details below.

What I verified

  • Pulled head 577a7ac locally; its own suite: 472 / 469 pass / 0 fail / 3 skip — matches your claim exactly. Typecheck + tsup green.
  • Traced the attribution chain independently: the kernel stamps compressCallId onto ranges at apply time and copies it onto the created block (acp-kernel bundle :881 / :2474); the adapter passes the host toolCallId through (src/compress-tool.ts:57,329-330). CompressionBlock.active/compressCallId/compressedTokens/summary exist in both 0.0.48 (your pin) and 0.0.56 (master's pin). The old code already required toolResult entries to carry toolCallId, so the new attribution adds no structural assumption.
  • Floor math proven end-to-end with instrumented runs: stale anchor 175K − 120K reclaimed → meter floors at 55,006 (30.6% < 45% band → correctly idle, no false EMERGENCY); stale anchor 174K − 1K reclaimed → floors at 173,006 (96.1% → nudge still fires). Both quadrants behave as designed.

Design verdict

Approving the approach over the alternative: subtracting genuinely-freed tokens from the provider's real number is exact and needs no magic constant; "add the fixed component back to the estimate" would require measuring tool schemas that are unmeasurable/unstable inside the extension. Right call.

Blocker: dirty merge vs master

Branch point is cbb753a; master has since absorbed #289 (sent-view recount), #316/#269 (growth re-inject), #268 (scale-flip reset, panel denominator), #323 (in-memory state save), and release v0.1.59 (acp-kernel 0.0.48 → 0.0.56) — all touching the floor region you modify. Conflicts in src/index.ts (imports + floor block) and tests/sent-view-arbitration.test.ts.

I resolved it locally and validated: full suite 633 / 630 pass / 0 fail / 3 skip, typecheck + build green. Recipe for the rebase:

  1. Keep master's structure (armedFloor, applyFloors, the view-recount gate) and replace the stale-skip with:
    hostFloor = realPromptTokens > 0 ? Math.max(realPromptTokens - (predates ? netReclaimed : 0), 0) : 0
    tokenCount = Math.max(sentTokens, hostFloor, armedFloor)
  2. Semantic decision worth calling out: the ruler-flip signal passed to runtime.noteTokenScale must be estScaleWins = hostFloor <= sentTokens, not raw predates. Under the adjusted floor, a stale anchor with small reclaim still lets the provider floor win (no actual ruler switch); resetting nudge tracking there would zero lastNudgeShownTokens so the next nudge passes the growth gate immediately — reintroducing exactly the [bug] Post-compression sent-view undercounts prompt by ~70–80K → false idle → host-floor emergency re-nudge loop #325 churn this PR exists to kill. Fresh-quadrant behavior is unchanged except a rare base-wins case that now also resets (more accurate).
  3. Test adaptations needed on the rebased tree:
    • growth-scale-flip: seed a real 150K-reclaim block before turn 1 — otherwise the no-block stale path floors turn 1 at the full 175K and it is not estimate-scale anymore (its baseline assertion breaks).
    • sent-view-arbitration stale case: needs a real reclaiming block plus enough compressible mass outside the protected recent zone (MID pad + ~1K reclaim → 96.1% → fires). With the SMALL pad the whole stream sits inside the protection zone and the kernel legitimately suppresses ("max pending < min benefit 5000") — correct kernel behavior, not a bug.

Minor finding (report-only, no separate issue per policy)

/acp's statusReport (src/commands.ts:153,171) applies the same stale-skip inside a display-only processTurn, so the panel under-reports right after a compress until fresh provider usage arrives. Cosmetic, self-heals next turn, no loop risk — fold into the rebase or take as later cleanup.

Recommendation: rebase onto current master with the recipe above (happy to share the exact hunks if useful). Fix code itself: LGTM.

@ranxianglei

Copy link
Copy Markdown
Owner Author

分诊(队列清理 #484): KEEP-VALID(#325 的两极缺陷是真问题),rebase 中等。

master 现行是二值跳过:src/floor-stale.ts:36-54 usageAnchorPredatesCompression() 在锚点早于成功压缩时整体弃 floor(src/status-tool.ts:76-81、src/index.ts:416/421 同步跳过)。PR 的 compressionAnchorStaleness() 返回 netReclaimed(floor=anchor−netReclaimed)在 master 无对应物(grep netReclaimed|reclaim 仅内核内部)。恰好治"陈旧 floor 假紧急 vs 跳过又漏计"两个极端。内核依赖(CompressionBlock.compressCallId/compressedTokens)0.0.81 均在。

rebase 风险:中等。 floor-stale.ts hunk 漂移小,但 src/index.ts meter 块被 #455/#289 重写——anchor−netReclaimed floor 与 measured×1.2 校准上限的交互必须在 rebase 里显式定义;tests/floor-stale.test.ts 与 tests/sent-view-arbitration.test.ts 两个现存测试文件需合并。

@github-actions

github-actions Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Extension Artifact

Branch: 2026-09-08_post-compress-token-floor (71c1529)

Option A — Install from npm PR tag (recommended)

pi install npm:billion-context-pi@pr-328

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

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pi-pr328.tgz
pi install ./package

This comment is automatically updated on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

已按分诊完成 rebase 到当前 master(v0.1.74 / acp-kernel 0.0.81),单 commit 保留。head 现为 55ca193。

冲突解决:src/floor-stale.ts、tests/floor-stale.test.ts 干净套用(master 未动);src/index.ts meter 块(被 #455/#289 重写)与 tests/sent-view-arbitration.test.ts(被 acp-kernel 0.0.55 迁移改动)手工合并。

关键交互(分诊点名的"floor 与校准上限的交互"):provider floor 从二值跳过改为连续值
hostFloor = max(0, realPrompt − (predates ? netReclaimed : 0)),接入 #455 校准上限与 #289 view-recount 的同一 applyFloors;#455 校准保持 fresh-only(gate on !predates)。另把 #267 growth-baseline 的 flip 触发从二值 stale 标志改为 estScaleWins = hostFloor <= sentTokens(以实际生效的 ruler 为准)——否则"陈旧但少回收、仍锚在近满额"的轮次会被误判为换尺而重置增长基线。

测试适配(新基座强制,已在 PR 描述补记):

验证:typecheck ✅ / build ✅(acp-kernel 内联,零运行时依赖)/ 三个受影响测试文件全绿(floor-stale 14、sent-view 5、growth-scale 2)。本地全量套件里非绿的仅为环境噪声:临时文件写入受限导致的 EACCES(CI 有可写 /tmp)+ 2 个 delegate-entry 主机解析断言(该文件只 import delegate-tool.js,与 master 字节一致,在 master 上同样失败,与本 diff 无关)。无任何失败与本 PR 改动相关。

未改 status-tool.ts / commands.ts 的展示层 stale-skip(纯显示、自愈,前面楼层已记录),留作后续。CI 在新 commit 上运行中。

PR: #328

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

补充:rebase 后的 head 55ca193 CI 已全部通过 —— PR Build Artifact ✅ / CI ✅ / E2E ✅(干净环境下全量套件通过,本地那批 EACCES / delegate-entry 环境噪声在 CI 不复现)。PR 现为 mergeable,待人工合并。

一句话:已把 #328 rebase 到当前 master 并解决 meter 块与两处测试的冲突(连续 floor + estScaleWins flip),CI 全绿,可合并。

…e it

After a successful compress, usageAnchorPredatesCompression() skipped the
provider-usage floor entirely, so tokenCount fell back to the raw sent-view
estimate — which structurally omits tool-definition schemas, ref-tag overhead,
and the injected nudge (a fixed ~70–80K for this host). The meter read
false-idle; on the next turn a fresh provider usage re-engaged the floor at the
full real prompt size (~84–95% of limit) and fired a spurious EMERGENCY, which
the model answered by compressing again → loop.

Fix: when the anchor predates a successful compress, floor at
(lastProviderUsage − netReclaimedSinceAnchor) instead of skipping. netReclaimed
sums max(0, compressedTokens − summaryTokens) over active blocks whose creating
compress toolResult lands after the last valid usage anchor. The provider's
real number already counts all fixed overhead accurately, so subtracting only
the genuinely-freed tokens yields an exact post-compression size without needing
to measure tool schemas (unmeasurable/unstable in the extension). New work added
after the compress still grows tokenCount via sentTokens as before.

No regression on the non-stale path (floor unchanged); a stale-anchor compress
that reclaimed little still correctly trips the nudge.
@ranxianglei
ranxianglei force-pushed the 2026-09-08_post-compress-token-floor branch from 261f611 to 71c1529 Compare September 26, 2026 00:51
@ranxianglei
ranxianglei merged commit 9e55d58 into master Sep 26, 2026
9 checks passed
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.

[bug] Post-compression sent-view undercounts prompt by ~70–80K → false idle → host-floor emergency re-nudge loop

1 participant