Skip to content
Open
2 changes: 1 addition & 1 deletion kernel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion kernel/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
151 changes: 149 additions & 2 deletions kernel/src/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
);
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) {
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
// after N fresh stuck events (#300).
Expand Down Expand Up @@ -1483,6 +1515,15 @@ 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;
// 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;
}
}
}

Expand Down Expand Up @@ -2066,6 +2107,13 @@ function decideNudge(input: NudgeInput): NudgeDecision {
// 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(
nudgeGrowthTokens * (config.nudge.tier2GrowthMultiplier ?? 1.5),
);
Expand Down Expand Up @@ -2153,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;
Expand All @@ -2173,10 +2235,95 @@ 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) {
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);
}
}
}
// 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
// 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 (
Expand Down
7 changes: 7 additions & 0 deletions kernel/src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ export function createInitialState(): CompressionState {
baselineTokens: 0,
anchors: {},
lastShownByTier: {},
// #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,
Expand Down
40 changes: 37 additions & 3 deletions kernel/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,17 @@ export interface NudgeState {
* tiers. Using a record (not N named fields) so adding tier 4+ needs no
* schema change. */
lastShownByTier: Record<number, number>;
/** 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
* the current meter, which skips not just the aborted turn's unreported
Expand All @@ -147,6 +158,25 @@ 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-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;
}

export interface CompressionStats {
Expand Down Expand Up @@ -407,11 +437,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;
}

Expand Down
Loading
Loading