Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/dead-ranges.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { markDirty, type Session } from "./session.js";

// #2638: session-level memory of spans whose preflight preview returned the kernel's
// STRUCTURAL "no new compressible messages" verdict. The kernel keeps advertising such spans
// (its recommend side does not mirror applySingleRange's live-carrier carve-out — see the
// issue for the minimal geometry), so without this memory every request re-nominates and
// re-rejects them: wasted preview work, warn spam, and — because the span's mass can never
// fold through plain refs — an auto-fold no-progress backoff cycle that resurrects classic
// nudges pointing the model at the same dead span. Entries are keyed by the exact
// startRef:endRef the kernel resolved; chunk-boundary shifts across turns self-heal through
// one extra preview (record again), and the cap bounds total memory.

const MAX_DEAD_RANGES = 64;
const STORAGE_KEY = "preflightDeadRanges";

interface DeadRangeEntry {
key: string;
startRef: string;
endRef: string;
/** Block ids named in the verdict ("covered by active block(s) b3, b5") — diagnostics
* only; invalidation deliberately does NOT trust the name list (see activeSnapshot). */
blocks: string[];
/** Sorted active block ids at record time. The entry stays dead only while EVERY one of
* them is still active (subsumption). */
activeSnapshot: string[];
}

function readStore(session: Session): DeadRangeEntry[] {
const raw = session.metadata?.[STORAGE_KEY];
if (!Array.isArray(raw)) return [];
return raw.filter((e): e is DeadRangeEntry =>
!!e && typeof e === "object"
&& typeof (e as DeadRangeEntry).key === "string"
&& typeof (e as DeadRangeEntry).startRef === "string"
&& typeof (e as DeadRangeEntry).endRef === "string"
&& Array.isArray((e as DeadRangeEntry).blocks)
&& Array.isArray((e as DeadRangeEntry).activeSnapshot));
}

function writeStore(session: Session, store: DeadRangeEntry[]): void {
(session.metadata ?? (session.metadata = {}))[STORAGE_KEY] = store;
markDirty(session);
}

function activeBlockIds(session: Session): string[] {
return session.state.blocks.filter((b) => b.active).map((b) => b.blockId).sort();
}

/** Both structural-empty wordings the kernel emits for a span with zero foldable content:
* - the #199 livelock guard: "...contains no new compressible messages — every message in it
* is already covered by active block(s) b3..."
* - validateCompressionRange: "Range contains no compressible messages — all are already
* covered by active blocks or protected."
* Returns the named covering blocks ([] for the unnamed variant); null when the verdict is
* NOT structural-empty — transient, zone, min-gate and length rejections must stay retryable
* (they can clear mid-invocation or next turn). Feed the RAW kernel error strings, not a
* truncated/joined rendering: the named-block list must survive intact. */
export function parseStructuralEmptyVerdict(verdict: string): string[] | null {
if (!/no (?:new )?compressible messages/.test(verdict)) return null;
const named = /active block\(s\) ([A-Za-z0-9]+(?:,\s*[A-Za-z0-9]+)*)/.exec(verdict)?.[1] ?? "";
return named ? named.split(/,\s*/).filter(Boolean) : [];
}

export function recordDeadRange(session: Session, startRef: string, endRef: string, namedBlocks: string[]): void {
const key = `${startRef}:${endRef}`;
const store = readStore(session).filter((e) => e.key !== key);
store.push({ key, startRef, endRef, blocks: namedBlocks, activeSnapshot: activeBlockIds(session) });
while (store.length > MAX_DEAD_RANGES) store.shift();
writeStore(session, store);
}

/** Keys still dead under the current state. Prunes invalidated entries in place.
*
* Invalidation is SNAPSHOT SUBSUMPTION, not the verdict's name list: the livelock guard names
* only the NESTED blocks whose coverage made the span empty, but the span's deadness also
* rests on whatever else carved its members out — notably LIVE CARRIER blocks (a checkpoint
* message's summaryOfBlockId target must stay active or the carrier becomes plain-foldable
* again), and those targets are never named in the verdict. Any active block dying anywhere
* in the session (consumed by a distillation, deactivated, expanded) therefore wakes every
* entry conservatively; append-only message growth never does, and a false wake costs exactly
* one CPU-only preview before the entry re-records itself. */
export function deadSkipKeys(session: Session): Set<string> {
const current = new Set(activeBlockIds(session));
const seen = readStore(session);
const kept = seen.filter((e) => e.activeSnapshot.every((id) => current.has(id)));
if (kept.length !== seen.length) writeStore(session, kept);
return new Set(kept.map((e) => e.key));
}

