@alexgreensh/token-optimizer 5.13.69 → 5.13.71
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +729 -767
- package/skills/token-optimizer/assets/savings_story.js +765 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +34 -76
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +144 -30
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -1,122 +1,20 @@
|
|
|
1
1
|
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
2
|
from __future__ import annotations
|
|
3
|
-
from . import _compat
|
|
4
|
-
|
|
3
|
+
from . import _compat, baseline_provenance, own_price_card, counted_orphans, counted_subagents, headline, structural_report, savings_story, transcript_stream, token_type_split, upgrade_drain_control
|
|
5
4
|
|
|
6
5
|
def _counted_event_utc(ts):
|
|
7
|
-
"""
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
"""Convert local event timestamps to UTC, respecting local DST."""
|
|
7
|
+
import os, time
|
|
8
|
+
from . import timestamp_cache
|
|
10
9
|
_measure_facade = _compat.facade()
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
return dt.astimezone(_measure_facade.timezone.utc).replace(tzinfo=None)
|
|
14
|
-
except (ValueError, TypeError, OSError):
|
|
15
|
-
return None
|
|
10
|
+
return timestamp_cache.parse(str(ts), _measure_facade.datetime, _measure_facade.timezone.utc,
|
|
11
|
+
os.environ.get('TZ'), time.tzname)
|
|
16
12
|
|
|
17
13
|
|
|
18
14
|
def _counted_walk_transcript(path, collect_markers=None):
|
|
19
|
-
"""
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
turns = [(utc-naive datetime, raw model id, full prompt tokens,
|
|
23
|
-
(cache write tokens, 1h part, 5m part, cache read tokens) or None)]
|
|
24
|
-
-- parent API calls, deduped on requestId/message.id (Claude Code
|
|
25
|
-
writes one assistant line per content block, all sharing the
|
|
26
|
-
same usage);
|
|
27
|
-
compacts= [utc-naive datetime] of real compact_boundary system lines;
|
|
28
|
-
markers = [(utc-naive datetime-or-None, tokens-or-None)] for
|
|
29
|
-
"Full result archived" injections (collect_markers only).
|
|
30
|
-
Never raises; returns ([], [], []) on unreadable files.
|
|
31
|
-
"""
|
|
32
|
-
_measure_facade = _compat.facade()
|
|
33
|
-
turns, compacts, markers = [], [], []
|
|
34
|
-
seen = {}
|
|
35
|
-
last_ts = None
|
|
36
|
-
try:
|
|
37
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
38
|
-
for line in f:
|
|
39
|
-
if collect_markers and "Full result archived" in line:
|
|
40
|
-
m = _measure_facade._COUNTED_MARKER_RX.search(line)
|
|
41
|
-
tok = None
|
|
42
|
-
if m and m.group(1):
|
|
43
|
-
tok = max(1, int(m.group(1).replace(",", "")) // 4)
|
|
44
|
-
markers.append((last_ts, tok))
|
|
45
|
-
if '"assistant"' not in line and "compact_boundary" not in line:
|
|
46
|
-
continue
|
|
47
|
-
try:
|
|
48
|
-
d = _measure_facade.json.loads(line)
|
|
49
|
-
except (_measure_facade.json.JSONDecodeError, ValueError):
|
|
50
|
-
continue
|
|
51
|
-
if not isinstance(d, dict):
|
|
52
|
-
continue
|
|
53
|
-
t = d.get("type")
|
|
54
|
-
ts = d.get("timestamp")
|
|
55
|
-
dt = None
|
|
56
|
-
if ts:
|
|
57
|
-
try:
|
|
58
|
-
dt = _measure_facade.datetime.strptime(str(ts)[:19], "%Y-%m-%dT%H:%M:%S")
|
|
59
|
-
except (ValueError, TypeError):
|
|
60
|
-
dt = None
|
|
61
|
-
if dt is not None:
|
|
62
|
-
last_ts = dt
|
|
63
|
-
if t == "system" and d.get("subtype") == "compact_boundary":
|
|
64
|
-
if dt is not None:
|
|
65
|
-
compacts.append(dt)
|
|
66
|
-
continue
|
|
67
|
-
if t != "assistant" or d.get("isSidechain"):
|
|
68
|
-
continue
|
|
69
|
-
msg = d.get("message") or {}
|
|
70
|
-
if not isinstance(msg, dict) or not msg.get("usage"):
|
|
71
|
-
continue
|
|
72
|
-
rid = _measure_facade._usage_request_key(d, msg)
|
|
73
|
-
if dt is None:
|
|
74
|
-
continue
|
|
75
|
-
# Raw model id: re-reads are priced by generation card
|
|
76
|
-
# (Opus 5.5 and Fable 5.1 read cache far cheaper than their family).
|
|
77
|
-
raw_model = msg.get("model")
|
|
78
|
-
usage = msg["usage"] if isinstance(msg["usage"], dict) else {}
|
|
79
|
-
prompt_parts = {k: usage[k] for k in (
|
|
80
|
-
"input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens") if k in usage}
|
|
81
|
-
nested = usage.get("cache_creation")
|
|
82
|
-
nested = nested if isinstance(nested, dict) else {}
|
|
83
|
-
for key in ("ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"):
|
|
84
|
-
if key in nested or key in usage:
|
|
85
|
-
prompt_parts[key] = nested.get(key) or usage.get(key, 0)
|
|
86
|
-
if rid is not None and rid in seen:
|
|
87
|
-
index, previous_parts = seen[rid]
|
|
88
|
-
for key, value in previous_parts.items():
|
|
89
|
-
current = prompt_parts.get(key)
|
|
90
|
-
if isinstance(value, int) and (not isinstance(current, int) or value > current):
|
|
91
|
-
prompt_parts[key] = value
|
|
92
|
-
prompt_tokens = None
|
|
93
|
-
cache_class = None
|
|
94
|
-
if ("input_tokens" in prompt_parts
|
|
95
|
-
and all(isinstance(v, int) and v >= 0 for v in prompt_parts.values())):
|
|
96
|
-
# Flat and TTL fields describe overlapping cache writes.
|
|
97
|
-
# Partial chunks can fill either form; never add both.
|
|
98
|
-
creation = max(prompt_parts.get("cache_creation_input_tokens", 0),
|
|
99
|
-
prompt_parts.get("ephemeral_1h_input_tokens", 0)
|
|
100
|
-
+ prompt_parts.get("ephemeral_5m_input_tokens", 0))
|
|
101
|
-
prompt_tokens = _measure_facade._context_token_count(dict(prompt_parts, cache_creation_input_tokens=creation))
|
|
102
|
-
cache_class = (creation, prompt_parts.get("ephemeral_1h_input_tokens", 0),
|
|
103
|
-
prompt_parts.get("ephemeral_5m_input_tokens", 0),
|
|
104
|
-
prompt_parts.get("cache_read_input_tokens", 0))
|
|
105
|
-
if rid is not None and rid in seen:
|
|
106
|
-
previous = turns[index]
|
|
107
|
-
turns[index] = (previous[0], previous[1] or raw_model, prompt_tokens, cache_class)
|
|
108
|
-
seen[rid] = (index, prompt_parts)
|
|
109
|
-
continue
|
|
110
|
-
if rid is not None:
|
|
111
|
-
seen[rid] = (len(turns), prompt_parts)
|
|
112
|
-
turns.append((dt, raw_model if isinstance(raw_model, str)
|
|
113
|
-
and not raw_model.startswith("<") else None, prompt_tokens, cache_class))
|
|
114
|
-
except (OSError, PermissionError):
|
|
115
|
-
return [], [], []
|
|
116
|
-
turns.sort(key=lambda x: ((_measure_facade := _compat.facade()), x[0])[1])
|
|
117
|
-
compacts.sort()
|
|
118
|
-
return turns, compacts, markers
|
|
119
|
-
|
|
15
|
+
"""Parent-transcript walk for the counted engine; see counted_subagents.walk.
|
|
16
|
+
Returns (turns, compacts, markers); never raises."""
|
|
17
|
+
return _compat.facade()._counted_subagents.walk(_compat.facade(), path, collect_markers)
|
|
120
18
|
|
|
121
19
|
def _claude_image_tokens(width, height):
|
|
122
20
|
"""Image input tokens on Claude: about width*height/750, after the API
|
|
@@ -144,7 +42,7 @@ def _counted_media_results(path):
|
|
|
144
42
|
import fnmatch
|
|
145
43
|
names, results = {}, []
|
|
146
44
|
try:
|
|
147
|
-
with
|
|
45
|
+
with transcript_stream.open_transcript(path) as f:
|
|
148
46
|
for line in f:
|
|
149
47
|
if '"tool_use"' not in line and '"tool_result"' not in line:
|
|
150
48
|
continue
|
|
@@ -370,8 +268,8 @@ def _counted_score_detail(turns, compacts, ev_dt, tokens, tier_data, oneshot_flo
|
|
|
370
268
|
import bisect as _bisect
|
|
371
269
|
import math
|
|
372
270
|
out = dict.fromkeys(_measure_facade._COUNTED_COVERAGE_KEYS, 0)
|
|
373
|
-
out.update(oneshot_usd=0.0, oneshot_class_premium_usd=0.0, reread_tokens=0,
|
|
374
|
-
|
|
271
|
+
out.update(oneshot_usd=0.0, oneshot_class_premium_usd=0.0, reread_tokens=0, reread_usd=0.0,
|
|
272
|
+
turns_counted=0, observed=False, reread_miss_turns=0, reread_miss_premium_usd=0.0)
|
|
375
273
|
times = [turn[0] for turn in turns]
|
|
376
274
|
first = _bisect.bisect_right(times, ev_dt)
|
|
377
275
|
boundary = next((c for c in compacts if c > ev_dt), None)
|
|
@@ -387,10 +285,13 @@ def _counted_score_detail(turns, compacts, ev_dt, tokens, tier_data, oneshot_flo
|
|
|
387
285
|
rate, basis = _measure_facade._counted_oneshot_rate(card, cache_class)
|
|
388
286
|
if oneshot_floor_only and basis == "class":
|
|
389
287
|
rate, basis = card["input"], "floor"
|
|
390
|
-
else:
|
|
391
|
-
rate = (card
|
|
288
|
+
else: # Rebuilds reaching the removal position use the write class.
|
|
289
|
+
rate, miss = _measure_facade._counted_pricing_v5.reread_turn_rate(card, turns[i][3] if len(turns[i]) > 3 else None, tokens, _measure_facade._counted_oneshot_rate, turns[i][2] if len(turns[i]) > 2 else None, turns[first][2] if len(turns[first]) > 2 else None)
|
|
392
290
|
out["reread_tokens"] += tokens
|
|
393
291
|
out["turns_counted"] += 1
|
|
292
|
+
if miss:
|
|
293
|
+
out["reread_miss_turns"] += 1
|
|
294
|
+
out["reread_miss_premium_usd"] += tokens * (rate - card["cache_read"]) / 1e6
|
|
394
295
|
if isinstance(rate, (int, float)) and math.isfinite(rate) and rate >= 0:
|
|
395
296
|
out[kind + "_usd"] += tokens * rate / 1e6
|
|
396
297
|
out["priced_oneshot_events" if kind == "oneshot" else "priced_reread_turns"] += 1
|
|
@@ -435,12 +336,18 @@ def _counted_window_summary(conn, window_start, window_end):
|
|
|
435
336
|
coverage = dict.fromkeys(_measure_facade._COUNTED_COVERAGE_KEYS, 0)
|
|
436
337
|
missing = dict(unmeasured_events=0, unmeasured_removed_tokens=0,
|
|
437
338
|
unmeasured_removed_credit_tokens=0, unmeasured_removed_debit_tokens=0)
|
|
438
|
-
|
|
339
|
+
candidates, direct = counted_orphans.window_events(_measure_facade, conn, _measure_facade._counted_candidate_events(conn)); scopes = {}
|
|
340
|
+
for _key, session_uuid, ts, tokens, _logged_cost, _model in candidates:
|
|
439
341
|
ev_dt = _measure_facade._counted_event_utc(ts)
|
|
440
342
|
if ev_dt is None or ev_dt < start or ev_dt > end:
|
|
441
343
|
continue
|
|
442
344
|
path = _measure_facade._counted_session_path(conn, session_uuid)
|
|
443
345
|
turns, compacts, _ = _measure_facade._counted_walk_transcript(path) if path is not None else ([], [], [])
|
|
346
|
+
if turns and session_uuid not in scopes: # v6: a sub-agent's removal scores on its own turns
|
|
347
|
+
scopes[session_uuid] = counted_orphans.apply_scope(counted_subagents.SessionScope(_measure_facade, conn, path, [(c[0], c[2]) for c in candidates if c[1] == session_uuid]), {c[0]: direct[c[0]] for c in candidates if c[1] == session_uuid and c[0] in direct}, path)
|
|
348
|
+
if turns and _key in scopes[session_uuid].unresolved: turns = []
|
|
349
|
+
if turns:
|
|
350
|
+
turns, compacts, _scope = scopes[session_uuid].turns_for(_key, turns, compacts)
|
|
444
351
|
if not turns:
|
|
445
352
|
missing["unmeasured_events"] += 1
|
|
446
353
|
missing["unmeasured_removed_tokens"] += int(tokens or 0)
|
|
@@ -643,6 +550,8 @@ def _counted_store_score(conn, key, source, uuid, ts, tokens, score, mtime,
|
|
|
643
550
|
"""Replace only a complete continuation of the previously observed file."""
|
|
644
551
|
_measure_facade = _compat.facade()
|
|
645
552
|
detail = _measure_facade._counted_pricing_detail(old["pricing_detail"]) if old else {}
|
|
553
|
+
if counted_orphans.can_relocate(old, key, source, ts, tokens, identity_verified):
|
|
554
|
+
old = None # versioned rebuild from a previously unlocated, zero-reread row
|
|
646
555
|
if old:
|
|
647
556
|
size = detail.get("file_size")
|
|
648
557
|
if size is not None:
|
|
@@ -675,7 +584,9 @@ def _counted_store_score(conn, key, source, uuid, ts, tokens, score, mtime,
|
|
|
675
584
|
return False
|
|
676
585
|
detail = {key: score[key] for key in _measure_facade._COUNTED_COVERAGE_KEYS}
|
|
677
586
|
detail.update(oneshot_class_premium_usd=round(score["oneshot_class_premium_usd"], 6),
|
|
678
|
-
|
|
587
|
+
reread_miss_turns=score.get("reread_miss_turns", 0),
|
|
588
|
+
reread_miss_premium_usd=round(score.get("reread_miss_premium_usd", 0.0), 6),
|
|
589
|
+
version=_measure_facade._COUNTED_PRICING_VERSION, refresh_incomplete=False, scope=score.get("scope", "parent"), resolved_agent=score.get("resolved_agent"),
|
|
679
590
|
magnitude_basis=magnitude_basis, file_size=proof["file_size"],
|
|
680
591
|
file_sha256=proof["file_sha256"])
|
|
681
592
|
conn.execute(
|
|
@@ -700,48 +611,27 @@ def _update_counted_cumulative(conn, max_sessions=None,
|
|
|
700
611
|
quiet=None):
|
|
701
612
|
"""Incrementally (re)compute counted_reread rows in the collect pass.
|
|
702
613
|
|
|
703
|
-
A session is
|
|
704
|
-
|
|
705
|
-
session keeps accruing re-reads). Unchanged sessions cost one stat() each.
|
|
706
|
-
Bounded by `max_sessions` and a soft wall-clock deadline so a hook-path
|
|
707
|
-
flush is never held up; the backlog converges over passes. Fail-open."""
|
|
614
|
+
A session is rewalked when events are new or its transcript has grown.
|
|
615
|
+
Bounded by a soft deadline; the backlog converges over passes. Fail-open."""
|
|
708
616
|
_measure_facade = _compat.facade()
|
|
709
|
-
|
|
710
|
-
|
|
617
|
+
from . import first_read_revive, mod_compaction_booking
|
|
618
|
+
first_read_revive.reconcile(conn, _measure_facade.SNAPSHOT_DIR)
|
|
619
|
+
stats = {"sessions_walked": 0, "rows_written": 0, "pending_sessions": 0, "unmeasured_events": 0, **_compat.facade()._counted_subagents.collect_stats()}
|
|
711
620
|
try:
|
|
712
621
|
started = _measure_facade.time.monotonic()
|
|
713
|
-
#
|
|
714
|
-
|
|
715
|
-
duplicates = conn.execute(
|
|
716
|
-
"DELETE FROM counted_reread WHERE event_key IN "
|
|
717
|
-
"(SELECT 'ce:'||id FROM compression_events "
|
|
718
|
-
"WHERE feature IN ('delta_read', 'structure_map'))")
|
|
719
|
-
stats["duplicate_rows_removed"] = max(0, duplicates.rowcount)
|
|
720
|
-
if duplicates.rowcount:
|
|
721
|
-
conn.commit()
|
|
722
|
-
# Derived rows whose source event is not a saving (see the counted
|
|
723
|
-
# views) are recomputable cache; drop them so they stop compounding.
|
|
724
|
-
if _measure_facade._ensure_counted_views(conn):
|
|
725
|
-
gone = conn.execute(_measure_facade._COUNTED_REREAD_PURGE_EXCLUDED_SQL)
|
|
726
|
-
stats["excluded_rows_removed"] = max(0, gone.rowcount)
|
|
727
|
-
if gone.rowcount:
|
|
728
|
-
conn.commit()
|
|
622
|
+
# Duplicate derived rows remain as evidence and are excluded at read time.
|
|
623
|
+
stats['duplicate_rows_removed'] = 0
|
|
729
624
|
_measure_facade._reprice_counted_rows_once(conn)
|
|
730
|
-
events = _measure_facade._counted_candidate_events(conn)
|
|
625
|
+
events = _measure_facade._counted_candidate_events(conn); mod_features = mod_compaction_booking.event_features(conn)
|
|
731
626
|
if not events:
|
|
732
627
|
return stats
|
|
733
628
|
stored = _measure_facade._counted_stored_rows(conn)
|
|
734
|
-
by_sess =
|
|
735
|
-
for key, uuid, ts, tok, cost, model in events:
|
|
736
|
-
by_sess.setdefault(uuid, []).append((key, ts, tok, cost, model))
|
|
629
|
+
by_sess, orphan_paths = counted_orphans.group_events(_measure_facade, conn, events, resolve=deadline_seconds is None)
|
|
737
630
|
tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
|
|
738
631
|
|
|
739
|
-
# Unjoinable events (no session uuid) have no transcript to price. Keep
|
|
740
|
-
# them out of the counted ledger rather than inventing a one-shot value.
|
|
741
632
|
for key, ts, tok, cost, model in by_sess.pop(None, []) + by_sess.pop("", []):
|
|
742
633
|
stats["unmeasured_events"] += 1
|
|
743
634
|
|
|
744
|
-
# Which sessions need a walk?
|
|
745
635
|
todo = []
|
|
746
636
|
for uuid, evs in by_sess.items():
|
|
747
637
|
path = _measure_facade._counted_session_path(conn, uuid)
|
|
@@ -758,14 +648,15 @@ def _update_counted_cumulative(conn, max_sessions=None,
|
|
|
758
648
|
continue
|
|
759
649
|
def fresh_event(key):
|
|
760
650
|
_measure_facade = _compat.facade()
|
|
761
|
-
if key not in stored:
|
|
651
|
+
if key not in stored or transcript_stream.needs_resume(orphan_paths.get(key, path)):
|
|
762
652
|
return False
|
|
763
653
|
detail = _measure_facade._counted_pricing_detail(stored[key].get("pricing_detail"))
|
|
654
|
+
st = orphan_paths.get(key, path).stat(); event_stamp = [st.st_mtime_ns, st.st_size]
|
|
764
655
|
if detail.get("refresh_incomplete"):
|
|
765
656
|
return (detail.get("attempted_version") == _measure_facade._COUNTED_PRICING_VERSION
|
|
766
|
-
and detail.get("attempted_source") ==
|
|
767
|
-
return (stored[key]["transcript_mtime"] ==
|
|
768
|
-
and detail.get("file_size") ==
|
|
657
|
+
and detail.get("attempted_source") == event_stamp)
|
|
658
|
+
return (stored[key]["transcript_mtime"] == st.st_mtime
|
|
659
|
+
and detail.get("file_size") == event_stamp[1]
|
|
769
660
|
and detail.get("version") == _measure_facade._COUNTED_PRICING_VERSION)
|
|
770
661
|
fresh = all(fresh_event(key) for key, *_ in evs)
|
|
771
662
|
if not fresh:
|
|
@@ -782,7 +673,7 @@ def _update_counted_cumulative(conn, max_sessions=None,
|
|
|
782
673
|
_measure_facade._counted_pricing_detail(stored[key].get("pricing_detail")).get("file_size", 0)
|
|
783
674
|
for key, *_ in evs if key in stored])
|
|
784
675
|
turns, compacts, _ = _measure_facade._counted_walk_transcript(path)
|
|
785
|
-
if path.stat().st_mtime_ns != proof["mtime_ns"] or path.stat().st_size != proof["file_size"]:
|
|
676
|
+
if transcript_stream.needs_resume(path) or path.stat().st_mtime_ns != proof["mtime_ns"] or path.stat().st_size != proof["file_size"]:
|
|
786
677
|
raise OSError("transcript changed while scoring")
|
|
787
678
|
except OSError:
|
|
788
679
|
if proof is None:
|
|
@@ -805,8 +696,12 @@ def _update_counted_cumulative(conn, max_sessions=None,
|
|
|
805
696
|
media_details.update(conn.execute(
|
|
806
697
|
"SELECT id, detail FROM savings_events WHERE id IN (%s)"
|
|
807
698
|
% ",".join("?" * len(part)), part).fetchall())
|
|
699
|
+
scope = counted_orphans.apply_scope(counted_subagents.SessionScope(_measure_facade, conn, path, [(e[0], e[1]) for e in evs]), {e[0]: orphan_paths[e[0]] for e in evs if e[0] in orphan_paths}, path)
|
|
700
|
+
counted_subagents.add_stats(stats, scope.stats)
|
|
701
|
+
event_proofs = {}
|
|
808
702
|
for key, ts, tok, cost, model in sorted(evs, key=lambda e: ((_measure_facade := _compat.facade()), str(e[1]))[1]):
|
|
809
703
|
ev_dt = _measure_facade._counted_event_utc(ts)
|
|
704
|
+
if key in scope.unresolved: stats["unmeasured_events"] += 1; continue
|
|
810
705
|
if ev_dt is None or not turns:
|
|
811
706
|
if key in stored:
|
|
812
707
|
_measure_facade._counted_mark_incomplete(conn, key, _measure_facade._counted_pricing_detail(stored[key].get("pricing_detail")), proof)
|
|
@@ -816,16 +711,22 @@ def _update_counted_cumulative(conn, max_sessions=None,
|
|
|
816
711
|
if key.startswith("md:"):
|
|
817
712
|
tok, basis = _measure_facade._counted_media_net_tokens(
|
|
818
713
|
media_results, media_used, ev_dt, media_details.get(int(key[3:])))
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
714
|
+
event_path = orphan_paths.get(key, path); before_walk = event_path.stat()
|
|
715
|
+
ev_turns, ev_compacts, ev_scope = scope.turns_for(key, turns, compacts)
|
|
716
|
+
score = dict(_measure_facade._counted_score_detail(ev_turns, ev_compacts, ev_dt, int(tok or 0), tier_data,
|
|
717
|
+
oneshot_floor_only=key.startswith("md:")), scope=ev_scope, resolved_agent=event_path.name if key in orphan_paths and ev_scope == "subagent" else None); score = mod_compaction_booking.adjust_score(_measure_facade, *mod_features[key], ev_turns, ev_dt, int(tok or 0), tier_data, score) if key in mod_features else score
|
|
718
|
+
old_size = (_measure_facade._counted_pricing_detail(stored[key].get("pricing_detail")).get("file_size", 0) or 0) if key in stored else 0; proof_key = (event_path, old_size, before_walk.st_mtime_ns, before_walk.st_size)
|
|
719
|
+
if proof_key not in event_proofs: event_proofs[proof_key] = _measure_facade._counted_file_proof(event_path, [old_size])
|
|
720
|
+
event_proof = event_proofs[proof_key]; event_stat = event_path.stat(); event_mtime = event_stat.st_mtime
|
|
721
|
+
if transcript_stream.needs_resume(event_path) or (before_walk.st_mtime_ns, before_walk.st_size) != (event_proof["mtime_ns"], event_proof["file_size"]) or (event_stat.st_mtime_ns, event_stat.st_size) != (event_proof["mtime_ns"], event_proof["file_size"]):
|
|
722
|
+
stats["unmeasured_events"] += 1; continue
|
|
822
723
|
if not _measure_facade._counted_store_score(conn, key, key.split(":", 1)[0], uuid,
|
|
823
|
-
ts, int(tok or 0), score,
|
|
824
|
-
old=stored.get(key), allow_unobserved=True,
|
|
724
|
+
ts, int(tok or 0), score, event_mtime, event_proof,
|
|
725
|
+
old=stored.get(key), allow_unobserved=True, identity_verified=key in orphan_paths,
|
|
825
726
|
magnitude_basis=basis,
|
|
826
727
|
append_check=lambda old, _ev=ev_dt, _tok=int(tok or 0): (
|
|
827
728
|
((_measure_facade := _compat.facade()), _measure_facade._counted_legacy_append_continuous(
|
|
828
|
-
old,
|
|
729
|
+
old, ev_turns, ev_compacts, _ev, _tok, tier_data))[1])):
|
|
829
730
|
stats["unmeasured_events"] += 1
|
|
830
731
|
continue
|
|
831
732
|
stats["rows_written"] += 1
|
|
@@ -910,6 +811,9 @@ def _counted_marker_backfill(conn, max_files=None,
|
|
|
910
811
|
processed_any = False
|
|
911
812
|
last = cursor
|
|
912
813
|
for sp in paths:
|
|
814
|
+
if processed_any and _measure_facade._collect_drain_mode() == "full":
|
|
815
|
+
upgrade_drain_control.commit_marker_cursor(conn, _measure_facade._COUNTED_META_MARKER_CURSOR, last)
|
|
816
|
+
processed_any = False
|
|
913
817
|
if sp <= cursor:
|
|
914
818
|
continue
|
|
915
819
|
if max_files is not None and stats["files_scanned"] >= max_files:
|
|
@@ -998,8 +902,7 @@ def _counted_marker_backfill(conn, max_files=None,
|
|
|
998
902
|
"VALUES (?, '1')", (_measure_facade._COUNTED_META_MARKER_DONE,))
|
|
999
903
|
stats["done"] = True
|
|
1000
904
|
else:
|
|
1001
|
-
|
|
1002
|
-
"VALUES (?, ?)", (_measure_facade._COUNTED_META_MARKER_CURSOR, last))
|
|
905
|
+
upgrade_drain_control.commit_marker_cursor(conn, _measure_facade._COUNTED_META_MARKER_CURSOR, last)
|
|
1003
906
|
conn.commit()
|
|
1004
907
|
if not quiet and stats["rows_written"]:
|
|
1005
908
|
print(f"[Token Optimizer] counted-cumulative marker backfill: "
|
|
@@ -1017,24 +920,7 @@ def _purge_counted_without_transcripts(conn):
|
|
|
1017
920
|
|
|
1018
921
|
def _counted_backfill_all(conn, quiet=None):
|
|
1019
922
|
"""Finish refresh attempts; unverifiable history stays quarantined."""
|
|
1020
|
-
|
|
1021
|
-
stats = _measure_facade._update_counted_cumulative(
|
|
1022
|
-
conn, max_sessions=10**9, deadline_seconds=None, quiet=quiet)
|
|
1023
|
-
marker_total = {"files_scanned": 0, "rows_written": 0, "done": False}
|
|
1024
|
-
while True:
|
|
1025
|
-
marker = _measure_facade._counted_marker_backfill(
|
|
1026
|
-
conn, max_files=500, deadline_seconds=None, quiet=quiet)
|
|
1027
|
-
marker_total["files_scanned"] += int(marker.get("files_scanned", 0) or 0)
|
|
1028
|
-
marker_total["rows_written"] += int(marker.get("rows_written", 0) or 0)
|
|
1029
|
-
marker_total["done"] = bool(marker.get("done"))
|
|
1030
|
-
if marker.get("done") or not marker.get("files_scanned"):
|
|
1031
|
-
break
|
|
1032
|
-
stats.update({"marker_files_scanned": marker_total["files_scanned"],
|
|
1033
|
-
"marker_rows_written": marker_total["rows_written"],
|
|
1034
|
-
"marker_backfill_done": marker_total["done"],
|
|
1035
|
-
"rows_removed_no_transcript": _measure_facade._purge_counted_without_transcripts(conn)})
|
|
1036
|
-
stats["pricing_coverage"] = _measure_facade._counted_rollup_rows(_measure_facade._counted_stored_rows(conn).values(), conn)
|
|
1037
|
-
return stats
|
|
923
|
+
return upgrade_drain_control.counted_backfill_all(_compat.facade(), conn, quiet)
|
|
1038
924
|
|
|
1039
925
|
|
|
1040
926
|
def _counted_session_cache_mix(conn, session_uuid, tier_data, memo, rate_key=None):
|
|
@@ -1060,23 +946,13 @@ def _counted_session_cache_mix(conn, session_uuid, tier_data, memo, rate_key=Non
|
|
|
1060
946
|
except (_measure_facade.sqlite3.Error, TypeError, ValueError):
|
|
1061
947
|
breakdown = None
|
|
1062
948
|
if isinstance(breakdown, dict):
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
weight = parts.get("cache_read") if isinstance(parts, dict) else None
|
|
1066
|
-
if not isinstance(weight, int) or isinstance(weight, bool) or weight <= 0:
|
|
1067
|
-
continue
|
|
1068
|
-
card = _measure_facade._counted_exact_card(model, tier_data)
|
|
1069
|
-
rate = (card or {}).get(rate_key)
|
|
1070
|
-
if not (isinstance(rate, (int, float)) and _measure_facade.math.isfinite(rate) and rate >= 0):
|
|
1071
|
-
rate = None
|
|
1072
|
-
terms.append((weight, rate))
|
|
1073
|
-
if any(rate is not None for _, rate in terms):
|
|
1074
|
-
mix = terms
|
|
949
|
+
mix = _measure_facade._counted_pricing_v5.session_cache_mix_terms(
|
|
950
|
+
breakdown, lambda model: _measure_facade._counted_exact_card(model, tier_data), rate_key)
|
|
1075
951
|
memo[memo_key] = mix
|
|
1076
952
|
return mix
|
|
1077
953
|
|
|
1078
954
|
|
|
1079
|
-
def _counted_rollup_rows(rows, conn=None):
|
|
955
|
+
def _counted_rollup_rows(rows, conn=None, mix_memo=None):
|
|
1080
956
|
"""Only per-row verified prices are eligible; retain all stored token evidence.
|
|
1081
957
|
|
|
1082
958
|
A stored row without a current per-turn price keeps its signed repeat-read
|
|
@@ -1089,11 +965,12 @@ def _counted_rollup_rows(rows, conn=None):
|
|
|
1089
965
|
out = dict.fromkeys(_measure_facade._COUNTED_COVERAGE_KEYS, 0)
|
|
1090
966
|
out.update(events=0, removed_tokens=0, reread_tokens=0, oneshot_usd=0.0,
|
|
1091
967
|
oneshot_class_premium_usd=0.0, reread_usd=0.0, legacy_unverified_events=0,
|
|
968
|
+
reread_miss_turns=0, reread_miss_premium_usd=0.0,
|
|
1092
969
|
unverified_history_events=0, estimated_magnitude_events=0,
|
|
1093
970
|
refresh_incomplete_events=0, reread_session_mix_priced_tokens=0,
|
|
1094
971
|
session_mix_priced_events=0)
|
|
1095
972
|
tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
|
|
1096
|
-
mix_memo = {}
|
|
973
|
+
if mix_memo is None: mix_memo = {}
|
|
1097
974
|
for row in rows:
|
|
1098
975
|
out["events"] += 1
|
|
1099
976
|
tokens, rereads = int(row["tokens"] or 0), int(row["reread_tokens"] or 0)
|
|
@@ -1106,6 +983,8 @@ def _counted_rollup_rows(rows, conn=None):
|
|
|
1106
983
|
out["oneshot_usd"] += float(row["oneshot_usd"] or 0)
|
|
1107
984
|
out["reread_usd"] += float(row["reread_usd"] or 0)
|
|
1108
985
|
out["oneshot_class_premium_usd"] += float(detail.get("oneshot_class_premium_usd") or 0)
|
|
986
|
+
out["reread_miss_turns"] += int(detail.get("reread_miss_turns") or 0)
|
|
987
|
+
out["reread_miss_premium_usd"] += float(detail.get("reread_miss_premium_usd") or 0)
|
|
1109
988
|
for key in _measure_facade._COUNTED_COVERAGE_KEYS:
|
|
1110
989
|
out[key] += detail[key]
|
|
1111
990
|
else:
|
|
@@ -1115,30 +994,17 @@ def _counted_rollup_rows(rows, conn=None):
|
|
|
1115
994
|
input_mix = (_measure_facade._counted_session_cache_mix(conn, row.get("session_uuid"), tier_data,
|
|
1116
995
|
mix_memo, rate_key="input")
|
|
1117
996
|
if conn is not None and tokens else None)
|
|
1118
|
-
for kind, amount in (("oneshot", tokens), ("reread", rereads)):
|
|
1119
|
-
if
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
amount = int(_measure_facade.math.copysign(abs(amount) - priced, amount))
|
|
1130
|
-
if kind == "reread" and mix:
|
|
1131
|
-
total_weight = sum(weight for weight, _ in mix)
|
|
1132
|
-
rated = [(weight, rate) for weight, rate in mix if rate is not None]
|
|
1133
|
-
rated_weight = sum(weight for weight, _ in rated)
|
|
1134
|
-
priced = round(abs(amount) * rated_weight / total_weight)
|
|
1135
|
-
out["reread_usd"] += (_measure_facade.math.copysign(1, amount) * abs(amount)
|
|
1136
|
-
* sum(weight * rate for weight, rate in rated)
|
|
1137
|
-
/ total_weight / 1e6)
|
|
1138
|
-
out["reread_session_mix_priced_tokens"] += priced
|
|
1139
|
-
out["session_mix_priced_events"] += 1
|
|
1140
|
-
out["priced_reread_turns"] += max(1, int(row.get("turns_counted") or 0))
|
|
1141
|
-
amount = int(_measure_facade.math.copysign(abs(amount) - priced, amount))
|
|
997
|
+
for kind, amount, terms in (("oneshot", tokens, input_mix), ("reread", rereads, mix)):
|
|
998
|
+
if terms:
|
|
999
|
+
usd, priced, amount = _measure_facade._counted_pricing_v5.session_mix_price(amount, terms)
|
|
1000
|
+
out[kind + "_usd"] += usd
|
|
1001
|
+
if kind == "oneshot":
|
|
1002
|
+
out["oneshot_floor_events"] += 1
|
|
1003
|
+
out["oneshot_floor_tokens"] += priced
|
|
1004
|
+
else:
|
|
1005
|
+
out["reread_session_mix_priced_tokens"] += priced
|
|
1006
|
+
out["session_mix_priced_events"] += 1
|
|
1007
|
+
out["priced_reread_turns"] += max(1, int(row.get("turns_counted") or 0))
|
|
1142
1008
|
out[kind + "_unpriced_" + ("credit" if amount >= 0 else "debit") + "_tokens"] += abs(amount)
|
|
1143
1009
|
if not current and row["transcript_mtime"] is None and row["source"] != "mk":
|
|
1144
1010
|
out["unverified_history_events"] += 1
|
|
@@ -1148,6 +1014,7 @@ def _counted_rollup_rows(rows, conn=None):
|
|
|
1148
1014
|
out["refresh_incomplete_events"] += bool(detail.get("refresh_incomplete"))
|
|
1149
1015
|
out["oneshot_usd"] = round(out["oneshot_usd"], 6)
|
|
1150
1016
|
out["oneshot_class_premium_usd"] = round(out["oneshot_class_premium_usd"], 6)
|
|
1017
|
+
out["reread_miss_premium_usd"] = round(out["reread_miss_premium_usd"], 6)
|
|
1151
1018
|
out["reread_usd"] = round(out["reread_usd"], 6)
|
|
1152
1019
|
out["total_usd"] = round(out["oneshot_usd"] + out["reread_usd"], 6)
|
|
1153
1020
|
return _measure_facade._counted_coverage_totals(out)
|
|
@@ -1191,8 +1058,10 @@ def _counted_cumulative_summary(days=None, now=None):
|
|
|
1191
1058
|
"SELECT 'ce:'||id FROM counted_compression_events"))
|
|
1192
1059
|
rows = []
|
|
1193
1060
|
stored = _measure_facade._counted_stored_rows(conn)
|
|
1061
|
+
candidates = _measure_facade._counted_candidate_events(conn)
|
|
1062
|
+
orphaned = _measure_facade._counted_pricing_v5.orphaned_keys(stored.values(), {c[0] for c in candidates}, conn)
|
|
1194
1063
|
for row in stored.values():
|
|
1195
|
-
if row["event_key"] in excluded:
|
|
1064
|
+
if row["event_key"] in excluded or row["event_key"] in orphaned:
|
|
1196
1065
|
continue
|
|
1197
1066
|
if start is not None:
|
|
1198
1067
|
if row["source"] == "mk":
|
|
@@ -1210,7 +1079,7 @@ def _counted_cumulative_summary(days=None, now=None):
|
|
|
1210
1079
|
continue
|
|
1211
1080
|
rows.append(row)
|
|
1212
1081
|
missing_by_month = {}
|
|
1213
|
-
for key, _uuid, ts, tokens, _cost, _model in
|
|
1082
|
+
for key, _uuid, ts, tokens, _cost, _model in candidates:
|
|
1214
1083
|
# A media archive without a row has no measured size yet; it
|
|
1215
1084
|
# adds nothing until the collect pass sizes it from its transcript.
|
|
1216
1085
|
if key in stored or key.startswith("md:"):
|
|
@@ -1230,7 +1099,8 @@ def _counted_cumulative_summary(days=None, now=None):
|
|
|
1230
1099
|
coverage["unmeasured_removed_debit_tokens"] = sum(-n for n in amounts if n < 0)
|
|
1231
1100
|
return _measure_facade._counted_coverage_totals(coverage)
|
|
1232
1101
|
|
|
1233
|
-
|
|
1102
|
+
mix_memo = {}
|
|
1103
|
+
totals = add_missing(_measure_facade._counted_rollup_rows(rows, conn, mix_memo),
|
|
1234
1104
|
[n for values in missing_by_month.values() for n in values])
|
|
1235
1105
|
# Rows stored under an older pricing version that the collect pass
|
|
1236
1106
|
# has not yet tried to re-score. Their price in the subtotal is
|
|
@@ -1254,7 +1124,7 @@ def _counted_cumulative_summary(days=None, now=None):
|
|
|
1254
1124
|
by_month = {}
|
|
1255
1125
|
for row in rows:
|
|
1256
1126
|
by_month.setdefault(row["event_month"], []).append(row)
|
|
1257
|
-
monthly_coverage = {m: add_missing(_measure_facade._counted_rollup_rows(by_month.get(m, []), conn),
|
|
1127
|
+
monthly_coverage = {m: add_missing(_measure_facade._counted_rollup_rows(by_month.get(m, []), conn, mix_memo),
|
|
1258
1128
|
missing_by_month.get(m, []))
|
|
1259
1129
|
for m in sorted(by_month.keys() | missing_by_month.keys(),
|
|
1260
1130
|
key=lambda month: month or "")}
|
|
@@ -1273,7 +1143,7 @@ def _counted_cumulative_summary(days=None, now=None):
|
|
|
1273
1143
|
return {
|
|
1274
1144
|
**totals,
|
|
1275
1145
|
"available": True,
|
|
1276
|
-
"attribution": "removal_time",
|
|
1146
|
+
"attribution": "removal_time", "token_type_breakdown": token_type_split.from_rows(rows, _measure_facade._COUNTED_PRICING_VERSION),
|
|
1277
1147
|
"period_start": start.isoformat() if start else None,
|
|
1278
1148
|
"period_end": end.isoformat(),
|
|
1279
1149
|
"window_start": (first_month + "-01") if first_month else None,
|
|
@@ -1288,6 +1158,7 @@ def _counted_cumulative_summary(days=None, now=None):
|
|
|
1288
1158
|
"media_priced_events": len(media_priced),
|
|
1289
1159
|
"media_removed_tokens": sum(int(row["tokens"] or 0) for row in media_priced),
|
|
1290
1160
|
"media_note": media_note,
|
|
1161
|
+
"orphaned_rows_excluded": len(orphaned),
|
|
1291
1162
|
# Same construction as the estimated tiers: the method is counted,
|
|
1292
1163
|
# the one modeling choice (trajectory held fixed) is disclosed on
|
|
1293
1164
|
# the card.
|
|
@@ -1320,8 +1191,19 @@ def _dashboard_savings_data(days=None, include_billing_mode=None, fail_open=None
|
|
|
1320
1191
|
if not isinstance(savings_data, dict):
|
|
1321
1192
|
savings_data = {"total_tokens": 0, "total_cost_usd": 0.0,
|
|
1322
1193
|
"by_category": {}}
|
|
1194
|
+
savings_data.pop("mcp_cap_estimated", None)
|
|
1323
1195
|
if source_failed:
|
|
1196
|
+
# Keep the bare fail-open shape: callers compare it verbatim to decide
|
|
1197
|
+
# whether the savings source produced a real payload.
|
|
1324
1198
|
return savings_data
|
|
1199
|
+
try:
|
|
1200
|
+
from . import cost_per_message_trend
|
|
1201
|
+
conn = _measure_facade._open_trends_db_readonly(timeout=1.0)
|
|
1202
|
+
try: savings_data["cost_per_message_trend"] = cost_per_message_trend.query(conn)
|
|
1203
|
+
finally: conn.close()
|
|
1204
|
+
except Exception:
|
|
1205
|
+
savings_data["cost_per_message_trend"] = []
|
|
1206
|
+
savings_data["skill_listing_budget"] = structural_report.skill_listing_budget(days or 30)
|
|
1325
1207
|
try:
|
|
1326
1208
|
savings_data["since_install"] = _measure_facade._savings_since_install()
|
|
1327
1209
|
except Exception:
|
|
@@ -1336,9 +1218,16 @@ def _dashboard_savings_data(days=None, include_billing_mode=None, fail_open=None
|
|
|
1336
1218
|
savings_data["counted_period"] = _measure_facade._counted_cumulative_summary(days=days)
|
|
1337
1219
|
except Exception:
|
|
1338
1220
|
savings_data["counted_period"] = {"available": False}
|
|
1221
|
+
savings_data["token_type_breakdown"] = (savings_data["counted_period"] or {}).get("token_type_breakdown", {})
|
|
1222
|
+
_compat.facade()._headline.attach(savings_data, days)
|
|
1339
1223
|
_measure_facade._apply_counted_oneshot_pricing(savings_data, savings_data["counted_period"])
|
|
1340
1224
|
savings_data["action_savings"] = _measure_facade._action_savings_components(
|
|
1341
1225
|
savings_data, savings_data["counted_period"])
|
|
1226
|
+
try:
|
|
1227
|
+
from . import savings_headline
|
|
1228
|
+
savings_data["savings_headline"] = savings_headline.build(savings_data)
|
|
1229
|
+
except Exception:
|
|
1230
|
+
savings_data["savings_headline"] = None
|
|
1342
1231
|
if include_billing_mode:
|
|
1343
1232
|
try:
|
|
1344
1233
|
savings_data["billing_mode"] = _measure_facade.keepwarm_billing_mode()
|
|
@@ -1359,8 +1248,8 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1359
1248
|
Returns (by_category, total_tokens, total_cost, total_events, popped,
|
|
1360
1249
|
repriced_to_session_mix) where *popped* holds the entries relocated out of
|
|
1361
1250
|
the realized total (setup_optimization, mcp_cap, hint_followed,
|
|
1362
|
-
verbosity_steer, resume_lean, checkpoint_restore),
|
|
1363
|
-
None.
|
|
1251
|
+
verbosity_steer, resume_lean, checkpoint_restore, verbosity_steer_measured),
|
|
1252
|
+
each an entry dict or None.
|
|
1364
1253
|
"""
|
|
1365
1254
|
_measure_facade = _compat.facade()
|
|
1366
1255
|
by_category = {}
|
|
@@ -1392,78 +1281,41 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1392
1281
|
total_cost += _delta
|
|
1393
1282
|
repriced_to_session_mix = True
|
|
1394
1283
|
|
|
1395
|
-
#
|
|
1396
|
-
#
|
|
1397
|
-
#
|
|
1398
|
-
#
|
|
1399
|
-
#
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
#
|
|
1408
|
-
#
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
#
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
# verbosity_steer: the UserPromptSubmit nudge is a deterministic trigger
|
|
1428
|
-
# but the output-token reduction is an ESTIMATE (we can't measure the
|
|
1429
|
-
# counterfactual output). Relocate to estimated tier, same as mcp_cap /
|
|
1430
|
-
# hint_followed. The trigger is observed; the magnitude is not metered.
|
|
1431
|
-
verbosity_steer_est = by_category.pop("verbosity_steer", None)
|
|
1432
|
-
if verbosity_steer_est:
|
|
1433
|
-
total_tokens -= int(verbosity_steer_est.get("tokens_saved", 0) or 0)
|
|
1434
|
-
total_cost -= float(verbosity_steer_est.get("cost_saved_usd", 0.0) or 0.0)
|
|
1435
|
-
total_events -= int(verbosity_steer_est.get("events", 0) or 0)
|
|
1436
|
-
|
|
1437
|
-
# resume_lean is a COUNTERFACTUAL --
|
|
1438
|
-
# the cold `claude --resume` the user would otherwise have run -- not a
|
|
1439
|
-
# removal of tokens already in flight (260/370 real events fired on the
|
|
1440
|
-
# best-guess "continue" path). v5.13.1 fixed its magnitude (target's
|
|
1441
|
-
# real last-turn context) and rate (cache-read when the cache is still
|
|
1442
|
-
# warm, 1h cache-write when cold), but the trigger stays counterfactual,
|
|
1443
|
-
# so it must not sit inside the measured counted total. Relocate to the
|
|
1444
|
-
# estimated tier exactly like mcp_cap. savings_events has no tier
|
|
1445
|
-
# column: this pop IS the tier=estimated stamp.
|
|
1446
|
-
resume_lean_est = by_category.pop("resume_lean", None)
|
|
1447
|
-
if resume_lean_est:
|
|
1448
|
-
total_tokens -= int(resume_lean_est.get("tokens_saved", 0) or 0)
|
|
1449
|
-
total_cost -= float(resume_lean_est.get("cost_saved_usd", 0.0) or 0.0)
|
|
1450
|
-
total_events -= int(resume_lean_est.get("events", 0) or 0)
|
|
1451
|
-
|
|
1452
|
-
# checkpoint_restore credits the working set the resumed session SKIPS
|
|
1453
|
-
# re-reading (_checkpoint_restore_recovery_tokens). That re-read never
|
|
1454
|
-
# happens, so nothing was metered: the magnitude is inferred from this
|
|
1455
|
-
# session's own read history, not observed avoided usage. Same class as
|
|
1456
|
-
# resume_lean -- counterfactual credit, estimated tier. Relocate it out of
|
|
1457
|
-
# the realized total; the pop IS the tier=estimated stamp.
|
|
1458
|
-
checkpoint_restore_est = by_category.pop("checkpoint_restore", None)
|
|
1459
|
-
if checkpoint_restore_est:
|
|
1460
|
-
total_tokens -= int(checkpoint_restore_est.get("tokens_saved", 0) or 0)
|
|
1461
|
-
total_cost -= float(checkpoint_restore_est.get("cost_saved_usd", 0.0) or 0.0)
|
|
1462
|
-
total_events -= int(checkpoint_restore_est.get("events", 0) or 0)
|
|
1284
|
+
# Relocated OUT of the realized total, each into its own non-realized line:
|
|
1285
|
+
# setup_optimization (A1): one-time prefix trim; structural_savings is the
|
|
1286
|
+
# ongoing model of the SAME trim, so the one-shot is never summed with it.
|
|
1287
|
+
# mcp_cap (A3): hardcoded-ratio estimate of Claude Code's own truncation.
|
|
1288
|
+
# hint_followed (U-G), verbosity_steer: observed trigger, estimated size.
|
|
1289
|
+
# resume_lean, checkpoint_restore: counterfactual credits (the cold
|
|
1290
|
+
# reload / working-set re-read never happened, so nothing was metered).
|
|
1291
|
+
# verbosity_steer_measured (savings-truth U5): a before/after of output
|
|
1292
|
+
# with no control. Against matched un-nudged replies it is not a
|
|
1293
|
+
# reduction, so both booked rows and the control study stay diagnostic.
|
|
1294
|
+
# savings_events has no tier column: this pop IS the tier=estimated stamp.
|
|
1295
|
+
popped = {}
|
|
1296
|
+
# codemap_lookup: a lookup answered instead of a Read; the avoided read is
|
|
1297
|
+
# a counterfactual (file not read within the follow-up window).
|
|
1298
|
+
for name in ("setup_optimization", "mcp_cap", "hint_followed", "verbosity_steer",
|
|
1299
|
+
"resume_lean", "checkpoint_restore", "verbosity_steer_measured",
|
|
1300
|
+
"codemap_lookup", "keepwarm_estimated"):
|
|
1301
|
+
entry = popped[name] = by_category.pop(name, None)
|
|
1302
|
+
if entry:
|
|
1303
|
+
total_tokens -= int(entry.get("tokens_saved", 0) or 0)
|
|
1304
|
+
total_cost -= float(entry.get("cost_saved_usd", 0.0) or 0.0)
|
|
1305
|
+
total_events -= int(entry.get("events", 0) or 0)
|
|
1306
|
+
|
|
1307
|
+
# Bash archive expansions reverse Bash output savings, not MCP replacements.
|
|
1308
|
+
bash = by_category.get("bash_archive_reexpand")
|
|
1309
|
+
if bash:
|
|
1310
|
+
total_tokens -= 2 * int(bash.get("tokens_saved") or 0)
|
|
1311
|
+
total_cost -= 2 * float(bash.get("cost_saved_usd") or 0)
|
|
1312
|
+
total_events -= int(bash.get("events") or 0)
|
|
1313
|
+
bash["tokens_saved"] = -int(bash.get("tokens_saved") or 0)
|
|
1314
|
+
bash["cost_saved_usd"] = -float(bash.get("cost_saved_usd") or 0)
|
|
1463
1315
|
|
|
1464
1316
|
# B6: net tool-archive re-expansions out of the tool_archive credit. A
|
|
1465
1317
|
# re-popped result didn't stay collapsed, so its eager credit is reversed
|
|
1466
|
-
#
|
|
1318
|
+
# even if the result is negative. tool_archive_reexpand is a DEBIT, never its own savings
|
|
1467
1319
|
# line, so it is removed from by_category and its spurious positive
|
|
1468
1320
|
# contribution backed out of the totals. The remaining tool_archive figure
|
|
1469
1321
|
# IS the measured progressive-disclosure win (collapsed and stayed so).
|
|
@@ -1472,11 +1324,11 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1472
1324
|
r_tok = int(reexpand.get("tokens_saved", 0) or 0)
|
|
1473
1325
|
r_cost = float(reexpand.get("cost_saved_usd", 0.0) or 0.0)
|
|
1474
1326
|
r_events = int(reexpand.get("events", 0) or 0)
|
|
1475
|
-
ta = by_category.
|
|
1327
|
+
ta = by_category.setdefault("tool_archive", {"events": 0, "tokens_saved": 0, "cost_saved_usd": 0.0})
|
|
1476
1328
|
c_tok = int(ta["tokens_saved"]) if ta else 0
|
|
1477
1329
|
c_cost = float(ta["cost_saved_usd"]) if ta else 0.0
|
|
1478
|
-
net_tok =
|
|
1479
|
-
net_cost =
|
|
1330
|
+
net_tok = c_tok - r_tok
|
|
1331
|
+
net_cost = c_cost - r_cost
|
|
1480
1332
|
if ta:
|
|
1481
1333
|
ta["tokens_saved"] = net_tok
|
|
1482
1334
|
ta["cost_saved_usd"] = round(net_cost, 4)
|
|
@@ -1485,14 +1337,6 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1485
1337
|
total_cost += (net_cost - c_cost) - r_cost
|
|
1486
1338
|
total_events -= r_events # re-expand rows are not savings events
|
|
1487
1339
|
|
|
1488
|
-
popped = {
|
|
1489
|
-
"setup_optimization": one_time,
|
|
1490
|
-
"mcp_cap": mcp_cap_est,
|
|
1491
|
-
"hint_followed": hint_followed_est,
|
|
1492
|
-
"verbosity_steer": verbosity_steer_est,
|
|
1493
|
-
"resume_lean": resume_lean_est,
|
|
1494
|
-
"checkpoint_restore": checkpoint_restore_est,
|
|
1495
|
-
}
|
|
1496
1340
|
return (by_category, total_tokens, total_cost, total_events, popped,
|
|
1497
1341
|
repriced_to_session_mix)
|
|
1498
1342
|
|
|
@@ -1506,7 +1350,7 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1506
1350
|
boundary (e.g. the subscription limit reset). When *since* is None / empty,
|
|
1507
1351
|
the rolling cutoff is computed from *days* as before.
|
|
1508
1352
|
"""
|
|
1509
|
-
_measure_facade = _compat.facade()
|
|
1353
|
+
_measure_facade = _compat.facade(); from . import keepwarm_economics, mod_fresh_booking, mod_compaction_booking
|
|
1510
1354
|
try:
|
|
1511
1355
|
conn = _measure_facade._init_trends_db()
|
|
1512
1356
|
try:
|
|
@@ -1514,9 +1358,11 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1514
1358
|
cutoff = since
|
|
1515
1359
|
else:
|
|
1516
1360
|
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
1361
|
+
table = _measure_facade._counted_table(conn, "savings_events")
|
|
1362
|
+
event_expr = _measure_facade._counted_cap.reexpand_type() if "detail" in {r[1] for r in conn.execute(f"PRAGMA table_info({table})")} else "event_type"
|
|
1517
1363
|
rows = conn.execute(
|
|
1518
|
-
"SELECT
|
|
1519
|
-
"FROM " +
|
|
1364
|
+
"SELECT " + event_expr + ", COUNT(*) as cnt, SUM(tokens_saved) as tok, SUM(cost_saved_usd) as cost "
|
|
1365
|
+
"FROM " + table + " WHERE timestamp >= ? GROUP BY 1 ORDER BY tok DESC",
|
|
1520
1366
|
(cutoff,),
|
|
1521
1367
|
).fetchall()
|
|
1522
1368
|
# Model-mix repair, same connection and same cutoff so the corrected
|
|
@@ -1525,17 +1371,24 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1525
1371
|
unpriced_reprice = {}
|
|
1526
1372
|
reprice_deltas, repriced_tokens, unmeasured_tokens = _measure_facade._session_model_reprice(
|
|
1527
1373
|
conn, cutoff, unpriced_out=unpriced_reprice)
|
|
1374
|
+
tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
|
|
1375
|
+
resume_fix = _measure_facade._counted_pricing_v5.resume_lean_reprice(conn, _measure_facade._counted_table(conn, "savings_events"), cutoff,
|
|
1376
|
+
lambda model: _measure_facade._counted_exact_card(model, tier_data))
|
|
1528
1377
|
finally:
|
|
1529
1378
|
conn.close()
|
|
1530
1379
|
|
|
1531
1380
|
(by_category, total_tokens, total_cost, total_events, popped,
|
|
1532
1381
|
repriced_to_session_mix) = _measure_facade._net_realized_savings(rows, reprice_deltas)
|
|
1533
1382
|
one_time = popped["setup_optimization"]
|
|
1534
|
-
mcp_cap_est = popped["mcp_cap"]
|
|
1535
1383
|
hint_followed_est = popped["hint_followed"]
|
|
1384
|
+
codemap_lookup_est = popped["codemap_lookup"]
|
|
1536
1385
|
verbosity_steer_est = popped["verbosity_steer"]
|
|
1537
1386
|
resume_lean_est = popped["resume_lean"]
|
|
1387
|
+
if resume_lean_est and resume_fix["repriced_events"]: # exact model card, not the family card
|
|
1388
|
+
resume_lean_est["cost_saved_usd"] = round(max(0.0, resume_lean_est["cost_saved_usd"] + resume_fix["delta_usd"]), 4)
|
|
1389
|
+
resume_lean_est["exact_card_reprice"] = resume_fix
|
|
1538
1390
|
checkpoint_restore_est = popped["checkpoint_restore"]
|
|
1391
|
+
verbosity_output_est = _measure_facade._output_reread.summary_pool(popped["verbosity_steer_measured"])
|
|
1539
1392
|
|
|
1540
1393
|
daily_avg = total_cost / days if days > 0 else 0.0
|
|
1541
1394
|
|
|
@@ -1548,12 +1401,12 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1548
1401
|
"period_days": days,
|
|
1549
1402
|
# A1: one-time first-trim (compare). Reported separately, NEVER summed
|
|
1550
1403
|
# into the realized total (structural_savings is the ongoing model).
|
|
1551
|
-
"one_time_setup": one_time,
|
|
1552
|
-
# A3: MCP-cap estimate, relocated to the estimated tier (not realized).
|
|
1553
|
-
"mcp_cap_estimated": mcp_cap_est,
|
|
1404
|
+
"one_time_setup": one_time, "keepwarm_estimated": keepwarm_economics.headline_pool(_measure_facade, cutoff), "mod_fresh_estimated": mod_fresh_booking.summary(_measure_facade, cutoff), "mod_compaction_actions": mod_compaction_booking.summary(_measure_facade, cutoff),
|
|
1554
1405
|
# U-G: observed-trigger / estimated-magnitude avoided-search from
|
|
1555
1406
|
# proactive hints. Estimated tier, never in the realized total.
|
|
1556
1407
|
"hint_followed_estimated": hint_followed_est,
|
|
1408
|
+
# Code map lookups: observed lookup, counterfactual avoided read. Estimated tier.
|
|
1409
|
+
"codemap_lookup_estimated": codemap_lookup_est,
|
|
1557
1410
|
# Verbosity-steer: estimated output-token reduction from conciseness
|
|
1558
1411
|
# nudges. Estimated tier, never in the realized total. Surfaced so
|
|
1559
1412
|
# _estimate_before_after_savings can add it to the transformation
|
|
@@ -1568,6 +1421,9 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1568
1421
|
# from this session's reads -- the avoided re-read never happened,
|
|
1569
1422
|
# so nothing was metered. Estimated tier, never realized.
|
|
1570
1423
|
"checkpoint_restore_estimated": checkpoint_restore_est,
|
|
1424
|
+
# Nudged replies and their later rereads, net of matched un-nudged
|
|
1425
|
+
# replies (U5). Estimated tier; the booked rows are reference only.
|
|
1426
|
+
"verbosity_output_estimated": verbosity_output_est,
|
|
1571
1427
|
# True when at least one event's dollars moved because its event-time
|
|
1572
1428
|
# model stamp disagreed with its own session's recorded model mix. The
|
|
1573
1429
|
# figure is then a rate ALLOCATION, not a pure event-time meter, so
|
|
@@ -1594,11 +1450,12 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1594
1450
|
"daily_avg_usd": 0.0,
|
|
1595
1451
|
"period_days": days,
|
|
1596
1452
|
"one_time_setup": None,
|
|
1597
|
-
"mcp_cap_estimated": None,
|
|
1598
1453
|
"hint_followed_estimated": None,
|
|
1454
|
+
"codemap_lookup_estimated": None,
|
|
1599
1455
|
"verbosity_steer_estimated": None,
|
|
1600
1456
|
"resume_lean_estimated": None,
|
|
1601
1457
|
"checkpoint_restore_estimated": None,
|
|
1458
|
+
"verbosity_output_estimated": None,
|
|
1602
1459
|
"repriced_to_session_mix": False,
|
|
1603
1460
|
"reprice_detail": None,
|
|
1604
1461
|
}
|
|
@@ -2344,14 +2201,18 @@ def _runway_saved_tokens(conn, cutoff, include_estimated=None):
|
|
|
2344
2201
|
multiplier, which the card labels as an estimate.
|
|
2345
2202
|
"""
|
|
2346
2203
|
_measure_facade = _compat.facade()
|
|
2204
|
+
table = _measure_facade._counted_table(conn, "savings_events")
|
|
2205
|
+
sql = _measure_facade._RUNWAY_SAVED_SQL[table]
|
|
2206
|
+
if "detail" not in {r[1] for r in conn.execute(f"PRAGMA table_info({table})")}: sql = sql.replace(_measure_facade._counted_cap.reexpand_type(), "event_type")
|
|
2347
2207
|
by_event = {
|
|
2348
2208
|
event_type: int(tokens or 0)
|
|
2349
2209
|
for event_type, tokens in conn.execute(
|
|
2350
|
-
|
|
2210
|
+
sql, (cutoff,))
|
|
2351
2211
|
if include_estimated or event_type not in _measure_facade._RUNWAY_ESTIMATED_EVENT_TYPES}
|
|
2352
2212
|
reexpanded = by_event.pop("tool_archive_reexpand", 0)
|
|
2353
|
-
if "
|
|
2354
|
-
|
|
2213
|
+
if "bash_archive_reexpand" in by_event: by_event["bash_archive_reexpand"] *= -1
|
|
2214
|
+
if reexpanded:
|
|
2215
|
+
by_event["tool_archive"] = by_event.get("tool_archive", 0) - reexpanded
|
|
2355
2216
|
saved = sum(by_event.values())
|
|
2356
2217
|
table = _measure_facade._counted_table(conn, "compression_events")
|
|
2357
2218
|
if "feature" not in {r[1] for r in conn.execute(f"PRAGMA table_info({table})")}:
|
|
@@ -2364,7 +2225,7 @@ def _runway_saved_tokens(conn, cutoff, include_estimated=None):
|
|
|
2364
2225
|
return saved
|
|
2365
2226
|
|
|
2366
2227
|
|
|
2367
|
-
def runway_snapshot(days=None, now=None):
|
|
2228
|
+
def runway_snapshot(days=None, now=None, token_headline=None):
|
|
2368
2229
|
"""Subscription runway: how much of your rate-limit window Token Optimizer
|
|
2369
2230
|
hands back, and what the same windows would read without it.
|
|
2370
2231
|
|
|
@@ -2408,53 +2269,51 @@ def runway_snapshot(days=None, now=None):
|
|
|
2408
2269
|
_measure_facade = _compat.facade()
|
|
2409
2270
|
try:
|
|
2410
2271
|
meters = _measure_facade._keepwarm_read_meters(now=now)
|
|
2411
|
-
#
|
|
2412
|
-
# multiplier and the weekly savings come from the savings ledger, not the
|
|
2413
|
-
# meter, so an UNAVAILABLE meter (missing/contentless rate-limits file)
|
|
2414
|
-
# must NOT vanish the whole card. It drops to empty windows (the renderer
|
|
2415
|
-
# shows a "meter refreshing" note), exactly like a stale meter. Bug A: the
|
|
2416
|
-
# old `if not available: return None` killed the entire card -- multiplier
|
|
2417
|
-
# and savings included -- the moment the meter file was gone, which is the
|
|
2418
|
-
# "section disappeared and never came back" report. The window loop below
|
|
2419
|
-
# already skips a None percentage, so an unavailable meter yields [].
|
|
2272
|
+
# Missing meters leave the ledger-backed headline visible.
|
|
2420
2273
|
meter_available = bool(meters.get("available"))
|
|
2421
2274
|
meter_stale = bool(meters.get("stale")) or not meter_available
|
|
2422
2275
|
|
|
2423
|
-
|
|
2424
|
-
resets_at=meters.get("seven_day_resets_at"), now=now)
|
|
2276
|
+
weekly_signal = bool(_measure_facade._weekly_full_savings(resets_at=meters.get("seven_day_resets_at"), now=now)); weekly_full = None # Do not surface the counterfactual dollars.
|
|
2425
2277
|
|
|
2426
|
-
#
|
|
2278
|
+
# Context uses dated input and output, including cache.
|
|
2427
2279
|
consumed = saved = context_saved = 0
|
|
2428
|
-
|
|
2280
|
+
traffic = None
|
|
2429
2281
|
try:
|
|
2430
2282
|
conn = _measure_facade._init_trends_db()
|
|
2431
2283
|
try:
|
|
2432
2284
|
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
2433
|
-
|
|
2434
|
-
consumed =
|
|
2285
|
+
traffic = _compat.facade()._headline.input_traffic(conn, cutoff[:10], _measure_facade.datetime.now().date().isoformat())
|
|
2286
|
+
consumed = traffic["tokens"]
|
|
2435
2287
|
saved = _measure_facade._runway_saved_tokens(conn, cutoff)
|
|
2436
|
-
# The multiplier is an estimate (the card says so), so it keeps
|
|
2437
|
-
# the estimated tiers; the measured floor line uses `saved`.
|
|
2438
|
-
context_saved = _measure_facade._runway_saved_tokens(conn, cutoff, include_estimated=True)
|
|
2439
2288
|
finally:
|
|
2440
2289
|
conn.close()
|
|
2441
2290
|
except Exception:
|
|
2442
2291
|
return None
|
|
2443
2292
|
if consumed <= 0 and not weekly_full:
|
|
2444
2293
|
return None
|
|
2294
|
+
try:
|
|
2295
|
+
if token_headline is None:
|
|
2296
|
+
token_source = _measure_facade._get_merged_savings(days=days)
|
|
2297
|
+
token_source["counted_period"] = _measure_facade._counted_cumulative_summary(days=days)
|
|
2298
|
+
token_headline = _compat.facade()._headline.token_headline(token_source)
|
|
2299
|
+
token_parts = token_headline
|
|
2300
|
+
except Exception:
|
|
2301
|
+
token_parts = _compat.facade()._headline.token_headline({})
|
|
2302
|
+
context_saved = token_parts["total_tokens"]
|
|
2445
2303
|
context_mult = (consumed + context_saved) / consumed if consumed > 0 else 1.0
|
|
2446
2304
|
|
|
2447
2305
|
# --- routing lever: the model-routing recipe's own standardized ratio ---
|
|
2448
|
-
# Pending or unavailable routing
|
|
2449
|
-
# state is returned, never replaced by a silent 1.0.
|
|
2306
|
+
# Pending or unavailable routing remains explicit.
|
|
2450
2307
|
routing = _measure_facade._runway_routing_lever(days=days)
|
|
2451
2308
|
routing_state = routing.get("state")
|
|
2452
2309
|
routing_mult = routing.get("factor")
|
|
2453
2310
|
|
|
2454
|
-
|
|
2455
|
-
#
|
|
2456
|
-
#
|
|
2457
|
-
|
|
2311
|
+
# A heavier model mix is the user's choice, not a cost Token Optimizer
|
|
2312
|
+
# caused, so it never shrinks what TO hands back (or hides the card).
|
|
2313
|
+
# The raw factor is still reported as routing_multiplier below.
|
|
2314
|
+
mult = context_mult * max(1.0, routing_mult if routing_mult is not None else 1.0)
|
|
2315
|
+
# Hide immaterial changes unless weekly savings are available.
|
|
2316
|
+
if mult < 1.02 and not weekly_signal:
|
|
2458
2317
|
return None
|
|
2459
2318
|
|
|
2460
2319
|
# --- USD-per-window: API-credit OVERAGE over each window's OWN real span ---
|
|
@@ -2527,16 +2386,7 @@ def runway_snapshot(days=None, now=None):
|
|
|
2527
2386
|
merged_ctx = float(wm.get("total_cost_usd", 0.0) or 0.0)
|
|
2528
2387
|
rt = float((wm.get("model_routing") or {}).get("realized_cost_usd", 0.0) or 0.0)
|
|
2529
2388
|
repriced = bool(wm.get("repriced_to_session_mix"))
|
|
2530
|
-
|
|
2531
|
-
# relocates OUT of total_cost_usd into the estimated tier
|
|
2532
|
-
# (resume_lean, verbosity_steer). The counted window excludes
|
|
2533
|
-
# resume_lean too, so both the counted and legacy ctx omit them
|
|
2534
|
-
# -- real, magnitude-metered (v5.13.1) savings that were simply
|
|
2535
|
-
# unlabelled. Window-scoped already (days/since passed above).
|
|
2536
|
-
_rl = wm.get("resume_lean_estimated") or {}
|
|
2537
|
-
_vs = wm.get("verbosity_steer") or wm.get("verbosity_steer_estimated") or {}
|
|
2538
|
-
est_add = float(_rl.get("cost_saved_usd", 0.0) or 0.0) \
|
|
2539
|
-
+ float(_vs.get("cost_saved_usd", 0.0) or 0.0)
|
|
2389
|
+
est_add = max(0.0, float((wm.get("resume_lean_verified") or {}).get("cost_saved_usd") or 0.0))
|
|
2540
2390
|
except Exception:
|
|
2541
2391
|
pass
|
|
2542
2392
|
try:
|
|
@@ -2645,9 +2495,8 @@ def runway_snapshot(days=None, now=None):
|
|
|
2645
2495
|
# `if not windows: return None` then dropped the ENTIRE card -- yet the
|
|
2646
2496
|
# throughput multiplier (extra_work_pct) and the weekly savings do NOT
|
|
2647
2497
|
# depend on the live meter; they come from the 30d/7d savings ledger. Keep
|
|
2648
|
-
# the card alive with empty windows
|
|
2649
|
-
# the
|
|
2650
|
-
# note. Populate the weekly $ spine directly since the 7d window that
|
|
2498
|
+
# the card alive with empty windows (last_known_windows carries the stored
|
|
2499
|
+
# reading). Populate the weekly $ spine directly since the 7d window that
|
|
2651
2500
|
# normally fills _overage_cache[...] may have been dropped above.
|
|
2652
2501
|
#
|
|
2653
2502
|
# Compute the aligned weekly cache key (same logic as _window_overage_usd)
|
|
@@ -2712,11 +2561,11 @@ def runway_snapshot(days=None, now=None):
|
|
|
2712
2561
|
"routing_standardized_actual_cost_usd": routing.get("standardized_actual_cost_usd"),
|
|
2713
2562
|
"extra_work_pct": round((mult - 1) * 100, 1),
|
|
2714
2563
|
"tokens_consumed": int(consumed),
|
|
2715
|
-
"tokens_consumed_basis":
|
|
2716
|
-
"tokens_consumed_basis_complete": bool(
|
|
2564
|
+
"tokens_consumed_basis": traffic["basis"] if traffic else None,
|
|
2565
|
+
"tokens_consumed_basis_complete": bool(traffic and traffic["complete"]),
|
|
2717
2566
|
"tokens_saved": int(saved),
|
|
2718
|
-
"context_tokens_saved": int(context_saved),
|
|
2719
|
-
"windows": windows,
|
|
2567
|
+
"context_tokens_saved": int(context_saved), "token_headline": token_parts,
|
|
2568
|
+
"windows": windows, "last_known_windows": savings_story.last_known_windows(meters, mult, windows),
|
|
2720
2569
|
# USD spine: metered context $ + estimated routing $ over the WEEKLY
|
|
2721
2570
|
# (7d) ledger -- the same span the weekly card shows. Exposed at the top
|
|
2722
2571
|
# level so the surface and tests can assert the no-double-count invariant
|
|
@@ -2887,127 +2736,40 @@ def _per_session_prefix_tokens(fallback=None):
|
|
|
2887
2736
|
|
|
2888
2737
|
|
|
2889
2738
|
def _compound_structural(s, days, fallback_prefix):
|
|
2890
|
-
"""
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
math. Returns a dict of the three terms + totals, or None when S<=0 or no DB.
|
|
2739
|
+
"""Forward value of S prefix tokens over the window (opportunity pricing).
|
|
2740
|
+
|
|
2741
|
+
Thin caller of structural_report.price_synthetic: per request, at that
|
|
2742
|
+
request's exact model card, S x cache_read on cache hits and S x the write
|
|
2743
|
+
class actually paid on misses (session starts, sub-agent starts, cache
|
|
2744
|
+
drops). Replaces the family-keyed mix rate and the "S / prefix x ALL cache
|
|
2745
|
+
writes" term, which overstated reads ~2.4x and writes ~2.9x. Only local
|
|
2746
|
+
sessions count: synced cloud sessions never load this machine's setup.
|
|
2747
|
+
`fallback_prefix` is unused, kept for call-site symmetry. None when S<=0.
|
|
2900
2748
|
"""
|
|
2901
|
-
|
|
2902
|
-
if s <= 0 or not _measure_facade.TRENDS_DB.exists():
|
|
2749
|
+
if s <= 0:
|
|
2903
2750
|
return None
|
|
2904
|
-
|
|
2905
|
-
conn = _measure_facade._init_trends_db()
|
|
2906
|
-
_measure_facade.ensure_activity_view(conn)
|
|
2907
|
-
try:
|
|
2908
|
-
row = conn.execute(
|
|
2909
|
-
"SELECT COALESCE(SUM(api_calls),0), COALESCE(SUM(cache_create_1h_tokens),0), "
|
|
2910
|
-
"COALESCE(SUM(cache_create_5m_tokens),0), "
|
|
2911
|
-
"COALESCE(SUM(CASE WHEN COALESCE(api_calls_known,0)=0 THEN 1 ELSE 0 END),0) "
|
|
2912
|
-
"FROM session_activity WHERE date >= ?",
|
|
2913
|
-
(cutoff,),
|
|
2914
|
-
).fetchone()
|
|
2915
|
-
finally:
|
|
2916
|
-
conn.close()
|
|
2917
|
-
sum_api_calls = int(row[0] or 0)
|
|
2918
|
-
sum_cc_1h = int(row[1] or 0)
|
|
2919
|
-
sum_cc_5m = int(row[2] or 0)
|
|
2920
|
-
api_calls_unknown_days = int(row[3] or 0)
|
|
2921
|
-
|
|
2922
|
-
per_session_prefix = _measure_facade._per_session_prefix_tokens(fallback=fallback_prefix)
|
|
2923
|
-
# Blended by the window's model mix, NOT the reporting session's model:
|
|
2924
|
-
# session-model rates make the same opportunity diverge several-fold between
|
|
2925
|
-
# sessions with different cache rate tiers, run minutes apart.
|
|
2926
|
-
read_rate, write_5m_rate, write_1h_rate = _measure_facade._mix_cache_rates(days=days)
|
|
2927
|
-
# Clamp to 1.0: the prefix trim S can never cache-write more than a full
|
|
2928
|
-
# per-session prefix worth of tokens. An unclamped ratio (S > prefix, e.g.
|
|
2929
|
-
# a stale/small prefix baseline) overstated the structural write-tier >2x.
|
|
2930
|
-
write_fraction = min(1.0, s / per_session_prefix) if per_session_prefix > 0 else 0.0
|
|
2931
|
-
|
|
2932
|
-
read_savings = s * sum_api_calls * read_rate / 1_000_000
|
|
2933
|
-
write_1h_savings = write_fraction * sum_cc_1h * write_1h_rate / 1_000_000
|
|
2934
|
-
write_5m_savings = write_fraction * sum_cc_5m * write_5m_rate / 1_000_000
|
|
2935
|
-
return {
|
|
2936
|
-
"events": sum_api_calls,
|
|
2937
|
-
# api_calls is a lower bound when any activity day lacks dated call
|
|
2938
|
-
# evidence (daily_calls_json was never recorded): those days contribute
|
|
2939
|
-
# NULL, not a measured zero, and are disclosed here.
|
|
2940
|
-
"api_calls_complete": api_calls_unknown_days == 0,
|
|
2941
|
-
"api_calls_unknown_days": api_calls_unknown_days,
|
|
2942
|
-
"tokens_saved": int(s * sum_api_calls + write_fraction * (sum_cc_1h + sum_cc_5m)),
|
|
2943
|
-
"read_savings_usd": round(read_savings, 4),
|
|
2944
|
-
"write_1h_savings_usd": round(write_1h_savings, 4),
|
|
2945
|
-
"write_5m_savings_usd": round(write_5m_savings, 4),
|
|
2946
|
-
"cost_saved_usd": round(read_savings + write_1h_savings + write_5m_savings, 4),
|
|
2947
|
-
}
|
|
2751
|
+
return _compat.facade()._structural_report.price_synthetic(s, days)
|
|
2948
2752
|
|
|
2949
2753
|
|
|
2950
2754
|
def _compute_structural_savings(days=None):
|
|
2951
|
-
"""Realized structural savings
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
The earlier model compared the snapshot against session_log.input_tokens,
|
|
2962
|
-
which is the TOTAL input mix (billions/month), so the delta always floored
|
|
2963
|
-
to zero.
|
|
2964
|
-
|
|
2965
|
-
Realized stays $0 until the user prunes below the captured baseline; the
|
|
2966
|
-
opportunity figure lives in _compute_structural_potential. Labelled
|
|
2967
|
-
"estimated" (the write term divides write tokens by prefix size, which
|
|
2968
|
-
slightly overcounts when mid-conversation output is cached). Returns zeros
|
|
2969
|
-
(baseline_source=None) with no baseline. Never raises.
|
|
2755
|
+
"""Realized structural savings from the per-component trim ledger.
|
|
2756
|
+
|
|
2757
|
+
Thin caller of structural_report.compute (scripts/_measure/structural_*):
|
|
2758
|
+
each trim is a dated event (audit action, owner attestation or detected
|
|
2759
|
+
shrink), credited for sessions where its component loads, from the trim
|
|
2760
|
+
until the item comes back, priced per request. Unrelated prefix growth
|
|
2761
|
+
never offsets a trim. Measured-tier trims are in tokens_saved /
|
|
2762
|
+
cost_saved_usd; attested ("estimated") and unattributed trims are reported
|
|
2763
|
+
in their own bands and never summed here. No trims -> zeros with
|
|
2764
|
+
status "no_trims". Never raises.
|
|
2970
2765
|
"""
|
|
2971
|
-
|
|
2972
|
-
zero = {
|
|
2973
|
-
"events": 0, "tokens_saved": 0, "cost_saved_usd": 0.0,
|
|
2974
|
-
"baseline_source": None, "baseline_date": None, "overhead_delta": 0,
|
|
2975
|
-
"read_savings_usd": 0.0, "write_1h_savings_usd": 0.0,
|
|
2976
|
-
"write_5m_savings_usd": 0.0, "evidence": "estimated",
|
|
2977
|
-
}
|
|
2978
|
-
try:
|
|
2979
|
-
baseline = _measure_facade._resolve_structural_baseline(days=days)
|
|
2980
|
-
if not baseline:
|
|
2981
|
-
return zero
|
|
2982
|
-
current_overhead = _measure_facade._current_overhead_tokens()
|
|
2983
|
-
if not current_overhead:
|
|
2984
|
-
return zero
|
|
2985
|
-
baseline_overhead = int(baseline["baseline_tokens"])
|
|
2986
|
-
known = {**zero, "baseline_source": baseline["source"], "baseline_date": baseline["date"]}
|
|
2987
|
-
s = max(0, baseline_overhead - current_overhead)
|
|
2988
|
-
if s <= 0:
|
|
2989
|
-
return known # baseline known, nothing trimmed below it yet -> realized $0
|
|
2990
|
-
terms = _measure_facade._compound_structural(s, days, fallback_prefix=baseline_overhead)
|
|
2991
|
-
if not terms:
|
|
2992
|
-
return known
|
|
2993
|
-
return {
|
|
2994
|
-
**terms,
|
|
2995
|
-
"baseline_source": baseline["source"],
|
|
2996
|
-
"baseline_date": baseline["date"],
|
|
2997
|
-
"overhead_delta": s,
|
|
2998
|
-
"evidence": "estimated",
|
|
2999
|
-
}
|
|
3000
|
-
except Exception:
|
|
3001
|
-
return zero
|
|
2766
|
+
return _compat.facade()._structural_report.compute(days=days or 30)
|
|
3002
2767
|
|
|
3003
2768
|
|
|
3004
2769
|
def _unused_skill_overhead_tokens(days=None):
|
|
3005
2770
|
"""Estimate recoverable prefix tokens from skills never used in the window.
|
|
3006
2771
|
|
|
3007
|
-
|
|
3008
|
-
each installed skill costs tokens in the startup menu every session whether
|
|
3009
|
-
invoked or not. Returns (tokens, unused_count). Conservative -- counts only
|
|
3010
|
-
skills with zero invocations in `days`. Never raises.
|
|
2772
|
+
Claude listing savings require transcript evidence, so inventory is not priced.
|
|
3011
2773
|
"""
|
|
3012
2774
|
_measure_facade = _compat.facade()
|
|
3013
2775
|
try:
|
|
@@ -3042,7 +2804,7 @@ def _unused_skill_overhead_tokens(days=None):
|
|
|
3042
2804
|
else:
|
|
3043
2805
|
used.add(s)
|
|
3044
2806
|
unused = installed - used
|
|
3045
|
-
return len(unused) * avg_per_skill, len(unused)
|
|
2807
|
+
return (0 if _measure_facade.detect_runtime() == "claude" else len(unused) * avg_per_skill), len(unused)
|
|
3046
2808
|
except Exception:
|
|
3047
2809
|
return 0, 0
|
|
3048
2810
|
|
|
@@ -3065,7 +2827,7 @@ def _compute_structural_potential(days=None):
|
|
|
3065
2827
|
try:
|
|
3066
2828
|
s_potential, unused_count = _measure_facade._unused_skill_overhead_tokens(days=days)
|
|
3067
2829
|
if s_potential <= 0:
|
|
3068
|
-
return zero
|
|
2830
|
+
return {**zero, "unused_skills": int(unused_count), "basis": "no measured listing reduction"}
|
|
3069
2831
|
current_overhead = _measure_facade._current_overhead_tokens() or s_potential
|
|
3070
2832
|
terms = _measure_facade._compound_structural(s_potential, days, fallback_prefix=current_overhead)
|
|
3071
2833
|
if not terms:
|
|
@@ -3539,105 +3301,57 @@ def _estimate_output_waste(days=None):
|
|
|
3539
3301
|
|
|
3540
3302
|
|
|
3541
3303
|
def _estimate_cache_drop_savings(days=None):
|
|
3542
|
-
"""
|
|
3543
|
-
|
|
3544
|
-
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
|
|
3548
|
-
|
|
3549
|
-
|
|
3550
|
-
|
|
3551
|
-
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3304
|
+
"""Cache rebuilds after idle gaps (the 'coffee-break reload'), in dollars.
|
|
3305
|
+
|
|
3306
|
+
Reads the same engine as cache health (`_cache_ttl_waste_cached`), so the
|
|
3307
|
+
fold and the health check never disagree. A rebuild is a turn that, after
|
|
3308
|
+
a gap longer than the cache TTL the user's own writes show (1 hour for a
|
|
3309
|
+
Claude Code user writing 1h caches, 5 minutes for a 5m user), re-wrote the
|
|
3310
|
+
prefix the previous turn had cached. Each one is priced on the prefix it
|
|
3311
|
+
actually rebuilt (min of the resume write and the prior cached prefix), at
|
|
3312
|
+
that turn's 1h/5m write rate for its model, minus the cache read it would
|
|
3313
|
+
have cost with the cache alive. Only rebuilds whose resume turn falls in
|
|
3314
|
+
the window count, and a transcript copied into two directories counts
|
|
3315
|
+
once. Dollars are at API rates. Never raises.
|
|
3316
|
+
|
|
3317
|
+
Returns {drop_sessions, est_drops, prefix_tokens, rebuilt_tokens,
|
|
3318
|
+
ttl_seconds, cost_saved_usd, by_class, rate_basis, price_basis,
|
|
3319
|
+
unpriced_share, evidence}. `est_drops * prefix_tokens` approximates
|
|
3320
|
+
`rebuilt_tokens` (the average rebuilt prefix); prefer rebuilt_tokens.
|
|
3321
|
+
OPPORTUNITY tier: rebuilds that already happened, avoidable by resuming
|
|
3322
|
+
inside the TTL. Never summed into the realized total.
|
|
3561
3323
|
"""
|
|
3562
3324
|
_measure_facade = _compat.facade()
|
|
3563
|
-
zero = {"drop_sessions": 0, "est_drops": 0, "prefix_tokens": 0,
|
|
3564
|
-
"cost_saved_usd": 0.0, "evidence": "opportunity"}
|
|
3325
|
+
zero = {"drop_sessions": 0, "est_drops": 0, "prefix_tokens": 0, "rebuilt_tokens": 0,
|
|
3326
|
+
"ttl_seconds": None, "cost_saved_usd": 0.0, "evidence": "opportunity"}
|
|
3565
3327
|
try:
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
try:
|
|
3572
|
-
# Quality filter removed (audit 2026-08-29): a short automation
|
|
3573
|
-
# session that had a cache drop is still a real cache drop.
|
|
3574
|
-
drop_where = ("FROM session_activity "
|
|
3575
|
-
"WHERE date >= ? AND max_call_gap_seconds > ? "
|
|
3576
|
-
"AND input_tokens IS NOT NULL "
|
|
3577
|
-
"AND COALESCE(is_sidechain, 0) = 0")
|
|
3578
|
-
drop_sessions = conn.execute(
|
|
3579
|
-
"SELECT COUNT(*) " + drop_where, (cutoff, _measure_facade._CACHE_DROP_GAP_SECONDS),
|
|
3580
|
-
).fetchone()[0] or 0
|
|
3581
|
-
breakdowns = [r[0] for r in conn.execute(
|
|
3582
|
-
"SELECT model_usage_breakdown_json " + drop_where,
|
|
3583
|
-
(cutoff, _measure_facade._CACHE_DROP_GAP_SECONDS))] if drop_sessions > 0 else []
|
|
3584
|
-
finally:
|
|
3585
|
-
conn.close()
|
|
3586
|
-
if drop_sessions <= 0:
|
|
3328
|
+
health = _measure_facade._cache_ttl_waste_cached(days=days) or {}
|
|
3329
|
+
rebuild = health.get("rebuild") or {}
|
|
3330
|
+
events = int(rebuild.get("events", 0) or 0)
|
|
3331
|
+
tokens = int(rebuild.get("tokens", 0) or 0)
|
|
3332
|
+
if events <= 0 or tokens <= 0:
|
|
3587
3333
|
return zero
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
for blob in breakdowns:
|
|
3598
|
-
try:
|
|
3599
|
-
recorded = _measure_facade.json.loads(blob) if blob else None
|
|
3600
|
-
except (TypeError, ValueError):
|
|
3601
|
-
continue
|
|
3602
|
-
for model, parts in (recorded.items() if isinstance(recorded, dict) else ()):
|
|
3603
|
-
written = parts.get("cache_create") if isinstance(parts, dict) else None
|
|
3604
|
-
if isinstance(written, int) and not isinstance(written, bool) and written > 0:
|
|
3605
|
-
weights[model] = weights.get(model, 0) + written
|
|
3606
|
-
total_weight = sum(weights.values())
|
|
3607
|
-
write_rate = read_rate = 0.0
|
|
3608
|
-
unpriced_share = 0.0
|
|
3609
|
-
rate_basis = "session_models"
|
|
3610
|
-
priced_weight = 0
|
|
3611
|
-
for model, weight in weights.items():
|
|
3612
|
-
card = _measure_facade._counted_exact_card(model, tier_data) or {}
|
|
3613
|
-
if card.get("cache_write") is None or card.get("cache_read") is None:
|
|
3614
|
-
continue
|
|
3615
|
-
priced_weight += weight
|
|
3616
|
-
write_rate += weight * float(card["cache_write"]) / total_weight
|
|
3617
|
-
read_rate += weight * float(card["cache_read"]) / total_weight
|
|
3618
|
-
if priced_weight:
|
|
3619
|
-
unpriced_share = round(1 - priced_weight / total_weight, 4)
|
|
3620
|
-
elif weights:
|
|
3621
|
-
# Every recorded model lacks an exact card: nothing is priced, so the
|
|
3622
|
-
# opportunity is zero and the whole share is reported as unpriced.
|
|
3623
|
-
unpriced_share = 1.0
|
|
3624
|
-
else:
|
|
3625
|
-
read_rate, write_rate, _ = _measure_facade._mix_cache_rates(days)
|
|
3626
|
-
rate_basis = "model_mix"
|
|
3627
|
-
tokens = est_drops * int(prefix)
|
|
3628
|
-
written_usd = tokens * write_rate / 1_000_000
|
|
3629
|
-
read_usd = tokens * read_rate / 1_000_000
|
|
3334
|
+
classes = rebuild.get("tokens_by_class") or {}
|
|
3335
|
+
write_usd = float(rebuild.get("write_usd", 0.0) or 0.0)
|
|
3336
|
+
read_usd = float(rebuild.get("read_instead_usd", 0.0) or 0.0)
|
|
3337
|
+
by_class = {}
|
|
3338
|
+
for name in ("cache_write_1h", "cache_write_5m"):
|
|
3339
|
+
n = int(classes.get(name, 0) or 0)
|
|
3340
|
+
if n > 0:
|
|
3341
|
+
by_class[name] = {"tokens": n, "usd": round(write_usd * n / tokens, 4)}
|
|
3342
|
+
by_class["cache_read_instead"] = {"tokens": tokens, "usd": round(-read_usd, 4)}
|
|
3630
3343
|
return {
|
|
3631
|
-
"drop_sessions": int(
|
|
3632
|
-
"est_drops":
|
|
3633
|
-
"prefix_tokens": int(
|
|
3634
|
-
"
|
|
3635
|
-
"
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
"
|
|
3640
|
-
|
|
3344
|
+
"drop_sessions": int(rebuild.get("sessions", 0) or 0),
|
|
3345
|
+
"est_drops": events,
|
|
3346
|
+
"prefix_tokens": int(round(tokens / events)),
|
|
3347
|
+
"rebuilt_tokens": tokens,
|
|
3348
|
+
"ttl_seconds": rebuild.get("ttl_seconds"),
|
|
3349
|
+
"cost_saved_usd": round(float(rebuild.get("cost_usd", 0.0) or 0.0), 4),
|
|
3350
|
+
"by_class": by_class,
|
|
3351
|
+
"rate_basis": "observed_turns",
|
|
3352
|
+
"price_basis": "api_rates",
|
|
3353
|
+
# Models without a rate card are never priced (they add nothing).
|
|
3354
|
+
"unpriced_share": 0.0,
|
|
3641
3355
|
"evidence": "opportunity",
|
|
3642
3356
|
}
|
|
3643
3357
|
except Exception:
|
|
@@ -4489,7 +4203,7 @@ def _subagent_pool_savings(baseline_opus_share, days=None, tier=None, fresh=None
|
|
|
4489
4203
|
# data in its own home and has no such transcripts, so this pool is an
|
|
4490
4204
|
# honest zero there -- scanning ~/.claude anyway would price a
|
|
4491
4205
|
# coexisting Claude Code install's delegated spend into another
|
|
4492
|
-
# runtime's savings
|
|
4206
|
+
# runtime's savings _compat.facade()._headline.
|
|
4493
4207
|
if _measure_facade.detect_runtime() != "claude":
|
|
4494
4208
|
return zero
|
|
4495
4209
|
if tier is None:
|
|
@@ -4799,56 +4513,14 @@ def _price_parent_window(conn, where, params, tier):
|
|
|
4799
4513
|
|
|
4800
4514
|
|
|
4801
4515
|
def _price_parent_rows(rows, tier, api_calls_unknown=None):
|
|
4802
|
-
|
|
4803
|
-
|
|
4804
|
-
return None
|
|
4805
|
-
default_model = _measure_facade._default_model_for_runtime()
|
|
4806
|
-
fr = _measure_facade._WEIGHT_POOL_FLAT_RATES
|
|
4807
|
-
usd = 0.0
|
|
4808
|
-
flat_usd = 0.0
|
|
4809
|
-
tokens = 0.0
|
|
4810
|
-
api_calls = 0
|
|
4811
|
-
messages = 0
|
|
4812
|
-
for r in rows:
|
|
4813
|
-
fi, cw, cr, out = _measure_facade._session_token_vector(r[:5])
|
|
4814
|
-
tokens += fi + cw + cr + out
|
|
4815
|
-
flat_usd += (fi * fr["input"] + out * fr["output"]
|
|
4816
|
-
+ cr * fr["cache_read"] + cw * fr["cache_write"]) / 1_000_000
|
|
4817
|
-
api_calls += int(r[7] or 0)
|
|
4818
|
-
messages += int(r[8] or 0)
|
|
4819
|
-
usage = _measure_facade._safe_json_dict(r[5]) or _measure_facade._safe_json_dict(r[6]) or {}
|
|
4820
|
-
grand = sum(int(v or 0) for v in usage.values() if v)
|
|
4821
|
-
if len(r) > 9 and _measure_facade._safe_json_dict(r[9]):
|
|
4822
|
-
cost = _measure_facade._cost_from_model_breakdown(_measure_facade._safe_json_dict(r[9]), tier=tier)
|
|
4823
|
-
elif grand > 0:
|
|
4824
|
-
# Share denominator is the session TOTAL, so an unpriced (non-Claude, local)
|
|
4825
|
-
# model is proxy-priced at the runtime default rather than letting a small
|
|
4826
|
-
# priced sliver stand for the whole session. Same rule as _cost_per_session.
|
|
4827
|
-
cost = 0.0
|
|
4828
|
-
for model, toks in usage.items():
|
|
4829
|
-
share = int(toks or 0) / grand
|
|
4830
|
-
if share <= 0:
|
|
4831
|
-
continue
|
|
4832
|
-
cost += share * _measure_facade._get_model_cost(
|
|
4833
|
-
model if _measure_facade._is_priced_model(model, tier) else default_model,
|
|
4834
|
-
int(fi), int(out), int(cr), int(cw), tier=tier)
|
|
4835
|
-
else:
|
|
4836
|
-
cost = _measure_facade._get_model_cost(default_model, int(fi), int(out), int(cr), int(cw),
|
|
4837
|
-
tier=tier)
|
|
4838
|
-
usd += cost
|
|
4839
|
-
return {"sessions": len(rows), "usd": usd, "tokens": tokens,
|
|
4840
|
-
"flat_usd": flat_usd, "api_calls": api_calls, "messages": messages,
|
|
4841
|
-
# Sessions whose dated per-day call evidence was never recorded.
|
|
4842
|
-
# api_calls is then a lower bound, not a measured total.
|
|
4843
|
-
"api_calls_unknown": int(api_calls_unknown or 0)}
|
|
4516
|
+
"""Sum parent rows: engine-priced and fixed-card USD, class tokens, work units."""
|
|
4517
|
+
return own_price_card.price_rows(_compat.facade(), rows, tier, api_calls_unknown)
|
|
4844
4518
|
|
|
4845
4519
|
|
|
4846
4520
|
def _pinned_workload_anchor():
|
|
4847
4521
|
"""This user's pinned pre-install workload anchor, or None until built.
|
|
4848
4522
|
|
|
4849
|
-
Built once from the user's
|
|
4850
|
-
sessions before Token Optimizer was installed), so every user is compared
|
|
4851
|
-
against their own starting point, never a fixed calendar month."""
|
|
4523
|
+
Built once from the user's baseline window in baseline_state.json."""
|
|
4852
4524
|
_measure_facade = _compat.facade()
|
|
4853
4525
|
try:
|
|
4854
4526
|
path = _measure_facade.SNAPSHOT_DIR / _measure_facade._PRETOOL_ANCHOR_FILE
|
|
@@ -4863,7 +4535,7 @@ def _pinned_workload_anchor():
|
|
|
4863
4535
|
for k in ("sessions", "usd", "tokens", "flat_usd", "api_calls", "messages"))
|
|
4864
4536
|
and m["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
4865
4537
|
and m["api_calls"] > 0 and m["flat_usd"] > 0):
|
|
4866
|
-
return {"metrics": m, "label": str(data.get("label") or "your pre-install baseline")}
|
|
4538
|
+
return {"metrics": m, "label": str(data.get("label") or "your earliest tracked month").replace("your pre-install baseline", "your earliest tracked month")}
|
|
4867
4539
|
except (OSError, ValueError, TypeError, AttributeError):
|
|
4868
4540
|
pass
|
|
4869
4541
|
return None
|
|
@@ -4884,64 +4556,9 @@ def _pretool_window():
|
|
|
4884
4556
|
|
|
4885
4557
|
|
|
4886
4558
|
def _pretool_anchor_step(budget_seconds=None, tier=None):
|
|
4887
|
-
"""Build the pinned pre-install anchor a few transcripts at a time
|
|
4888
|
-
|
|
4889
|
-
|
|
4890
|
-
it; their transcripts usually remain on disk. Each call prices up to
|
|
4891
|
-
`budget_seconds` of them with the same ruler as the live pool and banks
|
|
4892
|
-
running sums, then pins the result once the window is done. A window with
|
|
4893
|
-
too few surviving transcripts is marked unavailable, so the check stops.
|
|
4894
|
-
Returns the state string. Never raises.
|
|
4895
|
-
"""
|
|
4896
|
-
_measure_facade = _compat.facade()
|
|
4897
|
-
path = _measure_facade.SNAPSHOT_DIR / _measure_facade._PRETOOL_ANCHOR_FILE
|
|
4898
|
-
try:
|
|
4899
|
-
state = _measure_facade.json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
4900
|
-
if not isinstance(state, dict) or state.get("activity_basis") != 1:
|
|
4901
|
-
# State written before activity dating (or surviving an archive
|
|
4902
|
-
# collision) was computed on session-date windows; rebuild it.
|
|
4903
|
-
state = {}
|
|
4904
|
-
if state.get("status") in ("pinned", "unavailable"):
|
|
4905
|
-
return state["status"]
|
|
4906
|
-
window = _measure_facade._pretool_window()
|
|
4907
|
-
if not window:
|
|
4908
|
-
return "no_baseline"
|
|
4909
|
-
if tier is None:
|
|
4910
|
-
tier = _measure_facade._load_pricing_tier()
|
|
4911
|
-
start, end = window
|
|
4912
|
-
if state.get("window") != [start, end] or state.get("rates") != _measure_facade._WEIGHT_POOL_FLAT_RATES:
|
|
4913
|
-
state = {"status": "building", "window": [start, end], "rates": _measure_facade._WEIGHT_POOL_FLAT_RATES,
|
|
4914
|
-
"activity_basis": 1, "cursor": 0, "seen": [],
|
|
4915
|
-
"metrics": {"sessions": 0, "usd": 0.0, "tokens": 0.0, "flat_usd": 0.0,
|
|
4916
|
-
"api_calls": 0, "messages": 0}}
|
|
4917
|
-
files = sorted(str(f) for f, _mtime, _proj in _measure_facade._find_all_jsonl_files(None))
|
|
4918
|
-
seen = set(state["seen"])
|
|
4919
|
-
deadline = _measure_facade.time.monotonic() + budget_seconds
|
|
4920
|
-
cursor = int(state.get("cursor") or 0)
|
|
4921
|
-
while cursor < len(files) and _measure_facade.time.monotonic() < deadline:
|
|
4922
|
-
fp = files[cursor]
|
|
4923
|
-
cursor += 1
|
|
4924
|
-
uuid = _measure_facade._canonical_session_uuid(fp) or fp
|
|
4925
|
-
if uuid in seen:
|
|
4926
|
-
continue # another copy of a session already priced
|
|
4927
|
-
seen.add(uuid)
|
|
4928
|
-
row = _measure_facade._pretool_session_row(fp, start, end, state.setdefault("requests", {}))
|
|
4929
|
-
priced = _measure_facade._price_parent_rows([row], tier) if row else None
|
|
4930
|
-
if priced:
|
|
4931
|
-
for k in state["metrics"]:
|
|
4932
|
-
state["metrics"][k] += priced[k]
|
|
4933
|
-
state["cursor"], state["seen"] = cursor, sorted(seen)
|
|
4934
|
-
if cursor >= len(files):
|
|
4935
|
-
m = state["metrics"]
|
|
4936
|
-
ok = m["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS and m["api_calls"] > 0 and m["flat_usd"] > 0
|
|
4937
|
-
state = {"status": "pinned" if ok else "unavailable", "window": [start, end],
|
|
4938
|
-
"rates": _measure_facade._WEIGHT_POOL_FLAT_RATES, "activity_basis": 1, "metrics": m,
|
|
4939
|
-
"label": f"your pre-install baseline ({start} to {end})",
|
|
4940
|
-
"pinned_at": _measure_facade.datetime.now().isoformat()}
|
|
4941
|
-
_measure_facade._write_baseline_state(path, state)
|
|
4942
|
-
return state["status"]
|
|
4943
|
-
except Exception:
|
|
4944
|
-
return "error"
|
|
4559
|
+
"""Build the pinned pre-install anchor a few transcripts at a time
|
|
4560
|
+
(see own_price_card.anchor_step). Returns the state string. Never raises."""
|
|
4561
|
+
return own_price_card.anchor_step(_compat.facade(), budget_seconds, tier)
|
|
4945
4562
|
|
|
4946
4563
|
|
|
4947
4564
|
def _pretool_session_row(filepath, start, end, ledger):
|
|
@@ -4985,6 +4602,8 @@ def _stable_workload_anchor(before, month):
|
|
|
4985
4602
|
for k in ("sessions", "usd", "tokens", "flat_usd", "api_calls", "messages"))
|
|
4986
4603
|
and metrics["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
4987
4604
|
and metrics["api_calls"] > 0 and metrics["flat_usd"] > 0):
|
|
4605
|
+
if own_price_card.lend_classes(metrics, before if str(frozen["month"]) == month else None):
|
|
4606
|
+
_measure_facade._write_baseline_state(path, frozen)
|
|
4988
4607
|
return metrics, str(frozen["month"])
|
|
4989
4608
|
if (before and before["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
4990
4609
|
and before["api_calls"] > 0 and before["flat_usd"] > 0):
|
|
@@ -5144,6 +4763,11 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
5144
4763
|
b_n, b_usd, b_tok = before["sessions"], before["usd"], before["tokens"]
|
|
5145
4764
|
n_n, n_usd, n_tok = now["sessions"], now["usd"], now["tokens"]
|
|
5146
4765
|
b_flat, n_flat = before["flat_usd"], now["flat_usd"]
|
|
4766
|
+
# One card for both periods: the user's own current prices when both arms
|
|
4767
|
+
# carry class sums, else the fixed card (an older pinned baseline).
|
|
4768
|
+
own = own_price_card.apply(_measure_facade, before, now, days or 30)
|
|
4769
|
+
if own:
|
|
4770
|
+
b_flat, n_flat = own["before_usd"], own["now_usd"]
|
|
5147
4771
|
if (b_n < _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
5148
4772
|
or n_n < _measure_facade._AFTER_MIN_SESSIONS or b_usd <= 0 or b_flat <= 0):
|
|
5149
4773
|
return None
|
|
@@ -5225,8 +4849,6 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
5225
4849
|
"so it is not in the headline. Model price/mix drift worth about "
|
|
5226
4850
|
"${drift:,.0f} this period is also excluded: it would have happened without Token "
|
|
5227
4851
|
"Optimizer."
|
|
5228
|
-
+ ("" if pinned else " The anchor month already had partial Token Optimizer "
|
|
5229
|
-
"coverage, so if anything this understates the full pre-tool gap.")
|
|
5230
4852
|
).format(units=n_units,
|
|
5231
4853
|
unit_label="API calls" if unit == "api_call" else "messages",
|
|
5232
4854
|
unit_singular="API call" if unit == "api_call" else "message",
|
|
@@ -5252,7 +4874,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
5252
4874
|
"coverage": now.get("coverage"),
|
|
5253
4875
|
"engine_priced_transformation_usd": engine_transformation,
|
|
5254
4876
|
"engine_priced_actual_usd": n_usd,
|
|
5255
|
-
"price_mix_drift_usd": price_mix_drift,
|
|
4877
|
+
"price_mix_drift_usd": price_mix_drift, "price_card": own,
|
|
5256
4878
|
"capacity_assumption": capacity_note,
|
|
5257
4879
|
# Sessions in each window whose dated per-day call evidence was never
|
|
5258
4880
|
# recorded; api_calls above is a lower bound when either is nonzero.
|
|
@@ -5379,14 +5001,14 @@ def _weight_pool_payload(pool):
|
|
|
5379
5001
|
float(pool.get("engine_priced_transformation_usd", 0.0)), 2),
|
|
5380
5002
|
"engine_priced_actual_usd": round(
|
|
5381
5003
|
float(pool.get("engine_priced_actual_usd", 0.0)), 2),
|
|
5382
|
-
"price_mix_drift_usd": round(float(pool.get("price_mix_drift_usd", 0.0)), 2),
|
|
5004
|
+
"price_mix_drift_usd": round(float(pool.get("price_mix_drift_usd", 0.0)), 2), "flat_rates": dict((pool.get("price_card") or {}).get("rates") or _measure_facade._WEIGHT_POOL_FLAT_RATES), "price_basis": "own_prices" if pool.get("price_card") else "fixed_card",
|
|
5383
5005
|
"capacity_assumption": pool["capacity_assumption"],
|
|
5384
5006
|
}
|
|
5385
5007
|
|
|
5386
5008
|
|
|
5387
5009
|
def _estimate_before_after_savings(days=None, estimated_pools=None, model_routing=None, since=None):
|
|
5388
5010
|
"""THE headline saving: your FROZEN typical pre-TO session, priced at your PRE-TO
|
|
5389
|
-
efficiency (
|
|
5011
|
+
efficiency (the frozen baseline model mix + cache pattern) vs what that same session costs now.
|
|
5390
5012
|
|
|
5391
5013
|
This is a PER-SESSION COMPARISON on a FROZEN volume anchor. The "old way / session"
|
|
5392
5014
|
figure is computed entirely from frozen inputs (the captured typical_session token
|
|
@@ -5401,7 +5023,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5401
5023
|
bcr=cache_read, bcw=cache_write, bout=output. The current window over `days` is
|
|
5402
5024
|
read ONLY for the session count (recent_n) and the CURRENT cache-hit (cur_hit).
|
|
5403
5025
|
2. OLD WAY / session (counterfactual) = price(bfi, bcr, bout) + cache-write, all at
|
|
5404
|
-
the BASELINE
|
|
5026
|
+
the BASELINE mix. Depends only on frozen inputs + prices -> stable.
|
|
5405
5027
|
3. NOW / session (actual) = the SAME frozen tokens, but the fresh+cache_read pool
|
|
5406
5028
|
(t_pool = bfi + bcr) redistributed at cur_hit (cur_CR = cur_hit*t_pool; cur_F =
|
|
5407
5029
|
t_pool - cur_CR), priced at the CURRENT mix. Cache-write is held constant in
|
|
@@ -5410,9 +5032,10 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5410
5032
|
volume than the typical session held.
|
|
5411
5033
|
4. MAIN TRANSFORMATION (monthly) = (old_cps - now_cps) * recent_n, signed.
|
|
5412
5034
|
|
|
5413
|
-
Baseline model mix
|
|
5414
|
-
|
|
5415
|
-
|
|
5035
|
+
Baseline model mix: the user's stated pre-TO share when one is set, else the frozen
|
|
5036
|
+
measured share from their own install-era history; with neither (or a
|
|
5037
|
+
non-Anthropic runtime) the before arm uses the current mix, so routing is zero.
|
|
5038
|
+
No share is assumed for anyone. base_hit
|
|
5416
5039
|
comes from the frozen baseline typical session's cache pattern; if unavailable it
|
|
5417
5040
|
falls back to the current cache-hit (caching lever = 0, conservative).
|
|
5418
5041
|
|
|
@@ -5476,14 +5099,14 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5476
5099
|
# there, but (unlike Copilot's opaque credits) a list-price estimate is
|
|
5477
5100
|
# still surfaced by the collector — so the transformation renders
|
|
5478
5101
|
# nothing with an explicit "estimated_billing" reason instead of a
|
|
5479
|
-
# token-savings
|
|
5102
|
+
# token-savings _compat.facade()._headline.
|
|
5480
5103
|
if _measure_facade.detect_runtime() == "antigravity":
|
|
5481
5104
|
return {**zero, "reason": "estimated_billing"}
|
|
5482
5105
|
if not _measure_facade.TRENDS_DB.exists():
|
|
5483
5106
|
return zero
|
|
5484
5107
|
|
|
5485
5108
|
# The frozen robust baseline supplies the PRE-TO efficiency anchors: the model
|
|
5486
|
-
# mix (
|
|
5109
|
+
# mix (stated or measured share, never assumed) and the cache-hit
|
|
5487
5110
|
# pattern. It is NOT used for volume -- volume comes entirely from the current
|
|
5488
5111
|
# window, held constant across both arms.
|
|
5489
5112
|
baseline = _measure_facade._get_baseline_state()
|
|
@@ -5504,14 +5127,14 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5504
5127
|
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
|
|
5505
5128
|
# The transformation describes main work only. model_daily combines main and
|
|
5506
5129
|
# sidechain tokens, so premium delegation could otherwise make the "now" arm
|
|
5507
|
-
# costlier and lower the
|
|
5130
|
+
# costlier and lower the _compat.facade()._headline. Build the mix from non-sidechain rows.
|
|
5508
5131
|
after_shares = dict(_measure_facade._mix_from_session_rows(cutoff))
|
|
5509
5132
|
# H3: an empty after mix would silently price the ACTUAL arm at the sonnet default
|
|
5510
5133
|
# (via _cost_per_session's fallback), understating actual and INFLATING savings.
|
|
5511
5134
|
# If model_daily is empty/stale, derive the actual mix from the SAME session_log
|
|
5512
5135
|
# rows already loaded (their stored model_usage breakdown). Bail if still empty.
|
|
5513
|
-
# Baseline (pre-TO) model mix:
|
|
5514
|
-
# with
|
|
5136
|
+
# Baseline (pre-TO) model mix: the frozen share (stated or measured) for an
|
|
5137
|
+
# Anthropic runtime; with none, the current mix. A frozen share is trusted as-is;
|
|
5515
5138
|
# a non-Anthropic user is priced at their own measured mix, never fabricated Opus.
|
|
5516
5139
|
anthropic = _measure_facade.detect_runtime() not in {"codex", "hermes", "copilot", "opencode", "cursor", "antigravity", "grok"}
|
|
5517
5140
|
if anthropic and frozen_opus and frozen_opus > 0:
|
|
@@ -5531,7 +5154,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5531
5154
|
# Anthropic user with no MEASURED baseline. The pre-Token-Optimizer model
|
|
5532
5155
|
# mix is not knowable here, and a mix we cannot measure is a mix we do not
|
|
5533
5156
|
# claim: any assumed Opus share would directly scale the routing lever and
|
|
5534
|
-
# inflate the
|
|
5157
|
+
# inflate the _compat.facade()._headline. Price the before-arm at the user's real current mix
|
|
5535
5158
|
# so the routing lever is exactly zero until a baseline is measured.
|
|
5536
5159
|
baseline_opus_share = float(after_shares.get("opus", 0.0))
|
|
5537
5160
|
before_shares = dict(after_shares)
|
|
@@ -5670,7 +5293,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5670
5293
|
# SHORT-SESSION pool (below the quality gates): sub-minute / low-input
|
|
5671
5294
|
# one-shots are excluded from recent_n because the count multiplies the
|
|
5672
5295
|
# frozen typical-session anchor, but their billed tokens are real spend
|
|
5673
|
-
# whose routing delta belongs in the
|
|
5296
|
+
# whose routing delta belongs in the _compat.facade()._headline. Priced on their own real
|
|
5674
5297
|
# volume, parent-thread bundles only (no overlap with the sidechain pool).
|
|
5675
5298
|
short_pool = _measure_facade._short_session_pool_savings(
|
|
5676
5299
|
cutoff, baseline_opus_share=baseline_opus_share, tier=tier,
|
|
@@ -5791,8 +5414,8 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5791
5414
|
"hint_followed": (comp or {}).get("hint_followed_estimated") or {},
|
|
5792
5415
|
"handover_rerun": _measure_facade._estimate_handover_rerun_savings(days=days),
|
|
5793
5416
|
"retrieval_serve": _measure_facade._estimate_retrieval_serve_savings(days=days),
|
|
5794
|
-
"resume_lean": (comp or {}).get("resume_lean_estimated") or {},
|
|
5795
5417
|
"checkpoint_restore": (comp or {}).get("checkpoint_restore_estimated") or {},
|
|
5418
|
+
"codemap_lookup": (comp or {}).get("codemap_lookup_estimated") or {},
|
|
5796
5419
|
}
|
|
5797
5420
|
pool_labels = {
|
|
5798
5421
|
"uncaptured_runtime": "Compressed subagent context (estimated)",
|
|
@@ -5800,8 +5423,8 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5800
5423
|
"hint_followed": "Followed context hints (estimated)",
|
|
5801
5424
|
"handover_rerun": "Continuity handovers (estimated)",
|
|
5802
5425
|
"retrieval_serve": "Direct context retrieval (estimated)",
|
|
5803
|
-
"resume_lean": "Lean session resumes (estimated)",
|
|
5804
5426
|
"checkpoint_restore": "Checkpoint restores (estimated)",
|
|
5427
|
+
"codemap_lookup": "Code map lookups (estimated)",
|
|
5805
5428
|
}
|
|
5806
5429
|
estimated_volume_pools = {}
|
|
5807
5430
|
for key, label in pool_labels.items():
|
|
@@ -5826,7 +5449,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5826
5449
|
# rate: the old way would have produced the same verbose output at the
|
|
5827
5450
|
# baseline model mix's output rate, so the avoided cost is higher.
|
|
5828
5451
|
vs_est = (comp or {}).get("verbosity_steer_estimated") or {}
|
|
5829
|
-
vs_measured =
|
|
5452
|
+
vs_measured = 0.0 # diagnostic only; no verbosity credit
|
|
5830
5453
|
out_after = price(0.0, 0.0, 1_000_000.0, after_shares)
|
|
5831
5454
|
out_before = price(0.0, 0.0, 1_000_000.0, before_shares)
|
|
5832
5455
|
vs_reprice = (out_before / out_after) if out_after > 0 else 1.0
|
|
@@ -5907,6 +5530,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5907
5530
|
# eliminate ("no savings" must stay distinguishable from "the math broke").
|
|
5908
5531
|
# Both non-headlined states report the SAME real arms and real (signed) delta so the
|
|
5909
5532
|
# renderer can explain itself; `reason` / `transformation_state` carry which one.
|
|
5533
|
+
provenance = baseline_provenance.transformation(_measure_facade, baseline, weight_pool)
|
|
5910
5534
|
not_headlined = {**zero, "before_sessions": bn, "after_sessions": recent_n,
|
|
5911
5535
|
"actual_monthly_usd": round(combined_actual, 2),
|
|
5912
5536
|
"counterfactual_monthly_usd": round(combined_cf, 2),
|
|
@@ -5946,7 +5570,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5946
5570
|
if weight_pool else int(t_pool + bcw + bout)),
|
|
5947
5571
|
"after_tokens": (int(weight_pool["after_tokens_per_session"])
|
|
5948
5572
|
if weight_pool else int(t_pool + bcw + bout)),
|
|
5949
|
-
"baseline_source": baseline_source,
|
|
5573
|
+
"baseline_source": baseline_source, "baseline_provenance": provenance,
|
|
5950
5574
|
# A net-negative card used to return the `zero` per-session fields, so
|
|
5951
5575
|
# the dashboard rendered NOTHING and the user could not tell "no savings
|
|
5952
5576
|
# this period" from "the computation broke". Report the real arms and the
|
|
@@ -6010,7 +5634,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6010
5634
|
# redistribution). Decompose by morphing the counterfactual into the actual one
|
|
6011
5635
|
# lever at a time. Routing is credited first (the baseline footprint, INCLUDING CW,
|
|
6012
5636
|
# repriced from the baseline mix to today's mix), then caching at today's mix; the
|
|
6013
|
-
# two UNROUNDED steps telescope to the
|
|
5637
|
+
# two UNROUNDED steps telescope to the _compat.facade()._headline. Sequential attribution is
|
|
6014
5638
|
# order-dependent (fixed + disclosed via `waterfall_index`).
|
|
6015
5639
|
# v_route_s = the typical session's baseline cache split (bfi/bcr) + CW + output
|
|
6016
5640
|
# repriced at today's mix. CW carries the routing reprice, so the routing lever
|
|
@@ -6024,7 +5648,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6024
5648
|
s_cache = (v_route_s - now_cps) * recent_n # remaining gap = caching
|
|
6025
5649
|
# s_route + s_cache telescopes to the MAIN transformation; the subagent pool is a
|
|
6026
5650
|
# third lever whose own (cf - actual) is added so the breakdown sums to the COMBINED
|
|
6027
|
-
#
|
|
5651
|
+
# _compat.facade()._headline.
|
|
6028
5652
|
if weight_pool:
|
|
6029
5653
|
# The session-weight pool replaced the frozen-anchor arms, so the
|
|
6030
5654
|
# routing/caching decomposition of those arms no longer describes the
|
|
@@ -6083,31 +5707,12 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6083
5707
|
key=lambda x: ((_measure_facade := _compat.facade()), abs(x["monthly_usd"]))[1], reverse=True,
|
|
6084
5708
|
)
|
|
6085
5709
|
if weight_pool:
|
|
6086
|
-
breakdown_caveat = (
|
|
6087
|
-
"Work-normalized counterfactual: every API call you dispatched this "
|
|
6088
|
-
"period, priced at the anchor month's cost per call ("
|
|
6089
|
-
+ str(weight_pool["anchor_month"]) + ", your earliest complete month "
|
|
6090
|
-
"on record), at ONE constant rate card both eras -- so only how much "
|
|
6091
|
-
"context each call carries (and how often the cache serves it) moves "
|
|
6092
|
-
"the number; model-price and mix changes between eras are excluded and "
|
|
6093
|
-
"disclosed separately, not claimed. Sessions are not used as the unit "
|
|
6094
|
-
"because the lighter workflow itself splits the same work into more, "
|
|
6095
|
-
"smaller sessions, which would count capacity gained as money saved. "
|
|
6096
|
-
"The delta includes every volume mechanism at once (context "
|
|
6097
|
-
"compression, lean output, loop prevention, continuity handovers), so "
|
|
6098
|
-
"the metered and estimated pools are not added on top -- they would "
|
|
6099
|
-
"double-count; the directly-metered floor still shows in its own card. "
|
|
6100
|
-
"Delegated (subagent) work is excluded from this figure. Two caveats "
|
|
6101
|
-
"ride with it: the anchor month already had partial Token Optimizer "
|
|
6102
|
-
"coverage (the true pre-tool gap is larger), and the per-call delta "
|
|
6103
|
-
"cannot separate Token Optimizer's effect from your own behaviour "
|
|
6104
|
-
"drift -- the metered floor is the part we can prove action by action."
|
|
6105
|
-
)
|
|
5710
|
+
breakdown_caveat = baseline_provenance.weight_pool_caveat(weight_pool["anchor_month"], provenance)
|
|
6106
5711
|
else:
|
|
6107
5712
|
breakdown_caveat = (
|
|
6108
5713
|
"Counterfactual attribution: your FROZEN typical pre-TO session is priced two "
|
|
6109
5714
|
"ways -- the way you work now, and the way you worked before Token Optimizer "
|
|
6110
|
-
"(
|
|
5715
|
+
"(" + ("about %d%% Opus, " % round(100 * baseline_opus_share) if baseline_opus_share > 0 else "") + "your old cache pattern) -- then scaled by your session count this "
|
|
6111
5716
|
"period. The per-session difference is split between model routing (including "
|
|
6112
5717
|
"cache-write, which is billed at the writing model's rate) and caching. Subagent "
|
|
6113
5718
|
"(sidechain) work is a second pool: the window's real delegated tokens priced at "
|
|
@@ -6178,7 +5783,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6178
5783
|
f"${uncapped_transformation:,.2f}."
|
|
6179
5784
|
)
|
|
6180
5785
|
# Re-derive pct from the capped transformation so the percentage
|
|
6181
|
-
# stays consistent with the capped
|
|
5786
|
+
# stays consistent with the capped _compat.facade()._headline.
|
|
6182
5787
|
transformation_pct = (
|
|
6183
5788
|
transformation / combined_cf if combined_cf > 0 else 0.0
|
|
6184
5789
|
)
|
|
@@ -6253,7 +5858,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6253
5858
|
if weight_pool else bn),
|
|
6254
5859
|
"after_sessions": (int(weight_pool["sessions"])
|
|
6255
5860
|
if weight_pool else recent_n),
|
|
6256
|
-
"baseline_source": baseline_source,
|
|
5861
|
+
"baseline_source": baseline_source, "baseline_provenance": provenance,
|
|
6257
5862
|
"breakdown": breakdown,
|
|
6258
5863
|
"breakdown_caveat": breakdown_caveat,
|
|
6259
5864
|
"evidence": "estimated",
|
|
@@ -6308,15 +5913,9 @@ def _estimate_stale_reads_reclaimable(days=None):
|
|
|
6308
5913
|
|
|
6309
5914
|
|
|
6310
5915
|
def _progressive_disclosure_summary(days=None):
|
|
6311
|
-
"""
|
|
6312
|
-
|
|
6313
|
-
How many tool results were archived vs later re-expanded, and the net tokens
|
|
6314
|
-
that stayed collapsed. The $ value of the net is ALREADY in the realized
|
|
6315
|
-
tool_archive figure (re-pops are netted out in _get_savings_summary); this is
|
|
6316
|
-
a transparency count, NOT an additional saving to sum. Never raises.
|
|
6317
|
-
"""
|
|
5916
|
+
"""Summarize archive disclosures without assigning a counterfactual value."""
|
|
6318
5917
|
_measure_facade = _compat.facade()
|
|
6319
|
-
out = {"archived": 0, "reexpanded": 0, "net_collapsed_tokens": 0}
|
|
5918
|
+
out = {"archived": 0, "reexpanded": 0, "net_collapsed_tokens": 0, "full_bash_fetches": 0, "full_bash_tokens": 0}
|
|
6320
5919
|
try:
|
|
6321
5920
|
if not _measure_facade.TRENDS_DB.exists():
|
|
6322
5921
|
return out
|
|
@@ -6331,23 +5930,25 @@ def _progressive_disclosure_summary(days=None):
|
|
|
6331
5930
|
(cutoff,),
|
|
6332
5931
|
).fetchall()
|
|
6333
5932
|
re_rows = conn.execute(
|
|
6334
|
-
"SELECT detail FROM " + counted + " WHERE timestamp >= ? "
|
|
5933
|
+
"SELECT detail, tokens_saved, session_id, timestamp FROM " + counted + " WHERE timestamp >= ? "
|
|
6335
5934
|
"AND event_type = 'tool_archive_reexpand'",
|
|
6336
5935
|
(cutoff,),
|
|
6337
5936
|
).fetchall()
|
|
5937
|
+
from . import savings_story
|
|
5938
|
+
full_count, full_tokens = savings_story.full_bash_fetch_totals(conn, cutoff, re_rows, _measure_facade._is_fixture_session_id, _measure_facade.SNAPSHOT_DIR)
|
|
6338
5939
|
finally:
|
|
6339
5940
|
conn.close()
|
|
6340
5941
|
agg = {r[0]: (int(r[1]), int(r[2] or 0)) for r in rows}
|
|
6341
5942
|
arch_n, arch_tok = agg.get("tool_archive", (0, 0))
|
|
6342
5943
|
re_tok = agg.get("tool_archive_reexpand", (0, 0))[1]
|
|
6343
5944
|
out["archived"] = arch_n
|
|
6344
|
-
# Multiple bounded debits can hit one archived item; "re-expanded" is a
|
|
6345
|
-
# count of distinct tool_use_ids, not debit events.
|
|
6346
5945
|
out["reexpanded"] = len({
|
|
6347
5946
|
detail.split(" ", 1)[0]
|
|
6348
|
-
for (detail,) in re_rows
|
|
5947
|
+
for (detail, _, _, _) in re_rows
|
|
6349
5948
|
if detail and detail.strip()
|
|
6350
5949
|
})
|
|
5950
|
+
out["full_bash_fetches"] = full_count
|
|
5951
|
+
out["full_bash_tokens"] = full_tokens
|
|
6351
5952
|
out["net_collapsed_tokens"] = max(0, arch_tok - re_tok)
|
|
6352
5953
|
except (_measure_facade.sqlite3.Error, OSError):
|
|
6353
5954
|
pass
|
|
@@ -6468,15 +6069,15 @@ def _format_cents(cents):
|
|
|
6468
6069
|
|
|
6469
6070
|
|
|
6470
6071
|
def _action_savings_display(logged, routing_measured, routing_estimated, repeat_reads,
|
|
6471
|
-
estimates, total_clamped=None):
|
|
6072
|
+
estimates, total_clamped=None, class_premium=None):
|
|
6472
6073
|
"""Whole-cent display values for the action-savings components.
|
|
6473
6074
|
|
|
6474
6075
|
Raw component values stay exact elsewhere in the payload. Every displayed
|
|
6475
6076
|
part below adds up to `total_usd`, which is the cents of the exact total."""
|
|
6476
6077
|
_measure_facade = _compat.facade()
|
|
6477
|
-
names = ["logged", "routing_measured", "routing_estimated", "reread"] + [
|
|
6078
|
+
names = ["logged", "class_premium", "routing_measured", "routing_estimated", "reread"] + [
|
|
6478
6079
|
"estimate:" + key for key in estimates]
|
|
6479
|
-
values = [logged, routing_measured, routing_estimated, repeat_reads, *estimates.values()]
|
|
6080
|
+
values = [logged, class_premium or 0.0, routing_measured, routing_estimated, repeat_reads, *estimates.values()]
|
|
6480
6081
|
parts, total_cents = _measure_facade._allocate_cents(values)
|
|
6481
6082
|
if total_clamped:
|
|
6482
6083
|
total_cents = 0
|
|
@@ -6498,29 +6099,35 @@ def _action_savings_components(summary, reread=None):
|
|
|
6498
6099
|
Observed hints replace the retrieval estimate as soon as a hint fires.
|
|
6499
6100
|
Opportunity and the separate whole-workload comparison are not additive.
|
|
6500
6101
|
"""
|
|
6501
|
-
_measure_facade = _compat.facade()
|
|
6102
|
+
_measure_facade = _compat.facade(); from . import mod_fresh_booking
|
|
6502
6103
|
estimates = {
|
|
6503
|
-
key: float((summary.get(key) or {}).get("cost_saved_usd", 0) or 0)
|
|
6104
|
+
key: (0.0 if key in ("verbosity_steer", "verbosity_output_estimated", "resume_lean_estimated", "checkpoint_restore_estimated") else float((((summary.get("structural_detail") or {}).get("estimated") if key == "structural_estimated" else summary.get(key)) or {}).get("cost_saved_usd", 0) or 0))
|
|
6504
6105
|
for key in (
|
|
6505
|
-
"behavioral_estimate", "uncaptured_runtime",
|
|
6506
|
-
"contamination_exit", "handover_rerun", "resume_lean_estimated",
|
|
6507
|
-
"checkpoint_restore_estimated", "verbosity_steer",
|
|
6106
|
+
"behavioral_estimate", "uncaptured_runtime",
|
|
6107
|
+
"contamination_exit", "handover_rerun", "resume_lean_estimated", "resume_lean_verified",
|
|
6108
|
+
"checkpoint_restore_estimated", "verbosity_steer", "verbosity_output_estimated", "structural_estimated", "keepwarm_estimated",
|
|
6508
6109
|
)
|
|
6509
6110
|
}
|
|
6111
|
+
overhead = ((summary.get("session_effect") or {}).get("overhead") or {}); estimates["mod_fresh_estimated"] = mod_fresh_booking.additive(summary.get("mod_fresh_estimated"), summary.get("handover_rerun"))
|
|
6112
|
+
estimates["expand_overhead"] = -max(0.0, float(overhead.get("expand_usd") or 0))
|
|
6510
6113
|
hints = summary.get("hint_followed") or {}
|
|
6511
6114
|
avoided_source = "hint_followed" if int(hints.get("events") or 0) > 0 else "retrieval_serve"
|
|
6512
6115
|
estimates[avoided_source] = float(
|
|
6513
6116
|
(summary.get(avoided_source) or {}).get("cost_saved_usd", 0) or 0)
|
|
6514
|
-
|
|
6117
|
+
from . import savings_story
|
|
6118
|
+
logged = float(summary.get("total_cost_usd", 0) or 0) - savings_story.verbosity_logged(summary)
|
|
6515
6119
|
routing_data = summary.get("model_routing") or {}
|
|
6516
6120
|
routing = float(routing_data.get("realized_cost_usd", 0) or 0)
|
|
6517
6121
|
routing_measured = routing if routing_data.get("evidence", "measured") == "measured" else 0.0
|
|
6518
6122
|
reread_available = bool((reread or {}).get("available"))
|
|
6519
6123
|
repeat_reads = float(reread.get("reread_usd", 0) or 0) if reread_available else 0.0
|
|
6124
|
+
premium = _measure_facade._counted_pricing_v5.class_premium_usd(reread) # measured: the next call billed a cache write
|
|
6520
6125
|
estimated = sum(estimates.values())
|
|
6521
|
-
net_total = logged +
|
|
6126
|
+
net_total = logged + premium + repeat_reads + estimated
|
|
6522
6127
|
return {
|
|
6523
6128
|
"logged_usd": logged,
|
|
6129
|
+
"class_premium_usd": premium,
|
|
6130
|
+
"class_premium_events": int((reread or {}).get("oneshot_class_events", 0) or 0) if premium else 0,
|
|
6524
6131
|
"routing_usd": routing,
|
|
6525
6132
|
"routing_measured_usd": routing_measured,
|
|
6526
6133
|
"routing_estimated_usd": routing - routing_measured,
|
|
@@ -6537,8 +6144,8 @@ def _action_savings_components(summary, reread=None):
|
|
|
6537
6144
|
"total_usd": max(0.0, net_total),
|
|
6538
6145
|
"total_clamped": net_total < 0,
|
|
6539
6146
|
"display": _measure_facade._action_savings_display(
|
|
6540
|
-
logged,
|
|
6541
|
-
|
|
6147
|
+
logged, 0.0, 0.0, repeat_reads, estimates,
|
|
6148
|
+
total_clamped=net_total < 0, class_premium=premium),
|
|
6542
6149
|
}
|
|
6543
6150
|
|
|
6544
6151
|
|
|
@@ -6609,8 +6216,10 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6609
6216
|
handover_rerun = _measure_facade._estimate_handover_rerun_savings(days=days)
|
|
6610
6217
|
retrieval_serve = _measure_facade._estimate_retrieval_serve_savings(days=days)
|
|
6611
6218
|
model_routing = _measure_facade._compute_model_routing_savings(days=days, since=since)
|
|
6219
|
+
model_routing["baseline_provenance"] = baseline_provenance.routing(_measure_facade, model_routing)
|
|
6612
6220
|
output_waste = _measure_facade._estimate_output_waste(days=days)
|
|
6613
|
-
|
|
6221
|
+
import large_transcripts
|
|
6222
|
+
cache_drop = {**_measure_facade._estimate_cache_drop_savings(days=days), **large_transcripts.count(_measure_facade.CLAUDE_DIR, days)}
|
|
6614
6223
|
before_after = _measure_facade._estimate_before_after_savings(days=days, since=since, estimated_pools={
|
|
6615
6224
|
"uncaptured_runtime": uncaptured,
|
|
6616
6225
|
"behavioral_loops": behavioral,
|
|
@@ -6619,10 +6228,16 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6619
6228
|
"retrieval_serve": retrieval_serve,
|
|
6620
6229
|
"resume_lean": savings.get("resume_lean_estimated") or {},
|
|
6621
6230
|
"checkpoint_restore": savings.get("checkpoint_restore_estimated") or {},
|
|
6622
|
-
}, model_routing=model_routing)
|
|
6231
|
+
}, model_routing=model_routing) if not savings_story.skip_comparison() else None
|
|
6623
6232
|
stale_reads_reclaimable = _measure_facade._estimate_stale_reads_reclaimable(days=days)
|
|
6233
|
+
try:
|
|
6234
|
+
import lean_resume_carry
|
|
6235
|
+
verified_lean = lean_resume_carry.verified_summary(days=days, since=since)
|
|
6236
|
+
except Exception:
|
|
6237
|
+
verified_lean = None
|
|
6624
6238
|
|
|
6625
6239
|
return {
|
|
6240
|
+
"resume_lean_verified": verified_lean,
|
|
6626
6241
|
"total_tokens": total_tokens,
|
|
6627
6242
|
"total_cost_usd": round(total_cost, 4),
|
|
6628
6243
|
"total_events": total_events,
|
|
@@ -6680,9 +6295,7 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6680
6295
|
# $ is already inside realized tool_archive (re-pops netted); not summed.
|
|
6681
6296
|
"progressive_disclosure": _measure_facade._progressive_disclosure_summary(days=days),
|
|
6682
6297
|
# A1: one-time first-trim, surfaced separately, never in the realized total.
|
|
6683
|
-
"one_time_setup": savings.get("one_time_setup"),
|
|
6684
|
-
# A3: MCP-cap estimate lives in the estimated tier, never realized.
|
|
6685
|
-
"mcp_cap_estimated": savings.get("mcp_cap_estimated"),
|
|
6298
|
+
"one_time_setup": savings.get("one_time_setup"), "keepwarm_estimated": savings.get("keepwarm_estimated"), "mod_fresh_estimated": savings.get("mod_fresh_estimated"), "mod_compaction_actions": savings.get("mod_compaction_actions"),
|
|
6686
6299
|
# U-G: deterministically-triggered avoided-search from proactive hints
|
|
6687
6300
|
# (observed hint->read), estimated magnitude. Estimated tier, never realized.
|
|
6688
6301
|
"hint_followed": savings.get("hint_followed_estimated"),
|
|
@@ -6698,37 +6311,16 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6698
6311
|
# credited working set is inferred -- counterfactual, estimated tier,
|
|
6699
6312
|
# never in the realized total.
|
|
6700
6313
|
"checkpoint_restore_estimated": savings.get("checkpoint_restore_estimated"),
|
|
6314
|
+
"verbosity_output_estimated": savings.get("verbosity_output_estimated"),
|
|
6701
6315
|
}
|
|
6702
6316
|
|
|
6703
6317
|
|
|
6704
6318
|
def _install_date():
|
|
6705
|
-
"""Best-known install
|
|
6706
|
-
|
|
6707
|
-
|
|
6708
|
-
falls back to the earliest session_log date. Never raises.
|
|
6319
|
+
"""Best-known install date (ISO YYYY-MM-DD), or None: the first-run baseline
|
|
6320
|
+
snapshot or the earliest logged event, whichever is earlier; with neither,
|
|
6321
|
+
the earliest session on record. Never raises.
|
|
6709
6322
|
"""
|
|
6710
|
-
|
|
6711
|
-
try:
|
|
6712
|
-
snap = _measure_facade.SNAPSHOT_DIR / "snapshot_before.json"
|
|
6713
|
-
if snap.exists():
|
|
6714
|
-
ts = _measure_facade.json.loads(snap.read_text(encoding="utf-8")).get("timestamp")
|
|
6715
|
-
if ts:
|
|
6716
|
-
return ts[:10]
|
|
6717
|
-
except (_measure_facade.json.JSONDecodeError, OSError, ValueError):
|
|
6718
|
-
pass
|
|
6719
|
-
try:
|
|
6720
|
-
if _measure_facade.TRENDS_DB.exists():
|
|
6721
|
-
conn = _measure_facade._init_trends_db()
|
|
6722
|
-
_measure_facade.ensure_activity_view(conn)
|
|
6723
|
-
try:
|
|
6724
|
-
row = conn.execute("SELECT MIN(date) FROM session_activity").fetchone()
|
|
6725
|
-
finally:
|
|
6726
|
-
conn.close()
|
|
6727
|
-
if row and row[0]:
|
|
6728
|
-
return str(row[0])[:10]
|
|
6729
|
-
except (_measure_facade.sqlite3.Error, OSError):
|
|
6730
|
-
pass
|
|
6731
|
-
return None
|
|
6323
|
+
return baseline_provenance.install_evidence(_compat.facade()).get("date")
|
|
6732
6324
|
|
|
6733
6325
|
|
|
6734
6326
|
def _savings_since_install():
|
|
@@ -6747,31 +6339,34 @@ def _savings_since_install():
|
|
|
6747
6339
|
return None
|
|
6748
6340
|
days = (_measure_facade.datetime.now() - _measure_facade.datetime.fromisoformat(d)).days + 1
|
|
6749
6341
|
days = max(1, min(days, 3650))
|
|
6750
|
-
full = _measure_facade._get_merged_savings
|
|
6751
|
-
|
|
6752
|
-
|
|
6753
|
-
|
|
6754
|
-
|
|
6342
|
+
full = savings_story.since_install_summary(_measure_facade._get_merged_savings, days)
|
|
6343
|
+
try:
|
|
6344
|
+
from . import session_effect
|
|
6345
|
+
full["session_effect"] = session_effect.summary(days)
|
|
6346
|
+
except Exception:
|
|
6347
|
+
full["session_effect"] = {}
|
|
6348
|
+
# Measured = logged runtime + realized structural. Model routing is an
|
|
6349
|
+
# assumption and stays out of every savings total.
|
|
6350
|
+
measured = float(full.get("total_cost_usd", 0) or 0) - savings_story.verbosity_logged(full)
|
|
6755
6351
|
full_routing = full.get("model_routing") or {}
|
|
6756
|
-
|
|
6757
|
-
|
|
6758
|
-
|
|
6759
|
-
|
|
6352
|
+
# Since-install routing for every user: a stated pre-TO share
|
|
6353
|
+
# (pretool_baseline.json / TOKEN_OPTIMIZER_BASELINE_OPUS_SHARE) wins,
|
|
6354
|
+
# else the model mix measured at install (snapshot or earliest
|
|
6355
|
+
# history). Same pricing either way; no baseline, a non-Anthropic
|
|
6356
|
+
# runtime, or no Opus in the baseline means $0, never invented Opus.
|
|
6357
|
+
routing_source = savings_story.routing_baseline_kind(full_routing, _measure_facade.detect_runtime())
|
|
6358
|
+
stated = routing_source is not None
|
|
6359
|
+
stated_routing = max(0.0, float(full_routing.get("realized_cost_usd") or 0)) if stated else 0.0
|
|
6760
6360
|
# Estimated = genuine TO-realized counterfactuals only — the same
|
|
6761
6361
|
# categories the dashboard's estimated tier (estItems) sums, so the two
|
|
6762
6362
|
# cards agree about what "estimated" contains. cache_drop and
|
|
6763
6363
|
# output_waste are OPPORTUNITY (avoidable waste TO does not yet prevent),
|
|
6764
|
-
# so they are excluded here
|
|
6765
|
-
# was actually spent. mcp_cap_estimated does NOT double-count with
|
|
6766
|
-
# uncaptured_runtime: _get_savings_summary pops mcp_cap out of the
|
|
6767
|
-
# measured totals before _estimate_uncaptured_runtime derives its
|
|
6768
|
-
# per-session proxy from them, so the two pools are disjoint.
|
|
6364
|
+
# so they are excluded here, along with the unsupported MCP-cap estimate.
|
|
6769
6365
|
estimated = sum(
|
|
6770
6366
|
float((full.get(k) or {}).get("cost_saved_usd", 0) or 0)
|
|
6771
6367
|
for k in (
|
|
6772
|
-
"behavioral_estimate", "uncaptured_runtime",
|
|
6773
|
-
"contamination_exit", "handover_rerun", "
|
|
6774
|
-
"checkpoint_restore_estimated", "verbosity_steer",
|
|
6368
|
+
"behavioral_estimate", "uncaptured_runtime",
|
|
6369
|
+
"contamination_exit", "handover_rerun", "resume_lean_verified",
|
|
6775
6370
|
)
|
|
6776
6371
|
)
|
|
6777
6372
|
# Avoided-search: prefer the hint->read estimate (hint_followed; the
|
|
@@ -6782,21 +6377,33 @@ def _savings_since_install():
|
|
|
6782
6377
|
hf = full.get("hint_followed") or {}
|
|
6783
6378
|
rs = full.get("retrieval_serve") or {}
|
|
6784
6379
|
avoided = hf if int(hf.get("events") or 0) > 0 else rs
|
|
6785
|
-
estimated += float(avoided.get("cost_saved_usd", 0) or 0)
|
|
6786
|
-
if routing_is_estimate:
|
|
6787
|
-
estimated += full_routing_usd
|
|
6380
|
+
estimated += float(avoided.get("cost_saved_usd", 0) or 0) + float(((full.get("structural_detail") or {}).get("estimated") or {}).get("cost_saved_usd") or 0) + stated_routing - max(0.0, float(((full.get("session_effect") or {}).get("overhead") or {}).get("expand_usd") or 0))
|
|
6788
6381
|
# The all-in since install uses the monthly headline's own recipe
|
|
6789
|
-
# (logged +
|
|
6790
|
-
# so the two figures always mean the same thing.
|
|
6382
|
+
# (logged + repeat reads + estimates); routing stays out of both.
|
|
6791
6383
|
all_in = None
|
|
6792
6384
|
try:
|
|
6793
6385
|
counted = _measure_facade._counted_cumulative_summary(days=days)
|
|
6794
6386
|
_measure_facade._apply_counted_oneshot_pricing(full, counted)
|
|
6795
6387
|
components = _measure_facade._action_savings_components(full, counted)
|
|
6388
|
+
display_parts = dict(components["display"]["components_usd"], routing_estimated=round(stated_routing, 2))
|
|
6389
|
+
majority_period = None
|
|
6390
|
+
if stated_routing > 0:
|
|
6391
|
+
try:
|
|
6392
|
+
from . import routing_period
|
|
6393
|
+
rconn = _measure_facade._open_trends_db_readonly(timeout=1.0)
|
|
6394
|
+
share = float(full_routing.get("baseline_opus_share") or 0)
|
|
6395
|
+
try: majority_period = routing_period.strongest(rconn, _measure_facade, stated_routing, d, shares={"opus": share, "sonnet": round(1.0 - share, 4)})
|
|
6396
|
+
finally: rconn.close()
|
|
6397
|
+
except Exception:
|
|
6398
|
+
pass
|
|
6796
6399
|
all_in = {
|
|
6797
|
-
"total_usd": components["display"]["total_usd"],
|
|
6798
|
-
"components_usd":
|
|
6400
|
+
"total_usd": round(components["display"]["total_usd"] + stated_routing, 2),
|
|
6401
|
+
"components_usd": display_parts, "routing_majority_period": majority_period,
|
|
6799
6402
|
"estimated_usd": round(sum(components["display"]["estimates_usd"].values()), 2),
|
|
6403
|
+
"routing_usd": round(float(components.get("routing_usd", 0) or 0), 2),
|
|
6404
|
+
"routing_baseline_opus_share": full_routing.get("baseline_opus_share"), "routing_baseline_source": routing_source,
|
|
6405
|
+
"routing_baseline_basis": full_routing.get("baseline_source"), "routing_baseline_provenance": full_routing.get("baseline_provenance"),
|
|
6406
|
+
"routing_measured_baseline_opus_share": full_routing.get("measured_baseline_opus_share"), "routing_measured_baseline_realized_cost_usd": full_routing.get("measured_baseline_realized_cost_usd"),
|
|
6800
6407
|
"routing_pending": full_routing.get("evidence") == "pending",
|
|
6801
6408
|
"routing_pending_sessions": int(full_routing.get("pending_sessions") or 0),
|
|
6802
6409
|
"routing_unsplit_tokens": int(full_routing.get("unsplit_tokens") or 0),
|
|
@@ -6808,6 +6415,7 @@ def _savings_since_install():
|
|
|
6808
6415
|
return {
|
|
6809
6416
|
"install_date": d,
|
|
6810
6417
|
"days": days,
|
|
6418
|
+
"excluded_usd": dict(savings_story.excluded_since_install(full), routing=None) if stated else savings_story.excluded_since_install(full),
|
|
6811
6419
|
"measured_usd": round(measured, 2),
|
|
6812
6420
|
"estimated_usd": round(estimated, 2),
|
|
6813
6421
|
"total_usd": round(measured + estimated, 2),
|
|
@@ -6930,14 +6538,7 @@ def _reread_savings_for_window(days):
|
|
|
6930
6538
|
|
|
6931
6539
|
|
|
6932
6540
|
def savings_report(days=None, as_json=None):
|
|
6933
|
-
"""Display
|
|
6934
|
-
|
|
6935
|
-
Merges the legacy savings_events table (setup optimization, tool digests,
|
|
6936
|
-
checkpoint restores, etc.) with v5 Active Compression entries written to
|
|
6937
|
-
compression_events (delta reads, quality nudges, loop prevention, bash
|
|
6938
|
-
output compression). Dedup rule: legacy categories authoritative in
|
|
6939
|
-
savings_events; v5 categories authoritative in compression_events.
|
|
6940
|
-
"""
|
|
6541
|
+
"""Display savings from logged actions and the counted repeat-read cohort."""
|
|
6941
6542
|
_measure_facade = _compat.facade()
|
|
6942
6543
|
summary = _measure_facade._get_merged_savings(days=days)
|
|
6943
6544
|
# Use the same stored removal cohort as the dashboard. Its counted benefit
|
|
@@ -6947,6 +6548,7 @@ def savings_report(days=None, as_json=None):
|
|
|
6947
6548
|
except Exception:
|
|
6948
6549
|
summary["counted_period"] = {"available": False}
|
|
6949
6550
|
summary["reread_avoided"] = summary["counted_period"]
|
|
6551
|
+
_compat.facade()._headline.attach(summary, days)
|
|
6950
6552
|
_measure_facade._apply_counted_oneshot_pricing(summary, summary["counted_period"])
|
|
6951
6553
|
summary["action_savings"] = _measure_facade._action_savings_components(
|
|
6952
6554
|
summary, summary["reread_avoided"])
|
|
@@ -6982,10 +6584,9 @@ def savings_report(days=None, as_json=None):
|
|
|
6982
6584
|
# printed parts add up to the printed ALL IN.
|
|
6983
6585
|
_act = summary["action_savings"]
|
|
6984
6586
|
_shown = _measure_facade._action_savings_display(
|
|
6985
|
-
_mo(_act["logged_usd"]), _mo(_act["
|
|
6986
|
-
_mo(_act["routing_estimated_usd"]), _mo(_act["reread_usd"]),
|
|
6587
|
+
_mo(_act["logged_usd"]), 0.0, 0.0, _mo(_act["reread_usd"]),
|
|
6987
6588
|
{k: _mo(v) for k, v in _act["estimates_usd"].items()},
|
|
6988
|
-
total_clamped=_act["total_clamped"])
|
|
6589
|
+
total_clamped=_act["total_clamped"], class_premium=_mo(_act.get("class_premium_usd", 0.0)))
|
|
6989
6590
|
_cents = _shown["components_cents"]
|
|
6990
6591
|
_est_cents = _shown["estimates_cents"]
|
|
6991
6592
|
_money = _measure_facade._format_cents
|
|
@@ -6993,6 +6594,7 @@ def savings_report(days=None, as_json=None):
|
|
|
6993
6594
|
print("\n Token Optimizer Savings Report")
|
|
6994
6595
|
print(f" {'=' * 58}")
|
|
6995
6596
|
print(f" Period: Last {days} days ({start} to {end})")
|
|
6597
|
+
print(_compat.facade()._headline.cli_headline(summary["token_headline"], days, summary.get("session_effect")))
|
|
6996
6598
|
|
|
6997
6599
|
# Headline transformation. With the session-weight pool live it is the
|
|
6998
6600
|
# work-normalized (per-API-call, constant-price) figure; otherwise the legacy
|
|
@@ -7022,12 +6624,14 @@ def savings_report(days=None, as_json=None):
|
|
|
7022
6624
|
if wp:
|
|
7023
6625
|
unit_lbl = "API call" if wp.get("work_unit") == "api_call" else "message"
|
|
7024
6626
|
print(f" Each {unit_lbl} now carries less billed context than in "
|
|
7025
|
-
f"{wp.get('anchor_month')}
|
|
6627
|
+
f"{wp.get('anchor_month')}: "
|
|
7026
6628
|
f"${wp.get('after_cost_per_unit', 0):.4f} vs ${wp.get('before_cost_per_unit', 0):.4f} "
|
|
7027
6629
|
f"at constant token prices, x {int(wp.get('now_units', 0)):,} {unit_lbl}s "
|
|
7028
6630
|
f"this period "
|
|
7029
6631
|
f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs ${ba.get('counterfactual_monthly_usd', 0):,.0f} "
|
|
7030
6632
|
f"the old way) [estimated]")
|
|
6633
|
+
for line in _measure_facade.textwrap.wrap((ba.get("baseline_provenance") or {}).get("note") or "", width=72):
|
|
6634
|
+
print(f" {line}")
|
|
7031
6635
|
drift = float(wp.get("price_mix_drift_usd", 0.0) or 0.0)
|
|
7032
6636
|
if abs(drift) >= 1.0:
|
|
7033
6637
|
print(f" Not claimed: ~${abs(drift):,.0f} this period of model price/mix drift "
|
|
@@ -7114,22 +6718,11 @@ def savings_report(days=None, as_json=None):
|
|
|
7114
6718
|
print(" Pricing: known model rates, API equivalent")
|
|
7115
6719
|
|
|
7116
6720
|
struct = summary.get("structural_detail") or {}
|
|
7117
|
-
|
|
7118
|
-
|
|
7119
|
-
|
|
7120
|
-
delta = struct.get("overhead_delta", 0)
|
|
7121
|
-
# Labelled "Prefix baseline" (not just "Baseline") to distinguish from
|
|
7122
|
-
# the transformation card's session-cost anchors (2026-06-23 etc.).
|
|
7123
|
-
# These are two different baselines with two different jobs: this one
|
|
7124
|
-
# measures prefix token reduction (structural savings), the anchors
|
|
7125
|
-
# measure per-call cost drift. Calling both "baseline" on the same
|
|
7126
|
-
# screen caused the zero-cards confusion.
|
|
7127
|
-
if delta > 0:
|
|
7128
|
-
print(f" Prefix baseline: snapshot {b_date} (prefix trimmed {delta:,} tokens, compounding [est])")
|
|
7129
|
-
else:
|
|
7130
|
-
print(f" Prefix baseline: snapshot {b_date} (no prefix trimmed below baseline yet -> realized $0)")
|
|
6721
|
+
if struct.get("baseline_source") == "trim_ledger":
|
|
6722
|
+
print(f" Setup trims: {len(struct.get('trims') or [])} recorded since "
|
|
6723
|
+
f"{(struct.get('baseline_date') or '')[:10]} ({struct.get('overhead_delta', 0):,} tokens per call still trimmed)")
|
|
7131
6724
|
else:
|
|
7132
|
-
print("
|
|
6725
|
+
print(f" Setup trims: {struct.get('message') or 'no trims recorded yet'}")
|
|
7133
6726
|
|
|
7134
6727
|
print()
|
|
7135
6728
|
print(f" {'Category':<28s} {'Events':>8s} {'Tokens Saved':>14s} {'Cost Saved':>11s}")
|
|
@@ -7146,10 +6739,10 @@ def savings_report(days=None, as_json=None):
|
|
|
7146
6739
|
# measured table (that was the A1/A3 double-count). Without verbosity_steer
|
|
7147
6740
|
# here, the row shows "0 events" in the measured table even though the
|
|
7148
6741
|
# feature fires thousands of times/month — the raw nudge injection count is
|
|
7149
|
-
# an estimated-tier metric
|
|
7150
|
-
#
|
|
6742
|
+
# an estimated-tier metric. verbosity_steer_measured is an uncontrolled
|
|
6743
|
+
# before/after; its net-of-control figure prints in the estimated tier.
|
|
7151
6744
|
_RELOCATED = {"setup_optimization", "mcp_cap", "verbosity_steer", "resume_lean",
|
|
7152
|
-
"checkpoint_restore"}
|
|
6745
|
+
"checkpoint_restore", "verbosity_steer_measured"}
|
|
7153
6746
|
|
|
7154
6747
|
# Known measured categories (even if zero), then any unknown ones in the data.
|
|
7155
6748
|
table_rows = [(label, by_cat.get(key, {}))
|
|
@@ -7197,11 +6790,9 @@ def savings_report(days=None, as_json=None):
|
|
|
7197
6790
|
oneshot = summary.get("oneshot_pricing") or {}
|
|
7198
6791
|
if oneshot.get("removal_events"):
|
|
7199
6792
|
print(" Initial removals above are priced at the input rate, a minimum.")
|
|
7200
|
-
|
|
7201
|
-
if premium >= 0.005:
|
|
6793
|
+
if _cents.get("class_premium"):
|
|
7202
6794
|
print(f" The next call billed new context at a cache-write rate for "
|
|
7203
|
-
f"{int(oneshot.get('class_events', 0)):,} removals
|
|
7204
|
-
f"not in the total.")
|
|
6795
|
+
f"{int(oneshot.get('class_events', 0)):,} removals; that premium is its own line below.")
|
|
7205
6796
|
trip = _measure_facade._headline_tripwire(total_cost + rr_usd, total_events, days)
|
|
7206
6797
|
if trip:
|
|
7207
6798
|
print()
|
|
@@ -7213,21 +6804,30 @@ def savings_report(days=None, as_json=None):
|
|
|
7213
6804
|
print(f" Estimated monthly: ${_money(_cents['logged'])} (measured)")
|
|
7214
6805
|
else:
|
|
7215
6806
|
print(f" Total so far ({tracked} day{'' if tracked == 1 else 's'} tracked): ${_money(_cents['logged'])} (measured)")
|
|
6807
|
+
if _cents.get("class_premium"):
|
|
6808
|
+
print(f" + write-class premium: ~${_money(_cents['class_premium'])}{per} ({_act.get('class_premium_events', 0):,} "
|
|
6809
|
+
"removals whose next call wrote to the cache, priced at that write rate) [measured]")
|
|
7216
6810
|
|
|
7217
|
-
#
|
|
6811
|
+
# Model routing is an assumption, shown on its own line and kept out of ALL IN.
|
|
7218
6812
|
routing = summary.get("model_routing") or {}
|
|
7219
6813
|
routing_realized = float(routing.get("realized_cost_usd", 0.0) or 0.0)
|
|
7220
6814
|
routing_pending = int(routing.get("pending_sessions", 0) or 0) if routing.get("evidence") == "pending" else 0
|
|
7221
6815
|
if routing_pending:
|
|
7222
|
-
print(f"
|
|
7223
|
-
f"session{'' if routing_pending == 1 else 's'} left), not in ALL IN
|
|
6816
|
+
print(f" i model routing: re-measuring ({routing_pending:,} "
|
|
6817
|
+
f"session{'' if routing_pending == 1 else 's'} left), not in ALL IN")
|
|
7224
6818
|
if routing_realized > 0:
|
|
7225
|
-
|
|
6819
|
+
r_cents, _ = _measure_facade._allocate_cents([_mo(routing_realized)])
|
|
6820
|
+
r_monthly = _money(r_cents[0])
|
|
7226
6821
|
b_share = routing.get("baseline_opus_share", 0.0) * 100
|
|
7227
6822
|
c_share = routing.get("current_opus_share", 0.0) * 100
|
|
7228
6823
|
routing_label = "estimated" if routing.get("evidence") == "estimated" else "measured"
|
|
7229
|
-
|
|
7230
|
-
|
|
6824
|
+
basis = (routing.get("baseline_provenance") or {}).get("short") or (f"assuming {b_share:.0f}% Opus before Token Optimizer" if routing.get("baseline_source") == "pretool_baseline" else f"against a measured {b_share:.0f}% Opus baseline")
|
|
6825
|
+
print(f" i Model routing (not in ALL IN): ~${r_monthly}{per} "
|
|
6826
|
+
f"{basis} (now {c_share:.0f}%) [{routing_label}]")
|
|
6827
|
+
mb_share = routing.get("measured_baseline_opus_share")
|
|
6828
|
+
if mb_share is not None:
|
|
6829
|
+
mb_cents, _ = _measure_facade._allocate_cents([_mo(float(routing.get("measured_baseline_realized_cost_usd") or 0.0))])
|
|
6830
|
+
print(f" i measured alternative: your earliest tracked month had {float(mb_share) * 100:.1f}% Opus -> ~${_money(mb_cents[0])}{per}")
|
|
7231
6831
|
ref_priced = [str(f)[:1].upper() + str(f)[1:] for f in routing.get("baseline_reference_priced") or []]
|
|
7232
6832
|
if ref_priced:
|
|
7233
6833
|
print(f" i routing compares your earlier and current mix on one price list, the newest card of each "
|
|
@@ -7286,24 +6886,6 @@ def savings_report(days=None, as_json=None):
|
|
|
7286
6886
|
# cache_drop + output_waste are OPPORTUNITY (avoidable waste TO does not yet
|
|
7287
6887
|
# prevent), shown in the COULD SAVE block below, never in the estimated total.
|
|
7288
6888
|
|
|
7289
|
-
# Estimated tier — MCP-cap (relocated from measured; Claude Code's own
|
|
7290
|
-
# truncation, inferred not observed).
|
|
7291
|
-
mcp_cap_est = summary.get("mcp_cap_estimated") or {}
|
|
7292
|
-
mce_cost = float(mcp_cap_est.get("cost_saved_usd", 0.0) or 0.0)
|
|
7293
|
-
if mce_cost > 0:
|
|
7294
|
-
mce_monthly = _money(_est_cents["mcp_cap_estimated"])
|
|
7295
|
-
print(f" + est. MCP output cap: ~${mce_monthly}{per} "
|
|
7296
|
-
f"({mcp_cap_est.get('events', 0)} capped MCP results) [estimated]")
|
|
7297
|
-
|
|
7298
|
-
# Estimated tier — lean resumes (cold `--resume` reload avoided; the trigger
|
|
7299
|
-
# is a counterfactual, the magnitude is the target's real last-turn context).
|
|
7300
|
-
rl_est = summary.get("resume_lean_estimated") or {}
|
|
7301
|
-
rle_cost = float(rl_est.get("cost_saved_usd", 0.0) or 0.0)
|
|
7302
|
-
if rle_cost > 0:
|
|
7303
|
-
rle_monthly = _money(_est_cents["resume_lean_estimated"])
|
|
7304
|
-
print(f" + est. lean resumes: ~${rle_monthly}{per} "
|
|
7305
|
-
f"({rl_est.get('events', 0)} cold-resume reloads avoided) [estimated]")
|
|
7306
|
-
|
|
7307
6889
|
# Estimated tier — checkpoint restores (avoided working-set re-reads; the
|
|
7308
6890
|
# restore is observed, the credited re-read is inferred, never metered).
|
|
7309
6891
|
cr_est = summary.get("checkpoint_restore_estimated") or {}
|
|
@@ -7343,15 +6925,9 @@ def savings_report(days=None, as_json=None):
|
|
|
7343
6925
|
print(f" + est. avoided search ({label}): ~${_money(_est_cents[avoided_source])}{per} "
|
|
7344
6926
|
f"({detail}) [estimated]")
|
|
7345
6927
|
|
|
7346
|
-
verbosity = summary.get("verbosity_steer") or {}
|
|
7347
|
-
verbosity_cost = summary["action_savings"]["estimates_usd"]["verbosity_steer"]
|
|
7348
|
-
if verbosity_cost > 0:
|
|
7349
|
-
print(f" + est. concise output nudges: ~${_money(_est_cents['verbosity_steer'])}{per} "
|
|
7350
|
-
f"({verbosity.get('events', 0)} nudges) [estimated]")
|
|
7351
|
-
|
|
7352
6928
|
print(f" = ALL IN: ~${all_in}{per} (measured + modeled + estimated)")
|
|
7353
6929
|
if routing_pending:
|
|
7354
|
-
print(" i ALL IN leaves out model routing
|
|
6930
|
+
print(" i ALL IN leaves out model routing; the assumption stays separate.")
|
|
7355
6931
|
if summary["action_savings"].get("reread_pricing_complete") is False:
|
|
7356
6932
|
print(" i ALL IN is a priced subtotal; unpriced repeat-read credits and debits are not included.")
|
|
7357
6933
|
if summary["action_savings"]["total_clamped"]:
|
|
@@ -7366,7 +6942,7 @@ def savings_report(days=None, as_json=None):
|
|
|
7366
6942
|
if float(since_all_in.get("total_usd") or 0) > 0:
|
|
7367
6943
|
so_far = " so far" if since_all_in.get("routing_pending") or since_all_in.get("remeasuring") else ""
|
|
7368
6944
|
print(f" = SINCE INSTALL ({since['install_date']}, {since['days']} days): "
|
|
7369
|
-
f"~${since_all_in['total_usd']:,.2f}{so_far} (same
|
|
6945
|
+
f"~${since_all_in['total_usd']:,.2f}{so_far} (same parts, added up)")
|
|
7370
6946
|
|
|
7371
6947
|
# Informational (not summed): one-time first-trim + progressive disclosure.
|
|
7372
6948
|
one_time = summary.get("one_time_setup") or {}
|
|
@@ -7412,14 +6988,14 @@ def savings_report(days=None, as_json=None):
|
|
|
7412
6988
|
f"re-reads across {reclaimable.get('sessions', 0)} sessions — avoid re-reading or use .contextignore.")
|
|
7413
6989
|
if len(concrete_items) > 1:
|
|
7414
6990
|
print(f" = ~${_measure_facade._format_cents(items_total_cents)}{per} from the items above (API-rate equivalent)")
|
|
7415
|
-
if cd_tokens > 0:
|
|
7416
|
-
|
|
7417
|
-
|
|
6991
|
+
if cd_tokens > 0: # an opportunity at API rates: own line, never folded into the total above
|
|
6992
|
+
ttl = float(cache_drop.get("ttl_seconds") or 0) # the TTL the user's own cache writes show
|
|
6993
|
+
cache_name, resume = ("the 5-minute cache", "5 minutes") if 0 < ttl < 3600 else ("the 1-hour cache" if ttl >= 3600 else "the cache window", "the hour")
|
|
7418
6994
|
cd_dollars = f", about ${_mo(cd_cost):.2f}{per} at API rates" if cd_cost > 0 else ""
|
|
7419
6995
|
print()
|
|
7420
6996
|
print(f" Cache drops (an opportunity, not a measurement): {cache_drop.get('drop_sessions', 0)} sessions idled "
|
|
7421
|
-
f"past
|
|
7422
|
-
f"
|
|
6997
|
+
f"past {cache_name} and re-wrote ~{int(_mo(cd_tokens)):,} tokens{per} of prefix{cd_dollars}. "
|
|
6998
|
+
f"Resume within {resume}, or batch related work before stepping away.")
|
|
7423
6999
|
if routing_potential > 0:
|
|
7424
7000
|
# Routing is an assumption about the user's own Opus work, so it sits
|
|
7425
7001
|
# on its own line and is never folded into the total above.
|
|
@@ -7444,7 +7020,6 @@ def savings_report(days=None, as_json=None):
|
|
|
7444
7020
|
print(" - Restore from progressive checkpoints (Smart Compaction)")
|
|
7445
7021
|
print(" - Archive unused tools or skills")
|
|
7446
7022
|
|
|
7447
|
-
|
|
7448
7023
|
def validate_impact(strategy=None, days=None, as_json=None):
|
|
7449
7024
|
"""Compare session metrics before vs after an optimization event.
|
|
7450
7025
|
|