burnoff 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,719 @@
1
+ /**
2
+ * @file src/config/uncached-attribution.mjs
3
+ * Mutually exclusive 6-bucket uncached-token partitioner for session transcripts,
4
+ * enforcing strict 100% reconciliation (`reconciliationDeltaTokens === 0`).
5
+ */
6
+
7
+ import { valuateCall } from './pricing.mjs';
8
+
9
+ export const PROVIDER_QUIRK_CONSTANTS = Object.freeze({
10
+ GEMINI4_APPEND_FLOOR_TOKENS: 2050,
11
+ SHORT_GAP_EVICTION_MAX_SECONDS: 60,
12
+ BIMODAL_EVICTION_MIN_SECONDS: 150,
13
+ BIMODAL_EVICTION_MAX_SECONDS: 260,
14
+ SHARD_CUT_MIN_TOKENS: 18000,
15
+ SHARD_CUT_MAX_TOKENS: 22000,
16
+ SERVER_INJECTION_DELTA_TOKENS: 701,
17
+ SERVER_INJECTION_TOLERANCE_TOKENS: 25,
18
+ CLAUDE_55_COMPACT_MISS_MIN_VERSION: '2.1.289'
19
+ });
20
+
21
+ export const ATTRIBUTION_BUCKETS = Object.freeze([
22
+ 'cold_start',
23
+ 'compaction_rebuild',
24
+ 'model_or_effort_switch',
25
+ 'idle_ttl_miss',
26
+ 'unexplained_prefix_reset',
27
+ 'incremental_tail'
28
+ ]);
29
+
30
+ export const UNEXPLAINED_RESET_LIKELY_CAUSES = Object.freeze([
31
+ 'dynamic tool-list mutation or /mcp reload',
32
+ '/reload-plugins --force mid-session',
33
+ 'gateway cache_control stripping or volatile system-prompt header',
34
+ 'provider implicit-cache eviction under server load'
35
+ ]);
36
+
37
+ const UPSTREAM_EVICTION_ADVICE =
38
+ 'Upstream Gemini 4 serving eviction or shard cut detected; do not run /compact or shorten prompts (compacting forces another uncached rebuild).';
39
+ const CLAUDE_55_COMPACT_GUIDANCE =
40
+ 'Claude 5.5 /compact missed the warm prompt cache (#99624), rewriting full history; avoid unnecessary /compact on warm <1h sessions.';
41
+ const ORCHESTRATOR_THRASH_GUIDANCE =
42
+ 'Orchestrator multi-model thrash (#1638): planner/worker model hops broke KV prefix continuity; pin a homogeneous model during deep coding phases.';
43
+
44
+ function readNum(obj, keys, fallback = 0) {
45
+ for (const k of keys) {
46
+ if (obj[k] !== undefined && obj[k] !== null) {
47
+ const n = Number(obj[k]);
48
+ if (Number.isFinite(n)) return Math.max(0, n);
49
+ }
50
+ }
51
+ return fallback;
52
+ }
53
+
54
+ function hasAnyField(obj, keys) {
55
+ return keys.some((k) => obj[k] !== undefined && obj[k] !== null);
56
+ }
57
+
58
+ function detectGemini4Family(modelIdOrLabel = '') {
59
+ const s = String(modelIdOrLabel || '').toLowerCase();
60
+ const isGemini4 = /gemini[-\s]?4\b|gemini-4-|gemini-pro-orchestrator-|orchestrator \(/.test(s);
61
+ if (!isGemini4) return null;
62
+ for (const f of ['Neon', 'Carbon', 'Hydrogen', 'Argon']) {
63
+ if (s.includes(f.toLowerCase())) return f;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ function isClaude55Model(canonicalModelId = '', rawModel = '') {
69
+ const canon = String(canonicalModelId || '').toLowerCase();
70
+ if (canon === 'claude-opus-5-5' || canon === 'claude-sonnet-5-5') return true;
71
+ const raw = String(rawModel || '').toLowerCase();
72
+ return /claude[-_\s]?(opus|sonnet)[-_\s]?5[-.]5/.test(raw);
73
+ }
74
+
75
+ function isOrchestratorOrWorkerModel(model = '', label = '') {
76
+ return /orchestrator|gemini-flash-worker/i.test(`${model || ''} ${label || ''}`);
77
+ }
78
+
79
+ function parseVersionTuple(ver) {
80
+ if (!ver) return null;
81
+ const m = String(ver).trim().match(/(\d+)\.(\d+)\.(\d+)/);
82
+ if (!m) return null;
83
+ return [Number(m[1]), Number(m[2]), Number(m[3])];
84
+ }
85
+
86
+ function isVersionAtLeast(ver, minVer) {
87
+ if (!ver) return true;
88
+ const a = parseVersionTuple(ver);
89
+ const b = parseVersionTuple(minVer);
90
+ if (!a || !b) return true;
91
+ for (let i = 0; i < 3; i++) {
92
+ if (a[i] !== b[i]) return a[i] > b[i];
93
+ }
94
+ return true;
95
+ }
96
+
97
+ /**
98
+ * Normalizes Anthropic exclusive input accounting (`input_tokens` + `cache_creation_input_tokens` +
99
+ * `cache_read_input_tokens`), Gemini inclusive prompt accounting (`promptTokenCount` containing
100
+ * `cachedContentTokenCount`), and pre-split exclusive counters into a single canonical shape.
101
+ */
102
+ export function normalizeCacheTokenAccounting(raw = {}, canonicalModelId = '') {
103
+ const modelText = String(canonicalModelId || raw.model || raw.modelId || raw.rawModel || '').toLowerCase();
104
+ const isInclusive =
105
+ raw.promptTokenAccounting === 'inclusive' ||
106
+ raw.promptTokenCount !== undefined ||
107
+ raw.prompt_token_count !== undefined;
108
+
109
+ if (isInclusive) {
110
+ const cacheRead = readNum(raw, [
111
+ 'cachedContentTokenCount',
112
+ 'cached_content_token_count',
113
+ 'cachedTokens',
114
+ 'cacheRead',
115
+ 'cacheReadTokens',
116
+ 'cacheReadInputTokens',
117
+ 'cache_read_input_tokens'
118
+ ]);
119
+ const totalPrompt = Math.max(
120
+ cacheRead,
121
+ readNum(raw, ['promptTokenCount', 'prompt_token_count', 'promptTokens', 'totalPromptTokens'])
122
+ );
123
+ const uncached = Math.max(0, totalPrompt - cacheRead);
124
+ return {
125
+ accounting: 'gemini_inclusive',
126
+ freshInputTokens: uncached,
127
+ cacheCreationTokens: 0,
128
+ uncached,
129
+ cacheRead,
130
+ totalPrompt,
131
+ hitRate: totalPrompt > 0 ? cacheRead / totalPrompt : null
132
+ };
133
+ }
134
+
135
+ const write5m = readNum(raw, [
136
+ 'cacheWrite5mTokens',
137
+ 'write5mTokens',
138
+ 'cache_write_5m_tokens',
139
+ 'cacheCreationEphemeral5mInputTokens'
140
+ ]);
141
+ const write1h = readNum(raw, [
142
+ 'cacheWrite1hTokens',
143
+ 'write1hTokens',
144
+ 'cache_write_1h_tokens',
145
+ 'cacheCreationEphemeral1hInputTokens'
146
+ ]);
147
+ const genericWrite = readNum(raw, [
148
+ 'cacheCreationTokens',
149
+ 'cacheCreationInputTokens',
150
+ 'cache_creation_input_tokens'
151
+ ]);
152
+ const cacheCreation = write5m + write1h + Math.max(0, genericWrite - (write5m + write1h));
153
+ const freshInputTokens = readNum(raw, [
154
+ 'uncachedTokens',
155
+ 'uncached',
156
+ 'uncachedInputTokens',
157
+ 'freshInputTokens',
158
+ 'inputTokens',
159
+ 'input_tokens'
160
+ ]);
161
+ const cacheRead = readNum(raw, [
162
+ 'cachedTokens',
163
+ 'cacheRead',
164
+ 'cacheReadTokens',
165
+ 'cacheReadInputTokens',
166
+ 'cache_read_input_tokens',
167
+ 'cachedContentTokenCount',
168
+ 'cached_content_token_count'
169
+ ]);
170
+ const uncached = freshInputTokens + cacheCreation;
171
+ const totalPrompt = uncached + cacheRead;
172
+ const hasAnthropicFields = hasAnyField(raw, [
173
+ 'input_tokens',
174
+ 'cache_read_input_tokens',
175
+ 'cache_creation_input_tokens',
176
+ 'cacheCreationTokens',
177
+ 'cacheCreationInputTokens',
178
+ 'cacheCreationEphemeral5mInputTokens',
179
+ 'cacheCreationEphemeral1hInputTokens',
180
+ 'cacheWrite5mTokens',
181
+ 'cacheWrite1hTokens',
182
+ 'freshInputTokens'
183
+ ]);
184
+ const accounting =
185
+ raw.promptTokenAccounting === 'exclusive' || modelText.startsWith('claude') || hasAnthropicFields
186
+ ? 'anthropic_exclusive'
187
+ : 'presplit_exclusive';
188
+
189
+ return {
190
+ accounting,
191
+ freshInputTokens,
192
+ cacheCreationTokens: cacheCreation,
193
+ uncached,
194
+ cacheRead,
195
+ totalPrompt,
196
+ hitRate: totalPrompt > 0 ? cacheRead / totalPrompt : null
197
+ };
198
+ }
199
+
200
+ /**
201
+ * Computes normalized cache hit rate (`cacheRead / totalPrompt`) across Gemini inclusive
202
+ * and Anthropic/pre-split exclusive token schemas.
203
+ */
204
+ export function computeNormalizedCacheHitRate(raw = {}, canonicalModelId = '') {
205
+ return normalizeCacheTokenAccounting(raw, canonicalModelId);
206
+ }
207
+
208
+ function toSec(raw) {
209
+ if (typeof raw.start === 'number' && Number.isFinite(raw.start)) return raw.start;
210
+ if (raw.timestampSec !== undefined && raw.timestampSec !== null) {
211
+ const s = Number(raw.timestampSec);
212
+ if (Number.isFinite(s)) return s;
213
+ }
214
+ if (raw.timestampMs !== undefined && raw.timestampMs !== null) {
215
+ const ms = Number(raw.timestampMs);
216
+ if (Number.isFinite(ms)) return ms / 1000;
217
+ }
218
+ if (typeof raw.createdAt === 'string' && raw.createdAt.trim()) {
219
+ const ms = Date.parse(raw.createdAt.trim());
220
+ if (Number.isFinite(ms)) return ms / 1000;
221
+ }
222
+ if (typeof raw.createdAt === 'number' && Number.isFinite(raw.createdAt)) {
223
+ return raw.createdAt > 1e12 ? raw.createdAt / 1000 : raw.createdAt;
224
+ }
225
+ return null;
226
+ }
227
+
228
+ function normalizeCallRecord(raw = {}, orderIdx = 0) {
229
+ const preAcct = normalizeCacheTokenAccounting(raw);
230
+ const valInput = preAcct.accounting === 'gemini_inclusive'
231
+ ? { ...raw, uncachedTokens: preAcct.uncached, cachedTokens: preAcct.cacheRead, promptTokens: preAcct.totalPrompt }
232
+ : raw;
233
+ const val = valuateCall(valInput);
234
+ const acct = normalizeCacheTokenAccounting(raw, val.card.modelId);
235
+ const uncached = preAcct.accounting === 'gemini_inclusive'
236
+ ? preAcct.uncached
237
+ : (val.uncachedTokens + val.write5mTokens + val.write1hTokens);
238
+ const cacheRead = preAcct.accounting === 'gemini_inclusive'
239
+ ? preAcct.cacheRead
240
+ : val.cachedTokens;
241
+ const prompt = uncached + cacheRead;
242
+ const startSec = toSec(raw);
243
+ const endSec = (typeof raw.end === 'number' && Number.isFinite(raw.end)) ? raw.end : startSec;
244
+ const uncachedUsd = (val.card.unmappedModel || val.inputUncachedUsd === null)
245
+ ? null
246
+ : (val.inputUncachedUsd + (val.cacheWriteSurchargeUsd || 0));
247
+ const model = raw.model || raw.modelId || val.card.rawModel || 'unknown';
248
+ const label = raw.label || null;
249
+ const gemini4Family = detectGemini4Family(val.card.modelId) || detectGemini4Family(label) || detectGemini4Family(model);
250
+ const cacheCreationTokens = val.write5mTokens + val.write1hTokens;
251
+
252
+ return {
253
+ conv: String(raw.conv || raw.sessionId || 'default'),
254
+ idx: raw.idx ?? raw.stepIndex ?? orderIdx,
255
+ orderIdx,
256
+ model,
257
+ label,
258
+ canonicalModelId: val.card.modelId,
259
+ gemini4Family,
260
+ isClaude55: isClaude55Model(val.card.modelId, model),
261
+ accounting: acct.accounting,
262
+ streamKey: `${raw.model || raw.modelId || ''}|${raw.label || ''}`,
263
+ uncached,
264
+ cacheRead,
265
+ cacheCreationTokens,
266
+ prompt,
267
+ startSec,
268
+ endSec,
269
+ minCacheableTokens: val.card.minCacheableTokens || 4096,
270
+ uncachedUsd,
271
+ hadCompactionBefore: Boolean(raw.hadCompactionBefore),
272
+ isCompactSummary: Boolean(raw.isCompactSummary),
273
+ isCompactionBoundary: Boolean(raw.isCompactionBoundary),
274
+ isSubagent: Boolean(raw.isSubagent || raw.isSidechain),
275
+ shapeHash: raw.shapeHash || null,
276
+ toolsetHash: raw.toolsetHash || null,
277
+ hadToolsetChange: Boolean(raw.hadToolsetChange),
278
+ hadMcpReload: Boolean(raw.hadMcpReload),
279
+ hadHookEdit: Boolean(raw.hadHookEdit),
280
+ claudeCodeVersion: raw.claudeCodeVersion || null,
281
+ had1hTtl: Boolean(raw.cacheTtlTier === '1h' || Number(raw.cacheCreationEphemeral1hInputTokens || 0) > 0)
282
+ };
283
+ }
284
+
285
+ function classifyUpstreamProviderEviction(c, prevAny, idleSec, idleThreshold) {
286
+ const C = PROVIDER_QUIRK_CONSTANTS;
287
+ const localMutation = Boolean(
288
+ c.hadToolsetChange ||
289
+ c.hadMcpReload ||
290
+ c.hadHookEdit ||
291
+ (c.toolsetHash && prevAny.toolsetHash && c.toolsetHash !== prevAny.toolsetHash) ||
292
+ (c.shapeHash && prevAny.shapeHash && c.shapeHash !== prevAny.shapeHash)
293
+ );
294
+ if (localMutation || !c.gemini4Family) return null;
295
+
296
+ const prevPrompt = prevAny.prompt;
297
+ if (
298
+ c.cacheRead >= C.SHARD_CUT_MIN_TOKENS &&
299
+ c.cacheRead <= C.SHARD_CUT_MAX_TOKENS &&
300
+ prevPrompt > C.SHARD_CUT_MAX_TOKENS
301
+ ) {
302
+ return { pattern: 'prefix_shard_cut', issueRef: '#200026' };
303
+ }
304
+ const promptDelta = c.prompt - prevPrompt;
305
+ if (
306
+ c.cacheRead === 0 &&
307
+ (idleSec === null || idleSec < idleThreshold) &&
308
+ Math.abs(promptDelta - C.SERVER_INJECTION_DELTA_TOKENS) <= C.SERVER_INJECTION_TOLERANCE_TOKENS
309
+ ) {
310
+ return { pattern: 'server_701_injection', issueRef: '#200026' };
311
+ }
312
+ const isNeonOrCarbon = c.gemini4Family === 'Neon' || c.gemini4Family === 'Carbon';
313
+ if (c.cacheRead === 0 && isNeonOrCarbon && idleSec !== null && idleSec <= C.SHORT_GAP_EVICTION_MAX_SECONDS) {
314
+ return { pattern: 'neon_carbon_short_cliff', issueRef: '#1665' };
315
+ }
316
+ if (
317
+ c.cacheRead === 0 &&
318
+ isNeonOrCarbon &&
319
+ idleSec !== null &&
320
+ idleSec >= C.BIMODAL_EVICTION_MIN_SECONDS &&
321
+ idleSec <= C.BIMODAL_EVICTION_MAX_SECONDS
322
+ ) {
323
+ return { pattern: 'neon_carbon_bimodal_3_4m_cliff', issueRef: '#1665' };
324
+ }
325
+ if (c.cacheRead === 0 && idleSec !== null && idleSec <= C.SHORT_GAP_EVICTION_MAX_SECONDS) {
326
+ return { pattern: 'short_gap_eviction', issueRef: '#1665' };
327
+ }
328
+ return null;
329
+ }
330
+
331
+ function prorateUsd(rawUsd, partTokens, totalTokens) {
332
+ if (rawUsd === null || !Number.isFinite(rawUsd) || totalTokens <= 0 || partTokens <= 0) return 0;
333
+ return rawUsd * (partTokens / totalTokens);
334
+ }
335
+
336
+ /**
337
+ * Partitions every model call in `calls` into exactly one mutually exclusive bucket so
338
+ * `reconciledSumTokens === totalUncachedTokens` (`reconciliationDeltaTokens === 0`).
339
+ */
340
+ export function attributeUncachedTokens(calls = [], options = {}) {
341
+ const idleMissSeconds = Number.isFinite(Number(options.idleMissSeconds)) ? Number(options.idleMissSeconds) : 300;
342
+ const idle1hTtlSeconds = Number.isFinite(Number(options.idle1hTtlSeconds)) ? Number(options.idle1hTtlSeconds) : 3600;
343
+ const hitMinCachedShare = Number.isFinite(Number(options.hitMinCachedShare)) ? Number(options.hitMinCachedShare) : 0.50;
344
+ const compactionShrinkRatio = Number.isFinite(Number(options.compactionShrinkRatio)) ? Number(options.compactionShrinkRatio) : 0.80;
345
+ const unexplainedMinShare = Number.isFinite(Number(options.unexplainedMinShare)) ? Number(options.unexplainedMinShare) : 0.35;
346
+ const maxExamples = Math.max(0, Number(options.maxExamples ?? 5));
347
+ const gemini4AppendFloorTokens = Number.isFinite(Number(options.gemini4AppendFloorTokens))
348
+ ? Math.max(0, Number(options.gemini4AppendFloorTokens))
349
+ : PROVIDER_QUIRK_CONSTANTS.GEMINI4_APPEND_FLOOR_TOKENS;
350
+
351
+ const bucketState = {};
352
+ for (const name of ATTRIBUTION_BUCKETS) {
353
+ bucketState[name] = { calls: 0, tokens: 0, rawUsd: 0 };
354
+ }
355
+ bucketState.cold_start.subagentCalls = 0;
356
+
357
+ const appendFloorState = { calls: 0, tokens: 0, rawUsd: 0 };
358
+ const newTurnDeltaState = { calls: 0, tokens: 0, rawUsd: 0 };
359
+ const upstreamEvictionState = { calls: 0, tokens: 0, rawUsd: 0, byPattern: {} };
360
+ const actionableResetState = { calls: 0, tokens: 0, rawUsd: 0 };
361
+ const claude55MissState = { calls: 0, tokens: 0, cacheCreationTokens: 0, rawUsd: 0 };
362
+ const orchestratorThrashState = { calls: 0, tokens: 0, rawUsd: 0 };
363
+ const accountingTotals = {
364
+ gemini_inclusive: { calls: 0, promptTokens: 0, cacheReadTokens: 0 },
365
+ anthropic_exclusive: { calls: 0, promptTokens: 0, cacheReadTokens: 0 },
366
+ presplit_exclusive: { calls: 0, promptTokens: 0, cacheReadTokens: 0 }
367
+ };
368
+ let totalPromptTokens = 0;
369
+ let totalCacheReadTokens = 0;
370
+ const unexplainedExamples = [];
371
+
372
+ const byConv = new Map();
373
+ let totalUncachedTokens = 0;
374
+ for (let i = 0; i < calls.length; i++) {
375
+ const norm = normalizeCallRecord(calls[i], i);
376
+ totalUncachedTokens += norm.uncached;
377
+ totalPromptTokens += norm.prompt;
378
+ totalCacheReadTokens += norm.cacheRead;
379
+ const acctAgg = accountingTotals[norm.accounting];
380
+ if (acctAgg) {
381
+ acctAgg.calls += 1;
382
+ acctAgg.promptTokens += norm.prompt;
383
+ acctAgg.cacheReadTokens += norm.cacheRead;
384
+ }
385
+ if (!byConv.has(norm.conv)) byConv.set(norm.conv, []);
386
+ byConv.get(norm.conv).push(norm);
387
+ }
388
+
389
+ for (const list of byConv.values()) {
390
+ const allTimed = list.every((c) => c.startSec !== null);
391
+ list.sort((a, b) => {
392
+ if (allTimed && a.startSec !== b.startSec) return a.startSec - b.startSec;
393
+ return a.orderIdx - b.orderIdx;
394
+ });
395
+
396
+ let prevAny = null;
397
+ let prevPrevAny = null;
398
+ const lastByKey = new Map();
399
+
400
+ for (const c of list) {
401
+ let bucket = 'incremental_tail';
402
+ let resetContext = null;
403
+ let prevRefForFloor = prevAny;
404
+
405
+ if (!prevAny) {
406
+ bucket = 'cold_start';
407
+ if (c.isSubagent) bucketState.cold_start.subagentCalls += 1;
408
+ } else if (c.hadCompactionBefore || c.isCompactSummary || c.isCompactionBoundary) {
409
+ bucket = 'compaction_rebuild';
410
+ } else {
411
+ const prevSame = lastByKey.get(c.streamKey) || null;
412
+ const prevSamePrompt = prevSame ? prevSame.prompt : 0;
413
+ const prevAnyPrompt = prevAny.prompt;
414
+ const sameHit = Boolean(
415
+ prevSame &&
416
+ prevSamePrompt >= c.minCacheableTokens &&
417
+ (c.cacheRead / prevSamePrompt) >= hitMinCachedShare
418
+ );
419
+
420
+ if (sameHit) {
421
+ bucket = 'incremental_tail';
422
+ prevRefForFloor = prevSame;
423
+ } else if (c.streamKey !== prevAny.streamKey) {
424
+ if (prevSame) {
425
+ const sameIdleSec = (c.startSec !== null && prevSame.endSec !== null)
426
+ ? Math.max(0, c.startSec - prevSame.endSec)
427
+ : null;
428
+ const sameIdleThreshold = prevSame.had1hTtl ? idle1hTtlSeconds : idleMissSeconds;
429
+ if (prevSamePrompt < c.minCacheableTokens) {
430
+ bucket = 'cold_start';
431
+ } else if (c.prompt < compactionShrinkRatio * prevSamePrompt) {
432
+ bucket = 'compaction_rebuild';
433
+ } else if (sameIdleSec !== null && sameIdleSec >= sameIdleThreshold) {
434
+ bucket = 'idle_ttl_miss';
435
+ } else {
436
+ bucket = 'model_or_effort_switch';
437
+ }
438
+ } else {
439
+ if (prevAnyPrompt < c.minCacheableTokens) {
440
+ bucket = 'cold_start';
441
+ } else {
442
+ const anyHit = prevAnyPrompt > 0 && (c.cacheRead / prevAnyPrompt) >= hitMinCachedShare;
443
+ if (!anyHit && c.prompt < compactionShrinkRatio * prevAnyPrompt) {
444
+ bucket = 'compaction_rebuild';
445
+ } else if (!anyHit) {
446
+ bucket = 'model_or_effort_switch';
447
+ } else {
448
+ bucket = 'incremental_tail';
449
+ }
450
+ }
451
+ }
452
+ } else {
453
+ if (prevAnyPrompt < c.minCacheableTokens) {
454
+ bucket = 'cold_start';
455
+ } else {
456
+ const hit = prevAnyPrompt > 0 && (c.cacheRead / prevAnyPrompt) >= hitMinCachedShare;
457
+ if (!hit && c.prompt < compactionShrinkRatio * prevAnyPrompt) {
458
+ bucket = 'compaction_rebuild';
459
+ } else if (!hit && c.shapeHash && prevAny.shapeHash && c.shapeHash !== prevAny.shapeHash) {
460
+ bucket = 'model_or_effort_switch';
461
+ } else {
462
+ const idleSec = (c.startSec !== null && prevAny.endSec !== null)
463
+ ? Math.max(0, c.startSec - prevAny.endSec)
464
+ : null;
465
+ const idleThreshold = prevAny.had1hTtl ? idle1hTtlSeconds : idleMissSeconds;
466
+ if (!hit && idleSec !== null && idleSec >= idleThreshold) {
467
+ bucket = 'idle_ttl_miss';
468
+ } else if (
469
+ !hit &&
470
+ (idleSec === null || idleSec < idleThreshold) &&
471
+ c.uncached >= Math.max(c.minCacheableTokens, unexplainedMinShare * prevAnyPrompt)
472
+ ) {
473
+ bucket = 'unexplained_prefix_reset';
474
+ const eviction = classifyUpstreamProviderEviction(c, prevAny, idleSec, idleThreshold);
475
+ resetContext = {
476
+ conv: c.conv,
477
+ idx: c.idx,
478
+ idleSec: idleSec === null ? null : Math.round(idleSec),
479
+ prevPrompt: prevAnyPrompt,
480
+ cacheRead: c.cacheRead,
481
+ uncached: c.uncached,
482
+ model: c.model,
483
+ label: c.label,
484
+ classification: eviction ? 'upstream_provider_eviction' : 'actionable_prefix_reset',
485
+ evictionPattern: eviction ? eviction.pattern : null,
486
+ issueRef: eviction ? eviction.issueRef : null
487
+ };
488
+ } else {
489
+ bucket = 'incremental_tail';
490
+ }
491
+ }
492
+ }
493
+ }
494
+ }
495
+
496
+ bucketState[bucket].calls += 1;
497
+ bucketState[bucket].tokens += c.uncached;
498
+ if (c.uncachedUsd !== null) bucketState[bucket].rawUsd += c.uncachedUsd;
499
+
500
+ if (bucket === 'incremental_tail') {
501
+ let appendFloorTokens = 0;
502
+ if (c.gemini4Family !== null && prevRefForFloor && c.uncached > 0) {
503
+ if (c.uncached <= gemini4AppendFloorTokens) {
504
+ appendFloorTokens = c.uncached;
505
+ } else if (
506
+ prevRefForFloor.prompt > c.cacheRead &&
507
+ (prevRefForFloor.prompt - c.cacheRead) <= gemini4AppendFloorTokens
508
+ ) {
509
+ appendFloorTokens = Math.min(c.uncached, prevRefForFloor.prompt - c.cacheRead);
510
+ }
511
+ }
512
+ const newTurnTokens = c.uncached - appendFloorTokens;
513
+ if (appendFloorTokens > 0) {
514
+ appendFloorState.calls += 1;
515
+ appendFloorState.tokens += appendFloorTokens;
516
+ appendFloorState.rawUsd += prorateUsd(c.uncachedUsd, appendFloorTokens, c.uncached);
517
+ }
518
+ if (newTurnTokens > 0 || appendFloorTokens === 0) {
519
+ newTurnDeltaState.calls += 1;
520
+ newTurnDeltaState.tokens += newTurnTokens;
521
+ newTurnDeltaState.rawUsd += prorateUsd(c.uncachedUsd, newTurnTokens, c.uncached);
522
+ }
523
+ }
524
+
525
+ if (bucket === 'unexplained_prefix_reset' && resetContext) {
526
+ if (resetContext.classification === 'upstream_provider_eviction') {
527
+ upstreamEvictionState.calls += 1;
528
+ upstreamEvictionState.tokens += c.uncached;
529
+ if (c.uncachedUsd !== null) upstreamEvictionState.rawUsd += c.uncachedUsd;
530
+ upstreamEvictionState.byPattern[resetContext.evictionPattern] =
531
+ (upstreamEvictionState.byPattern[resetContext.evictionPattern] || 0) + 1;
532
+ } else {
533
+ actionableResetState.calls += 1;
534
+ actionableResetState.tokens += c.uncached;
535
+ if (c.uncachedUsd !== null) actionableResetState.rawUsd += c.uncachedUsd;
536
+ }
537
+ unexplainedExamples.push(resetContext);
538
+ }
539
+
540
+ if (bucket === 'compaction_rebuild' && c.isClaude55) {
541
+ const effVersion = c.claudeCodeVersion || options.claudeCodeVersion || null;
542
+ const versionAffected = isVersionAtLeast(effVersion, PROVIDER_QUIRK_CONSTANTS.CLAUDE_55_COMPACT_MISS_MIN_VERSION);
543
+ const warmCache = !prevAny ||
544
+ c.startSec === null ||
545
+ prevAny.endSec === null ||
546
+ Math.max(0, c.startSec - prevAny.endSec) < (prevAny.had1hTtl ? idle1hTtlSeconds : idleMissSeconds);
547
+ const cacheMiss = prevAny
548
+ ? c.cacheRead < hitMinCachedShare * prevAny.prompt
549
+ : c.cacheRead === 0;
550
+ if (versionAffected && warmCache && cacheMiss && c.cacheCreationTokens >= c.minCacheableTokens) {
551
+ claude55MissState.calls += 1;
552
+ claude55MissState.tokens += c.uncached;
553
+ claude55MissState.cacheCreationTokens += c.cacheCreationTokens;
554
+ if (c.uncachedUsd !== null) claude55MissState.rawUsd += c.uncachedUsd;
555
+ }
556
+ }
557
+
558
+ if (bucket === 'model_or_effort_switch' && prevAny) {
559
+ const idleSec = (c.startSec !== null && prevAny.endSec !== null)
560
+ ? Math.max(0, c.startSec - prevAny.endSec)
561
+ : null;
562
+ const isOrch = isOrchestratorOrWorkerModel(c.model, c.label) || isOrchestratorOrWorkerModel(prevAny.model, prevAny.label);
563
+ const isRapidPingPong = Boolean(
564
+ prevPrevAny &&
565
+ prevPrevAny.streamKey === c.streamKey &&
566
+ c.streamKey !== prevAny.streamKey &&
567
+ idleSec !== null &&
568
+ idleSec <= PROVIDER_QUIRK_CONSTANTS.SHORT_GAP_EVICTION_MAX_SECONDS
569
+ );
570
+ if (isOrch || isRapidPingPong) {
571
+ orchestratorThrashState.calls += 1;
572
+ orchestratorThrashState.tokens += c.uncached;
573
+ if (c.uncachedUsd !== null) orchestratorThrashState.rawUsd += c.uncachedUsd;
574
+ }
575
+ }
576
+
577
+ prevPrevAny = prevAny;
578
+ prevAny = c;
579
+ lastByKey.set(c.streamKey, c);
580
+ }
581
+ }
582
+
583
+ let reconciledSumTokens = 0;
584
+ const buckets = {};
585
+ for (const name of ATTRIBUTION_BUCKETS) {
586
+ const b = bucketState[name];
587
+ reconciledSumTokens += b.tokens;
588
+ const outBucket = {
589
+ calls: b.calls,
590
+ tokens: b.tokens,
591
+ sharePct: totalUncachedTokens > 0 ? Number(((b.tokens / totalUncachedTokens) * 100).toFixed(1)) : 0,
592
+ estimatedUsd: Number(b.rawUsd.toFixed(2))
593
+ };
594
+ if (name === 'cold_start') {
595
+ outBucket.subagentCalls = b.subagentCalls;
596
+ }
597
+ if (name === 'incremental_tail') {
598
+ outBucket.subBuckets = {
599
+ provider_append_floor: {
600
+ calls: appendFloorState.calls,
601
+ tokens: appendFloorState.tokens,
602
+ shareOfBucketPct: b.tokens > 0 ? Number(((appendFloorState.tokens / b.tokens) * 100).toFixed(1)) : 0,
603
+ estimatedUsd: Number(appendFloorState.rawUsd.toFixed(2))
604
+ },
605
+ new_turn_delta: {
606
+ calls: newTurnDeltaState.calls,
607
+ tokens: newTurnDeltaState.tokens,
608
+ shareOfBucketPct: b.tokens > 0 ? Number(((newTurnDeltaState.tokens / b.tokens) * 100).toFixed(1)) : 0,
609
+ estimatedUsd: Number(newTurnDeltaState.rawUsd.toFixed(2))
610
+ }
611
+ };
612
+ }
613
+ if (name === 'compaction_rebuild' && claude55MissState.calls > 0) {
614
+ outBucket.claude55CompactCacheMiss = {
615
+ calls: claude55MissState.calls,
616
+ tokens: claude55MissState.tokens,
617
+ cacheCreationTokens: claude55MissState.cacheCreationTokens,
618
+ estimatedUsd: Number(claude55MissState.rawUsd.toFixed(2)),
619
+ issueRef: '#99624',
620
+ guidance: CLAUDE_55_COMPACT_GUIDANCE
621
+ };
622
+ }
623
+ if (name === 'model_or_effort_switch' && orchestratorThrashState.calls > 0) {
624
+ outBucket.orchestratorThrash = {
625
+ calls: orchestratorThrashState.calls,
626
+ tokens: orchestratorThrashState.tokens,
627
+ estimatedUsd: Number(orchestratorThrashState.rawUsd.toFixed(2)),
628
+ issueRef: '#1638',
629
+ guidance: ORCHESTRATOR_THRASH_GUIDANCE
630
+ };
631
+ }
632
+ if (name === 'unexplained_prefix_reset') {
633
+ outBucket.likelyCauses = [...UNEXPLAINED_RESET_LIKELY_CAUSES];
634
+ outBucket.subBuckets = {
635
+ upstream_provider_eviction: {
636
+ calls: upstreamEvictionState.calls,
637
+ tokens: upstreamEvictionState.tokens,
638
+ shareOfBucketPct: b.tokens > 0 ? Number(((upstreamEvictionState.tokens / b.tokens) * 100).toFixed(1)) : 0,
639
+ estimatedUsd: Number(upstreamEvictionState.rawUsd.toFixed(2)),
640
+ byPattern: { ...upstreamEvictionState.byPattern },
641
+ advice: UPSTREAM_EVICTION_ADVICE
642
+ },
643
+ actionable_prefix_reset: {
644
+ calls: actionableResetState.calls,
645
+ tokens: actionableResetState.tokens,
646
+ shareOfBucketPct: b.tokens > 0 ? Number(((actionableResetState.tokens / b.tokens) * 100).toFixed(1)) : 0,
647
+ estimatedUsd: Number(actionableResetState.rawUsd.toFixed(2))
648
+ }
649
+ };
650
+ outBucket.examples = unexplainedExamples
651
+ .sort((a, b) => b.uncached - a.uncached)
652
+ .slice(0, maxExamples);
653
+ }
654
+ buckets[name] = outBucket;
655
+ }
656
+
657
+ const byAccounting = {};
658
+ for (const [mode, agg] of Object.entries(accountingTotals)) {
659
+ byAccounting[mode] = {
660
+ calls: agg.calls,
661
+ promptTokens: agg.promptTokens,
662
+ cacheReadTokens: agg.cacheReadTokens,
663
+ hitRate: agg.promptTokens > 0 ? Number((agg.cacheReadTokens / agg.promptTokens).toFixed(4)) : null
664
+ };
665
+ }
666
+
667
+ return {
668
+ totalUncachedTokens,
669
+ reconciledSumTokens,
670
+ reconciliationDeltaTokens: totalUncachedTokens - reconciledSumTokens,
671
+ buckets,
672
+ providerQuirks: {
673
+ provider_append_floor: {
674
+ calls: appendFloorState.calls,
675
+ tokens: appendFloorState.tokens,
676
+ estimatedUsd: Number(appendFloorState.rawUsd.toFixed(2)),
677
+ floorTokens: gemini4AppendFloorTokens
678
+ },
679
+ upstream_provider_eviction: {
680
+ calls: upstreamEvictionState.calls,
681
+ tokens: upstreamEvictionState.tokens,
682
+ estimatedUsd: Number(upstreamEvictionState.rawUsd.toFixed(2)),
683
+ byPattern: { ...upstreamEvictionState.byPattern },
684
+ advice: UPSTREAM_EVICTION_ADVICE
685
+ },
686
+ claude55_compact_cache_miss: {
687
+ calls: claude55MissState.calls,
688
+ tokens: claude55MissState.tokens,
689
+ cacheCreationTokens: claude55MissState.cacheCreationTokens,
690
+ estimatedUsd: Number(claude55MissState.rawUsd.toFixed(2)),
691
+ issueRef: '#99624',
692
+ guidance: CLAUDE_55_COMPACT_GUIDANCE
693
+ },
694
+ orchestrator_thrash: {
695
+ calls: orchestratorThrashState.calls,
696
+ tokens: orchestratorThrashState.tokens,
697
+ estimatedUsd: Number(orchestratorThrashState.rawUsd.toFixed(2)),
698
+ issueRef: '#1638',
699
+ guidance: ORCHESTRATOR_THRASH_GUIDANCE
700
+ }
701
+ },
702
+ normalizedHitRate: {
703
+ totalPromptTokens,
704
+ cacheReadTokens: totalCacheReadTokens,
705
+ uncachedTokens: totalUncachedTokens,
706
+ hitRate: totalPromptTokens > 0 ? Number((totalCacheReadTokens / totalPromptTokens).toFixed(4)) : null,
707
+ byAccounting
708
+ }
709
+ };
710
+ }
711
+
712
+ export default {
713
+ PROVIDER_QUIRK_CONSTANTS,
714
+ ATTRIBUTION_BUCKETS,
715
+ UNEXPLAINED_RESET_LIKELY_CAUSES,
716
+ normalizeCacheTokenAccounting,
717
+ computeNormalizedCacheHitRate,
718
+ attributeUncachedTokens
719
+ };