/** Drop remembered-dead ranges from an advertised list (nudge surface, preflight candidates).
* Exact key match only — a wider advertised range that merely CONTAINS a dead chunk stays:
* its live members outside the chunk are genuinely foldable. */
export function filterDeadRanges<T extends { startRef: string; endRef: string }>(session: Session, ranges: readonly T[]): T[] {
const dead = deadSkipKeys(session);
return ranges.filter((r) => !dead.has(`${r.startRef}:${r.endRef}`));
}
53 changes: 48 additions & 5 deletions src/preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { fetchWithTimeout, isTransientUpstreamError, replayMaxAttempts, replayBa
import { dumpSummaryRejection } from "./error-dump.js";
import { proxyDispatcher } from "./upstream-proxy.js";
import { lastCompressSuffix, type Session } from "./session.js";
import { deadSkipKeys, filterDeadRanges, parseStructuralEmptyVerdict, recordDeadRange } from "./dead-ranges.js";
import { peekRegistryOutputLimit } from "./registry.js";
import { safePrefix } from "./text-safe.js";
import { applyEstimateCalibration, currentCalibrationFactor } from "./util.js";
Expand Down Expand Up @@ -257,6 +258,12 @@ export interface PreflightResult {
/** Why the loop stopped while the payload still overflows the window.
* Undefined when the payload fits. */
failure?: PreflightFailure;
/** #2638: some round saw at least one range that passed every list-level gate
* (viability, minCompressRange, dead-range memory). The caller uses it to tell a
* failed fold chain (candidates existed, none delivered — backoff is right) from
* lean steady state (nothing foldable remained at all — arming the auto-fold
* backoff would only cycle classic nudges at dead spans). */
hadFoldableCandidates: boolean;
}

function refMaps(messages: CoreMessage[], state: Session["state"]): { refToIdx: Map<string, number>; idxToRef: Map<number, string> } {
Expand Down Expand Up @@ -1223,7 +1230,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
const kFactor = currentCalibrationFactor(deps.session.stats, deps.session.metadata?.lastModel);
const kOrigin = deps.session.stats.calibratedEstimateOrigin;
let textTarget = Math.max(0, Math.min(limit, deps.compressionTarget ?? limit) - imageReserve);
const result: PreflightResult = { compressedRanges: 0, savedTokens: 0, payloadEstimate: applyEstimateCalibration(estimateCoreMessages(messages) + wireOverhead, kFactor, kOrigin, deps.upstreamOrigin) + imageReserve, rangesRemaining: 0, fitsWindow: true };
const result: PreflightResult = { compressedRanges: 0, savedTokens: 0, payloadEstimate: applyEstimateCalibration(estimateCoreMessages(messages) + wireOverhead, kFactor, kOrigin, deps.upstreamOrigin) + imageReserve, rangesRemaining: 0, fitsWindow: true, hadFoldableCandidates: false };
if (limit <= 0) return result;
if (deps.externalSummary === undefined) {
try {
Expand Down Expand Up @@ -1268,6 +1275,11 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
// skipSet keys are stable across folds because refs are content-fingerprinted,
// so a range found unusable is never retried within this invocation.
const skipSet = new Set<string>();
// #2638: seed with the session-level memory of spans whose previews returned a
// structural "no new compressible messages" verdict — without this, every request
// re-nominates and re-rejects them (the permanent rejection loop). The kernel keeps
// advertising them, so the list-level filter below and this seed share one source.
for (const key of deadSkipKeys(deps.session)) skipSet.add(key);
// #1372: every silent skip leaves a trace — preflight and the plugin compress
// path judge the same range at different pipeline positions, so their verdicts
// can legitimately diverge; recording where+why makes the divergence diffable.
Expand All @@ -1276,6 +1288,8 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
if (skipReasons.length < 8 && !skipReasons.includes(reason)) skipReasons.push(safePrefix(reason, 200));
};
let subMinNoted = false;
let deadNoted = false;
let deadDroppedTotal = 0;
let summaryCalls = 0;
let budgetHit = false;
let transientRetryBudget = TRANSIENT_EMPTY_RETRY_BUDGET;
Expand Down Expand Up @@ -1375,16 +1389,31 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
// rounds and misreports "N viable ranges tried"; with them gone the
// empty-list path below can reach the #330 soft-zone relaxation.
const viable = viableRanges(turn.nudge?.compressibleRanges ?? []);
const ranges = viable.filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars);
const aboveMin = viable.filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars);
// #2638: spans whose previews returned a structural "no new compressible
// messages" verdict can never fold through plain refs — the kernel keeps
// advertising them, so without this filter every round re-walks and
// re-previews them. Exact key match only: a wider range that merely
// contains a dead chunk keeps its live members.
let ranges = filterDeadRanges(deps.session, aboveMin);
const deadDropped = aboveMin.length - ranges.length;
if (deadDropped > 0) {
deadDroppedTotal += deadDropped;
if (!deadNoted) {
deadNoted = true;
deps.log("debug", `[preflight] ${deadDropped} candidate range(s) suppressed: previously-dead structural verdicts (#2638)`);
}
}
// #1372: the list-level minCompressRange filter used to drop sub-minimum
// ranges silently — "no compressible ranges remain" gave no hint that
// ranges existed but were all under the gate.
if (ranges.length === 0 && viable.length > 0 && !subMinNoted) {
if (ranges.length === 0 && aboveMin.length === 0 && viable.length > 0 && !subMinNoted) {
subMinNoted = true;
deps.log("warn", `[preflight] ${viable.length} viable range(s) are below minCompressRange (${minChars} chars); none foldable`);
noteSkip(`all ${viable.length} viable range(s) below minCompressRange (${minChars} chars)`);
}
rangesRemaining = ranges.length;
if (ranges.length > 0) result.hadFoldableCandidates = true;
if (baselineKnown && ranges.length > 0) {
// #1841: round-level futility gate. A fold removes its span's mass
// at best (its summary re-enters the payload), so the sum of all
Expand Down Expand Up @@ -1429,7 +1458,8 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
renderTags: "text-only",
contentStore: contentStoreOf(deps.session),
});
const relaxedRanges = viableRanges(probe.nudge?.compressibleRanges ?? []).filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars);
// #2638: structural verdicts hold under relax too (coverage-based, zone-independent) — dead mass cannot close the gap either.
const relaxedRanges = filterDeadRanges(deps.session, viableRanges(probe.nudge?.compressibleRanges ?? []).filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars));
const relaxedPotential = resolvableMass(relaxedRanges);
if (relaxedPotential * FUTILITY_SLACK >= deficit) {
activeConfig = relaxedConfig(deps.config);
Expand Down Expand Up @@ -1473,7 +1503,9 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
}
failure = { kind: "exhausted", detail: relaxed ? relaxedExhaustedDetail : subMinNoted
? `no foldable compressible ranges remain: all ${viable.length} viable range(s) are below minCompressRange (${minChars} chars)`
: "no compressible ranges remain in the conversation" };
: deadNoted
? `no foldable compressible ranges remain: ${deadDroppedTotal} range(s) carry previously-dead structural verdicts (#2638)`
: "no compressible ranges remain in the conversation" };
break;
}
const ordered = [...ranges].sort((a, b) => refNum(a.startRef) - refNum(b.startRef));
Expand Down Expand Up @@ -1588,6 +1620,17 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
|| "the kernel created no block and reported no error";
deps.log("warn", `[preflight] preview rejected range ${skipKey}: ${verdict}`);
noteSkip(`${skipKey}: preview rejected — ${verdict}`);
// #2638: ONLY the structural "no new compressible messages" verdicts are
// regime-independent — coverage-based, they hold under the #330 relax flip
// too, so the span is skipped for the rest of this invocation and
// remembered across invocations. Zone/min-gate/length verdicts can clear
// mid-invocation (relax, newer messages) and stay retryable. Raw errors,
// not the truncated verdict: the named-block list must survive intact.
const named = parseStructuralEmptyVerdict(preview.result.errors.join("\n"));
if (named !== null) {
skipSet.add(skipKey);
recordDeadRange(deps.session, startRef, endRef, named);
}
continue;
}
// Direct raw messages render host-side: #781 image notes live in BiliMessage
Expand Down
29 changes: 23 additions & 6 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2812,9 +2812,19 @@ export async function preflightCompressIfNeeded(
// and no recovery (PR #2581 review) — now the straddle arms too, and
// the forwarded request's 400 arms overflow-shrink with real evidence.
if (growthArmed) {
log("warn", `[${session.id}] auto-fold made no progress (0 range(s) folded) — forwarding as-is (estimate fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS / 60_000)}m so classic nudges resume`);
armAutoFoldBackoff(session);
markDirty(session);
if (result.hadFoldableCandidates) {
log("warn", `[${session.id}] auto-fold made no progress (0 range(s) folded) — forwarding as-is (estimate fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS / 60_000)}m so classic nudges resume`);
armAutoFoldBackoff(session);
markDirty(session);
} else {
// #2638: lean steady state — no candidate ever passed the list gates
// (advertised spans carry remembered structural dead verdicts / are
// sub-minimum), so zero progress is EXPECTED and a dead chain is not the
// cause. Arming the cooldown here cycled classic nudges at the same dead
// spans every AUTO_FOLD_BACKOFF_MS (the issue's nudge churn); forward
// quietly — the next growth turn re-evaluates from live state.
log("info", `[${session.id}] auto-fold steady state: payload fits and no foldable candidates remained — forwarding as-is without backoff (#2638)`);
}
} else {
log("warn", `[${session.id}] preflight made no progress but the payload fits; forwarding as-is`);
}
Expand All @@ -2832,9 +2842,16 @@ export async function preflightCompressIfNeeded(
// never armed for growth: the key comparison paths above returned
// earlier, and the contentDeadEnd arm below is unreachable from here).
if (growthArmed && payloadFitsWindow) {
log("warn", `[${session.id}] auto-fold did not reach the growth target ${compressionTarget} (${result.compressedRanges} range(s) folded) — forwarding anyway (payload fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS / 60_000)}m so classic nudges resume`);
armAutoFoldBackoff(session);
markDirty(session);
if (result.hadFoldableCandidates) {
log("warn", `[${session.id}] auto-fold did not reach the growth target ${compressionTarget} (${result.compressedRanges} range(s) folded) — forwarding anyway (payload fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS / 60_000)}m so classic nudges resume`);
armAutoFoldBackoff(session);
markDirty(session);
} else {
// #2638: same lean-steady-state distinction as the fits branch above — no
// foldable candidate existed, so the unreachable target is a property of the
// session state, not of the chain; do not cycle nudges at dead spans.
log("info", `[${session.id}] auto-fold steady state: growth target ${compressionTarget} unreachable while nothing foldable remained (${result.compressedRanges} range(s) folded) — forwarding anyway (payload fits the model window ${limit}) without backoff (#2638)`);
}
return outbound;
}
// #1800: still over-window after compression, but the residual excess is carried
Expand Down
4 changes: 3 additions & 1 deletion src/server/prepare-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, dropRetri
import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote } from "../image-compress.js";
import { rulesEnabled, storeEffectiveRules } from "../rules-feature.js";
import { autoFoldEngaged, externalSummaryEnabled, growthFoldingArmed } from "../external-summary-surface.js";
import { filterDeadRanges } from "../dead-ranges.js";
import { attachSubagentSessions } from "../subagent-sessions.js";
import { estimateCoreMessages, estimateCoreMessagesUpper, extractBillingAttributionBlock } from "../preflight.js";
import { recordConflict } from "../conflict-watch.js";
Expand Down Expand Up @@ -186,7 +187,8 @@ export async function prepareAnthropic(
// Drop sub-viability fragments before any consumer sees them: a tiny
// range in the list makes batched compress attempts fail atomically
// (kernel validates the whole batch). Mirrors billion-context-pi.
if (turn.nudge) turn.nudge.compressibleRanges = viableRanges(turn.nudge.compressibleRanges);
// #2638: also drop remembered structurally-dead spans — a nudge advertising them steers the model into an atomically-refused compress call.
if (turn.nudge) turn.nudge.compressibleRanges = filterDeadRanges(session, viableRanges(turn.nudge.compressibleRanges));
nudge = turn.nudge;
session.stats.contextTokens = tokenCount;
session.stats.contextTokensSource = tokenCountSource;
Expand Down
Loading
Loading