From c6087c00e529d78ddd7508df89361884e931cc4e Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 19:04:12 +0800 Subject: [PATCH 1/8] kernel: rotate count-triggered T2/T3 nudges with ready T1 on the growth path (#2513) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The growth path of decideNudge() short-circuited on t1Eff >= the T1 mass threshold before ever reaching the tier-2/tier-3 count branches, so an explicitly lowered tiers.tier2Trigger/tier3Trigger was structurally dead in any session whose raw compressible mass stayed above the threshold (billion-context-pi#628: 22 active T1 blocks + t1Eff 100K-400K, zero T2 nudges across the whole session). Fix (issue direction A, ported from acp-kernel#510 fixing acp-kernel#509, migrated here as #2513): count-ready tiers now join a rotation pool with a ready T1 on the growth path. T1 keeps first pick until it has gone (nudge.lastInjectedTier !== 1); then the slot hands to the count-ready tier with the oldest cadence stamp (never-shown = oldest, tie -> lower tier) and back to T1 the next cycle — neither side starves whether the model ignores or complies with one of them. Rotation memory lives in a new OPTIONAL state field nudge.lastInjectedTier, deliberately NOT cleared by the compression-success reset (which still clears lastShownByTier/baselines): using the existing per-tier stamps would let a model that keeps draining raw ranges restart every tie at T1 — the exact production shape of #628. Absent field = null = legacy T1-first, so persisted pre-fix states need no migration. With the default triggers (1000/2000) the candidate pool stays empty and the legacy cascade runs unchanged — default behavior is byte-identical (pinned by a dedicated test). The pressure path, token-mass cascade, first-sight bypass and reason-string formats are untouched. --- kernel/package.json | 2 +- kernel/src/compress.ts | 71 +++++++++- kernel/src/state.ts | 1 + kernel/src/types.ts | 7 + kernel/tests/nudge.test.ts | 279 +++++++++++++++++++++++++++++++++++-- package-lock.json | 2 +- 6 files changed, 348 insertions(+), 14 deletions(-) diff --git a/kernel/package.json b/kernel/package.json index 2317456b31..a759139819 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.109", + "version": "0.0.110", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/compress.ts b/kernel/src/compress.ts index c7875397ba..55f63d2939 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -1114,6 +1114,9 @@ const nudgeNode: PipelineNode = { ...stamped.lastShownByTier, [nudge.tier]: ctx.tokenCount, }; + // Rotation memory (#509): survives the compression-success reset so a + // compliant model draining raw ranges cannot restart every T1/T2 tie. + stamped.lastInjectedTier = nudge.tier; } } @@ -1814,9 +1817,16 @@ function decideNudge(input: NudgeInput): NudgeDecision { // threshold AND exceeds the effective pending of every lower tier (T2 > T1 // effective; T3 > T2 and > T1 effective). Per-tier thresholds (#2376): // nudge.tierGrowthTokens.{t1,t2,t3} may pin each mass trigger independently; - // each unset tier keeps its derived default (T1 = growth step, T2/T3 = the - // shared multiplier threshold), so absent config decides byte-identically. - const tier2Threshold = Math.round( + // each unset tier keeps its derived default (T1 = growth step, T2/T3 = the + // shared multiplier threshold), so absent config decides byte-identically. + // On the growth path a count-ready tier is NEVER short-circuited behind a + // ready T1 (#509): slots alternate — T1 keeps first pick until it has gone + // (nudge.lastInjectedTier), then the count-ready tier with the oldest + // cadence stamp wins (never-shown = oldest; tie -> lower tier) — so an + // explicitly lowered trigger is heard in sessions whose raw pending stays + // high, and neither side starves even if the model keeps ignoring or + // complying with one of them. + const tier2Threshold = Math.round( nudgeGrowthTokens * (config.nudge.tier2GrowthMultiplier ?? 1.5), ); const tierThresholds: Record = { @@ -1894,7 +1904,60 @@ function decideNudge(input: NudgeInput): NudgeDecision { : `${label} T${best} distill: max pending ${bestPending} (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}), usage ${Math.round(usage * 100)}%`; } } else if (growthReady) { - if (t1Eff >= tierThresholds[1]) { + // Explicit count-triggered candidates (#509): reachable on the growth path + // REGARDLESS of t1Eff. The old T1-first short-circuit made an explicitly + // lowered tier2Trigger/tier3Trigger dead in any session whose raw + // compressible mass stayed >= nudgeGrowthTokens (billion-context-pi#628: + // 22 T1 blocks, t1Eff 100K-400K, zero T2 nudges across the session). + // Token-mass paths keep the legacy cascade below (implicit-vs-implicit, + // #379); with the default triggers (1000/2000) this pool stays empty -> + // byte-identical default behavior. + const countCandidates: CompressionTier[] = []; + if (config.tiers.enabled) { + if (t2CountReady) { + const lastShown = state.nudge.lastShownByTier[2] ?? 0; + if (lastShown === 0 || tokenCount - lastShown >= growthFloor) { + countCandidates.push(2); + } + } + if (t3CountReady) { + const lastShown = state.nudge.lastShownByTier[3] ?? 0; + if (lastShown === 0 || tokenCount - lastShown >= growthFloor) { + countCandidates.push(3); + } + } + } + if (countCandidates.length > 0) { + // Slot rotation (#509): T1 keeps first pick until it has gone + // (lastInjectedTier !== 1 — fresh state, or the previous slot was a + // distill); then the slot hands to a count-ready tier, oldest cadence + // stamp first (never-shown = oldest, tie -> lower tier), and back to T1 + // the next cycle. lastInjectedTier survives the compression-success + // reset, so a model that keeps draining raw ranges cannot restart every + // tie at T1 (the billion-context-pi#628 shape). + const t1Ready = t1Eff >= tierThresholds[1]; + let chosen: CompressionTier; + if (t1Ready && (state.nudge.lastInjectedTier ?? null) !== 1) { + chosen = 1; + } else { + chosen = countCandidates[0]!; + let chosenStamp = state.nudge.lastShownByTier[chosen] ?? 0; + for (let i = 1; i < countCandidates.length; i++) { + const stamp = state.nudge.lastShownByTier[countCandidates[i]!] ?? 0; + if (stamp < chosenStamp) { + chosenStamp = stamp; + chosen = countCandidates[i]!; + } + } + } + injectedTier = chosen; + injectedReason = + chosen === 1 + ? `T1 effective ${t1Eff} >= ${tierThresholds[1]}, growth ${growthSinceReference}, usage ${Math.round(usage * 100)}%` + : chosen === 2 + ? `T2 distill ready: ${t2Count} tier-1 blocks >= tier2Trigger ${config.tiers.tier2Trigger} (${t2Pen} tokens), usage ${Math.round(usage * 100)}%` + : `T3 condense ready: ${t3Count} tier-2 blocks >= tier3Trigger ${config.tiers.tier3Trigger} (${t3Pen} tokens), usage ${Math.round(usage * 100)}%`; + } else if (t1Eff >= tierThresholds[1]) { injectedTier = 1; injectedReason = `T1 effective ${t1Eff} >= ${tierThresholds[1]}, growth ${growthSinceReference}, usage ${Math.round(usage * 100)}%`; } else if ( diff --git a/kernel/src/state.ts b/kernel/src/state.ts index cb4d2a2a95..d067f4fdf6 100644 --- a/kernel/src/state.ts +++ b/kernel/src/state.ts @@ -11,6 +11,7 @@ export function createInitialState(): CompressionState { baselineTokens: 0, anchors: {}, lastShownByTier: {}, + lastInjectedTier: null, }, stats: { tokensCompressed: 0, diff --git a/kernel/src/types.ts b/kernel/src/types.ts index f47f842c88..fa365fa050 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -94,6 +94,13 @@ export interface NudgeState { * tiers. Using a record (not N named fields) so adding tier 4+ needs no * schema change. */ lastShownByTier: Record; + /** Last tier that received a nudge slot (growth or pressure path). Unlike + * lastShownByTier this is NOT cleared by a successful applyCompression: it + * is the rotation memory that keeps an explicitly configured + * tier2Trigger/tier3Trigger alternating with T1 instead of being starved by + * a persistently high T1 pending (#509). Optional for pre-#509 persisted + * states (absent = null = legacy T1-first). */ + lastInjectedTier?: CompressionTier | null; } export interface CompressionStats { diff --git a/kernel/tests/nudge.test.ts b/kernel/tests/nudge.test.ts index f4deb722e4..d59f6c6a41 100644 --- a/kernel/tests/nudge.test.ts +++ b/kernel/tests/nudge.test.ts @@ -1402,7 +1402,7 @@ test("arbitration: below tier2Trigger count and below token gate -> no T2 nudge" assert.doesNotMatch(turn.nudge.reason ?? "", /tier2Trigger/); }); -test("arbitration: count-triggered T2 does not preempt ready T1 raw compression", () => { +test("arbitration: T1 keeps first pick over count-ready T2, then rotates (#509)", () => { const core = createCore(); const config = buildConfig({ compress: { @@ -1413,24 +1413,35 @@ test("arbitration: count-triggered T2 does not preempt ready T1 raw compression" preserveRecentMessages: 0, }); const messages = makeMessages(10); - let state = core.processTurn({ + // First sight of the 50K backlog fires T1 (fresh rotation memory). + const first = core.processTurn({ messages, state: createInitialState(), config, tokenCount: 50000, - }).state; - state = { - ...state, + }); + assert.equal(first.nudge.shouldInject, true, `reason: ${first.nudge.reason}`); + assert.equal(first.nudge.tier, 1, "first slot goes to T1 raw pending"); + let state = { + ...first.state, blocks: t1Blocks([["m1"], ["m2"], ["m3"], ["m4"], ["m5"]], 400), }; + // T1 has gone -> the next slot hands to the count-ready T2 (pre-#509 this + // returned T1 forever while t1Eff stayed >= nudgeGrowthTokens). const turn = core.processTurn({ messages, state, config, tokenCount: 60000 }); assert.equal(turn.nudge.shouldInject, true, `reason: ${turn.nudge.reason}`); assert.equal( turn.nudge.tier, - 1, - "T1 raw pending still has priority over count-ready T2", + 2, + "rotation hands the slot to count-ready T2 after T1 went", ); - assert.match(turn.nudge.reason ?? "", /T1 effective/); + assert.match(turn.nudge.reason ?? "", /T2 distill ready/); + // And back to T1 the cycle after that. + state = turn.state; + const back = core.processTurn({ messages, state, config, tokenCount: 66000 }); + assert.equal(back.nudge.shouldInject, true, `reason: ${back.nudge.reason}`); + assert.equal(back.nudge.tier, 1, "slot returns to T1 — strict alternation"); + assert.match(back.nudge.reason ?? "", /T1 effective/); }); test("arbitration: count-triggered T2 still respects the growthFloor cadence", () => { @@ -1517,6 +1528,258 @@ test("arbitration: tiers disabled -> count trigger cannot fire T2", () => { assert.doesNotMatch(turn.nudge.reason ?? "", /tier2Trigger/); }); +// #509: the growth path's T1-first short-circuit made an explicitly configured +// tier2Trigger/tier3Trigger structurally unreachable in any session whose raw +// compressible mass stayed >= nudgeGrowthTokens (billion-context-pi#628: 22 T1 +// blocks + t1Eff 100K-400K, zero T2 nudges across the whole session). Fix: +// count-ready tiers join a rotation pool with a ready T1 and are picked by +// OLDEST last-shown stamp (never-shown = oldest; tie -> lower tier), so neither +// side starves. Setup below mirrors the production shape: 5 of 10 messages are +// already compressed into 5 T1 blocks (count-ready at trigger 5) while the +// remaining raw messages keep t1Eff ~25K >= nudgeGrowthTokens 6000 every turn. +test("arbitration: count-ready T2 is heard while t1Eff stays high (#509)", () => { + const core = createCore(); + const config = buildConfig({ + compress: { + minCompressRange: 5000, + maxSummaryLength: 0, + minSummaryLength: 0, + }, + preserveRecentMessages: 0, + }); + const messages = makeMessages(10); + let state = core.processTurn({ + messages, + state: createInitialState(), + config, + tokenCount: 10_000, + }).state; + state = { + ...state, + blocks: t1Blocks([["m0"], ["m1"], ["m2"], ["m3"], ["m4"]], 400), + }; + + // Fresh stamps tie -> lower tier keeps the first pick (legacy behavior). + const turnA = core.processTurn({ + messages, + state, + config, + tokenCount: 60_000, + }); + assert.equal(turnA.nudge.shouldInject, true, `reason: ${turnA.nudge.reason}`); + assert.equal(turnA.nudge.tier, 1); + + // T1 still ready AND 5 blocks >= tier2Trigger 5. Pre-fix this returned T1 + // forever — the explicit trigger was dead. Rotation hands the slot to the + // never-shown T2. + const turnB = core.processTurn({ + messages, + state: turnA.state, + config, + tokenCount: 66_000, + }); + assert.equal(turnB.nudge.shouldInject, true, `reason: ${turnB.nudge.reason}`); + assert.equal( + turnB.nudge.tier, + 2, + `expected rotated T2: ${turnB.nudge.reason}`, + ); + assert.match(turnB.nudge.reason ?? "", /5 tier-1 blocks >= tier2Trigger 5/); +}); + +test("arbitration: T1/T2 rotation alternates — neither side starves (#509)", () => { + const core = createCore(); + const config = buildConfig({ + compress: { + minCompressRange: 5000, + maxSummaryLength: 0, + minSummaryLength: 0, + }, + preserveRecentMessages: 0, + }); + const messages = makeMessages(10); + let state = core.processTurn({ + messages, + state: createInitialState(), + config, + tokenCount: 10_000, + }).state; + state = { + ...state, + blocks: t1Blocks([["m0"], ["m1"], ["m2"], ["m3"], ["m4"]], 400), + }; + + const seen: number[] = []; + for (const tc of [60_000, 66_000, 72_000, 78_000]) { + const turn = core.processTurn({ messages, state, config, tokenCount: tc }); + assert.equal(turn.nudge.shouldInject, true, `@${tc}: ${turn.nudge.reason}`); + seen.push(turn.nudge.tier ?? 0); + state = turn.state; + } + assert.deepEqual( + seen, + [1, 2, 1, 2], + "oldest-stamp rotation alternates T1/T2", + ); +}); + +test("arbitration: count-ready T3 rotates in under high t1Eff (#509)", () => { + const core = createCore(); + const config = buildConfig({ + tiers: { enabled: true, tier2Trigger: 5, tier3Trigger: 3 }, + compress: { + minCompressRange: 5000, + maxSummaryLength: 0, + minSummaryLength: 0, + }, + preserveRecentMessages: 0, + }); + const messages = makeMessages(10); + let state = core.processTurn({ + messages, + state: createInitialState(), + config, + tokenCount: 10_000, + }).state; + // 2 T1 blocks (< tier2Trigger 5 → T2 not count-ready) + 4 T2 blocks (>= 3). + // t3Pen ~400 << 9000 mass gate — only the count path is live. + state = { + ...state, + blocks: [...t1Blocks([["m0"], ["m1"]], 400), ...t2Blocks(4, 400, ["m2"])], + }; + const turnA = core.processTurn({ + messages, + state, + config, + tokenCount: 60_000, + }); + assert.equal(turnA.nudge.shouldInject, true, `reason: ${turnA.nudge.reason}`); + assert.equal(turnA.nudge.tier, 1, "fresh stamps -> T1 first pick"); + const turnB = core.processTurn({ + messages, + state: turnA.state, + config, + tokenCount: 66_000, + }); + assert.equal(turnB.nudge.shouldInject, true, `reason: ${turnB.nudge.reason}`); + assert.equal( + turnB.nudge.tier, + 3, + `expected rotated T3: ${turnB.nudge.reason}`, + ); + assert.match(turnB.nudge.reason ?? "", /4 tier-2 blocks >= tier3Trigger 3/); +}); + +test("arbitration: T2 slot survives repeated T1 compressions (#509 rotation memory)", () => { + const core = createCore(); + const config = buildConfig({ + compress: { + minCompressRange: 5000, + maxSummaryLength: 0, + minSummaryLength: 0, + }, + preserveRecentMessages: 0, + }); + const messages = makeMessages(20); + let state = core.processTurn({ + messages, + state: createInitialState(), + config, + tokenCount: 10_000, + }).state; + // 5 count-ready T1 blocks over m0-m4; m5-m19 raw (~100K) keep t1Eff high. + state = { + ...state, + blocks: t1Blocks([["m0"], ["m1"], ["m2"], ["m3"], ["m4"]], 400), + }; + + const turnA = core.processTurn({ + messages, + state, + config, + tokenCount: 60_000, + }); + assert.equal(turnA.nudge.shouldInject, true, `reason: ${turnA.nudge.reason}`); + assert.equal(turnA.nudge.tier, 1, "fresh rotation memory -> T1 first"); + + // Model complies: compresses a raw slice. Success resets baselines and the + // per-tier cadence stamps — but NOT the rotation memory. + const compressed = core.applyCompression({ + ranges: [ + { startRef: "m00006", endRef: "m00010", summary: "drained a raw slice" }, + ], + messages, + state: turnA.state, + config, + }); + assert.ok(compressed.result.blocksCreated > 0, "compression succeeded"); + assert.equal( + compressed.state.nudge.lastInjectedTier, + 1, + "rotation memory must survive the compression-success reset", + ); + + // Backlog still high (m10-m19 uncovered ~50K) and 5 blocks still count-ready: + // the slot goes to T2 — exactly what billion-context-pi#628 never received. + const turnB = core.processTurn({ + messages, + state: compressed.state, + config, + tokenCount: 66_000, + }); + assert.equal(turnB.nudge.shouldInject, true, `reason: ${turnB.nudge.reason}`); + assert.equal( + turnB.nudge.tier, + 2, + `expected rotated T2 after a compliant T1 compress: ${turnB.nudge.reason}`, + ); +}); + +test("arbitration: default triggers (1000/2000) keep T1-first under high t1Eff (#509 no default drift)", () => { + const core = createCore(); + const config = buildConfig({ + tiers: { enabled: true, tier2Trigger: 1000, tier3Trigger: 2000 }, + compress: { + minCompressRange: 5000, + maxSummaryLength: 0, + minSummaryLength: 0, + }, + preserveRecentMessages: 0, + }); + const messages = makeMessages(10); + let state = core.processTurn({ + messages, + state: createInitialState(), + config, + tokenCount: 10_000, + }).state; + state = { + ...state, + blocks: t1Blocks([["m0"], ["m1"], ["m2"], ["m3"], ["m4"]], 400), + }; + + const turnA = core.processTurn({ + messages, + state, + config, + tokenCount: 60_000, + }); + assert.equal(turnA.nudge.shouldInject, true, `reason: ${turnA.nudge.reason}`); + assert.equal(turnA.nudge.tier, 1); + const turnB = core.processTurn({ + messages, + state: turnA.state, + config, + tokenCount: 66_000, + }); + assert.equal(turnB.nudge.shouldInject, true, `reason: ${turnB.nudge.reason}`); + assert.equal( + turnB.nudge.tier, + 1, + "5 < 1000: count path off by default, T1 continues", + ); +}); + // #194 first-sight mass bypass: a session that ARRIVES with a huge ready mass // (stateless full-history ingest) must not wait a full growth floor of NEW // tokens for its first compress. #351: growthReference seeded to the ingest diff --git a/package-lock.json b/package-lock.json index 04ad1c16f0..67ae4cdc7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,7 +48,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.109", + "version": "0.0.110", "dev": true, "license": "MIT", "devDependencies": { From 0b71a95780ab2efea2ae6d701475f355b5a9406d Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 19:09:13 +0800 Subject: [PATCH 2/8] kernel: correct tier2Trigger/tier3Trigger default drift in docs (5/10 -> 1000/2000 since #379) The TierConfig JSDoc still documented "Default 5" / "Default 10" while the actual defaults have been 1000 / 2000 ever since #379 turned the count path off by default. Same mechanism domain as #509 (the count path's semantics), so it rides along as its own labeled commit: fix the drifted values and document the new rotation behavior in the README nudge section. --- kernel/README.md | 2 +- kernel/src/types.ts | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/kernel/README.md b/kernel/README.md index 86b52d4a9c..eb18adeadf 100644 --- a/kernel/README.md +++ b/kernel/README.md @@ -268,7 +268,7 @@ The nudge system tells the model _when_ to compress. It implements: - **First-sight mass bypass** (#194): a session that arrives with ready compressible mass ≥ threshold gets its first nudge without waiting for new growth, provided usage ≥ `nudge.minContextLimitPct`. Steady-state nudges are gated on growth/token-mass, not percentage (#379). - **Growth-gating**: a repeat nudge requires positive growth since the baseline (prevents re-firing every turn). `"strong"` force relaxes this. -- **Tier-distillation triggers**: when active tier-1 blocks pile up past `tiers.tier2Trigger`, emit a tier-2 distillation nudge; tier-3 analogously. Block COUNT is not a need signal, so the count path defaults OFF (`tier2Trigger: 1000`, `tier3Trigger: 2000`) — no usage gate: token-mass paths (T1 ≥ growth step, T2/T3 ≥ 1.5× growth step by default) and the T1 growth path are the need signal and fire ungated (#379, supersedes the #237/#238 usage band). Each token-mass trigger can be pinned independently via `nudge.tierGrowthTokens.{t1,t2,t3}`; every unset tier keeps its derived default, so absent config decides identically (#2376). +- **Tier-distillation triggers**: when active tier-1 blocks pile up past `tiers.tier2Trigger`, emit a tier-2 distillation nudge; tier-3 analogously. Block COUNT is not a need signal, so the count path defaults OFF (`tier2Trigger: 1000`, `tier3Trigger: 2000`) — no usage gate: token-mass paths (T1 ≥ growth step, T2/T3 ≥ 1.5× growth step by default) and the T1 growth path are the need signal and fire ungated (#379, supersedes the #237/#238 usage band). Each token-mass trigger can be pinned independently via `nudge.tierGrowthTokens.{t1,t2,t3}`; every unset tier keeps its derived default, so absent config decides identically (#2376). When a count trigger IS explicitly lowered and met, the count-ready tier alternates slots with a ready T1 on the growth path (T1 keeps first pick until it has gone; rotation memory survives successful compressions) instead of being short-circuited behind it (#509). - **Compressible-range computation**: reports the actual compressible ranges (excluding covered + preserved-recent messages) so the model knows what to target. - **Baseline reset on compress**: `applyCompression` clears the growth baseline on success, preventing the feedback-loop bug where the nudge re-fires post-compress. diff --git a/kernel/src/types.ts b/kernel/src/types.ts index fa365fa050..acc542beed 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -318,11 +318,15 @@ export interface CompressionState { export interface TierConfig { enabled: boolean; /** Distill to tier 2 once the count of ACTIVE tier-1 blocks reaches this. - * Default 5. Independent of raw-message pending: summaries are ~10:1 - * condensed, so a token-mass comparison against T1 pending would starve. */ + * Default 1000 (#379: block count is not a need signal, so the path + * defaults OFF; lowering it explicitly opts back in, and a count-ready + * tier then alternates slots with a ready T1 on the growth path instead + * of being short-circuited behind it — #509). Independent of raw-message + * pending: summaries are ~10:1 condensed, so a token-mass comparison + * against T1 pending would starve. */ tier2Trigger: number; /** Condense to tier 3 once the count of ACTIVE tier-2 blocks reaches this. - * Default 10. */ + * Default 2000 (#379, see tier2Trigger). */ tier3Trigger: number; } From 229418f591e802703b71ba2284c4dba218be0e9b Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 19:32:49 +0800 Subject: [PATCH 3/8] kernel: align re-wrapped comment indent in decideNudge (#2519 review) --- kernel/src/compress.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/kernel/src/compress.ts b/kernel/src/compress.ts index 55f63d2939..96ff0a76be 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -1817,16 +1817,16 @@ function decideNudge(input: NudgeInput): NudgeDecision { // threshold AND exceeds the effective pending of every lower tier (T2 > T1 // effective; T3 > T2 and > T1 effective). Per-tier thresholds (#2376): // nudge.tierGrowthTokens.{t1,t2,t3} may pin each mass trigger independently; - // each unset tier keeps its derived default (T1 = growth step, T2/T3 = the - // shared multiplier threshold), so absent config decides byte-identically. - // On the growth path a count-ready tier is NEVER short-circuited behind a - // ready T1 (#509): slots alternate — T1 keeps first pick until it has gone - // (nudge.lastInjectedTier), then the count-ready tier with the oldest - // cadence stamp wins (never-shown = oldest; tie -> lower tier) — so an - // explicitly lowered trigger is heard in sessions whose raw pending stays - // high, and neither side starves even if the model keeps ignoring or - // complying with one of them. - const tier2Threshold = Math.round( + // each unset tier keeps its derived default (T1 = growth step, T2/T3 = the + // shared multiplier threshold), so absent config decides byte-identically. + // On the growth path a count-ready tier is NEVER short-circuited behind a + // ready T1 (#509): slots alternate — T1 keeps first pick until it has gone + // (nudge.lastInjectedTier), then the count-ready tier with the oldest + // cadence stamp wins (never-shown = oldest; tie -> lower tier) — so an + // explicitly lowered trigger is heard in sessions whose raw pending stays + // high, and neither side starves even if the model keeps ignoring or + // complying with one of them. + const tier2Threshold = Math.round( nudgeGrowthTokens * (config.nudge.tier2GrowthMultiplier ?? 1.5), ); const tierThresholds: Record = { From 81f6e1ca1cbae5f9fb4c94b419c9ee6d09f88532 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 19:32:49 +0800 Subject: [PATCH 4/8] =?UTF-8?q?kernel:=20pin=20dual=20count-ready=20pool?= =?UTF-8?q?=20selection=20=E2=80=94=20oldest=20stamp=20wins,=20tie=20to=20?= =?UTF-8?q?lower=20tier=20(#2519=20review)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kernel/tests/nudge.test.ts | 82 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/kernel/tests/nudge.test.ts b/kernel/tests/nudge.test.ts index d59f6c6a41..ce27c43da6 100644 --- a/kernel/tests/nudge.test.ts +++ b/kernel/tests/nudge.test.ts @@ -1670,6 +1670,88 @@ test("arbitration: count-ready T3 rotates in under high t1Eff (#509)", () => { assert.match(turnB.nudge.reason ?? "", /4 tier-2 blocks >= tier3Trigger 3/); }); +test("arbitration: dual count-ready pool — oldest stamp wins, tie breaks to lower tier (#509)", () => { + const core = createCore(); + const config = buildConfig({ + tiers: { enabled: true, tier2Trigger: 5, tier3Trigger: 3 }, + compress: { + minCompressRange: 5000, + maxSummaryLength: 0, + minSummaryLength: 0, + }, + preserveRecentMessages: 0, + }); + const messages = makeMessages(10); + let state = core.processTurn({ + messages, + state: createInitialState(), + config, + tokenCount: 10_000, + }).state; + // 5 T1 blocks (>= tier2Trigger 5) + 4 T2 blocks (>= tier3Trigger 3): BOTH + // distillation triggers count-ready at once, masses far below the mass gate. + state = { + ...state, + blocks: [ + ...t1Blocks([["m0"], ["m1"], ["m2"], ["m3"], ["m4"]], 400), + ...t2Blocks(4, 400, ["m2"]), + ], + }; + const turnA = core.processTurn({ + messages, + state, + config, + tokenCount: 60_000, + }); + assert.equal(turnA.nudge.shouldInject, true, `reason: ${turnA.nudge.reason}`); + assert.equal(turnA.nudge.tier, 1, "fresh rotation memory -> T1 first pick"); + + // T2 shown a while ago (cadence met), T3 never shown (absent stamp = 0 = + // oldest): the never-shown tier must rotate in ahead of the lower-tier one. + const stateB = { + ...turnA.state, + nudge: { + ...turnA.state.nudge, + lastShownByTier: { ...turnA.state.nudge.lastShownByTier, 2: 50_000 }, + }, + }; + const turnB = core.processTurn({ + messages, + state: stateB, + config, + tokenCount: 66_000, + }); + assert.equal(turnB.nudge.shouldInject, true, `reason: ${turnB.nudge.reason}`); + assert.equal( + turnB.nudge.tier, + 3, + `never-shown T3 outranks older-stamped T2: ${turnB.nudge.reason}`, + ); + + // Tie: the slot just went to T1 (so T1 keeps no first pick), both distill + // tiers never shown -> the lower tier (T2) wins the equal-stamp comparison. + const stateC = { + ...turnB.state, + nudge: { + ...turnB.state.nudge, + lastInjectedTier: 1, + lastShownByTier: { 1: 66_000 }, + }, + }; + const turnC = core.processTurn({ + messages, + state: stateC, + config, + tokenCount: 72_000, + }); + assert.equal(turnC.nudge.shouldInject, true, `reason: ${turnC.nudge.reason}`); + assert.equal( + turnC.nudge.tier, + 2, + `equal stamps break to the lower tier: ${turnC.nudge.reason}`, + ); +}); + test("arbitration: T2 slot survives repeated T1 compressions (#509 rotation memory)", () => { const core = createCore(); const config = buildConfig({ From 56b68bced614e8e69b77c25fe70e0e0571505c49 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 5 Nov 2026 11:56:35 +0800 Subject: [PATCH 5/8] kernel: route nudge slots to delivering tiers when T1 harvest stalls (#5698) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a host model only partially complies with T1 compression nudges (folds a few K of the offered mass each time), decideNudge's growth cascade starves T2/T3 distillation forever: the T2 mass leg demands t2Pen > t1Eff behind a T1-first short-circuit, so a persistently high t1Eff makes the distillation slot structurally unreachable even after its own threshold passes — summary blocks accumulate monotonically until the session ceiling (#5671 production incident; #5698 root cause). T1 harvest-stall detection: - A T1 nudge fire records the offered raw mass (breakdown.pendingT1) in state.nudge.lastT1FirePending (consume-once). - On successful applyCompression, realized tokensCompressed is compared against it: a distillation fold (new tier >= 2 block) clears the stall unconditionally; otherwise a T1-shaped fold harvesting less than STALL_HARVEST_RATIO (0.5) of the offered mass latches state.nudge.t1HarvestStall, at/above ratio clears it. No-op calls are not evidence and leave the armed measurement in place. - decideNudge consumes the flag only when tiers.enabled: in the growth band a stalled T1 yields its slot to a cadence-met T2/T3 whose own mass threshold is met (the legacy "> t1Eff" demand drops for this path); in the pressure band the stall removes T1 from candidates when max(t2,t3) clears minPressureBenefit, so arbitration picks the tier that actually delivers. Reasons carry "[T1 harvest stall]". Composes with the #509 count-trigger slot rotation already on this branch: the stall override sits above the count-ready pool, explicit count triggers keep working independently of the flag, and per-tier cadence applies to the redirected slot as usual. Untouched by design: flat 50K growth cadence (KDD #8), the #379 mass-as-demand philosophy (the stall is consulted only once a higher tier's mass leg crossed its own threshold), #194 first-sight re-arm, and the minPressureBenefit gate. Compatibility: both new state fields are optional — pre-fix snapshots lack them, detection stays off, and arbitration is byte-identical (pinned). Eager lanes never latch. Tests: kernel/tests/nudge.test.ts +9 rows (core latch to slot handoff, full-compliance never latches, distillation clears, legacy absent-flag byte-identity, pressure drop/keep, cadence respect, no-op-not-evidence, count-trigger independence). Red-check: 7/9 fail without the fix. --- kernel/package.json | 2 +- kernel/src/compress.ts | 88 ++++++++++++- kernel/src/state.ts | 1 + kernel/src/types.ts | 17 +++ kernel/tests/nudge.test.ts | 259 +++++++++++++++++++++++++++++++++++++ package-lock.json | 2 +- 6 files changed, 365 insertions(+), 4 deletions(-) diff --git a/kernel/package.json b/kernel/package.json index 3c313f565f..1f8a27ec2a 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.180", + "version": "0.0.181", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/compress.ts b/kernel/src/compress.ts index c69387cf5a..8f4c9187df 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -168,6 +168,16 @@ type RangeResolution = * clears the latch, so normal sessions hold a handful at most. Oldest drop. */ const MAX_TRUNCATE_LATCH = 64; +/** #5698: harvest ratio below which a successful T1-shaped fold counts as a + * stalled T1 channel. The nudge offered `lastT1FirePending` raw tokens; if + * the fold that followed reclaimed less than half of it, the model is only + * partially complying and t1Eff stays pinned high forever — the exact shape + * where the legacy mass legs (`t2Pen > t1Eff`) can never fire and the tier-2 + * backlog grows unboundedly while every slot re-fires T1. A distillation + * fold (new block tier >= 2) clears the stall regardless of ratio: it is by + * definition progress on the higher tiers. */ +const STALL_HARVEST_RATIO = 0.5; + function rangeError( spec: { startRef: string; endRef: string }, message: string, @@ -862,6 +872,28 @@ export function createCore(ports: Ports = {}): CompressionCore { // tracked — a fresh cadence starts from a clean slate. state.nudge.absorbedDebt = 0; state.nudge.absorbCount = 0; + // T1 harvest-stall measurement (#5698): compare what this fold actually + // reclaimed against the raw mass the last T1 nudge offered. A + // distillation fold (new tier >= 2 block) clears the flag regardless of + // ratio — progress on the higher tiers by definition; otherwise a + // harvest below STALL_HARVEST_RATIO latches the flag so decideNudge stops + // spending slots re-firing the unresponsive channel. Consume-once + // either way; no-op calls (blocksCreated === 0) leave the armed value in + // place, so only real folds count as evidence. + const producedDistillation = state.blocks.some( + (b) => !preFoldBlockIds.has(b.blockId) && b.tier >= 2, + ); + if (producedDistillation) { + // Progress on the higher tiers clears the latch even when no T1 fire + // is being measured right now — the channel moved where it counts. + state.nudge.t1HarvestStall = false; + } + const armedT1Pending = state.nudge.lastT1FirePending; + state.nudge.lastT1FirePending = undefined; + if (!producedDistillation && armedT1Pending !== undefined && armedT1Pending > 0) { + state.nudge.t1HarvestStall = + tokensCompressed / armedT1Pending < STALL_HARVEST_RATIO; + } // A successful compression is by definition viable progress — restart // the terminal-floor streak so the escape signal can only fire again // after N fresh stuck events (#300). @@ -1486,6 +1518,12 @@ const nudgeNode: PipelineNode = { // Rotation memory (#509): survives the compression-success reset so a // compliant model draining raw ranges cannot restart every T1/T2 tie. stamped.lastInjectedTier = nudge.tier; + // Harvest-stall arming (#5698): remember how much raw mass this T1 + // nudge offered so the next successful fold can measure what the T1 + // channel actually delivered (consume-once in applyCompression). + if (nudge.tier === 1) { + stamped.lastT1FirePending = nudge.breakdown.pendingT1; + } } } @@ -2163,7 +2201,21 @@ function decideNudge(input: NudgeInput): NudgeDecision { // changes the reason label/voice; truncate.threshold remains the // independent last resort when there is genuinely nothing to compress. const candidates: CompressionTier[] = [1]; + let stallDroppedT1 = false; if (config.tiers.enabled) { + // T1 harvest-stall (#5698): max-pending arbitration keeps picking the + // unresponsive T1 channel — its pending stays high precisely BECAUSE + // nothing folds it. With the stall flag latched and the remaining tiers + // able to clear the benefit floor, drop T1 so the tier that actually + // delivers gets the slot. Below the floor the drop would suppress the + // whole nudge — keep the legacy behavior instead. + if ( + state.nudge.t1HarvestStall === true && + Math.max(t2Pen, t3Pen) >= minPressureBenefit + ) { + candidates.length = 0; + stallDroppedT1 = true; + } candidates.push(2, 3); } let best: CompressionTier | null = null; @@ -2183,7 +2235,7 @@ function decideNudge(input: NudgeInput): NudgeDecision { injectedReason = best === 1 ? `${label} T1: max effective pending ${bestPending}, usage ${Math.round(usage * 100)}%` - : `${label} T${best} distill: max pending ${bestPending} (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}), usage ${Math.round(usage * 100)}%`; + : `${label} T${best} distill: max pending ${bestPending} (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}), usage ${Math.round(usage * 100)}%${stallDroppedT1 ? " [T1 harvest stall]" : ""}`; } } else if (growthReady) { // Explicit count-triggered candidates (#509): reachable on the growth path @@ -2209,7 +2261,39 @@ function decideNudge(input: NudgeInput): NudgeDecision { } } } - if (countCandidates.length > 0) { + // T1 harvest-stall override (#5698): while the T1 channel demonstrably + // fails to deliver (last successful T1-shaped fold harvested below + // STALL_HARVEST_RATIO of the offered mass — partial compliance pins t1Eff + // high forever), a higher tier whose MASS leg crossed its OWN threshold + // takes the slot before T1 keeps firing into the same unresponsive + // channel. The legacy mass legs additionally demanded "> t1Eff", which + // made them structurally unreachable in this shape; the stall flag IS the + // evidence the lower channel cannot deliver, so the demand is dropped + // here and only here. Cadence rules unchanged; if neither higher tier is + // ready/cadence-open the cascade below runs legacy (stall only redirects + // when a delivering channel exists). Absent flag (legacy states) = + // byte-identical arbitration. + let stallChosen: CompressionTier | null = null; + let stallReason = ""; + if (config.tiers.enabled && state.nudge.t1HarvestStall === true) { + if (t2Pen >= tierThresholds[2]) { + const lastShown = state.nudge.lastShownByTier[2] ?? 0; + if (lastShown === 0 || tokenCount - lastShown >= growthFloor) { + stallChosen = 2; + stallReason = `T2 distill ready: ${tiers[2]!.targetBlocks.length} tier-1 blocks (${t2Pen} tokens) >= ${tierThresholds[2]}${config.nudge.tierGrowthTokens?.t2 === undefined ? " (1.5x)" : ""}, T1 effective ${t1Eff} [T1 harvest stall], usage ${Math.round(usage * 100)}%`; + } + } else if (t3Pen >= tierThresholds[3]) { + const lastShown = state.nudge.lastShownByTier[3] ?? 0; + if (lastShown === 0 || tokenCount - lastShown >= growthFloor) { + stallChosen = 3; + stallReason = `T3 condense ready: ${tiers[3]!.targetBlocks.length} tier-2 blocks (${t3Pen} tokens) >= ${tierThresholds[3]}${config.nudge.tierGrowthTokens?.t3 === undefined ? " (1.5x)" : ""}, T1 effective ${t1Eff} [T1 harvest stall], usage ${Math.round(usage * 100)}%`; + } + } + } + if (stallChosen !== null) { + injectedTier = stallChosen; + injectedReason = stallReason; + } else if (countCandidates.length > 0) { // Slot rotation (#509): T1 keeps first pick until it has gone // (lastInjectedTier !== 1 — fresh state, or the previous slot was a // distill); then the slot hands to a count-ready tier, oldest cadence diff --git a/kernel/src/state.ts b/kernel/src/state.ts index a5d53e6bf6..538e2d9344 100644 --- a/kernel/src/state.ts +++ b/kernel/src/state.ts @@ -16,6 +16,7 @@ export function createInitialState(): CompressionState { anchors: {}, lastShownByTier: {}, lastInjectedTier: null, + t1HarvestStall: false, }, stats: { tokensCompressed: 0, diff --git a/kernel/src/types.ts b/kernel/src/types.ts index 05c41b1824..4f2831f972 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -155,6 +155,23 @@ export interface NudgeState { * by applyCompression alongside the other baselines. */ absorbedDebt?: number; absorbCount?: number; + + /** #5698: the raw T1 pending mass (decision breakdown.pendingT1) recorded + * when the most recent T1 nudge fired (growth or pressure path). Consumed + * by the next successful applyCompression, which compares its own + * tokensCompressed against it to set or clear t1HarvestStall — this is how + * partial compliance ("every nudge folds only a few K") becomes measurable + * as T1-channel ineffectiveness instead of invisible. Optional for + * pre-#5698 persisted states (absent = nothing armed = no measurement). */ + lastT1FirePending?: number; + /** #5698: latched by applyCompression when the last successful T1-shaped + * fold harvested less than STALL_HARVEST_RATIO of the offered mass. While + * set, decideNudge routes the growth-path slot to a higher tier whose MASS + * leg crossed its own threshold (dropping the legacy "> t1Eff" demand) and + * removes T1 from the pressure candidates whenever the remaining tiers can + * clear minPressureBenefit. Cleared by a harvest at/above the ratio or by a + * distillation fold. Optional (absent = false = legacy arbitration). */ + t1HarvestStall?: boolean; } export interface CompressionStats { diff --git a/kernel/tests/nudge.test.ts b/kernel/tests/nudge.test.ts index 6670d647c3..0fa075ed93 100644 --- a/kernel/tests/nudge.test.ts +++ b/kernel/tests/nudge.test.ts @@ -2104,3 +2104,262 @@ test("nudge: first-sight bypass falls silent once usage drops below the band (#1 "20% < 45% band → drain complete, pacing resumes", ); }); + +// --------------------------------------------------------------------------- +// T1 harvest-stall detection (#5698) +// +// Mass model: each makeMessages message ≈ 5000 tokens (20000 chars / 4); +// block summary mass = summaryChars / 4. Under buildConfig the derived +// thresholds are T1 = 6000, T2/T3 = 9000 (1.5x), growthFloor = 5000, +// minPressureBenefit = 5000. The shared fixture below reproduces the +// production starvation shape: a mass-ready T2 (10000 tokens of tier-1 +// summaries) sitting behind a persistently high T1 effective pending +// (~50K of raw compressible messages) — where the legacy cascade's +// "> t1Eff" demand makes the T2 mass leg structurally unreachable. +// --------------------------------------------------------------------------- + +type StallCore = ReturnType; + +function stallFixture( + core: StallCore, + overrides: Partial = {}, +): { config: Config; messages: CoreMessage[]; state: CompressionState } { + const config = buildConfig({ + tiers: { enabled: true, tier2Trigger: 1000, tier3Trigger: 2000 }, + compress: { minCompressRange: 5000, maxSummaryLength: 0, minSummaryLength: 0 }, + ...overrides, + }); + const messages = makeMessages(14); + let state = createInitialState(); + state = core.processTurn({ messages, state, config, tokenCount: 10000 }).state; + // Four T1 blocks anchored to m0..m3 (they cover those messages): 10000-char + // summaries each → T2 pending 4 × 2500 = 10000 >= 9000. m4..m13 stay raw + // (~50K) so T1 effective keeps clearing its own 6000 threshold forever. + // nextBlockId advances past the injected ids — block ids are never reused + // (kernel contract), so real folds must not collide with b1..b4. + state = { + ...state, + nextBlockId: 5, + blocks: t1Blocks([["m0"], ["m1"], ["m2"], ["m3"]], 10000), + }; + return { config, messages, state }; +} + +/** Drive one T1 nudge fire (arming the harvest measurement), return state. */ +function armT1Fire( + core: StallCore, + config: Config, + messages: CoreMessage[], + state: CompressionState, +): CompressionState { + const turn = core.processTurn({ messages, state, config, tokenCount: 55000 }); + if (turn.nudge.tier !== 1 || !turn.nudge.shouldInject) { + throw new Error(`expected a T1 arm fire, got tier=${turn.nudge.tier} inject=${turn.nudge.shouldInject}: ${turn.nudge.reason}`); + } + return turn.state; +} + +/** One lazy fold: a single ~5K message of the ~50K offered. */ +function lazyFold( + core: StallCore, + config: Config, + messages: CoreMessage[], + state: CompressionState, +): CompressionState { + return core.applyCompression({ + ranges: [{ startRef: "m00005", endRef: "m00005", summary: "one small fold" }], + messages, + state, + config, + }).state; +} + +test("harvest-stall: lazy partial folds latch the stall and hand the slot to mass-ready T2 (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + const s1 = armT1Fire(core, config, messages, s0); + assert.ok( + (s1.nudge.lastT1FirePending ?? 0) > 0, + "the T1 fire arms the offered-mass measurement", + ); + const s2 = lazyFold(core, config, messages, s1); + assert.equal(s2.nudge.t1HarvestStall, true, "harvest << 50% of offered latches the stall"); + assert.equal(s2.nudge.lastT1FirePending, undefined, "measurement is consume-once"); + const turn = core.processTurn({ messages, state: s2, config, tokenCount: 56000 }); + assert.equal(turn.nudge.shouldInject, true); + assert.equal( + turn.nudge.tier, + 2, + "stalled T1 yields the slot to the mass-ready T2 instead of re-firing into the same channel", + ); + assert.match(turn.nudge.reason, /\[T1 harvest stall\]/); +}); + +test("harvest-stall: full compliance (>= 50% harvest) never latches — T1 keeps the slot (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + const s1 = armT1Fire(core, config, messages, s0); + const s2 = core.applyCompression({ + ranges: [{ startRef: "m00005", endRef: "m00012", summary: "eager batch fold" }], + messages, + state: s1, + config, + }).state; + assert.equal(s2.nudge.t1HarvestStall, false, "a delivering channel clears/never sets the stall"); + const turn = core.processTurn({ messages, state: s2, config, tokenCount: 56000 }); + assert.equal(turn.nudge.shouldInject, true); + assert.equal(turn.nudge.tier, 1, "no stall → legacy T1-first arbitration unchanged"); +}); + +test("harvest-stall: a distillation fold clears a latched stall regardless of ratio (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + const s1 = armT1Fire(core, config, messages, s0); + const s2 = lazyFold(core, config, messages, s1); + assert.equal(s2.nudge.t1HarvestStall, true); + const s3 = core.applyCompression({ + ranges: [{ startRef: "b1", endRef: "b4", summary: "tier-2 distillation" }], + messages, + state: s2, + config, + }).state; + assert.equal(s3.nudge.t1HarvestStall, false, "progress on the higher tiers clears the stall"); + const turn = core.processTurn({ messages, state: s3, config, tokenCount: 56000 }); + assert.equal(turn.nudge.shouldInject, true); + assert.equal(turn.nudge.tier, 1, "stall cleared → T1 may take the slot again"); +}); + +test("harvest-stall: legacy persisted state without the flag keeps byte-identical arbitration (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + // Simulate a pre-#5698 snapshot restored mid-session: neither stall field + // exists at all, and the timing stamps read like a just-compressed session + // (so first-sight mass is ready and arbitration is actually reached). + const legacy: CompressionState = { + ...s0, + nudge: { + ...s0.nudge, + lastPerMessageNudgeTokens: 0, + lastNudgeShownTokens: 0, + }, + }; + delete legacy.nudge.t1HarvestStall; + delete legacy.nudge.lastT1FirePending; + const turn = core.processTurn({ messages, state: legacy, config, tokenCount: 56000 }); + assert.equal(turn.nudge.shouldInject, true); + assert.equal( + turn.nudge.tier, + 1, + "absent flag = no stall evidence = legacy T1-first short-circuit (t2Pen 10000 >= 9000 stays unreachable)", + ); + assert.doesNotMatch(turn.nudge.reason, /\[T1 harvest stall\]/); +}); + +test("harvest-stall: pressure band drops T1 from candidates when the remaining tiers clear the benefit floor (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + const s1 = armT1Fire(core, config, messages, s0); + const s2 = lazyFold(core, config, messages, s1); + assert.equal(s2.nudge.t1HarvestStall, true); + const turn = core.processTurn({ messages, state: s2, config, tokenCount: 95000 }); + assert.equal(turn.nudge.shouldInject, true, "95% usage sits in the pressure band"); + assert.equal( + turn.nudge.tier, + 2, + "max-pending arbitration would pick T1 (~45K) — the stall drops it for the delivering T2", + ); + assert.match(turn.nudge.reason, /\[T1 harvest stall\]/); +}); + +test("harvest-stall: pressure band keeps T1 when the remaining tiers cannot clear the benefit floor (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + const s1 = armT1Fire(core, config, messages, s0); + const s2 = lazyFold(core, config, messages, s1); + // Shrink the tier-1 backlog below the 5000-token benefit floor: dropping T1 + // here would suppress the whole nudge, so legacy behavior must win. + const pair = t1Blocks([["m0"], ["m1"]], 8000); + const s3: CompressionState = { + ...s2, + blocks: [ + { ...s2.blocks[s2.blocks.length - 1]!, active: true }, + ...pair, + ], + }; + const turn = core.processTurn({ messages, state: s3, config, tokenCount: 95000 }); + assert.equal(turn.nudge.shouldInject, true); + assert.equal( + turn.nudge.tier, + 1, + "stall below the benefit floor must NOT suppress the only actionable channel", + ); + assert.doesNotMatch(turn.nudge.reason, /\[T1 harvest stall\]/); +}); + +test("harvest-stall: the stall redirect still respects per-tier cadence (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + const s1 = armT1Fire(core, config, messages, s0); + const s2 = lazyFold(core, config, messages, s1); + assert.equal(s2.nudge.t1HarvestStall, true); + // Stamp T2 as having fired 100 tokens ago (< growthFloor 5000). + const s3: CompressionState = { + ...s2, + nudge: { ...s2.nudge, lastShownByTier: { ...s2.nudge.lastShownByTier, 2: 55900 } }, + }; + const turn = core.processTurn({ messages, state: s3, config, tokenCount: 56000 }); + assert.equal(turn.nudge.shouldInject, true); + assert.equal( + turn.nudge.tier, + 1, + "cadence-unmet T2 falls back to the legacy cascade (T1 fires, as before)", + ); +}); + +test("harvest-stall: no-op calls are not evidence — the armed measurement survives until a real fold (#5698)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core); + const s1 = armT1Fire(core, config, messages, s0); + const armedBefore = s1.nudge.lastT1FirePending ?? 0; + assert.ok(armedBefore > 0); + // Target a range already covered by the injected T1 blocks → consumed skip. + const noop = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00002", summary: "already folded" }], + messages, + state: s1, + config, + }); + assert.equal(noop.result.blocksCreated, 0, "covered range commits nothing"); + assert.equal(noop.result.noop, true); + assert.equal( + noop.state.nudge.lastT1FirePending, + armedBefore, + "a no-op leaves the armed measurement in place", + ); + assert.notEqual(noop.state.nudge.t1HarvestStall, true, "no evidence yet, no latch"); + const s2 = lazyFold(core, config, messages, noop.state); + assert.equal(s2.nudge.t1HarvestStall, true, "the first REAL fold measures and latches"); +}); + +test("harvest-stall: explicit count triggers keep working independently of the stall flag (#5698 × #509)", () => { + const core = createCore(); + const { config, messages, state: s0 } = stallFixture(core, { + tiers: { enabled: true, tier2Trigger: 3, tier3Trigger: 2000 }, + }); + // Shrink the tier-1 backlog to THREE blocks whose summaries total well below + // the 9000-token mass threshold (3 × 1000 = 3000) — mass leg NOT ready, + // count leg IS (3 >= tier2Trigger 3). + const small = t1Blocks([["m0"], ["m1"], ["m2"]], 4000); + const sA: CompressionState = { ...s0, blocks: small }; + const s1 = armT1Fire(core, config, messages, sA); + const s2 = lazyFold(core, config, messages, s1); + assert.equal(s2.nudge.t1HarvestStall, true); + const turn = core.processTurn({ messages, state: s2, config, tokenCount: 56000 }); + assert.equal(turn.nudge.shouldInject, true); + assert.equal( + turn.nudge.tier, + 2, + "count-ready T2 reaches the slot through the #509 pool even though the stall mass leg is not ready", + ); + assert.doesNotMatch(turn.nudge.reason, /\[T1 harvest stall\]/); +}); diff --git a/package-lock.json b/package-lock.json index 2ce6f14148..74d37a2968 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.180", + "version": "0.0.181", "dev": true, "license": "MIT", "devDependencies": { From cff2d7928633586a9de5200f73981227ee26f081 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 5 Nov 2026 12:05:23 +0800 Subject: [PATCH 6/8] fix(#5698): sync kernel lockfile version echo after the 0.0.181 bump MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The nudge-slot-rotation change bumped kernel/package.json to 0.0.181 but left kernel/package-lock.json echoing 0.0.180. lock-sync regenerates the kernel lockfile (npm install --package-lock-only) and fails on any drift, so the job went red. Regenerate so the two version fields agree again. Pure lockfile sync — no dependency or semantic change. --- kernel/package-lock.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kernel/package-lock.json b/kernel/package-lock.json index f7b4086762..afce17e85d 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.180", + "version": "0.0.181", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.180", + "version": "0.0.181", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", From fcf1e080db9cc9c735f63076e4f1ac3b321176aa Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 5 Nov 2026 12:50:17 +0800 Subject: [PATCH 7/8] kernel: store T1 harvest-stall state absent-only to keep snapshots stable (#5698) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A stored false serializes into every measured session's persisted nudge state and drifts the storage-render goldens for zero information; an initializer in createInitialState did the same for fresh sessions. Absent-only storage: a latch stores true, a clear deletes the key (the createInitialState default is likewise omitted). Consumers already test === true, so behavior is unchanged and feature-inactive snapshots stay byte-identical to pre-feature ones — no golden regeneration needed. --- kernel/src/compress.ts | 14 +++++++------- kernel/src/state.ts | 7 ++++++- kernel/src/types.ts | 4 +++- kernel/tests/nudge.test.ts | 4 ++-- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/kernel/src/compress.ts b/kernel/src/compress.ts index 8f4c9187df..2cd741b74b 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -883,16 +883,16 @@ export function createCore(ports: Ports = {}): CompressionCore { const producedDistillation = state.blocks.some( (b) => !preFoldBlockIds.has(b.blockId) && b.tier >= 2, ); - if (producedDistillation) { - // Progress on the higher tiers clears the latch even when no T1 fire - // is being measured right now — the channel moved where it counts. - state.nudge.t1HarvestStall = false; - } const armedT1Pending = state.nudge.lastT1FirePending; state.nudge.lastT1FirePending = undefined; + // Absent-only storage (#5698): "no stall" is the ABSENCE of the key, never a stored + // false — a stored false would serialize into every measured session's snapshot + // and drift the persistence goldens for zero information. if (!producedDistillation && armedT1Pending !== undefined && armedT1Pending > 0) { - state.nudge.t1HarvestStall = - tokensCompressed / armedT1Pending < STALL_HARVEST_RATIO; + if (tokensCompressed / armedT1Pending < STALL_HARVEST_RATIO) state.nudge.t1HarvestStall = true; + else delete state.nudge.t1HarvestStall; + } else if (producedDistillation) { + delete state.nudge.t1HarvestStall; } // A successful compression is by definition viable progress — restart // the terminal-floor streak so the escape signal can only fire again diff --git a/kernel/src/state.ts b/kernel/src/state.ts index 538e2d9344..7cd03454ab 100644 --- a/kernel/src/state.ts +++ b/kernel/src/state.ts @@ -16,7 +16,12 @@ export function createInitialState(): CompressionState { anchors: {}, lastShownByTier: {}, lastInjectedTier: null, - t1HarvestStall: false, + // #5698: t1HarvestStall / lastT1FirePending are deliberately NOT + // initialized — absent (undefined) is the legacy/never-measured state, + // and undefined keys drop out of persisted snapshots entirely, so a + // fresh session stays byte-identical to pre-#5698 until the stall + // actually latches. (A `false` default would serialize and drift the + // storage-render goldens.) }, stats: { tokensCompressed: 0, diff --git a/kernel/src/types.ts b/kernel/src/types.ts index 4f2831f972..0342196562 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -170,7 +170,9 @@ export interface NudgeState { * leg crossed its own threshold (dropping the legacy "> t1Eff" demand) and * removes T1 from the pressure candidates whenever the remaining tiers can * clear minPressureBenefit. Cleared by a harvest at/above the ratio or by a - * distillation fold. Optional (absent = false = legacy arbitration). */ + * distillation fold. Optional, absent-only storage: a latch stores true, a clear + * DELETES the key rather than storing false, so feature-inactive snapshots stay + * byte-identical to pre-#5698 ones. Absent = no stall = legacy arbitration. */ t1HarvestStall?: boolean; } diff --git a/kernel/tests/nudge.test.ts b/kernel/tests/nudge.test.ts index 0fa075ed93..2c023827fc 100644 --- a/kernel/tests/nudge.test.ts +++ b/kernel/tests/nudge.test.ts @@ -2205,7 +2205,7 @@ test("harvest-stall: full compliance (>= 50% harvest) never latches — T1 keeps state: s1, config, }).state; - assert.equal(s2.nudge.t1HarvestStall, false, "a delivering channel clears/never sets the stall"); + assert.equal(s2.nudge.t1HarvestStall, undefined, "a delivering channel clears/never sets the stall"); const turn = core.processTurn({ messages, state: s2, config, tokenCount: 56000 }); assert.equal(turn.nudge.shouldInject, true); assert.equal(turn.nudge.tier, 1, "no stall → legacy T1-first arbitration unchanged"); @@ -2223,7 +2223,7 @@ test("harvest-stall: a distillation fold clears a latched stall regardless of ra state: s2, config, }).state; - assert.equal(s3.nudge.t1HarvestStall, false, "progress on the higher tiers clears the stall"); + assert.equal(s3.nudge.t1HarvestStall, undefined, "progress on the higher tiers clears the stall"); const turn = core.processTurn({ messages, state: s3, config, tokenCount: 56000 }); assert.equal(turn.nudge.shouldInject, true); assert.equal(turn.nudge.tier, 1, "stall cleared → T1 may take the slot again"); From 6cbffcddea5fba643ab254def945f1ab22dcd367 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 5 Nov 2026 14:01:44 +0800 Subject: [PATCH 8/8] kernel: store lastInjectedTier absent-only so re-hydrated snapshots stay stable (#5698) The #509 rotation memory was initialized to null in createInitialState. Newer master hydration fills missing nudge keys from the fresh defaults, so every re-hydrated legacy session picked up nudge.lastInjectedTier=null and all nine storage-corpus digest pins drifted (folded/twinfile/zstd red in CI). The sole reader already normalizes via (lastInjectedTier ?? null), so dropping the initializer is behavior-neutral: absent = never injected = legacy T1-first, and undefined keys drop out of persisted snapshots. --- kernel/src/state.ts | 14 +++++++------- kernel/src/types.ts | 17 ++++++++++------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/kernel/src/state.ts b/kernel/src/state.ts index 7cd03454ab..ead01c9cae 100644 --- a/kernel/src/state.ts +++ b/kernel/src/state.ts @@ -15,13 +15,13 @@ export function createInitialState(): CompressionState { baselineTokens: 0, anchors: {}, lastShownByTier: {}, - lastInjectedTier: null, - // #5698: t1HarvestStall / lastT1FirePending are deliberately NOT - // initialized — absent (undefined) is the legacy/never-measured state, - // and undefined keys drop out of persisted snapshots entirely, so a - // fresh session stays byte-identical to pre-#5698 until the stall - // actually latches. (A `false` default would serialize and drift the - // storage-render goldens.) + // #509/#5698: lastInjectedTier, t1HarvestStall and lastT1FirePending are + // deliberately NOT initialized — absent (undefined) is the legacy / + // never-measured state, and undefined keys drop out of persisted + // snapshots entirely, so a fresh or re-hydrated session stays + // byte-identical to pre-feature until the mechanism actually fires. + // (A stored null/false default serializes into every snapshot and + // drifts the storage-corpus + storage-render golden pins.) }, stats: { tokensCompressed: 0, diff --git a/kernel/src/types.ts b/kernel/src/types.ts index 0342196562..4c0b37b313 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -133,13 +133,16 @@ export interface NudgeState { * tiers. Using a record (not N named fields) so adding tier 4+ needs no * schema change. */ lastShownByTier: Record; - /** Last tier that received a nudge slot (growth or pressure path). Unlike - * lastShownByTier this is NOT cleared by a successful applyCompression: it - * is the rotation memory that keeps an explicitly configured - * tier2Trigger/tier3Trigger alternating with T1 instead of being starved by - * a persistently high T1 pending (#509). Optional for pre-#509 persisted - * states (absent = null = legacy T1-first). */ - lastInjectedTier?: CompressionTier | null; + /** Last tier that received a nudge slot (growth or pressure path). Unlike + * lastShownByTier this is NOT cleared by a successful applyCompression: it + * is the rotation memory that keeps an explicitly configured + * tier2Trigger/tier3Trigger alternating with T1 instead of being starved by + * a persistently high T1 pending (#509). Absent-only storage: a slot stamp + * writes the actual tier and nothing ever stores null — absent = never + * injected = legacy T1-first (the sole reader normalizes undefined via + * `?? null`). A stored null default would serialize into every re- + * hydrated snapshot and drift the storage-corpus pins. */ + lastInjectedTier?: CompressionTier | null; /** #5415: growth debt + absorb count booked by the host's #5293 * abort-absorb. absorbAbortedTurnGrowth() re-anchors the reference to