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
28 changes: 19 additions & 9 deletions src/preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,16 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
// as absent (raw estimate) rather than deciding with a cross-model scale.
const kFactor = currentCalibrationFactor(deps.session.stats, deps.session.metadata?.lastModel);
const kOrigin = deps.session.stats.calibratedEstimateOrigin;
// #3645: kernel range.tokens are the UNCALIBRATED count, but
// result.payloadEstimate (hence every deficit derived from it) sits on the
// CALIBRATED scale once a matching-origin k̂ is set (#1933 F1). Folding a
// raw-mass range removes its mass from the text, so its calibrated saving
// is bounded by mass*k̂ — compare the foldable pool to the deficit on that
// same scale, or a k̂>1 session inflates the deficit ×k̂ against an
// un-scaled mass and the gate calls a recoverable round futile. Identity
// for k̂=1 / absent / mismatched-origin (applyEstimateCalibration → raw), so
// the uncalibrated #1841 path stays byte-identical.
const calibrateFoldMass = (rawMass: number): number => applyEstimateCalibration(rawMass, kFactor, kOrigin, deps.upstreamOrigin);
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 };
if (limit <= 0) return result;
Expand Down Expand Up @@ -1914,7 +1924,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
}, 0);
let potential = resolvableMass(ranges);
const deficit = result.payloadEstimate - limit;
if (potential > 0 && deficit > 0 && potential * FUTILITY_SLACK < deficit) {
if (potential > 0 && deficit > 0 && calibrateFoldMass(potential) * FUTILITY_SLACK < deficit) {
if (!relaxed) {
// The soft-protected recent zone is not in `ranges` yet; #330
// makes it foldable on relax. Probe the relaxed view (CPU-only,
Expand All @@ -1931,14 +1941,14 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
});
const relaxedRanges = viableRanges(probe.nudge?.compressibleRanges ?? []).filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars);
const relaxedPotential = resolvableMass(relaxedRanges);
if (relaxedPotential * FUTILITY_SLACK >= deficit) {
if (calibrateFoldMass(relaxedPotential) * FUTILITY_SLACK >= deficit) {
activeConfig = relaxedConfig(deps.config);
relaxed = true;
textTarget = Math.max(0, limit - imageReserve);
summaryCalls = 0;
budgetHit = false;
transientRetryBudget = TRANSIENT_EMPTY_RETRY_BUDGET;
deps.log("warn", `[preflight] foldable mass outside the protected recent zone (~${potential} tok) cannot close the ${deficit}-tok gap; relaxing soft protection up front and retrying (#1841)`);
deps.log("warn", `[preflight] foldable mass outside the protected recent zone (~${calibrateFoldMass(potential)} tok) cannot close the ${deficit}-tok gap; relaxing soft protection up front and retrying (#1841)`);
continue;
}
// The relaxed pool is the superset: quote it as the true bound.
Expand All @@ -1953,15 +1963,15 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
// instead of declaring futility here. Never entered for tiers=false
// or emergency digest mode, so both paths stay byte-identical.
if (eligibleForTierRecovery()) {
deps.log("info", `[preflight] raw-fold pool (~${potential} tok${zoneNote}) below deficit (~${deficit} tok); deferring to bounded tier-distillation recovery (#2952)`);
deps.log("info", `[preflight] raw-fold pool (~${calibrateFoldMass(potential)} tok${zoneNote}) below deficit (~${deficit} tok); deferring to bounded tier-distillation recovery (#2952)`);
break;
}
// #3461: structurally doomed only when NO draw ever came back
// unusable and the pool never dropped — an unusable draw means
// the shortfall may be the relay, not the content, and the
// retry/canary machinery (#726/#2832) owns that case.
failure = { kind: "exhausted", deterministic: lastUnusableDetail === undefined && !poolQueueDrop, detail: `futile round: the maximum possible saving from all foldable content (~${potential} tokens${zoneNote}) is below the required reduction (~${deficit} tokens) — no combination of folds can bring the payload under the target. Raise the model context window or restart the session.` };
deps.log("warn", `[preflight] skipping futile round: max possible saving ~${potential} tok < required ~${deficit} tok${zoneNote}; zero summarization calls spent (#1841)`);
failure = { kind: "exhausted", deterministic: lastUnusableDetail === undefined && !poolQueueDrop, detail: `futile round: the maximum possible saving from all foldable content (~${calibrateFoldMass(potential)} tokens${zoneNote}) is below the required reduction (~${deficit} tokens) — no combination of folds can bring the payload under the target. Raise the model context window or restart the session.` };
deps.log("warn", `[preflight] skipping futile round: max possible saving ~${calibrateFoldMass(potential)} tok < required ~${deficit} tok${zoneNote}; zero summarization calls spent (#1841)`);
break;
}
}
Expand Down Expand Up @@ -2303,11 +2313,11 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
if (si !== undefined && ei !== undefined && si <= ei) remaining += rj.tokens;
}
const deficit = result.payloadEstimate - limit;
if (remaining > 0 && deficit > 0 && remaining * FUTILITY_SLACK < deficit) {
if (remaining > 0 && deficit > 0 && calibrateFoldMass(remaining) * FUTILITY_SLACK < deficit) {
futileBail = true;
bailRemaining = remaining;
bailRemaining = calibrateFoldMass(remaining);
bailDeficit = deficit;
deps.log("warn", `[preflight] remaining foldable mass (~${remaining} tok) cannot close the ~${deficit}-tok gap; stopping further summarization calls (#1841)`);
deps.log("warn", `[preflight] remaining foldable mass (~${calibrateFoldMass(remaining)} tok) cannot close the ~${deficit}-tok gap; stopping further summarization calls (#1841)`);
break;
}
}
Expand Down
14 changes: 9 additions & 5 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3358,6 +3358,7 @@ export async function preflightCompressIfNeeded(
// #553) — the optimistic re-estimate is exactly what that regime distrusts.
let outbound: Prepared = prepared;
let fits: boolean;
let foldedCalibratedSize: number | undefined;
if (result.compressedRanges > 0) {
const rebuilt = await runPrepare();
// runPrepare re-incremented stats.requests; the rebuild is internal
Expand All @@ -3382,15 +3383,18 @@ export async function preflightCompressIfNeeded(
session.stats.lastInputTokens = rebuiltTextSize;
session.stats.lastInputTokensSource = "estimate";
}
log("info", `[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} → ${session.stats.lastInputTokens}) in ${Date.now() - started}ms`);
// Same calibrated caliber as the trigger above — gate, per-round exit
// and this final fit must judge the payload on one scale (#1933 F1).
// The baseline anchor above stays raw deliberately: it is a floor for
// future meters, and a deflated (k̂ < 1) value would only delay the
// next trigger, never advance it.
fits = unknownBaseline
? result.fitsWindow
: applyEstimateCalibration(rebuiltTextSize, kFactor, kOrigin, currentOrigin) + imageTokens < limit;
const rebuiltCalibrated = applyEstimateCalibration(rebuiltTextSize, kFactor, kOrigin, currentOrigin) + imageTokens;
// #3645: hoist the calibrated post-fold figure so the fail-fast message
// quotes the same scale as this fit and the pre-fold tokenCount — quoting
// the raw size there claimed a sub-window number exceeds the window when k̂>1.
foldedCalibratedSize = rebuiltCalibrated;
log("info", `[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} → ${foldedCalibratedSize}) in ${Date.now() - started}ms`);
fits = unknownBaseline ? result.fitsWindow : rebuiltCalibrated < limit;
// #1820: anchor the meter to the rebuilt payload's measured size — the
// rebuild request's own usage report (the only sample that can supersede
// this) hasn't landed yet, and the meter's fallback branches would size
Expand Down Expand Up @@ -3534,7 +3538,7 @@ export async function preflightCompressIfNeeded(
// rejection — deterministic for the identical payload) overrides the
// status-based heuristic below; every other path keeps today's mapping.
const retryable = f?.retryable === false ? false : f?.retryable === true || (f?.kind === "upstream" && f.status !== undefined && (f.status === 429 || f.status >= 500));
const ff = failFast(status, f?.detail ?? "the payload still exceeds the window after preflight compression", retryable, result.compressedRanges > 0 ? session.stats.lastInputTokens : undefined, result.rangesRemaining);
const ff = failFast(status, f?.detail ?? "the payload still exceeds the window after preflight compression", retryable, result.compressedRanges > 0 ? foldedCalibratedSize : undefined, result.rangesRemaining);
const contentDeadEnd = f?.kind === "exhausted" || (f?.kind === "upstream" && f.status !== undefined && f.status >= 400 && f.status < 500 && !retryable);
if (contentDeadEnd && result.compressedRanges === 0) {
const cooldownMs = preflightDeadEndCooldownMs();
Expand Down
Loading
Loading