Skip to content
Open
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
7 changes: 7 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,13 @@ const CONTEXT_LIMIT_TABLE: Array<{ match: RegExp; limit: number }> = [
{ match: /^minimax/i, limit: 204_800 },
{ match: /^qwen/i, limit: 200_000 },
{ match: /^kimi/i, limit: 200_000 },
// StepFun step-5 line serves a 1M window (field evidence #5500: an nvidia_nim
// deployment of stepfun-ai/step-5-preview enforces max_input_tokens=1048576
// and its models registry lists contextWindow=1048576). The miss used to fall
// to the 2e5 env default → 150K effective window, stranding step-family
// sessions in the preflight fail-fast loop (#852 doctrine: too-large guesses
// self-heal on first upstream overflow, too-small ones strand).
{ match: /^step-/i, limit: 1_048_576 },
{ match: /^llama-/i, limit: 200_000 },
];

Expand Down
13 changes: 11 additions & 2 deletions src/preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1823,8 +1823,17 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
// upper bound (never undershoots). The regime is caller-decided and fixed
// for the whole loop — lastInputTokens mutates mid-loop and must not flip it.
const baselineKnown = deps.unknownBaseline !== true;
// #5500: an ESTIMATE-grade baseline (#604/#1498-F1 failure arm persisted at
// char-bound scale) or a legacy unprovenanced value is an arming quantity,
// not a size measurement — the per-round floor below already refuses it for
// measured payloads; the entry reads must apply the same discipline or a
// poisoned arm replayed from stats_json inflates entryTokens/overshoot
// budgets and the first processTurn meter on every request after restart.
const anchorGradeOk = deps.session.stats.lastInputTokensSource === "usage" || deps.session.stats.lastInputTokensSource === "overflow-arm";
const countText = baselineKnown ? defaultCountTokens : (text: string): number => text.length;
let currentTokens = baselineKnown ? deps.session.stats.lastInputTokens : estimateCoreMessagesUpper(messages);
let currentTokens = messages.length > 0
? (baselineKnown && anchorGradeOk ? deps.session.stats.lastInputTokens : estimateCoreMessagesUpper(messages))
: deps.session.stats.lastInputTokens;
let decisionTokens = 0;
let finalUpper = baselineKnown ? 0 : estimateCoreMessagesUpper(messages);
let startTokens = -1;
Expand Down Expand Up @@ -1916,7 +1925,7 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa
// payloads exit early exactly as before; only genuinely huge payloads burn
// toward it before the fail-fast reports how far it ran out.
const entryLocal = (baselineKnown ? estimateCoreMessages(messages) : estimateCoreMessagesUpper(messages)) + imageReserve + wireOverhead;
const entryTokens = Math.max(baselineKnown ? deps.session.stats.lastInputTokens : 0, entryLocal);
const entryTokens = Math.max(baselineKnown && anchorGradeOk ? deps.session.stats.lastInputTokens : 0, entryLocal);
const overshootRatio = limit > 0 && entryTokens > 0 ? entryTokens / limit : 1;
const summaryBudget = Math.min(MAX_SUMMARY_CALLS_PER_PREFLIGHT * 2, Math.max(MAX_SUMMARY_CALLS_PER_PREFLIGHT, Math.ceil(MAX_SUMMARY_CALLS_PER_PREFLIGHT * overshootRatio)));
const roundBudget = Math.min(MAX_PREFLIGHT_ROUNDS * 2, Math.max(MAX_PREFLIGHT_ROUNDS, Math.ceil(MAX_PREFLIGHT_ROUNDS * overshootRatio)));
Expand Down
9 changes: 8 additions & 1 deletion src/request-membership.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,14 @@ export function probeRequestMembership(session: Session, ids: string[], payloadU
// Needle discipline: only member / first-turn / main-scale requests may
// move it — a tiny foreign payload must never own the needle, or the
// next main turn would probe against the polluter's id and be gated.
const referenceScale = session.stats.lastInputTokens > 0 ? session.stats.lastInputTokens : (t.needlePayloadUpper ?? 0);
// #5500 family (kill-at-reader, #1839 discipline): an ESTIMATE-grade or
// unprovenanced scalar is an arming quantity, not a measurement — prefer
// the needle's own per-request scale over it. (The incoming payloadUpper
// rides the same char-bound caliber as a poisoned arm today, so the ratio
// self-normalizes; the gate makes the reference robust to any future
// caliber drift instead of silently skewing ~4x.)
const anchorGradeOk = session.stats.lastInputTokensSource === "usage" || session.stats.lastInputTokensSource === "overflow-arm";
const referenceScale = anchorGradeOk && session.stats.lastInputTokens > 0 ? session.stats.lastInputTokens : (t.needlePayloadUpper ?? 0);
const mainScale = payloadUpper >= referenceScale * MEMBERSHIP_RECORD_SCALE_RATIO;
if (member || mainScale) {
t.latestKnownMsgId = ids[ids.length - 1];
Expand Down
18 changes: 18 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2969,6 +2969,24 @@ export function effectiveTokenCount(session: Session, msgs: CoreMessage[], inbou
if (fallback !== null) return { tokens: fallback, source: "estimate" };
return { tokens: grade, source: "usage" };
}
// #5500 (round 3): a CYCLE-STALE demotion means a usage-grade anchor exists
// but the last send's report hasn't settled yet — one lost/absent report
// (stream abort, client cancel, flaky upstream) must not hand the meter
// the char-count bound: inflating the decision value ~2–4× crosses the
// kernel's DESTRUCTIVE emergency-truncate band (0.95×window) on sessions
// whose MEASURED size sits safely under it, and the clips LATCH until the
// next successful fold (#3939 ③), destroying delivered tool output. Ride
// the billing-caliber estimate of that send instead (contextEstimateTokens,
// k̂-scaled where provenance matches) — the same replacement reading
// staleSmallAnchorFallback returns for its own demotion class (#1595).
// Capped by the current payload's own upper bound so a mis-calibrated k̂
// can never exceed today's fail-closed worst case. Anchor-less sessions
// (no usage-grade source at all) skip this branch and keep #728's
// fail-closed bound below: there is nothing fresher to prefer.
if (anchorStale) {
const scaled = session.stats.contextEstimateTokens ?? 0;
if (scaled > 0) return { tokens: Math.min(scaled, raw), source: "estimate" };
}
// #553: zero-baseline ANCHOR-LESS anonymous sessions (prefix-affinity
// mints/forks/reloads) fall back to the raw-history upper bound — see the
// function header for why feeding 0 blinds them.
Expand Down
8 changes: 7 additions & 1 deletion src/server/prepare-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,8 +606,14 @@ reconcileFoldCoverage(session, msgs, { mode: foldMode, sessionId, log, markerStr
// usage we mint here must not read as an empty context: fall back to
// estimating the payload itself when lastInputTokens is stale/zero.
// The reply honors parsed.stream (JSON body when not streaming).
// #5500 family (kill-at-reader): an ESTIMATE-grade/unprovenanced arm is
// char-bound (~4x tokens) while est is chars/4 — the scales don't
// cancel, so a poisoned scalar would inflate the minted input_tokens
// and codex's recomputed ledger until the next real report. Only a
// trustworthy scalar keeps precedence over the raw-body estimate.
const anchorGradeOk = session.stats.lastInputTokensSource === "usage" || session.stats.lastInputTokensSource === "overflow-arm";
const est = defaultCountTokens(typeof parsed.input === "string" ? parsed.input : JSON.stringify(parsed.input ?? ""));
const total = Math.max(session.stats.lastInputTokens, est, 1);
const total = Math.max(anchorGradeOk ? session.stats.lastInputTokens : 0, est, 1);
codexForge = compactForm === "trigger"
? {
kind: "trigger",
Expand Down
13 changes: 10 additions & 3 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1087,11 +1087,18 @@ export function truncatedUpstreamOf(session: Session): { at: number; protocol: s
/** Stamp a pending aborted-turn re-anchor; call from the plugin pipe's
* client-abort path AFTER settleUsage has landed whatever the interrupted
* stream reported (the request's input size — the partial output itself
* never reports). A zero/unknown meter carries no information: skip. */
* never reports). A zero/unknown meter carries no information: skip. An
* ESTIMATE-grade/unprovenanced meter carries FALSE information (#5500
* family): a char-bound arm would delay the re-anchor ~4x — the absorb
* never sees the calibrated meter cross it — and #5415 would bank phantom
* growth debt (anchor − reference) into the nudge cadence, so those are
* skipped too. */
export function noteAbortedTurn(session: Session): void {
if (!Number.isFinite(session.stats.lastInputTokens) || session.stats.lastInputTokens <= 0) return;
const st = session.stats;
const trustworthy = st.lastInputTokensSource === "usage" || st.lastInputTokensSource === "overflow-arm";
if (!trustworthy || !Number.isFinite(st.lastInputTokens) || st.lastInputTokens <= 0) return;
session.transient ??= {};
session.transient.abortReanchor = { anchor: session.stats.lastInputTokens, at: Date.now() };
session.transient.abortReanchor = { anchor: st.lastInputTokens, at: Date.now() };
}

/** Consume a pending aborted-turn re-anchor if — and only if — the meter has
Expand Down
12 changes: 8 additions & 4 deletions tests/issue4383-stale-usage-anchor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,13 @@ test("#4383 frozen shape: last cycle ended without a settle → per-send estimat
// many later cycles: every send stamps fresh estimates, no usage ever settles
noteOutboundContextEstimates(session, { upperBound: 303_092, scaledText: 150_000, imageTokens: 0, calibrated: false });
assert.equal(usageAnchorCycleStale(session.stats), true);
// pre-fix: { tokens: 4733, source: "usage" } — growth read 0, nudge idle 154 turns
// pre-fix: { tokens: 4733, source: "usage" } — growth read 0, nudge idle 154 turns.
// #5500 round 3: the ride-on upgraded from the char bound (upperBound 303_092)
// to the calibrated per-send estimate (scaledText 150_000) — the char bound
// crossed the destructive emergency-truncate band on measured-safe sessions.
const sizing = effectiveTokenCount(session, bigMsgs());
assert.equal(sizing.source, "estimate");
assert.equal(sizing.tokens, 303_092);
assert.equal(sizing.tokens, 150_000);
assert.equal(statusInputBaseline(session), 303_092);
});

Expand Down Expand Up @@ -84,10 +87,11 @@ test("#4383 grade branch is bypassed too: a drained anchor's stale grade must no
session.stats.lastInputTokensSource = "usage";
session.stats.lastUsageGradeTokens = 4_733;
noteOutboundContextEstimates(session, { upperBound: 303_092, scaledText: 150_000, imageTokens: 0, calibrated: false });
// pre-fix: branch 3 returned the frozen grade 4733
// pre-fix: branch 3 returned the frozen grade 4733; #5500 round 3 moved the
// stale ride-on from the char bound to the calibrated per-send estimate.
const sizing = effectiveTokenCount(session, bigMsgs());
assert.equal(sizing.source, "estimate");
assert.equal(sizing.tokens, 303_092);
assert.equal(sizing.tokens, 150_000);
assert.equal(statusInputBaseline(session), 303_092);
});

Expand Down
4 changes: 4 additions & 0 deletions tests/issue5293-abort-nudge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ test("#5293 unit: noteAbortedTurn / absorbAbortedTurnGrowth edge cases", async (

const s1 = createSession("u-stamp");
s1.stats.lastInputTokens = 42_000;
s1.stats.lastInputTokensSource = "usage"; // #5500: the stamp now requires a trustworthy meter
noteAbortedTurn(s1);
assert.equal(s1.transient?.abortReanchor?.anchor, 42_000, "stamp records the pre-abort anchor");

Expand All @@ -111,6 +112,7 @@ test("#5293 unit: noteAbortedTurn / absorbAbortedTurnGrowth edge cases", async (

const s3 = createSession("u-wait");
s3.stats.lastInputTokens = 42_000;
s3.stats.lastInputTokensSource = "usage"; // #5500: the stamp now requires a trustworthy meter
noteAbortedTurn(s3);
s3.state.nudge.lastPerMessageNudgeTokens = 40_000;
absorbAbortedTurnGrowth(s3, 42_000);
Expand All @@ -119,6 +121,7 @@ test("#5293 unit: noteAbortedTurn / absorbAbortedTurnGrowth edge cases", async (

const s4 = createSession("u-absorb");
s4.stats.lastInputTokens = 42_000;
s4.stats.lastInputTokensSource = "usage"; // #5500: the stamp now requires a trustworthy meter
noteAbortedTurn(s4);
s4.state.nudge.lastPerMessageNudgeTokens = 40_000;
s4.state.nudge.lastNudgeShownTokens = 41_000;
Expand All @@ -131,6 +134,7 @@ test("#5293 unit: noteAbortedTurn / absorbAbortedTurnGrowth edge cases", async (

const s5 = createSession("u-max");
s5.stats.lastInputTokens = 42_000;
s5.stats.lastInputTokensSource = "usage"; // #5500: the stamp now requires a trustworthy meter
noteAbortedTurn(s5);
s5.state.nudge.lastPerMessageNudgeTokens = 45_000;
absorbAbortedTurnGrowth(s5, 43_000);
Expand Down
4 changes: 3 additions & 1 deletion tests/issue5415-absorb-debt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ import type { Session } from "../src/session.ts";
const makeSession = (reference: number, lastInputTokens: number): Session =>
({
id: "s5415",
stats: { lastInputTokens },
// usage-grade meter: noteAbortedTurn only stamps trustworthy scalars
// since #5500 (estimate-grade/unprovenanced arms carry false information).
stats: { lastInputTokens, lastInputTokensSource: "usage" },
state: {
nudge: {
lastPerMessageNudgeTokens: reference,
Expand Down
Loading
Loading