Skip to content
Open
Show file tree
Hide file tree
Changes from 11 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
2 changes: 2 additions & 0 deletions src/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ interface PersistedSession {
emergencyShrinkAt?: number;
emergencyShrinkEstimate?: number;
lastInputTokensOrigin?: string;
lastInputTokensModel?: string;
overflowArmTokens?: number;
preflightRuns?: number;
overflowArmCompletionReserve?: number;
Expand Down Expand Up @@ -4528,6 +4529,7 @@ function buildSession(parsed: PersistedSession): Session {
localInputEstimate: typeof stats.localInputEstimate === "number" && Number.isFinite(stats.localInputEstimate) && stats.localInputEstimate > 0 ? stats.localInputEstimate : undefined,
lastUsageGradeTokens: typeof stats.lastUsageGradeTokens === "number" && Number.isFinite(stats.lastUsageGradeTokens) && stats.lastUsageGradeTokens >= 0 ? stats.lastUsageGradeTokens : undefined,
lastInputTokensOrigin: typeof stats.lastInputTokensOrigin === "string" && stats.lastInputTokensOrigin.trim().length > 0 ? stats.lastInputTokensOrigin : undefined,
lastInputTokensModel: typeof stats.lastInputTokensModel === "string" && stats.lastInputTokensModel.trim().length > 0 ? stats.lastInputTokensModel : undefined,
calibratedEstimate: restoreCalibratedEstimate(stats.calibratedEstimate),
calibratedEstimateOrigin: typeof stats.calibratedEstimateOrigin === "string" && stats.calibratedEstimateOrigin.trim().length > 0 ? stats.calibratedEstimateOrigin : undefined,
calibratedEstimateModel: typeof stats.calibratedEstimateModel === "string" && stats.calibratedEstimateModel.trim().length > 0 ? stats.calibratedEstimateModel : undefined,
Expand Down
34 changes: 33 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4098,6 +4098,22 @@ export async function preflightCompressIfNeeded(
log("info", `[${session.id}] preflight usage-baseline ~${baselineFloor} tok was measured on ${maskUrlForLog(baselineOrigin)}, request now routes to ${maskUrlForLog(currentOrigin)} — demoting to untrusted, judging by this payload's own estimate (#1933)`);
baselineFloor = 0;
}
// #6430: the baseline's MODEL provenance — a usage-grade baseline measured
// under a different model (same route) is not authoritative for this
// request's billing scale: tokenizers bill differently across models, so a
// cross-model baseline can sit far above (or below) the current model's true
// size (the incident: a 282K opus reading drove preflight on a fable payload
// that billed ~55K). The k̂ read gate (currentCalibrationFactor) already
// demotes on model mismatch; the baseline floor must match it, or a stale
// cross-model baseline keeps arming preflight on the same route. Mirrors the
// #1933 F2 origin demotion above. Absent model (legacy files / unprovenanced)
// keeps the legacy behavior — never invalidated by missing info.
const baselineModel = typeof session.stats.lastInputTokensModel === "string" && session.stats.lastInputTokensModel !== "" ? session.stats.lastInputTokensModel : undefined;
const currentModel = typeof session.metadata?.lastModel === "string" && session.metadata.lastModel !== "" ? session.metadata.lastModel : undefined;
if (baselineFloor > 0 && baselineModel !== undefined && currentModel !== undefined && baselineModel !== currentModel) {
log("info", `[${session.id}] preflight usage-baseline ~${baselineFloor} tok was measured under model ${baselineModel}, request now runs ${currentModel} — demoting to untrusted, judging by this payload's own estimate (#6430)`);
baselineFloor = 0;
}
// Identity fast path (2026-11-22 opencode 413 incident): when the server
// already knows this conversation (identified sid) AND has REAL upstream
// reality on record for this exact origin+model — a successful usage bill
Expand Down Expand Up @@ -4153,7 +4169,23 @@ export async function preflightCompressIfNeeded(
// with a cross-model billing scale (currentCalibrationFactor).
const kFactor = currentCalibrationFactor(session.stats, session.metadata?.lastModel);
const kOrigin = session.stats.calibratedEstimateOrigin;
const calibratedText = applyEstimateCalibration(textEstimate + overheadEstimate, kFactor, kOrigin, currentOrigin);
// #6430: a fresh same-route+same-model usage baseline (not demoted above) is
// the most recent MEASURED reading of this lane's real billed size. When the
// current payload's RAW estimate is not bigger than that reading, the payload
// has not genuinely grown past the last measurement — any excess of the k̂-
// scaled estimate over the baseline is calibration over-correction (a stale
// k̂>1 inflating a payload the provider just billed below the target), not
// real growth. Cap the calibrated text at the measured baseline so a stale k̂
// cannot fire preflight below a fresh measurement: the measurement wins over
// the inflated estimate. Genuine growth (raw > baseline) leaves the
// calibrated estimate untouched, so a payload that really has crossed the
// target still folds; a missed fold here self-heals via the overflow arm on
// the next 400. The cap only applies while the baseline is trusted (same
// route+model); a demoted baseline floors at 0 and the estimate decides.
const rawTextEstimate = textEstimate + overheadEstimate;
const calibratedText = rawTextEstimate <= baselineFloor
? Math.min(applyEstimateCalibration(rawTextEstimate, kFactor, kOrigin, currentOrigin), baselineFloor)
: applyEstimateCalibration(rawTextEstimate, kFactor, kOrigin, currentOrigin);
const calibratedPayload = calibratedText + imageTokens;
const tokenCount = unknownBaseline
? estimateCoreMessagesUpper(prepared.processedMessages) + overheadEstimate + imageTokens
Expand Down
4 changes: 3 additions & 1 deletion src/server/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1782,6 +1782,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// probe-forward gate) treat the arm as current-route evidence
// instead of demoting it against a stale settle origin.
s.stats.lastInputTokensOrigin = normalizeUpstreamOrigin(upstreamUrl);
// #6430: model provenance for the armed baseline — the preflight gate
// demotes it when the current request runs on a different model.
if (typeof reqModel === "string" && reqModel !== "") s.stats.lastInputTokensModel = reqModel;
// #1110: record the arm SEPARATELY so the side-request guard
// can read it without ever touching the nudge baseline. The guard
Expand Down Expand Up @@ -1859,7 +1861,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
s.stats.lastInputTokensSource = "overflow-arm";
s.stats.overflowArmTokens = arm; // #1110: guard reads this, not the baseline
s.stats.lastInputTokensOrigin = normalizeUpstreamOrigin(upstreamUrl); // #2313: same-route evidence, see the window branch above
if (typeof reqModel === "string" && reqModel !== "") s.stats.lastInputTokensModel = reqModel;
if (typeof reqModel === "string" && reqModel !== "") s.stats.lastInputTokensModel = reqModel; // #6430: model provenance, see the window branch above
}
log("warn", `[${s.id}] upstream context overflow (window not parseable, model=${reqModel ?? "unknown"}) — armed emergency shrink at ~${arm} tokens (min of judging window ${judging} and payload estimate), nothing learned (#987): ${info.message}`);
}
Expand Down
22 changes: 15 additions & 7 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,13 +585,20 @@ export type Session = {
* provider says nothing about whether another accepts the payload.
* Absent on legacy session files → baseline keeps legacy behavior. */
lastInputTokensOrigin?: string;
/** Identity-fast-path: the REQUEST MODEL that measured lastInputTokens
* — stamped at usage settlement (settleUsageReport / applyUsageSample)
* and at overflow arming, alongside lastInputTokensOrigin. Acceptance
* evidence on one model says nothing about another model's wall on
* the same origin (#2189: 300k billed on claude-big does not bind
* claude-small). Absent on legacy session files → the gate demotes
* conservatively and the protection chain judges. */
/** #6430 / identity-fast-path: the REQUEST MODEL that measured
* lastInputTokens — stamped at usage settlement (settleUsageReport /
* applyUsageSample) and at overflow arming, alongside
* lastInputTokensOrigin. Two gates demote on model mismatch: the
* preflight baseline floor (tokenizers bill differently across
* models, so a cross-model baseline — e.g. a 282K opus reading on a
* fable lane — is not authoritative for this request's size; the k̂
* read gate (currentCalibrationFactor) already demotes on model
* mismatch and the baseline floor must match it) and the identity
* fast path (acceptance evidence on one model says nothing about
* another model's wall on the same origin, #2189: 300k billed on
* claude-big does not bind claude-small). Absent on legacy session
* files → the baseline keeps legacy behavior and the fast path
* demotes conservatively. */
lastInputTokensModel?: string;
/** #1933 F1: calibrated scale factor k̂ = mean of up to 3 recent
* consistent same-route samples of (upstream-billed input ÷ local
Expand Down Expand Up @@ -1894,6 +1901,7 @@ export function resetSessionCompression(session: Session): void {
// learned against the pre-compaction content class, and the baseline's
// measuring route no longer bounds this rebuilt session.
delete session.stats.lastInputTokensOrigin;
// #6430: the baseline's model provenance dies with the baseline.
delete session.stats.lastInputTokensModel;
delete session.stats.calibratedEstimate;
delete session.stats.calibratedEstimateOrigin;
Expand Down
6 changes: 3 additions & 3 deletions tests/golden/storage-render/anthropic.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@
"foldAt": 9,
"editedAt": 12,
"summaryFrom": 9,
"stateDigest": "44a84ad7828c93f6cdaa854b553bc410e707cf06c4fe3809c49a144e06f3fd6c",
"stateDigestAligned": "72352c435a860ef25568d606677e98a1f07d8b4fd4b9a2c28905b9247624559c",
"stateDigest": "4227905268f168da7407972040487b29f1897f78ca3c3f7de5c48851aa8939cb",
"stateDigestAligned": "10b9cc2489e7e9e8d83bd2b9f80569b0b444b3fb82293d9e7dd950efa41d4555",
"sectionDigests": {
"state": "b5d31cb2e41094fc",
"blockContents": "dc7d13d250c94bb4",
"stats": "4c520066c80afae5",
"stats": "6af87e937ecffa8e",
"metadata": "f8224a93d19e91af"
},
"stateKeyDigests": {
Expand Down
6 changes: 3 additions & 3 deletions tests/golden/storage-render/chat.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@
"foldAt": 9,
"editedAt": 12,
"summaryFrom": 9,
"stateDigest": "5e70517c497ad055fc4e06f8c3406ef3243f3cd236fe598cc1a969b7dd37eb2f",
"stateDigestAligned": "adca2907fe7fe01c049829dab7616f2e28a65586d62a06aa74696366a7430029",
"stateDigest": "8a61c5f92b63326acc4eb25fe954bab1cd5c44ae1a815df14efe4277a9bcc9fb",
"stateDigestAligned": "b9ea29eee6a1b885aa7770a04c63cb77a993cb9d30ec36c1b0952c5b04a27e6e",
"sectionDigests": {
"state": "3e5d2359fce3dc33",
"blockContents": "94a58f96d7c5cfc3",
"stats": "4f4a11e236765aee",
"stats": "187de7f20bc7ba58",
"metadata": "67a22c96c5bc4d87"
},
"stateKeyDigests": {
Expand Down
6 changes: 3 additions & 3 deletions tests/golden/storage-render/google.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@
"foldAt": 9,
"editedAt": 12,
"summaryFrom": 9,
"stateDigest": "723cfc0096bb6b1a81fd3dd143a7d506806f870ef00f889e7ee6829f3d696098",
"stateDigestAligned": "0017ba03fc657b625eb0425c34591eda67acf3bbbe4248e2901fe9c9968bde73",
"stateDigest": "90448b3627d6b0c759cbdd61f4b3b4d30e7fe104ddc9d28972c61d7f058ec99b",
"stateDigestAligned": "d7d77b13cc4533f46064afa70a6ee5c79003b232e2541d00a10fd64bc099a85e",
"sectionDigests": {
"state": "e5cccb797d2918a2",
"blockContents": "473264d9df8ba338",
"stats": "9830bb7537328268",
"stats": "68a5b370624bd863",
"metadata": "ea5ad310ea118420"
},
"stateKeyDigests": {
Expand Down
6 changes: 3 additions & 3 deletions tests/golden/storage-render/responses.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@
"foldAt": 9,
"editedAt": 12,
"summaryFrom": 9,
"stateDigest": "f8962d4b26d878f80ae8c7894e0b125bdf3107c42b6b929bf9f9c8f0f71514f2",
"stateDigestAligned": "44a976df261453fddd23dfb2385f48ff1f9749c111d833d5653b419c6d73a0da",
"stateDigest": "cc9bf245474fd25176d48f9cacd67545170595e8636ae3e8cac80f028f115eac",
"stateDigestAligned": "5cc12b924aabb49fb6a8c348649fd3df6394c8a3994736f23143dfa3b8292c0a",
"sectionDigests": {
"state": "9e6108eb64108ade",
"blockContents": "b6701268a0bdcd8a",
"stats": "b3f39cb7f862eb07",
"stats": "9e3dfe21d53f614a",
"metadata": "b4cba5723355c2f1"
},
"stateKeyDigests": {
Expand Down
2 changes: 2 additions & 0 deletions tests/issue2129-restart-measurement-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ test("measurement-state stats survive a reload round-trip (#2129)", async () =>
st.localInputEstimate = 12345;
st.lastUsageGradeTokens = 9876;
st.lastInputTokensOrigin = "http://127.0.0.1:8787";
st.lastInputTokensModel = "claude-opus-5-5";
st.calibratedEstimate = 0.4375;
st.calibratedEstimateOrigin = "http://127.0.0.1:8787";
st.calibrationRing = { origin: "http://127.0.0.1:8787", values: [0.4, 0.45, 0.48] };
Expand All @@ -75,6 +76,7 @@ test("measurement-state stats survive a reload round-trip (#2129)", async () =>
assert.equal(back.stats.localInputEstimate, 12345, "localInputEstimate round-trips");
assert.equal(back.stats.lastUsageGradeTokens, 9876, "lastUsageGradeTokens round-trips");
assert.equal(back.stats.lastInputTokensOrigin, "http://127.0.0.1:8787", "lastInputTokensOrigin round-trips");
assert.equal(back.stats.lastInputTokensModel, "claude-opus-5-5", "lastInputTokensModel round-trips (#6430)");
assert.equal(back.stats.calibratedEstimate, 0.4375, "calibratedEstimate round-trips");
assert.equal(back.stats.calibratedEstimateOrigin, "http://127.0.0.1:8787", "calibratedEstimateOrigin round-trips");
assert.deepEqual(back.stats.calibrationRing, { origin: "http://127.0.0.1:8787", values: [0.4, 0.45, 0.48] }, "calibrationRing round-trips");
Expand Down
24 changes: 20 additions & 4 deletions tests/issue2189-preflight-billing-block.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ test("#2189 anthropic summary carries the client billing-attribution block at sy
const { proxy, upstream, proxyPort, upstreamPort } = await makePair(calls, 200, "");
try {
const r1 = await drive(proxyPort, upstreamPort, "s2189-main", {
model: "claude-big", max_tokens: 1024, stream: true, system: ccSystem(), messages: [{ role: "user", content: "hello" }],
model: "claude-small", max_tokens: 1024, stream: true, system: ccSystem(), messages: [{ role: "user", content: "hello" }],
});
assert.equal(r1.status, 200);
await r1.text();
Expand Down Expand Up @@ -233,7 +233,7 @@ test("#2189 legacy string system keeps the byte-identical summary shape", async
try {
const sys = "You are a helpful assistant.";
const r1 = await drive(proxyPort, upstreamPort, "s2189-legacy", {
model: "claude-big", max_tokens: 1024, stream: true, system: sys, messages: [{ role: "user", content: "hello" }],
model: "claude-small", max_tokens: 1024, stream: true, system: sys, messages: [{ role: "user", content: "hello" }],
});
assert.equal(r1.status, 200);
await r1.text();
Expand Down Expand Up @@ -268,11 +268,19 @@ test("#2189 bare-Error 429 fails fast after ONE attempt, retryable=false, retrie
const { proxy, upstream, proxyPort, upstreamPort } = await makePair(calls, 429, SHAPE_429_BODY, true);
try {
const r1 = await drive(proxyPort, upstreamPort, "s2189-shape", {
model: "claude-big", max_tokens: 1024, stream: true, system: ccSystem(), messages: [{ role: "user", content: "hello" }],
model: "claude-small", max_tokens: 1024, stream: true, system: ccSystem(), messages: [{ role: "user", content: "hello" }],
});
assert.equal(r1.status, 200);
await r1.text();

// Pin a stated upstream wall: the session's same-origin+model usage
// reality (300k) would otherwise open the identity fast path and
// forward the over-window outbound instead of failing fast, bypassing
// the 429 handling under test (#7532). The wall demotes the fast path.
const seed = listSessions().find((s) => s.id.includes("s2189-shape"));
assert.ok(seed, "session exists after r1");
seed.stats.overflowArmTokens = 12_000;

const body2 = { model: "claude-small", max_tokens: 1024, stream: true, system: ccSystem(), messages: bigConversation() };
const r2 = await drive(proxyPort, upstreamPort, "s2189-shape", body2);
assert.equal(r2.status, 503);
Expand Down Expand Up @@ -314,11 +322,19 @@ test("#2189 a genuine rate limit keeps the legacy 3-attempt replay and retryable
const { proxy, upstream, proxyPort, upstreamPort } = await makePair(calls, 429, GENUINE_429_BODY, true);
try {
const r1 = await drive(proxyPort, upstreamPort, "s2189-genuine", {
model: "claude-big", max_tokens: 1024, stream: true, system: ccSystem(), messages: [{ role: "user", content: "hello" }],
model: "claude-small", max_tokens: 1024, stream: true, system: ccSystem(), messages: [{ role: "user", content: "hello" }],
});
assert.equal(r1.status, 200);
await r1.text();

// Pin a stated upstream wall: the session's same-origin+model usage
// reality (300k) would otherwise open the identity fast path and
// forward the over-window outbound instead of failing fast, bypassing
// the 429 handling under test (#7532). The wall demotes the fast path.
const seed = listSessions().find((s) => s.id.includes("s2189-genuine"));
assert.ok(seed, "session exists after r1");
seed.stats.overflowArmTokens = 12_000;

const r2 = await drive(proxyPort, upstreamPort, "s2189-genuine", {
model: "claude-small", max_tokens: 1024, stream: true, system: ccSystem(), messages: bigConversation(),
});
Expand Down
Loading
Loading