@alexgreensh/token-optimizer 5.13.68 → 5.13.70
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/fleet-auditor/references/fleet-systems.md +38 -0
- package/skills/fleet-auditor/scripts/fleet.py +63 -92
- package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
- package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
- package/skills/token-coach/SKILL.md +21 -23
- package/skills/token-dashboard/SKILL.md +5 -4
- package/skills/token-optimizer/SKILL.md +1 -1
- package/skills/token-optimizer/assets/dashboard.html +492 -551
- package/skills/token-optimizer/assets/savings_story.js +661 -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/cursor-workflow.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/references/phase0-setup.md +1 -1
- package/skills/token-optimizer/references/presentation-workflow.md +1 -1
- 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 +98 -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 +64 -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 +28 -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 +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
- package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -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 +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -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 +59 -168
- 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 +173 -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 +451 -933
- 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 +154 -216
- 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/_measure/weekly_activity.py +69 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +6 -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 +22 -83
- package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
- package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
- 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 +6 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
- package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
- package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
- package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
- package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
- package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
- package/skills/token-optimizer/scripts/cursor_install.py +118 -19
- package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
- package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
- package/skills/token-optimizer/scripts/cursor_session.py +26 -5
- package/skills/token-optimizer/scripts/cursor_state.py +8 -0
- package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
- package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
- package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
- 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 +19 -4
- package/skills/token-optimizer/scripts/devin_verify.py +13 -6
- package/skills/token-optimizer/scripts/grok_install.py +6 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -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 +36 -78
- 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 +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
- package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
|
@@ -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,17 @@ 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:
|
|
1324
1196
|
return savings_data
|
|
1197
|
+
try:
|
|
1198
|
+
from . import cost_per_message_trend
|
|
1199
|
+
conn = _measure_facade._open_trends_db_readonly(timeout=1.0)
|
|
1200
|
+
try: savings_data["cost_per_message_trend"] = cost_per_message_trend.query(conn)
|
|
1201
|
+
finally: conn.close()
|
|
1202
|
+
except Exception:
|
|
1203
|
+
savings_data["cost_per_message_trend"] = []
|
|
1204
|
+
savings_data["skill_listing_budget"] = structural_report.skill_listing_budget(days or 30)
|
|
1325
1205
|
try:
|
|
1326
1206
|
savings_data["since_install"] = _measure_facade._savings_since_install()
|
|
1327
1207
|
except Exception:
|
|
@@ -1336,6 +1216,8 @@ def _dashboard_savings_data(days=None, include_billing_mode=None, fail_open=None
|
|
|
1336
1216
|
savings_data["counted_period"] = _measure_facade._counted_cumulative_summary(days=days)
|
|
1337
1217
|
except Exception:
|
|
1338
1218
|
savings_data["counted_period"] = {"available": False}
|
|
1219
|
+
savings_data["token_type_breakdown"] = (savings_data["counted_period"] or {}).get("token_type_breakdown", {})
|
|
1220
|
+
_compat.facade()._headline.attach(savings_data, days)
|
|
1339
1221
|
_measure_facade._apply_counted_oneshot_pricing(savings_data, savings_data["counted_period"])
|
|
1340
1222
|
savings_data["action_savings"] = _measure_facade._action_savings_components(
|
|
1341
1223
|
savings_data, savings_data["counted_period"])
|
|
@@ -1359,8 +1241,8 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1359
1241
|
Returns (by_category, total_tokens, total_cost, total_events, popped,
|
|
1360
1242
|
repriced_to_session_mix) where *popped* holds the entries relocated out of
|
|
1361
1243
|
the realized total (setup_optimization, mcp_cap, hint_followed,
|
|
1362
|
-
verbosity_steer, resume_lean, checkpoint_restore),
|
|
1363
|
-
None.
|
|
1244
|
+
verbosity_steer, resume_lean, checkpoint_restore, verbosity_steer_measured),
|
|
1245
|
+
each an entry dict or None.
|
|
1364
1246
|
"""
|
|
1365
1247
|
_measure_facade = _compat.facade()
|
|
1366
1248
|
by_category = {}
|
|
@@ -1392,78 +1274,41 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1392
1274
|
total_cost += _delta
|
|
1393
1275
|
repriced_to_session_mix = True
|
|
1394
1276
|
|
|
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)
|
|
1277
|
+
# Relocated OUT of the realized total, each into its own non-realized line:
|
|
1278
|
+
# setup_optimization (A1): one-time prefix trim; structural_savings is the
|
|
1279
|
+
# ongoing model of the SAME trim, so the one-shot is never summed with it.
|
|
1280
|
+
# mcp_cap (A3): hardcoded-ratio estimate of Claude Code's own truncation.
|
|
1281
|
+
# hint_followed (U-G), verbosity_steer: observed trigger, estimated size.
|
|
1282
|
+
# resume_lean, checkpoint_restore: counterfactual credits (the cold
|
|
1283
|
+
# reload / working-set re-read never happened, so nothing was metered).
|
|
1284
|
+
# verbosity_steer_measured (savings-truth U5): a before/after of output
|
|
1285
|
+
# with no control. Against matched un-nudged replies it is not a
|
|
1286
|
+
# reduction, so both booked rows and the control study stay diagnostic.
|
|
1287
|
+
# savings_events has no tier column: this pop IS the tier=estimated stamp.
|
|
1288
|
+
popped = {}
|
|
1289
|
+
# codemap_lookup: a lookup answered instead of a Read; the avoided read is
|
|
1290
|
+
# a counterfactual (file not read within the follow-up window).
|
|
1291
|
+
for name in ("setup_optimization", "mcp_cap", "hint_followed", "verbosity_steer",
|
|
1292
|
+
"resume_lean", "checkpoint_restore", "verbosity_steer_measured",
|
|
1293
|
+
"codemap_lookup", "keepwarm_estimated"):
|
|
1294
|
+
entry = popped[name] = by_category.pop(name, None)
|
|
1295
|
+
if entry:
|
|
1296
|
+
total_tokens -= int(entry.get("tokens_saved", 0) or 0)
|
|
1297
|
+
total_cost -= float(entry.get("cost_saved_usd", 0.0) or 0.0)
|
|
1298
|
+
total_events -= int(entry.get("events", 0) or 0)
|
|
1299
|
+
|
|
1300
|
+
# Bash archive expansions reverse Bash output savings, not MCP replacements.
|
|
1301
|
+
bash = by_category.get("bash_archive_reexpand")
|
|
1302
|
+
if bash:
|
|
1303
|
+
total_tokens -= 2 * int(bash.get("tokens_saved") or 0)
|
|
1304
|
+
total_cost -= 2 * float(bash.get("cost_saved_usd") or 0)
|
|
1305
|
+
total_events -= int(bash.get("events") or 0)
|
|
1306
|
+
bash["tokens_saved"] = -int(bash.get("tokens_saved") or 0)
|
|
1307
|
+
bash["cost_saved_usd"] = -float(bash.get("cost_saved_usd") or 0)
|
|
1463
1308
|
|
|
1464
1309
|
# B6: net tool-archive re-expansions out of the tool_archive credit. A
|
|
1465
1310
|
# re-popped result didn't stay collapsed, so its eager credit is reversed
|
|
1466
|
-
#
|
|
1311
|
+
# even if the result is negative. tool_archive_reexpand is a DEBIT, never its own savings
|
|
1467
1312
|
# line, so it is removed from by_category and its spurious positive
|
|
1468
1313
|
# contribution backed out of the totals. The remaining tool_archive figure
|
|
1469
1314
|
# IS the measured progressive-disclosure win (collapsed and stayed so).
|
|
@@ -1472,11 +1317,11 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1472
1317
|
r_tok = int(reexpand.get("tokens_saved", 0) or 0)
|
|
1473
1318
|
r_cost = float(reexpand.get("cost_saved_usd", 0.0) or 0.0)
|
|
1474
1319
|
r_events = int(reexpand.get("events", 0) or 0)
|
|
1475
|
-
ta = by_category.
|
|
1320
|
+
ta = by_category.setdefault("tool_archive", {"events": 0, "tokens_saved": 0, "cost_saved_usd": 0.0})
|
|
1476
1321
|
c_tok = int(ta["tokens_saved"]) if ta else 0
|
|
1477
1322
|
c_cost = float(ta["cost_saved_usd"]) if ta else 0.0
|
|
1478
|
-
net_tok =
|
|
1479
|
-
net_cost =
|
|
1323
|
+
net_tok = c_tok - r_tok
|
|
1324
|
+
net_cost = c_cost - r_cost
|
|
1480
1325
|
if ta:
|
|
1481
1326
|
ta["tokens_saved"] = net_tok
|
|
1482
1327
|
ta["cost_saved_usd"] = round(net_cost, 4)
|
|
@@ -1485,14 +1330,6 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1485
1330
|
total_cost += (net_cost - c_cost) - r_cost
|
|
1486
1331
|
total_events -= r_events # re-expand rows are not savings events
|
|
1487
1332
|
|
|
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
1333
|
return (by_category, total_tokens, total_cost, total_events, popped,
|
|
1497
1334
|
repriced_to_session_mix)
|
|
1498
1335
|
|
|
@@ -1506,7 +1343,7 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1506
1343
|
boundary (e.g. the subscription limit reset). When *since* is None / empty,
|
|
1507
1344
|
the rolling cutoff is computed from *days* as before.
|
|
1508
1345
|
"""
|
|
1509
|
-
_measure_facade = _compat.facade()
|
|
1346
|
+
_measure_facade = _compat.facade(); from . import keepwarm_economics, mod_fresh_booking, mod_compaction_booking
|
|
1510
1347
|
try:
|
|
1511
1348
|
conn = _measure_facade._init_trends_db()
|
|
1512
1349
|
try:
|
|
@@ -1514,9 +1351,11 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1514
1351
|
cutoff = since
|
|
1515
1352
|
else:
|
|
1516
1353
|
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
1354
|
+
table = _measure_facade._counted_table(conn, "savings_events")
|
|
1355
|
+
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
1356
|
rows = conn.execute(
|
|
1518
|
-
"SELECT
|
|
1519
|
-
"FROM " +
|
|
1357
|
+
"SELECT " + event_expr + ", COUNT(*) as cnt, SUM(tokens_saved) as tok, SUM(cost_saved_usd) as cost "
|
|
1358
|
+
"FROM " + table + " WHERE timestamp >= ? GROUP BY 1 ORDER BY tok DESC",
|
|
1520
1359
|
(cutoff,),
|
|
1521
1360
|
).fetchall()
|
|
1522
1361
|
# Model-mix repair, same connection and same cutoff so the corrected
|
|
@@ -1525,17 +1364,24 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1525
1364
|
unpriced_reprice = {}
|
|
1526
1365
|
reprice_deltas, repriced_tokens, unmeasured_tokens = _measure_facade._session_model_reprice(
|
|
1527
1366
|
conn, cutoff, unpriced_out=unpriced_reprice)
|
|
1367
|
+
tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
|
|
1368
|
+
resume_fix = _measure_facade._counted_pricing_v5.resume_lean_reprice(conn, _measure_facade._counted_table(conn, "savings_events"), cutoff,
|
|
1369
|
+
lambda model: _measure_facade._counted_exact_card(model, tier_data))
|
|
1528
1370
|
finally:
|
|
1529
1371
|
conn.close()
|
|
1530
1372
|
|
|
1531
1373
|
(by_category, total_tokens, total_cost, total_events, popped,
|
|
1532
1374
|
repriced_to_session_mix) = _measure_facade._net_realized_savings(rows, reprice_deltas)
|
|
1533
1375
|
one_time = popped["setup_optimization"]
|
|
1534
|
-
mcp_cap_est = popped["mcp_cap"]
|
|
1535
1376
|
hint_followed_est = popped["hint_followed"]
|
|
1377
|
+
codemap_lookup_est = popped["codemap_lookup"]
|
|
1536
1378
|
verbosity_steer_est = popped["verbosity_steer"]
|
|
1537
1379
|
resume_lean_est = popped["resume_lean"]
|
|
1380
|
+
if resume_lean_est and resume_fix["repriced_events"]: # exact model card, not the family card
|
|
1381
|
+
resume_lean_est["cost_saved_usd"] = round(max(0.0, resume_lean_est["cost_saved_usd"] + resume_fix["delta_usd"]), 4)
|
|
1382
|
+
resume_lean_est["exact_card_reprice"] = resume_fix
|
|
1538
1383
|
checkpoint_restore_est = popped["checkpoint_restore"]
|
|
1384
|
+
verbosity_output_est = _measure_facade._output_reread.summary_pool(popped["verbosity_steer_measured"])
|
|
1539
1385
|
|
|
1540
1386
|
daily_avg = total_cost / days if days > 0 else 0.0
|
|
1541
1387
|
|
|
@@ -1548,12 +1394,12 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1548
1394
|
"period_days": days,
|
|
1549
1395
|
# A1: one-time first-trim (compare). Reported separately, NEVER summed
|
|
1550
1396
|
# 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,
|
|
1397
|
+
"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
1398
|
# U-G: observed-trigger / estimated-magnitude avoided-search from
|
|
1555
1399
|
# proactive hints. Estimated tier, never in the realized total.
|
|
1556
1400
|
"hint_followed_estimated": hint_followed_est,
|
|
1401
|
+
# Code map lookups: observed lookup, counterfactual avoided read. Estimated tier.
|
|
1402
|
+
"codemap_lookup_estimated": codemap_lookup_est,
|
|
1557
1403
|
# Verbosity-steer: estimated output-token reduction from conciseness
|
|
1558
1404
|
# nudges. Estimated tier, never in the realized total. Surfaced so
|
|
1559
1405
|
# _estimate_before_after_savings can add it to the transformation
|
|
@@ -1568,6 +1414,9 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1568
1414
|
# from this session's reads -- the avoided re-read never happened,
|
|
1569
1415
|
# so nothing was metered. Estimated tier, never realized.
|
|
1570
1416
|
"checkpoint_restore_estimated": checkpoint_restore_est,
|
|
1417
|
+
# Nudged replies and their later rereads, net of matched un-nudged
|
|
1418
|
+
# replies (U5). Estimated tier; the booked rows are reference only.
|
|
1419
|
+
"verbosity_output_estimated": verbosity_output_est,
|
|
1571
1420
|
# True when at least one event's dollars moved because its event-time
|
|
1572
1421
|
# model stamp disagreed with its own session's recorded model mix. The
|
|
1573
1422
|
# figure is then a rate ALLOCATION, not a pure event-time meter, so
|
|
@@ -1594,11 +1443,12 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1594
1443
|
"daily_avg_usd": 0.0,
|
|
1595
1444
|
"period_days": days,
|
|
1596
1445
|
"one_time_setup": None,
|
|
1597
|
-
"mcp_cap_estimated": None,
|
|
1598
1446
|
"hint_followed_estimated": None,
|
|
1447
|
+
"codemap_lookup_estimated": None,
|
|
1599
1448
|
"verbosity_steer_estimated": None,
|
|
1600
1449
|
"resume_lean_estimated": None,
|
|
1601
1450
|
"checkpoint_restore_estimated": None,
|
|
1451
|
+
"verbosity_output_estimated": None,
|
|
1602
1452
|
"repriced_to_session_mix": False,
|
|
1603
1453
|
"reprice_detail": None,
|
|
1604
1454
|
}
|
|
@@ -2344,14 +2194,18 @@ def _runway_saved_tokens(conn, cutoff, include_estimated=None):
|
|
|
2344
2194
|
multiplier, which the card labels as an estimate.
|
|
2345
2195
|
"""
|
|
2346
2196
|
_measure_facade = _compat.facade()
|
|
2197
|
+
table = _measure_facade._counted_table(conn, "savings_events")
|
|
2198
|
+
sql = _measure_facade._RUNWAY_SAVED_SQL[table]
|
|
2199
|
+
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
2200
|
by_event = {
|
|
2348
2201
|
event_type: int(tokens or 0)
|
|
2349
2202
|
for event_type, tokens in conn.execute(
|
|
2350
|
-
|
|
2203
|
+
sql, (cutoff,))
|
|
2351
2204
|
if include_estimated or event_type not in _measure_facade._RUNWAY_ESTIMATED_EVENT_TYPES}
|
|
2352
2205
|
reexpanded = by_event.pop("tool_archive_reexpand", 0)
|
|
2353
|
-
if "
|
|
2354
|
-
|
|
2206
|
+
if "bash_archive_reexpand" in by_event: by_event["bash_archive_reexpand"] *= -1
|
|
2207
|
+
if reexpanded:
|
|
2208
|
+
by_event["tool_archive"] = by_event.get("tool_archive", 0) - reexpanded
|
|
2355
2209
|
saved = sum(by_event.values())
|
|
2356
2210
|
table = _measure_facade._counted_table(conn, "compression_events")
|
|
2357
2211
|
if "feature" not in {r[1] for r in conn.execute(f"PRAGMA table_info({table})")}:
|
|
@@ -2364,7 +2218,7 @@ def _runway_saved_tokens(conn, cutoff, include_estimated=None):
|
|
|
2364
2218
|
return saved
|
|
2365
2219
|
|
|
2366
2220
|
|
|
2367
|
-
def runway_snapshot(days=None, now=None):
|
|
2221
|
+
def runway_snapshot(days=None, now=None, token_headline=None):
|
|
2368
2222
|
"""Subscription runway: how much of your rate-limit window Token Optimizer
|
|
2369
2223
|
hands back, and what the same windows would read without it.
|
|
2370
2224
|
|
|
@@ -2408,53 +2262,51 @@ def runway_snapshot(days=None, now=None):
|
|
|
2408
2262
|
_measure_facade = _compat.facade()
|
|
2409
2263
|
try:
|
|
2410
2264
|
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 [].
|
|
2265
|
+
# Missing meters leave the ledger-backed headline visible.
|
|
2420
2266
|
meter_available = bool(meters.get("available"))
|
|
2421
2267
|
meter_stale = bool(meters.get("stale")) or not meter_available
|
|
2422
2268
|
|
|
2423
|
-
|
|
2424
|
-
resets_at=meters.get("seven_day_resets_at"), now=now)
|
|
2269
|
+
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
2270
|
|
|
2426
|
-
#
|
|
2271
|
+
# Context uses dated input and output, including cache.
|
|
2427
2272
|
consumed = saved = context_saved = 0
|
|
2428
|
-
|
|
2273
|
+
traffic = None
|
|
2429
2274
|
try:
|
|
2430
2275
|
conn = _measure_facade._init_trends_db()
|
|
2431
2276
|
try:
|
|
2432
2277
|
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
2433
|
-
|
|
2434
|
-
consumed =
|
|
2278
|
+
traffic = _compat.facade()._headline.input_traffic(conn, cutoff[:10], _measure_facade.datetime.now().date().isoformat())
|
|
2279
|
+
consumed = traffic["tokens"]
|
|
2435
2280
|
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
2281
|
finally:
|
|
2440
2282
|
conn.close()
|
|
2441
2283
|
except Exception:
|
|
2442
2284
|
return None
|
|
2443
2285
|
if consumed <= 0 and not weekly_full:
|
|
2444
2286
|
return None
|
|
2287
|
+
try:
|
|
2288
|
+
if token_headline is None:
|
|
2289
|
+
token_source = _measure_facade._get_merged_savings(days=days)
|
|
2290
|
+
token_source["counted_period"] = _measure_facade._counted_cumulative_summary(days=days)
|
|
2291
|
+
token_headline = _compat.facade()._headline.token_headline(token_source)
|
|
2292
|
+
token_parts = token_headline
|
|
2293
|
+
except Exception:
|
|
2294
|
+
token_parts = _compat.facade()._headline.token_headline({})
|
|
2295
|
+
context_saved = token_parts["total_tokens"]
|
|
2445
2296
|
context_mult = (consumed + context_saved) / consumed if consumed > 0 else 1.0
|
|
2446
2297
|
|
|
2447
2298
|
# --- 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.
|
|
2299
|
+
# Pending or unavailable routing remains explicit.
|
|
2450
2300
|
routing = _measure_facade._runway_routing_lever(days=days)
|
|
2451
2301
|
routing_state = routing.get("state")
|
|
2452
2302
|
routing_mult = routing.get("factor")
|
|
2453
2303
|
|
|
2454
|
-
|
|
2455
|
-
#
|
|
2456
|
-
#
|
|
2457
|
-
|
|
2304
|
+
# A heavier model mix is the user's choice, not a cost Token Optimizer
|
|
2305
|
+
# caused, so it never shrinks what TO hands back (or hides the card).
|
|
2306
|
+
# The raw factor is still reported as routing_multiplier below.
|
|
2307
|
+
mult = context_mult * max(1.0, routing_mult if routing_mult is not None else 1.0)
|
|
2308
|
+
# Hide immaterial changes unless weekly savings are available.
|
|
2309
|
+
if mult < 1.02 and not weekly_signal:
|
|
2458
2310
|
return None
|
|
2459
2311
|
|
|
2460
2312
|
# --- USD-per-window: API-credit OVERAGE over each window's OWN real span ---
|
|
@@ -2527,16 +2379,7 @@ def runway_snapshot(days=None, now=None):
|
|
|
2527
2379
|
merged_ctx = float(wm.get("total_cost_usd", 0.0) or 0.0)
|
|
2528
2380
|
rt = float((wm.get("model_routing") or {}).get("realized_cost_usd", 0.0) or 0.0)
|
|
2529
2381
|
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)
|
|
2382
|
+
est_add = max(0.0, float((wm.get("resume_lean_verified") or {}).get("cost_saved_usd") or 0.0))
|
|
2540
2383
|
except Exception:
|
|
2541
2384
|
pass
|
|
2542
2385
|
try:
|
|
@@ -2645,9 +2488,8 @@ def runway_snapshot(days=None, now=None):
|
|
|
2645
2488
|
# `if not windows: return None` then dropped the ENTIRE card -- yet the
|
|
2646
2489
|
# throughput multiplier (extra_work_pct) and the weekly savings do NOT
|
|
2647
2490
|
# 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
|
|
2491
|
+
# the card alive with empty windows (last_known_windows carries the stored
|
|
2492
|
+
# reading). Populate the weekly $ spine directly since the 7d window that
|
|
2651
2493
|
# normally fills _overage_cache[...] may have been dropped above.
|
|
2652
2494
|
#
|
|
2653
2495
|
# Compute the aligned weekly cache key (same logic as _window_overage_usd)
|
|
@@ -2712,11 +2554,11 @@ def runway_snapshot(days=None, now=None):
|
|
|
2712
2554
|
"routing_standardized_actual_cost_usd": routing.get("standardized_actual_cost_usd"),
|
|
2713
2555
|
"extra_work_pct": round((mult - 1) * 100, 1),
|
|
2714
2556
|
"tokens_consumed": int(consumed),
|
|
2715
|
-
"tokens_consumed_basis":
|
|
2716
|
-
"tokens_consumed_basis_complete": bool(
|
|
2557
|
+
"tokens_consumed_basis": traffic["basis"] if traffic else None,
|
|
2558
|
+
"tokens_consumed_basis_complete": bool(traffic and traffic["complete"]),
|
|
2717
2559
|
"tokens_saved": int(saved),
|
|
2718
|
-
"context_tokens_saved": int(context_saved),
|
|
2719
|
-
"windows": windows,
|
|
2560
|
+
"context_tokens_saved": int(context_saved), "token_headline": token_parts,
|
|
2561
|
+
"windows": windows, "last_known_windows": savings_story.last_known_windows(meters, mult, windows),
|
|
2720
2562
|
# USD spine: metered context $ + estimated routing $ over the WEEKLY
|
|
2721
2563
|
# (7d) ledger -- the same span the weekly card shows. Exposed at the top
|
|
2722
2564
|
# level so the surface and tests can assert the no-double-count invariant
|
|
@@ -2887,127 +2729,40 @@ def _per_session_prefix_tokens(fallback=None):
|
|
|
2887
2729
|
|
|
2888
2730
|
|
|
2889
2731
|
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.
|
|
2732
|
+
"""Forward value of S prefix tokens over the window (opportunity pricing).
|
|
2733
|
+
|
|
2734
|
+
Thin caller of structural_report.price_synthetic: per request, at that
|
|
2735
|
+
request's exact model card, S x cache_read on cache hits and S x the write
|
|
2736
|
+
class actually paid on misses (session starts, sub-agent starts, cache
|
|
2737
|
+
drops). Replaces the family-keyed mix rate and the "S / prefix x ALL cache
|
|
2738
|
+
writes" term, which overstated reads ~2.4x and writes ~2.9x. Only local
|
|
2739
|
+
sessions count: synced cloud sessions never load this machine's setup.
|
|
2740
|
+
`fallback_prefix` is unused, kept for call-site symmetry. None when S<=0.
|
|
2900
2741
|
"""
|
|
2901
|
-
|
|
2902
|
-
if s <= 0 or not _measure_facade.TRENDS_DB.exists():
|
|
2742
|
+
if s <= 0:
|
|
2903
2743
|
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
|
-
}
|
|
2744
|
+
return _compat.facade()._structural_report.price_synthetic(s, days)
|
|
2948
2745
|
|
|
2949
2746
|
|
|
2950
2747
|
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.
|
|
2748
|
+
"""Realized structural savings from the per-component trim ledger.
|
|
2749
|
+
|
|
2750
|
+
Thin caller of structural_report.compute (scripts/_measure/structural_*):
|
|
2751
|
+
each trim is a dated event (audit action, owner attestation or detected
|
|
2752
|
+
shrink), credited for sessions where its component loads, from the trim
|
|
2753
|
+
until the item comes back, priced per request. Unrelated prefix growth
|
|
2754
|
+
never offsets a trim. Measured-tier trims are in tokens_saved /
|
|
2755
|
+
cost_saved_usd; attested ("estimated") and unattributed trims are reported
|
|
2756
|
+
in their own bands and never summed here. No trims -> zeros with
|
|
2757
|
+
status "no_trims". Never raises.
|
|
2970
2758
|
"""
|
|
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
|
|
2759
|
+
return _compat.facade()._structural_report.compute(days=days or 30)
|
|
3002
2760
|
|
|
3003
2761
|
|
|
3004
2762
|
def _unused_skill_overhead_tokens(days=None):
|
|
3005
2763
|
"""Estimate recoverable prefix tokens from skills never used in the window.
|
|
3006
2764
|
|
|
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.
|
|
2765
|
+
Claude listing savings require transcript evidence, so inventory is not priced.
|
|
3011
2766
|
"""
|
|
3012
2767
|
_measure_facade = _compat.facade()
|
|
3013
2768
|
try:
|
|
@@ -3042,7 +2797,7 @@ def _unused_skill_overhead_tokens(days=None):
|
|
|
3042
2797
|
else:
|
|
3043
2798
|
used.add(s)
|
|
3044
2799
|
unused = installed - used
|
|
3045
|
-
return len(unused) * avg_per_skill, len(unused)
|
|
2800
|
+
return (0 if _measure_facade.detect_runtime() == "claude" else len(unused) * avg_per_skill), len(unused)
|
|
3046
2801
|
except Exception:
|
|
3047
2802
|
return 0, 0
|
|
3048
2803
|
|
|
@@ -3065,7 +2820,7 @@ def _compute_structural_potential(days=None):
|
|
|
3065
2820
|
try:
|
|
3066
2821
|
s_potential, unused_count = _measure_facade._unused_skill_overhead_tokens(days=days)
|
|
3067
2822
|
if s_potential <= 0:
|
|
3068
|
-
return zero
|
|
2823
|
+
return {**zero, "unused_skills": int(unused_count), "basis": "no measured listing reduction"}
|
|
3069
2824
|
current_overhead = _measure_facade._current_overhead_tokens() or s_potential
|
|
3070
2825
|
terms = _measure_facade._compound_structural(s_potential, days, fallback_prefix=current_overhead)
|
|
3071
2826
|
if not terms:
|
|
@@ -3539,105 +3294,57 @@ def _estimate_output_waste(days=None):
|
|
|
3539
3294
|
|
|
3540
3295
|
|
|
3541
3296
|
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
|
-
|
|
3297
|
+
"""Cache rebuilds after idle gaps (the 'coffee-break reload'), in dollars.
|
|
3298
|
+
|
|
3299
|
+
Reads the same engine as cache health (`_cache_ttl_waste_cached`), so the
|
|
3300
|
+
fold and the health check never disagree. A rebuild is a turn that, after
|
|
3301
|
+
a gap longer than the cache TTL the user's own writes show (1 hour for a
|
|
3302
|
+
Claude Code user writing 1h caches, 5 minutes for a 5m user), re-wrote the
|
|
3303
|
+
prefix the previous turn had cached. Each one is priced on the prefix it
|
|
3304
|
+
actually rebuilt (min of the resume write and the prior cached prefix), at
|
|
3305
|
+
that turn's 1h/5m write rate for its model, minus the cache read it would
|
|
3306
|
+
have cost with the cache alive. Only rebuilds whose resume turn falls in
|
|
3307
|
+
the window count, and a transcript copied into two directories counts
|
|
3308
|
+
once. Dollars are at API rates. Never raises.
|
|
3309
|
+
|
|
3310
|
+
Returns {drop_sessions, est_drops, prefix_tokens, rebuilt_tokens,
|
|
3311
|
+
ttl_seconds, cost_saved_usd, by_class, rate_basis, price_basis,
|
|
3312
|
+
unpriced_share, evidence}. `est_drops * prefix_tokens` approximates
|
|
3313
|
+
`rebuilt_tokens` (the average rebuilt prefix); prefer rebuilt_tokens.
|
|
3314
|
+
OPPORTUNITY tier: rebuilds that already happened, avoidable by resuming
|
|
3315
|
+
inside the TTL. Never summed into the realized total.
|
|
3561
3316
|
"""
|
|
3562
3317
|
_measure_facade = _compat.facade()
|
|
3563
|
-
zero = {"drop_sessions": 0, "est_drops": 0, "prefix_tokens": 0,
|
|
3564
|
-
"cost_saved_usd": 0.0, "evidence": "opportunity"}
|
|
3318
|
+
zero = {"drop_sessions": 0, "est_drops": 0, "prefix_tokens": 0, "rebuilt_tokens": 0,
|
|
3319
|
+
"ttl_seconds": None, "cost_saved_usd": 0.0, "evidence": "opportunity"}
|
|
3565
3320
|
try:
|
|
3566
|
-
|
|
3321
|
+
health = _measure_facade._cache_ttl_waste_cached(days=days) or {}
|
|
3322
|
+
rebuild = health.get("rebuild") or {}
|
|
3323
|
+
events = int(rebuild.get("events", 0) or 0)
|
|
3324
|
+
tokens = int(rebuild.get("tokens", 0) or 0)
|
|
3325
|
+
if events <= 0 or tokens <= 0:
|
|
3567
3326
|
return zero
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
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:
|
|
3587
|
-
return zero
|
|
3588
|
-
# Use the measured current overhead as the prefix fallback when no JSONL
|
|
3589
|
-
# session-start baselines are available, so the estimate still computes.
|
|
3590
|
-
prefix = _measure_facade._per_session_prefix_tokens(fallback=_measure_facade._current_overhead_tokens() or 0)
|
|
3591
|
-
if prefix <= 1:
|
|
3592
|
-
return {**zero, "drop_sessions": int(drop_sessions)}
|
|
3593
|
-
# Conservative: one avoidable reload per qualifying session.
|
|
3594
|
-
est_drops = int(drop_sessions)
|
|
3595
|
-
tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
|
|
3596
|
-
weights = {}
|
|
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
|
|
3327
|
+
classes = rebuild.get("tokens_by_class") or {}
|
|
3328
|
+
write_usd = float(rebuild.get("write_usd", 0.0) or 0.0)
|
|
3329
|
+
read_usd = float(rebuild.get("read_instead_usd", 0.0) or 0.0)
|
|
3330
|
+
by_class = {}
|
|
3331
|
+
for name in ("cache_write_1h", "cache_write_5m"):
|
|
3332
|
+
n = int(classes.get(name, 0) or 0)
|
|
3333
|
+
if n > 0:
|
|
3334
|
+
by_class[name] = {"tokens": n, "usd": round(write_usd * n / tokens, 4)}
|
|
3335
|
+
by_class["cache_read_instead"] = {"tokens": tokens, "usd": round(-read_usd, 4)}
|
|
3630
3336
|
return {
|
|
3631
|
-
"drop_sessions": int(
|
|
3632
|
-
"est_drops":
|
|
3633
|
-
"prefix_tokens": int(
|
|
3634
|
-
"
|
|
3635
|
-
"
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
"
|
|
3640
|
-
|
|
3337
|
+
"drop_sessions": int(rebuild.get("sessions", 0) or 0),
|
|
3338
|
+
"est_drops": events,
|
|
3339
|
+
"prefix_tokens": int(round(tokens / events)),
|
|
3340
|
+
"rebuilt_tokens": tokens,
|
|
3341
|
+
"ttl_seconds": rebuild.get("ttl_seconds"),
|
|
3342
|
+
"cost_saved_usd": round(float(rebuild.get("cost_usd", 0.0) or 0.0), 4),
|
|
3343
|
+
"by_class": by_class,
|
|
3344
|
+
"rate_basis": "observed_turns",
|
|
3345
|
+
"price_basis": "api_rates",
|
|
3346
|
+
# Models without a rate card are never priced (they add nothing).
|
|
3347
|
+
"unpriced_share": 0.0,
|
|
3641
3348
|
"evidence": "opportunity",
|
|
3642
3349
|
}
|
|
3643
3350
|
except Exception:
|
|
@@ -4489,7 +4196,7 @@ def _subagent_pool_savings(baseline_opus_share, days=None, tier=None, fresh=None
|
|
|
4489
4196
|
# data in its own home and has no such transcripts, so this pool is an
|
|
4490
4197
|
# honest zero there -- scanning ~/.claude anyway would price a
|
|
4491
4198
|
# coexisting Claude Code install's delegated spend into another
|
|
4492
|
-
# runtime's savings
|
|
4199
|
+
# runtime's savings _compat.facade()._headline.
|
|
4493
4200
|
if _measure_facade.detect_runtime() != "claude":
|
|
4494
4201
|
return zero
|
|
4495
4202
|
if tier is None:
|
|
@@ -4799,56 +4506,14 @@ def _price_parent_window(conn, where, params, tier):
|
|
|
4799
4506
|
|
|
4800
4507
|
|
|
4801
4508
|
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)}
|
|
4509
|
+
"""Sum parent rows: engine-priced and fixed-card USD, class tokens, work units."""
|
|
4510
|
+
return own_price_card.price_rows(_compat.facade(), rows, tier, api_calls_unknown)
|
|
4844
4511
|
|
|
4845
4512
|
|
|
4846
4513
|
def _pinned_workload_anchor():
|
|
4847
4514
|
"""This user's pinned pre-install workload anchor, or None until built.
|
|
4848
4515
|
|
|
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."""
|
|
4516
|
+
Built once from the user's baseline window in baseline_state.json."""
|
|
4852
4517
|
_measure_facade = _compat.facade()
|
|
4853
4518
|
try:
|
|
4854
4519
|
path = _measure_facade.SNAPSHOT_DIR / _measure_facade._PRETOOL_ANCHOR_FILE
|
|
@@ -4863,7 +4528,7 @@ def _pinned_workload_anchor():
|
|
|
4863
4528
|
for k in ("sessions", "usd", "tokens", "flat_usd", "api_calls", "messages"))
|
|
4864
4529
|
and m["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
4865
4530
|
and m["api_calls"] > 0 and m["flat_usd"] > 0):
|
|
4866
|
-
return {"metrics": m, "label": str(data.get("label") or "your pre-install baseline")}
|
|
4531
|
+
return {"metrics": m, "label": str(data.get("label") or "your earliest tracked month").replace("your pre-install baseline", "your earliest tracked month")}
|
|
4867
4532
|
except (OSError, ValueError, TypeError, AttributeError):
|
|
4868
4533
|
pass
|
|
4869
4534
|
return None
|
|
@@ -4884,64 +4549,9 @@ def _pretool_window():
|
|
|
4884
4549
|
|
|
4885
4550
|
|
|
4886
4551
|
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"
|
|
4552
|
+
"""Build the pinned pre-install anchor a few transcripts at a time
|
|
4553
|
+
(see own_price_card.anchor_step). Returns the state string. Never raises."""
|
|
4554
|
+
return own_price_card.anchor_step(_compat.facade(), budget_seconds, tier)
|
|
4945
4555
|
|
|
4946
4556
|
|
|
4947
4557
|
def _pretool_session_row(filepath, start, end, ledger):
|
|
@@ -4985,6 +4595,8 @@ def _stable_workload_anchor(before, month):
|
|
|
4985
4595
|
for k in ("sessions", "usd", "tokens", "flat_usd", "api_calls", "messages"))
|
|
4986
4596
|
and metrics["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
4987
4597
|
and metrics["api_calls"] > 0 and metrics["flat_usd"] > 0):
|
|
4598
|
+
if own_price_card.lend_classes(metrics, before if str(frozen["month"]) == month else None):
|
|
4599
|
+
_measure_facade._write_baseline_state(path, frozen)
|
|
4988
4600
|
return metrics, str(frozen["month"])
|
|
4989
4601
|
if (before and before["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
4990
4602
|
and before["api_calls"] > 0 and before["flat_usd"] > 0):
|
|
@@ -5144,6 +4756,11 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
5144
4756
|
b_n, b_usd, b_tok = before["sessions"], before["usd"], before["tokens"]
|
|
5145
4757
|
n_n, n_usd, n_tok = now["sessions"], now["usd"], now["tokens"]
|
|
5146
4758
|
b_flat, n_flat = before["flat_usd"], now["flat_usd"]
|
|
4759
|
+
# One card for both periods: the user's own current prices when both arms
|
|
4760
|
+
# carry class sums, else the fixed card (an older pinned baseline).
|
|
4761
|
+
own = own_price_card.apply(_measure_facade, before, now, days or 30)
|
|
4762
|
+
if own:
|
|
4763
|
+
b_flat, n_flat = own["before_usd"], own["now_usd"]
|
|
5147
4764
|
if (b_n < _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
5148
4765
|
or n_n < _measure_facade._AFTER_MIN_SESSIONS or b_usd <= 0 or b_flat <= 0):
|
|
5149
4766
|
return None
|
|
@@ -5223,10 +4840,8 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
5223
4840
|
"{then_n:,} in {month}, {growth:.1f}x, at about the same total spend) -- "
|
|
5224
4841
|
"that extra capacity is real, but it is capacity gained, not dollars saved, "
|
|
5225
4842
|
"so it is not in the headline. Model price/mix drift worth about "
|
|
5226
|
-
"${drift:,.0f}
|
|
4843
|
+
"${drift:,.0f} this period is also excluded: it would have happened without Token "
|
|
5227
4844
|
"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
4845
|
).format(units=n_units,
|
|
5231
4846
|
unit_label="API calls" if unit == "api_call" else "messages",
|
|
5232
4847
|
unit_singular="API call" if unit == "api_call" else "message",
|
|
@@ -5249,9 +4864,10 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
5249
4864
|
"counterfactual_usd": counterfactual,
|
|
5250
4865
|
"transformation_usd": transformation,
|
|
5251
4866
|
"crosscheck": crosscheck,
|
|
4867
|
+
"coverage": now.get("coverage"),
|
|
5252
4868
|
"engine_priced_transformation_usd": engine_transformation,
|
|
5253
4869
|
"engine_priced_actual_usd": n_usd,
|
|
5254
|
-
"price_mix_drift_usd": price_mix_drift,
|
|
4870
|
+
"price_mix_drift_usd": price_mix_drift, "price_card": own,
|
|
5255
4871
|
"capacity_assumption": capacity_note,
|
|
5256
4872
|
# Sessions in each window whose dated per-day call evidence was never
|
|
5257
4873
|
# recorded; api_calls above is a lower bound when either is nonzero.
|
|
@@ -5265,61 +4881,9 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
5265
4881
|
|
|
5266
4882
|
|
|
5267
4883
|
def _price_parent_activity_window(conn, start, end, tier):
|
|
5268
|
-
"""
|
|
5269
|
-
|
|
5270
|
-
|
|
5271
|
-
background collection catches up. Missing files produce an unavailable
|
|
5272
|
-
estimate instead of silently treating missing work as zero cost.
|
|
5273
|
-
"""
|
|
5274
|
-
_measure_facade = _compat.facade()
|
|
5275
|
-
paths = conn.execute(
|
|
5276
|
-
"SELECT jsonl_path, date FROM session_log WHERE input_tokens IS NOT NULL "
|
|
5277
|
-
"AND COALESCE(is_sidechain,0)=0").fetchall()
|
|
5278
|
-
# Include new sessions before bounded collection reaches them.
|
|
5279
|
-
known = {str(name) for name, _ in paths}
|
|
5280
|
-
for path, _mtime, _ in _measure_facade._find_all_jsonl_files(None):
|
|
5281
|
-
if str(path) not in known:
|
|
5282
|
-
paths.append((str(path), ""))
|
|
5283
|
-
known.add(str(path))
|
|
5284
|
-
rows = []
|
|
5285
|
-
request_ledger = {} # a request repeated in another transcript counts once (largest usage)
|
|
5286
|
-
for name, recorded_date in paths:
|
|
5287
|
-
path = _measure_facade.Path(name)
|
|
5288
|
-
if not path.exists():
|
|
5289
|
-
if recorded_date and str(recorded_date) < start.date().isoformat():
|
|
5290
|
-
continue
|
|
5291
|
-
return None
|
|
5292
|
-
children = _measure_facade._find_subagent_jsonl_files(path)
|
|
5293
|
-
parsed = _measure_facade._parse_session_jsonl(path, window_start=start, window_end=end)
|
|
5294
|
-
if parsed and parsed.get("is_sidechain"):
|
|
5295
|
-
continue
|
|
5296
|
-
if parsed:
|
|
5297
|
-
parsed = _measure_facade._parsed_net_of_ledger(parsed, request_ledger)
|
|
5298
|
-
if not parsed:
|
|
5299
|
-
parsed = {"total_input_tokens": 0, "total_output_tokens": 0,
|
|
5300
|
-
"total_cache_create_1h": 0, "total_cache_create_5m": 0,
|
|
5301
|
-
"cache_hit_rate": 0, "model_usage": {}, "api_calls": 0,
|
|
5302
|
-
"message_count": 0}
|
|
5303
|
-
inp, out = parsed["total_input_tokens"], parsed["total_output_tokens"]
|
|
5304
|
-
cw1, cw5 = parsed["total_cache_create_1h"], parsed["total_cache_create_5m"]
|
|
5305
|
-
child_cache_read = 0
|
|
5306
|
-
for child in children:
|
|
5307
|
-
cp = _measure_facade._parse_session_jsonl(child, window_start=start, window_end=end)
|
|
5308
|
-
if cp:
|
|
5309
|
-
cp = _measure_facade._parsed_net_of_ledger(cp, request_ledger)
|
|
5310
|
-
inp += cp["total_input_tokens"]
|
|
5311
|
-
out += cp["total_output_tokens"]
|
|
5312
|
-
cw1 += cp["total_cache_create_1h"]
|
|
5313
|
-
cw5 += cp["total_cache_create_5m"]
|
|
5314
|
-
child_cache_read += cp["total_cache_read"]
|
|
5315
|
-
if not parsed["api_calls"] and inp + out == 0:
|
|
5316
|
-
continue
|
|
5317
|
-
usage = _measure_facade.json.dumps(parsed["model_usage"])
|
|
5318
|
-
hit = (parsed["cache_hit_rate"] if parsed["api_calls"] else
|
|
5319
|
-
child_cache_read / inp if inp else 0)
|
|
5320
|
-
rows.append((inp, out, cw5, cw1, hit, usage, usage,
|
|
5321
|
-
parsed["api_calls"], parsed["message_count"]))
|
|
5322
|
-
return _measure_facade._price_parent_rows(rows, tier)
|
|
4884
|
+
"""Price in-window activity and disclose incomplete transcript coverage."""
|
|
4885
|
+
from . import weekly_activity
|
|
4886
|
+
return weekly_activity.price(_compat.facade(), conn, start, end, tier)
|
|
5323
4887
|
|
|
5324
4888
|
|
|
5325
4889
|
def _weekly_full_savings(resets_at=None, now=None):
|
|
@@ -5348,7 +4912,7 @@ def _weekly_full_savings(resets_at=None, now=None):
|
|
|
5348
4912
|
age = end.timestamp() - float(cached["computed_at"])
|
|
5349
4913
|
if (0 <= age < 60 and cached["start"] == start.isoformat()
|
|
5350
4914
|
and cached["anchor_stamp"] == anchor_stamp
|
|
5351
|
-
and cached.get("activity_basis") ==
|
|
4915
|
+
and cached.get("activity_basis") == 2
|
|
5352
4916
|
and cached["version"] == _measure_facade.TOKEN_OPTIMIZER_VERSION):
|
|
5353
4917
|
return _measure_facade._positive_full_value(cached["value"])
|
|
5354
4918
|
except (OSError, ValueError, TypeError, KeyError):
|
|
@@ -5369,13 +4933,14 @@ def _weekly_full_savings(resets_at=None, now=None):
|
|
|
5369
4933
|
"uncapped_usd": round(pool["transformation_usd"], 2),
|
|
5370
4934
|
"actual_usd": round(pool["actual_usd"], 2),
|
|
5371
4935
|
"counterfactual_usd": round(pool["counterfactual_usd"], 2),
|
|
5372
|
-
"api_calls": pool["now_units"], "anchor_month": pool["anchor_month"]
|
|
4936
|
+
"api_calls": pool["now_units"], "anchor_month": pool["anchor_month"],
|
|
4937
|
+
"coverage": pool.get("coverage")}
|
|
5373
4938
|
if now is None:
|
|
5374
4939
|
try:
|
|
5375
4940
|
_measure_facade._write_baseline_state(cache_path, {
|
|
5376
4941
|
"computed_at": end.timestamp(), "start": start.isoformat(),
|
|
5377
4942
|
"anchor_stamp": anchor_path.stat().st_mtime_ns if anchor_path.exists() else None,
|
|
5378
|
-
"activity_basis":
|
|
4943
|
+
"activity_basis": 2,
|
|
5379
4944
|
"version": _measure_facade.TOKEN_OPTIMIZER_VERSION, "value": value})
|
|
5380
4945
|
except OSError:
|
|
5381
4946
|
pass
|
|
@@ -5429,14 +4994,14 @@ def _weight_pool_payload(pool):
|
|
|
5429
4994
|
float(pool.get("engine_priced_transformation_usd", 0.0)), 2),
|
|
5430
4995
|
"engine_priced_actual_usd": round(
|
|
5431
4996
|
float(pool.get("engine_priced_actual_usd", 0.0)), 2),
|
|
5432
|
-
"price_mix_drift_usd": round(float(pool.get("price_mix_drift_usd", 0.0)), 2),
|
|
4997
|
+
"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",
|
|
5433
4998
|
"capacity_assumption": pool["capacity_assumption"],
|
|
5434
4999
|
}
|
|
5435
5000
|
|
|
5436
5001
|
|
|
5437
5002
|
def _estimate_before_after_savings(days=None, estimated_pools=None, model_routing=None, since=None):
|
|
5438
5003
|
"""THE headline saving: your FROZEN typical pre-TO session, priced at your PRE-TO
|
|
5439
|
-
efficiency (
|
|
5004
|
+
efficiency (the frozen baseline model mix + cache pattern) vs what that same session costs now.
|
|
5440
5005
|
|
|
5441
5006
|
This is a PER-SESSION COMPARISON on a FROZEN volume anchor. The "old way / session"
|
|
5442
5007
|
figure is computed entirely from frozen inputs (the captured typical_session token
|
|
@@ -5451,7 +5016,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5451
5016
|
bcr=cache_read, bcw=cache_write, bout=output. The current window over `days` is
|
|
5452
5017
|
read ONLY for the session count (recent_n) and the CURRENT cache-hit (cur_hit).
|
|
5453
5018
|
2. OLD WAY / session (counterfactual) = price(bfi, bcr, bout) + cache-write, all at
|
|
5454
|
-
the BASELINE
|
|
5019
|
+
the BASELINE mix. Depends only on frozen inputs + prices -> stable.
|
|
5455
5020
|
3. NOW / session (actual) = the SAME frozen tokens, but the fresh+cache_read pool
|
|
5456
5021
|
(t_pool = bfi + bcr) redistributed at cur_hit (cur_CR = cur_hit*t_pool; cur_F =
|
|
5457
5022
|
t_pool - cur_CR), priced at the CURRENT mix. Cache-write is held constant in
|
|
@@ -5460,9 +5025,10 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5460
5025
|
volume than the typical session held.
|
|
5461
5026
|
4. MAIN TRANSFORMATION (monthly) = (old_cps - now_cps) * recent_n, signed.
|
|
5462
5027
|
|
|
5463
|
-
Baseline model mix
|
|
5464
|
-
|
|
5465
|
-
|
|
5028
|
+
Baseline model mix: the user's stated pre-TO share when one is set, else the frozen
|
|
5029
|
+
measured share from their own install-era history; with neither (or a
|
|
5030
|
+
non-Anthropic runtime) the before arm uses the current mix, so routing is zero.
|
|
5031
|
+
No share is assumed for anyone. base_hit
|
|
5466
5032
|
comes from the frozen baseline typical session's cache pattern; if unavailable it
|
|
5467
5033
|
falls back to the current cache-hit (caching lever = 0, conservative).
|
|
5468
5034
|
|
|
@@ -5526,14 +5092,14 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5526
5092
|
# there, but (unlike Copilot's opaque credits) a list-price estimate is
|
|
5527
5093
|
# still surfaced by the collector — so the transformation renders
|
|
5528
5094
|
# nothing with an explicit "estimated_billing" reason instead of a
|
|
5529
|
-
# token-savings
|
|
5095
|
+
# token-savings _compat.facade()._headline.
|
|
5530
5096
|
if _measure_facade.detect_runtime() == "antigravity":
|
|
5531
5097
|
return {**zero, "reason": "estimated_billing"}
|
|
5532
5098
|
if not _measure_facade.TRENDS_DB.exists():
|
|
5533
5099
|
return zero
|
|
5534
5100
|
|
|
5535
5101
|
# The frozen robust baseline supplies the PRE-TO efficiency anchors: the model
|
|
5536
|
-
# mix (
|
|
5102
|
+
# mix (stated or measured share, never assumed) and the cache-hit
|
|
5537
5103
|
# pattern. It is NOT used for volume -- volume comes entirely from the current
|
|
5538
5104
|
# window, held constant across both arms.
|
|
5539
5105
|
baseline = _measure_facade._get_baseline_state()
|
|
@@ -5554,14 +5120,14 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5554
5120
|
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
|
|
5555
5121
|
# The transformation describes main work only. model_daily combines main and
|
|
5556
5122
|
# sidechain tokens, so premium delegation could otherwise make the "now" arm
|
|
5557
|
-
# costlier and lower the
|
|
5123
|
+
# costlier and lower the _compat.facade()._headline. Build the mix from non-sidechain rows.
|
|
5558
5124
|
after_shares = dict(_measure_facade._mix_from_session_rows(cutoff))
|
|
5559
5125
|
# H3: an empty after mix would silently price the ACTUAL arm at the sonnet default
|
|
5560
5126
|
# (via _cost_per_session's fallback), understating actual and INFLATING savings.
|
|
5561
5127
|
# If model_daily is empty/stale, derive the actual mix from the SAME session_log
|
|
5562
5128
|
# rows already loaded (their stored model_usage breakdown). Bail if still empty.
|
|
5563
|
-
# Baseline (pre-TO) model mix:
|
|
5564
|
-
# with
|
|
5129
|
+
# Baseline (pre-TO) model mix: the frozen share (stated or measured) for an
|
|
5130
|
+
# Anthropic runtime; with none, the current mix. A frozen share is trusted as-is;
|
|
5565
5131
|
# a non-Anthropic user is priced at their own measured mix, never fabricated Opus.
|
|
5566
5132
|
anthropic = _measure_facade.detect_runtime() not in {"codex", "hermes", "copilot", "opencode", "cursor", "antigravity", "grok"}
|
|
5567
5133
|
if anthropic and frozen_opus and frozen_opus > 0:
|
|
@@ -5581,7 +5147,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5581
5147
|
# Anthropic user with no MEASURED baseline. The pre-Token-Optimizer model
|
|
5582
5148
|
# mix is not knowable here, and a mix we cannot measure is a mix we do not
|
|
5583
5149
|
# claim: any assumed Opus share would directly scale the routing lever and
|
|
5584
|
-
# inflate the
|
|
5150
|
+
# inflate the _compat.facade()._headline. Price the before-arm at the user's real current mix
|
|
5585
5151
|
# so the routing lever is exactly zero until a baseline is measured.
|
|
5586
5152
|
baseline_opus_share = float(after_shares.get("opus", 0.0))
|
|
5587
5153
|
before_shares = dict(after_shares)
|
|
@@ -5720,7 +5286,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5720
5286
|
# SHORT-SESSION pool (below the quality gates): sub-minute / low-input
|
|
5721
5287
|
# one-shots are excluded from recent_n because the count multiplies the
|
|
5722
5288
|
# frozen typical-session anchor, but their billed tokens are real spend
|
|
5723
|
-
# whose routing delta belongs in the
|
|
5289
|
+
# whose routing delta belongs in the _compat.facade()._headline. Priced on their own real
|
|
5724
5290
|
# volume, parent-thread bundles only (no overlap with the sidechain pool).
|
|
5725
5291
|
short_pool = _measure_facade._short_session_pool_savings(
|
|
5726
5292
|
cutoff, baseline_opus_share=baseline_opus_share, tier=tier,
|
|
@@ -5841,8 +5407,8 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5841
5407
|
"hint_followed": (comp or {}).get("hint_followed_estimated") or {},
|
|
5842
5408
|
"handover_rerun": _measure_facade._estimate_handover_rerun_savings(days=days),
|
|
5843
5409
|
"retrieval_serve": _measure_facade._estimate_retrieval_serve_savings(days=days),
|
|
5844
|
-
"resume_lean": (comp or {}).get("resume_lean_estimated") or {},
|
|
5845
5410
|
"checkpoint_restore": (comp or {}).get("checkpoint_restore_estimated") or {},
|
|
5411
|
+
"codemap_lookup": (comp or {}).get("codemap_lookup_estimated") or {},
|
|
5846
5412
|
}
|
|
5847
5413
|
pool_labels = {
|
|
5848
5414
|
"uncaptured_runtime": "Compressed subagent context (estimated)",
|
|
@@ -5850,8 +5416,8 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5850
5416
|
"hint_followed": "Followed context hints (estimated)",
|
|
5851
5417
|
"handover_rerun": "Continuity handovers (estimated)",
|
|
5852
5418
|
"retrieval_serve": "Direct context retrieval (estimated)",
|
|
5853
|
-
"resume_lean": "Lean session resumes (estimated)",
|
|
5854
5419
|
"checkpoint_restore": "Checkpoint restores (estimated)",
|
|
5420
|
+
"codemap_lookup": "Code map lookups (estimated)",
|
|
5855
5421
|
}
|
|
5856
5422
|
estimated_volume_pools = {}
|
|
5857
5423
|
for key, label in pool_labels.items():
|
|
@@ -5876,7 +5442,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5876
5442
|
# rate: the old way would have produced the same verbose output at the
|
|
5877
5443
|
# baseline model mix's output rate, so the avoided cost is higher.
|
|
5878
5444
|
vs_est = (comp or {}).get("verbosity_steer_estimated") or {}
|
|
5879
|
-
vs_measured =
|
|
5445
|
+
vs_measured = 0.0 # diagnostic only; no verbosity credit
|
|
5880
5446
|
out_after = price(0.0, 0.0, 1_000_000.0, after_shares)
|
|
5881
5447
|
out_before = price(0.0, 0.0, 1_000_000.0, before_shares)
|
|
5882
5448
|
vs_reprice = (out_before / out_after) if out_after > 0 else 1.0
|
|
@@ -5957,6 +5523,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5957
5523
|
# eliminate ("no savings" must stay distinguishable from "the math broke").
|
|
5958
5524
|
# Both non-headlined states report the SAME real arms and real (signed) delta so the
|
|
5959
5525
|
# renderer can explain itself; `reason` / `transformation_state` carry which one.
|
|
5526
|
+
provenance = baseline_provenance.transformation(_measure_facade, baseline, weight_pool)
|
|
5960
5527
|
not_headlined = {**zero, "before_sessions": bn, "after_sessions": recent_n,
|
|
5961
5528
|
"actual_monthly_usd": round(combined_actual, 2),
|
|
5962
5529
|
"counterfactual_monthly_usd": round(combined_cf, 2),
|
|
@@ -5996,7 +5563,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5996
5563
|
if weight_pool else int(t_pool + bcw + bout)),
|
|
5997
5564
|
"after_tokens": (int(weight_pool["after_tokens_per_session"])
|
|
5998
5565
|
if weight_pool else int(t_pool + bcw + bout)),
|
|
5999
|
-
"baseline_source": baseline_source,
|
|
5566
|
+
"baseline_source": baseline_source, "baseline_provenance": provenance,
|
|
6000
5567
|
# A net-negative card used to return the `zero` per-session fields, so
|
|
6001
5568
|
# the dashboard rendered NOTHING and the user could not tell "no savings
|
|
6002
5569
|
# this period" from "the computation broke". Report the real arms and the
|
|
@@ -6060,7 +5627,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6060
5627
|
# redistribution). Decompose by morphing the counterfactual into the actual one
|
|
6061
5628
|
# lever at a time. Routing is credited first (the baseline footprint, INCLUDING CW,
|
|
6062
5629
|
# repriced from the baseline mix to today's mix), then caching at today's mix; the
|
|
6063
|
-
# two UNROUNDED steps telescope to the
|
|
5630
|
+
# two UNROUNDED steps telescope to the _compat.facade()._headline. Sequential attribution is
|
|
6064
5631
|
# order-dependent (fixed + disclosed via `waterfall_index`).
|
|
6065
5632
|
# v_route_s = the typical session's baseline cache split (bfi/bcr) + CW + output
|
|
6066
5633
|
# repriced at today's mix. CW carries the routing reprice, so the routing lever
|
|
@@ -6074,7 +5641,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6074
5641
|
s_cache = (v_route_s - now_cps) * recent_n # remaining gap = caching
|
|
6075
5642
|
# s_route + s_cache telescopes to the MAIN transformation; the subagent pool is a
|
|
6076
5643
|
# third lever whose own (cf - actual) is added so the breakdown sums to the COMBINED
|
|
6077
|
-
#
|
|
5644
|
+
# _compat.facade()._headline.
|
|
6078
5645
|
if weight_pool:
|
|
6079
5646
|
# The session-weight pool replaced the frozen-anchor arms, so the
|
|
6080
5647
|
# routing/caching decomposition of those arms no longer describes the
|
|
@@ -6133,31 +5700,12 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6133
5700
|
key=lambda x: ((_measure_facade := _compat.facade()), abs(x["monthly_usd"]))[1], reverse=True,
|
|
6134
5701
|
)
|
|
6135
5702
|
if weight_pool:
|
|
6136
|
-
breakdown_caveat = (
|
|
6137
|
-
"Work-normalized counterfactual: every API call you dispatched this "
|
|
6138
|
-
"period, priced at the anchor month's cost per call ("
|
|
6139
|
-
+ str(weight_pool["anchor_month"]) + ", your earliest complete month "
|
|
6140
|
-
"on record), at ONE constant rate card both eras -- so only how much "
|
|
6141
|
-
"context each call carries (and how often the cache serves it) moves "
|
|
6142
|
-
"the number; model-price and mix changes between eras are excluded and "
|
|
6143
|
-
"disclosed separately, not claimed. Sessions are not used as the unit "
|
|
6144
|
-
"because the lighter workflow itself splits the same work into more, "
|
|
6145
|
-
"smaller sessions, which would count capacity gained as money saved. "
|
|
6146
|
-
"The delta includes every volume mechanism at once (context "
|
|
6147
|
-
"compression, lean output, loop prevention, continuity handovers), so "
|
|
6148
|
-
"the metered and estimated pools are not added on top -- they would "
|
|
6149
|
-
"double-count; the directly-metered floor still shows in its own card. "
|
|
6150
|
-
"Delegated (subagent) work is excluded from this figure. Two caveats "
|
|
6151
|
-
"ride with it: the anchor month already had partial Token Optimizer "
|
|
6152
|
-
"coverage (the true pre-tool gap is larger), and the per-call delta "
|
|
6153
|
-
"cannot separate Token Optimizer's effect from your own behaviour "
|
|
6154
|
-
"drift -- the metered floor is the part we can prove action by action."
|
|
6155
|
-
)
|
|
5703
|
+
breakdown_caveat = baseline_provenance.weight_pool_caveat(weight_pool["anchor_month"], provenance)
|
|
6156
5704
|
else:
|
|
6157
5705
|
breakdown_caveat = (
|
|
6158
5706
|
"Counterfactual attribution: your FROZEN typical pre-TO session is priced two "
|
|
6159
5707
|
"ways -- the way you work now, and the way you worked before Token Optimizer "
|
|
6160
|
-
"(
|
|
5708
|
+
"(" + ("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 "
|
|
6161
5709
|
"period. The per-session difference is split between model routing (including "
|
|
6162
5710
|
"cache-write, which is billed at the writing model's rate) and caching. Subagent "
|
|
6163
5711
|
"(sidechain) work is a second pool: the window's real delegated tokens priced at "
|
|
@@ -6228,7 +5776,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6228
5776
|
f"${uncapped_transformation:,.2f}."
|
|
6229
5777
|
)
|
|
6230
5778
|
# Re-derive pct from the capped transformation so the percentage
|
|
6231
|
-
# stays consistent with the capped
|
|
5779
|
+
# stays consistent with the capped _compat.facade()._headline.
|
|
6232
5780
|
transformation_pct = (
|
|
6233
5781
|
transformation / combined_cf if combined_cf > 0 else 0.0
|
|
6234
5782
|
)
|
|
@@ -6303,7 +5851,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
6303
5851
|
if weight_pool else bn),
|
|
6304
5852
|
"after_sessions": (int(weight_pool["sessions"])
|
|
6305
5853
|
if weight_pool else recent_n),
|
|
6306
|
-
"baseline_source": baseline_source,
|
|
5854
|
+
"baseline_source": baseline_source, "baseline_provenance": provenance,
|
|
6307
5855
|
"breakdown": breakdown,
|
|
6308
5856
|
"breakdown_caveat": breakdown_caveat,
|
|
6309
5857
|
"evidence": "estimated",
|
|
@@ -6358,15 +5906,9 @@ def _estimate_stale_reads_reclaimable(days=None):
|
|
|
6358
5906
|
|
|
6359
5907
|
|
|
6360
5908
|
def _progressive_disclosure_summary(days=None):
|
|
6361
|
-
"""
|
|
6362
|
-
|
|
6363
|
-
How many tool results were archived vs later re-expanded, and the net tokens
|
|
6364
|
-
that stayed collapsed. The $ value of the net is ALREADY in the realized
|
|
6365
|
-
tool_archive figure (re-pops are netted out in _get_savings_summary); this is
|
|
6366
|
-
a transparency count, NOT an additional saving to sum. Never raises.
|
|
6367
|
-
"""
|
|
5909
|
+
"""Summarize archive disclosures without assigning a counterfactual value."""
|
|
6368
5910
|
_measure_facade = _compat.facade()
|
|
6369
|
-
out = {"archived": 0, "reexpanded": 0, "net_collapsed_tokens": 0}
|
|
5911
|
+
out = {"archived": 0, "reexpanded": 0, "net_collapsed_tokens": 0, "full_bash_fetches": 0, "full_bash_tokens": 0}
|
|
6370
5912
|
try:
|
|
6371
5913
|
if not _measure_facade.TRENDS_DB.exists():
|
|
6372
5914
|
return out
|
|
@@ -6381,23 +5923,25 @@ def _progressive_disclosure_summary(days=None):
|
|
|
6381
5923
|
(cutoff,),
|
|
6382
5924
|
).fetchall()
|
|
6383
5925
|
re_rows = conn.execute(
|
|
6384
|
-
"SELECT detail FROM " + counted + " WHERE timestamp >= ? "
|
|
5926
|
+
"SELECT detail, tokens_saved, session_id, timestamp FROM " + counted + " WHERE timestamp >= ? "
|
|
6385
5927
|
"AND event_type = 'tool_archive_reexpand'",
|
|
6386
5928
|
(cutoff,),
|
|
6387
5929
|
).fetchall()
|
|
5930
|
+
from . import savings_story
|
|
5931
|
+
full_count, full_tokens = savings_story.full_bash_fetch_totals(conn, cutoff, re_rows, _measure_facade._is_fixture_session_id, _measure_facade.SNAPSHOT_DIR)
|
|
6388
5932
|
finally:
|
|
6389
5933
|
conn.close()
|
|
6390
5934
|
agg = {r[0]: (int(r[1]), int(r[2] or 0)) for r in rows}
|
|
6391
5935
|
arch_n, arch_tok = agg.get("tool_archive", (0, 0))
|
|
6392
5936
|
re_tok = agg.get("tool_archive_reexpand", (0, 0))[1]
|
|
6393
5937
|
out["archived"] = arch_n
|
|
6394
|
-
# Multiple bounded debits can hit one archived item; "re-expanded" is a
|
|
6395
|
-
# count of distinct tool_use_ids, not debit events.
|
|
6396
5938
|
out["reexpanded"] = len({
|
|
6397
5939
|
detail.split(" ", 1)[0]
|
|
6398
|
-
for (detail,) in re_rows
|
|
5940
|
+
for (detail, _, _, _) in re_rows
|
|
6399
5941
|
if detail and detail.strip()
|
|
6400
5942
|
})
|
|
5943
|
+
out["full_bash_fetches"] = full_count
|
|
5944
|
+
out["full_bash_tokens"] = full_tokens
|
|
6401
5945
|
out["net_collapsed_tokens"] = max(0, arch_tok - re_tok)
|
|
6402
5946
|
except (_measure_facade.sqlite3.Error, OSError):
|
|
6403
5947
|
pass
|
|
@@ -6518,15 +6062,15 @@ def _format_cents(cents):
|
|
|
6518
6062
|
|
|
6519
6063
|
|
|
6520
6064
|
def _action_savings_display(logged, routing_measured, routing_estimated, repeat_reads,
|
|
6521
|
-
estimates, total_clamped=None):
|
|
6065
|
+
estimates, total_clamped=None, class_premium=None):
|
|
6522
6066
|
"""Whole-cent display values for the action-savings components.
|
|
6523
6067
|
|
|
6524
6068
|
Raw component values stay exact elsewhere in the payload. Every displayed
|
|
6525
6069
|
part below adds up to `total_usd`, which is the cents of the exact total."""
|
|
6526
6070
|
_measure_facade = _compat.facade()
|
|
6527
|
-
names = ["logged", "routing_measured", "routing_estimated", "reread"] + [
|
|
6071
|
+
names = ["logged", "class_premium", "routing_measured", "routing_estimated", "reread"] + [
|
|
6528
6072
|
"estimate:" + key for key in estimates]
|
|
6529
|
-
values = [logged, routing_measured, routing_estimated, repeat_reads, *estimates.values()]
|
|
6073
|
+
values = [logged, class_premium or 0.0, routing_measured, routing_estimated, repeat_reads, *estimates.values()]
|
|
6530
6074
|
parts, total_cents = _measure_facade._allocate_cents(values)
|
|
6531
6075
|
if total_clamped:
|
|
6532
6076
|
total_cents = 0
|
|
@@ -6548,29 +6092,35 @@ def _action_savings_components(summary, reread=None):
|
|
|
6548
6092
|
Observed hints replace the retrieval estimate as soon as a hint fires.
|
|
6549
6093
|
Opportunity and the separate whole-workload comparison are not additive.
|
|
6550
6094
|
"""
|
|
6551
|
-
_measure_facade = _compat.facade()
|
|
6095
|
+
_measure_facade = _compat.facade(); from . import mod_fresh_booking
|
|
6552
6096
|
estimates = {
|
|
6553
|
-
key: float((summary.get(key) or {}).get("cost_saved_usd", 0) or 0)
|
|
6097
|
+
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))
|
|
6554
6098
|
for key in (
|
|
6555
|
-
"behavioral_estimate", "uncaptured_runtime",
|
|
6556
|
-
"contamination_exit", "handover_rerun", "resume_lean_estimated",
|
|
6557
|
-
"checkpoint_restore_estimated", "verbosity_steer",
|
|
6099
|
+
"behavioral_estimate", "uncaptured_runtime",
|
|
6100
|
+
"contamination_exit", "handover_rerun", "resume_lean_estimated", "resume_lean_verified",
|
|
6101
|
+
"checkpoint_restore_estimated", "verbosity_steer", "verbosity_output_estimated", "structural_estimated", "keepwarm_estimated",
|
|
6558
6102
|
)
|
|
6559
6103
|
}
|
|
6104
|
+
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"))
|
|
6105
|
+
estimates["expand_overhead"] = -max(0.0, float(overhead.get("expand_usd") or 0))
|
|
6560
6106
|
hints = summary.get("hint_followed") or {}
|
|
6561
6107
|
avoided_source = "hint_followed" if int(hints.get("events") or 0) > 0 else "retrieval_serve"
|
|
6562
6108
|
estimates[avoided_source] = float(
|
|
6563
6109
|
(summary.get(avoided_source) or {}).get("cost_saved_usd", 0) or 0)
|
|
6564
|
-
|
|
6110
|
+
from . import savings_story
|
|
6111
|
+
logged = float(summary.get("total_cost_usd", 0) or 0) - savings_story.verbosity_logged(summary)
|
|
6565
6112
|
routing_data = summary.get("model_routing") or {}
|
|
6566
6113
|
routing = float(routing_data.get("realized_cost_usd", 0) or 0)
|
|
6567
6114
|
routing_measured = routing if routing_data.get("evidence", "measured") == "measured" else 0.0
|
|
6568
6115
|
reread_available = bool((reread or {}).get("available"))
|
|
6569
6116
|
repeat_reads = float(reread.get("reread_usd", 0) or 0) if reread_available else 0.0
|
|
6117
|
+
premium = _measure_facade._counted_pricing_v5.class_premium_usd(reread) # measured: the next call billed a cache write
|
|
6570
6118
|
estimated = sum(estimates.values())
|
|
6571
|
-
net_total = logged +
|
|
6119
|
+
net_total = logged + premium + repeat_reads + estimated
|
|
6572
6120
|
return {
|
|
6573
6121
|
"logged_usd": logged,
|
|
6122
|
+
"class_premium_usd": premium,
|
|
6123
|
+
"class_premium_events": int((reread or {}).get("oneshot_class_events", 0) or 0) if premium else 0,
|
|
6574
6124
|
"routing_usd": routing,
|
|
6575
6125
|
"routing_measured_usd": routing_measured,
|
|
6576
6126
|
"routing_estimated_usd": routing - routing_measured,
|
|
@@ -6587,8 +6137,8 @@ def _action_savings_components(summary, reread=None):
|
|
|
6587
6137
|
"total_usd": max(0.0, net_total),
|
|
6588
6138
|
"total_clamped": net_total < 0,
|
|
6589
6139
|
"display": _measure_facade._action_savings_display(
|
|
6590
|
-
logged,
|
|
6591
|
-
|
|
6140
|
+
logged, 0.0, 0.0, repeat_reads, estimates,
|
|
6141
|
+
total_clamped=net_total < 0, class_premium=premium),
|
|
6592
6142
|
}
|
|
6593
6143
|
|
|
6594
6144
|
|
|
@@ -6659,8 +6209,9 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6659
6209
|
handover_rerun = _measure_facade._estimate_handover_rerun_savings(days=days)
|
|
6660
6210
|
retrieval_serve = _measure_facade._estimate_retrieval_serve_savings(days=days)
|
|
6661
6211
|
model_routing = _measure_facade._compute_model_routing_savings(days=days, since=since)
|
|
6212
|
+
model_routing["baseline_provenance"] = baseline_provenance.routing(_measure_facade, model_routing)
|
|
6662
6213
|
output_waste = _measure_facade._estimate_output_waste(days=days)
|
|
6663
|
-
cache_drop = _measure_facade._estimate_cache_drop_savings(days=days)
|
|
6214
|
+
cache_drop = {**_measure_facade._estimate_cache_drop_savings(days=days), **__import__("large_transcripts").count(_measure_facade.CLAUDE_DIR, days)}
|
|
6664
6215
|
before_after = _measure_facade._estimate_before_after_savings(days=days, since=since, estimated_pools={
|
|
6665
6216
|
"uncaptured_runtime": uncaptured,
|
|
6666
6217
|
"behavioral_loops": behavioral,
|
|
@@ -6669,10 +6220,16 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6669
6220
|
"retrieval_serve": retrieval_serve,
|
|
6670
6221
|
"resume_lean": savings.get("resume_lean_estimated") or {},
|
|
6671
6222
|
"checkpoint_restore": savings.get("checkpoint_restore_estimated") or {},
|
|
6672
|
-
}, model_routing=model_routing)
|
|
6223
|
+
}, model_routing=model_routing) if not savings_story.skip_comparison() else None
|
|
6673
6224
|
stale_reads_reclaimable = _measure_facade._estimate_stale_reads_reclaimable(days=days)
|
|
6225
|
+
try:
|
|
6226
|
+
import lean_resume_carry
|
|
6227
|
+
verified_lean = lean_resume_carry.verified_summary(days=days, since=since)
|
|
6228
|
+
except Exception:
|
|
6229
|
+
verified_lean = None
|
|
6674
6230
|
|
|
6675
6231
|
return {
|
|
6232
|
+
"resume_lean_verified": verified_lean,
|
|
6676
6233
|
"total_tokens": total_tokens,
|
|
6677
6234
|
"total_cost_usd": round(total_cost, 4),
|
|
6678
6235
|
"total_events": total_events,
|
|
@@ -6730,9 +6287,7 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6730
6287
|
# $ is already inside realized tool_archive (re-pops netted); not summed.
|
|
6731
6288
|
"progressive_disclosure": _measure_facade._progressive_disclosure_summary(days=days),
|
|
6732
6289
|
# A1: one-time first-trim, surfaced separately, never in the realized total.
|
|
6733
|
-
"one_time_setup": savings.get("one_time_setup"),
|
|
6734
|
-
# A3: MCP-cap estimate lives in the estimated tier, never realized.
|
|
6735
|
-
"mcp_cap_estimated": savings.get("mcp_cap_estimated"),
|
|
6290
|
+
"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"),
|
|
6736
6291
|
# U-G: deterministically-triggered avoided-search from proactive hints
|
|
6737
6292
|
# (observed hint->read), estimated magnitude. Estimated tier, never realized.
|
|
6738
6293
|
"hint_followed": savings.get("hint_followed_estimated"),
|
|
@@ -6748,37 +6303,16 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6748
6303
|
# credited working set is inferred -- counterfactual, estimated tier,
|
|
6749
6304
|
# never in the realized total.
|
|
6750
6305
|
"checkpoint_restore_estimated": savings.get("checkpoint_restore_estimated"),
|
|
6306
|
+
"verbosity_output_estimated": savings.get("verbosity_output_estimated"),
|
|
6751
6307
|
}
|
|
6752
6308
|
|
|
6753
6309
|
|
|
6754
6310
|
def _install_date():
|
|
6755
|
-
"""Best-known install
|
|
6756
|
-
|
|
6757
|
-
|
|
6758
|
-
falls back to the earliest session_log date. Never raises.
|
|
6311
|
+
"""Best-known install date (ISO YYYY-MM-DD), or None: the first-run baseline
|
|
6312
|
+
snapshot or the earliest logged event, whichever is earlier; with neither,
|
|
6313
|
+
the earliest session on record. Never raises.
|
|
6759
6314
|
"""
|
|
6760
|
-
|
|
6761
|
-
try:
|
|
6762
|
-
snap = _measure_facade.SNAPSHOT_DIR / "snapshot_before.json"
|
|
6763
|
-
if snap.exists():
|
|
6764
|
-
ts = _measure_facade.json.loads(snap.read_text(encoding="utf-8")).get("timestamp")
|
|
6765
|
-
if ts:
|
|
6766
|
-
return ts[:10]
|
|
6767
|
-
except (_measure_facade.json.JSONDecodeError, OSError, ValueError):
|
|
6768
|
-
pass
|
|
6769
|
-
try:
|
|
6770
|
-
if _measure_facade.TRENDS_DB.exists():
|
|
6771
|
-
conn = _measure_facade._init_trends_db()
|
|
6772
|
-
_measure_facade.ensure_activity_view(conn)
|
|
6773
|
-
try:
|
|
6774
|
-
row = conn.execute("SELECT MIN(date) FROM session_activity").fetchone()
|
|
6775
|
-
finally:
|
|
6776
|
-
conn.close()
|
|
6777
|
-
if row and row[0]:
|
|
6778
|
-
return str(row[0])[:10]
|
|
6779
|
-
except (_measure_facade.sqlite3.Error, OSError):
|
|
6780
|
-
pass
|
|
6781
|
-
return None
|
|
6315
|
+
return baseline_provenance.install_evidence(_compat.facade()).get("date")
|
|
6782
6316
|
|
|
6783
6317
|
|
|
6784
6318
|
def _savings_since_install():
|
|
@@ -6797,31 +6331,34 @@ def _savings_since_install():
|
|
|
6797
6331
|
return None
|
|
6798
6332
|
days = (_measure_facade.datetime.now() - _measure_facade.datetime.fromisoformat(d)).days + 1
|
|
6799
6333
|
days = max(1, min(days, 3650))
|
|
6800
|
-
full = _measure_facade._get_merged_savings
|
|
6801
|
-
|
|
6802
|
-
|
|
6803
|
-
|
|
6804
|
-
|
|
6334
|
+
full = savings_story.since_install_summary(_measure_facade._get_merged_savings, days)
|
|
6335
|
+
try:
|
|
6336
|
+
from . import session_effect
|
|
6337
|
+
full["session_effect"] = session_effect.summary(days)
|
|
6338
|
+
except Exception:
|
|
6339
|
+
full["session_effect"] = {}
|
|
6340
|
+
# Measured = logged runtime + realized structural. Model routing is an
|
|
6341
|
+
# assumption and stays out of every savings total.
|
|
6342
|
+
measured = float(full.get("total_cost_usd", 0) or 0) - savings_story.verbosity_logged(full)
|
|
6805
6343
|
full_routing = full.get("model_routing") or {}
|
|
6806
|
-
|
|
6807
|
-
|
|
6808
|
-
|
|
6809
|
-
|
|
6344
|
+
# Since-install routing for every user: a stated pre-TO share
|
|
6345
|
+
# (pretool_baseline.json / TOKEN_OPTIMIZER_BASELINE_OPUS_SHARE) wins,
|
|
6346
|
+
# else the model mix measured at install (snapshot or earliest
|
|
6347
|
+
# history). Same pricing either way; no baseline, a non-Anthropic
|
|
6348
|
+
# runtime, or no Opus in the baseline means $0, never invented Opus.
|
|
6349
|
+
routing_source = savings_story.routing_baseline_kind(full_routing, _measure_facade.detect_runtime())
|
|
6350
|
+
stated = routing_source is not None
|
|
6351
|
+
stated_routing = max(0.0, float(full_routing.get("realized_cost_usd") or 0)) if stated else 0.0
|
|
6810
6352
|
# Estimated = genuine TO-realized counterfactuals only — the same
|
|
6811
6353
|
# categories the dashboard's estimated tier (estItems) sums, so the two
|
|
6812
6354
|
# cards agree about what "estimated" contains. cache_drop and
|
|
6813
6355
|
# output_waste are OPPORTUNITY (avoidable waste TO does not yet prevent),
|
|
6814
|
-
# so they are excluded here
|
|
6815
|
-
# was actually spent. mcp_cap_estimated does NOT double-count with
|
|
6816
|
-
# uncaptured_runtime: _get_savings_summary pops mcp_cap out of the
|
|
6817
|
-
# measured totals before _estimate_uncaptured_runtime derives its
|
|
6818
|
-
# per-session proxy from them, so the two pools are disjoint.
|
|
6356
|
+
# so they are excluded here, along with the unsupported MCP-cap estimate.
|
|
6819
6357
|
estimated = sum(
|
|
6820
6358
|
float((full.get(k) or {}).get("cost_saved_usd", 0) or 0)
|
|
6821
6359
|
for k in (
|
|
6822
|
-
"behavioral_estimate", "uncaptured_runtime",
|
|
6823
|
-
"contamination_exit", "handover_rerun", "
|
|
6824
|
-
"checkpoint_restore_estimated", "verbosity_steer",
|
|
6360
|
+
"behavioral_estimate", "uncaptured_runtime",
|
|
6361
|
+
"contamination_exit", "handover_rerun", "resume_lean_verified",
|
|
6825
6362
|
)
|
|
6826
6363
|
)
|
|
6827
6364
|
# Avoided-search: prefer the hint->read estimate (hint_followed; the
|
|
@@ -6832,21 +6369,33 @@ def _savings_since_install():
|
|
|
6832
6369
|
hf = full.get("hint_followed") or {}
|
|
6833
6370
|
rs = full.get("retrieval_serve") or {}
|
|
6834
6371
|
avoided = hf if int(hf.get("events") or 0) > 0 else rs
|
|
6835
|
-
estimated += float(avoided.get("cost_saved_usd", 0) or 0)
|
|
6836
|
-
if routing_is_estimate:
|
|
6837
|
-
estimated += full_routing_usd
|
|
6372
|
+
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))
|
|
6838
6373
|
# The all-in since install uses the monthly headline's own recipe
|
|
6839
|
-
# (logged +
|
|
6840
|
-
# so the two figures always mean the same thing.
|
|
6374
|
+
# (logged + repeat reads + estimates); routing stays out of both.
|
|
6841
6375
|
all_in = None
|
|
6842
6376
|
try:
|
|
6843
6377
|
counted = _measure_facade._counted_cumulative_summary(days=days)
|
|
6844
6378
|
_measure_facade._apply_counted_oneshot_pricing(full, counted)
|
|
6845
6379
|
components = _measure_facade._action_savings_components(full, counted)
|
|
6380
|
+
display_parts = dict(components["display"]["components_usd"], routing_estimated=round(stated_routing, 2))
|
|
6381
|
+
majority_period = None
|
|
6382
|
+
if stated_routing > 0:
|
|
6383
|
+
try:
|
|
6384
|
+
from . import routing_period
|
|
6385
|
+
rconn = _measure_facade._open_trends_db_readonly(timeout=1.0)
|
|
6386
|
+
share = float(full_routing.get("baseline_opus_share") or 0)
|
|
6387
|
+
try: majority_period = routing_period.strongest(rconn, _measure_facade, stated_routing, d, shares={"opus": share, "sonnet": round(1.0 - share, 4)})
|
|
6388
|
+
finally: rconn.close()
|
|
6389
|
+
except Exception:
|
|
6390
|
+
pass
|
|
6846
6391
|
all_in = {
|
|
6847
|
-
"total_usd": components["display"]["total_usd"],
|
|
6848
|
-
"components_usd":
|
|
6392
|
+
"total_usd": round(components["display"]["total_usd"] + stated_routing, 2),
|
|
6393
|
+
"components_usd": display_parts, "routing_majority_period": majority_period,
|
|
6849
6394
|
"estimated_usd": round(sum(components["display"]["estimates_usd"].values()), 2),
|
|
6395
|
+
"routing_usd": round(float(components.get("routing_usd", 0) or 0), 2),
|
|
6396
|
+
"routing_baseline_opus_share": full_routing.get("baseline_opus_share"), "routing_baseline_source": routing_source,
|
|
6397
|
+
"routing_baseline_basis": full_routing.get("baseline_source"), "routing_baseline_provenance": full_routing.get("baseline_provenance"),
|
|
6398
|
+
"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"),
|
|
6850
6399
|
"routing_pending": full_routing.get("evidence") == "pending",
|
|
6851
6400
|
"routing_pending_sessions": int(full_routing.get("pending_sessions") or 0),
|
|
6852
6401
|
"routing_unsplit_tokens": int(full_routing.get("unsplit_tokens") or 0),
|
|
@@ -6858,6 +6407,7 @@ def _savings_since_install():
|
|
|
6858
6407
|
return {
|
|
6859
6408
|
"install_date": d,
|
|
6860
6409
|
"days": days,
|
|
6410
|
+
"excluded_usd": dict(savings_story.excluded_since_install(full), routing=None) if stated else savings_story.excluded_since_install(full),
|
|
6861
6411
|
"measured_usd": round(measured, 2),
|
|
6862
6412
|
"estimated_usd": round(estimated, 2),
|
|
6863
6413
|
"total_usd": round(measured + estimated, 2),
|
|
@@ -6980,14 +6530,7 @@ def _reread_savings_for_window(days):
|
|
|
6980
6530
|
|
|
6981
6531
|
|
|
6982
6532
|
def savings_report(days=None, as_json=None):
|
|
6983
|
-
"""Display
|
|
6984
|
-
|
|
6985
|
-
Merges the legacy savings_events table (setup optimization, tool digests,
|
|
6986
|
-
checkpoint restores, etc.) with v5 Active Compression entries written to
|
|
6987
|
-
compression_events (delta reads, quality nudges, loop prevention, bash
|
|
6988
|
-
output compression). Dedup rule: legacy categories authoritative in
|
|
6989
|
-
savings_events; v5 categories authoritative in compression_events.
|
|
6990
|
-
"""
|
|
6533
|
+
"""Display savings from logged actions and the counted repeat-read cohort."""
|
|
6991
6534
|
_measure_facade = _compat.facade()
|
|
6992
6535
|
summary = _measure_facade._get_merged_savings(days=days)
|
|
6993
6536
|
# Use the same stored removal cohort as the dashboard. Its counted benefit
|
|
@@ -6997,6 +6540,7 @@ def savings_report(days=None, as_json=None):
|
|
|
6997
6540
|
except Exception:
|
|
6998
6541
|
summary["counted_period"] = {"available": False}
|
|
6999
6542
|
summary["reread_avoided"] = summary["counted_period"]
|
|
6543
|
+
_compat.facade()._headline.attach(summary, days)
|
|
7000
6544
|
_measure_facade._apply_counted_oneshot_pricing(summary, summary["counted_period"])
|
|
7001
6545
|
summary["action_savings"] = _measure_facade._action_savings_components(
|
|
7002
6546
|
summary, summary["reread_avoided"])
|
|
@@ -7032,10 +6576,9 @@ def savings_report(days=None, as_json=None):
|
|
|
7032
6576
|
# printed parts add up to the printed ALL IN.
|
|
7033
6577
|
_act = summary["action_savings"]
|
|
7034
6578
|
_shown = _measure_facade._action_savings_display(
|
|
7035
|
-
_mo(_act["logged_usd"]), _mo(_act["
|
|
7036
|
-
_mo(_act["routing_estimated_usd"]), _mo(_act["reread_usd"]),
|
|
6579
|
+
_mo(_act["logged_usd"]), 0.0, 0.0, _mo(_act["reread_usd"]),
|
|
7037
6580
|
{k: _mo(v) for k, v in _act["estimates_usd"].items()},
|
|
7038
|
-
total_clamped=_act["total_clamped"])
|
|
6581
|
+
total_clamped=_act["total_clamped"], class_premium=_mo(_act.get("class_premium_usd", 0.0)))
|
|
7039
6582
|
_cents = _shown["components_cents"]
|
|
7040
6583
|
_est_cents = _shown["estimates_cents"]
|
|
7041
6584
|
_money = _measure_facade._format_cents
|
|
@@ -7043,6 +6586,7 @@ def savings_report(days=None, as_json=None):
|
|
|
7043
6586
|
print("\n Token Optimizer Savings Report")
|
|
7044
6587
|
print(f" {'=' * 58}")
|
|
7045
6588
|
print(f" Period: Last {days} days ({start} to {end})")
|
|
6589
|
+
print(_compat.facade()._headline.cli_headline(summary["token_headline"], days, summary.get("session_effect")))
|
|
7046
6590
|
|
|
7047
6591
|
# Headline transformation. With the session-weight pool live it is the
|
|
7048
6592
|
# work-normalized (per-API-call, constant-price) figure; otherwise the legacy
|
|
@@ -7051,7 +6595,7 @@ def savings_report(days=None, as_json=None):
|
|
|
7051
6595
|
if float(ba.get("monthly_savings_usd", 0.0) or 0.0) > 0:
|
|
7052
6596
|
wp = ba.get("session_weight_pool") or None
|
|
7053
6597
|
print()
|
|
7054
|
-
print(f" YOUR TRANSFORMATION: ~${ba['monthly_savings_usd']:,.0f}
|
|
6598
|
+
print(f" YOUR TRANSFORMATION: ~${ba['monthly_savings_usd']:,.0f} over {days} days")
|
|
7055
6599
|
# Spend cap disclosure: when the counterfactual exceeds actual spend,
|
|
7056
6600
|
# the headline is capped and the user must see why, not wonder why the
|
|
7057
6601
|
# number stopped moving.
|
|
@@ -7072,15 +6616,17 @@ def savings_report(days=None, as_json=None):
|
|
|
7072
6616
|
if wp:
|
|
7073
6617
|
unit_lbl = "API call" if wp.get("work_unit") == "api_call" else "message"
|
|
7074
6618
|
print(f" Each {unit_lbl} now carries less billed context than in "
|
|
7075
|
-
f"{wp.get('anchor_month')}
|
|
6619
|
+
f"{wp.get('anchor_month')}: "
|
|
7076
6620
|
f"${wp.get('after_cost_per_unit', 0):.4f} vs ${wp.get('before_cost_per_unit', 0):.4f} "
|
|
7077
6621
|
f"at constant token prices, x {int(wp.get('now_units', 0)):,} {unit_lbl}s "
|
|
7078
6622
|
f"this period "
|
|
7079
6623
|
f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs ${ba.get('counterfactual_monthly_usd', 0):,.0f} "
|
|
7080
6624
|
f"the old way) [estimated]")
|
|
6625
|
+
for line in _measure_facade.textwrap.wrap((ba.get("baseline_provenance") or {}).get("note") or "", width=72):
|
|
6626
|
+
print(f" {line}")
|
|
7081
6627
|
drift = float(wp.get("price_mix_drift_usd", 0.0) or 0.0)
|
|
7082
6628
|
if abs(drift) >= 1.0:
|
|
7083
|
-
print(f" Not claimed: ~${abs(drift):,.0f}
|
|
6629
|
+
print(f" Not claimed: ~${abs(drift):,.0f} this period of model price/mix drift "
|
|
7084
6630
|
f"({'cheaper' if drift >= 0 else 'costlier'} models would have moved "
|
|
7085
6631
|
f"your bill without Token Optimizer).")
|
|
7086
6632
|
cross = wp.get("crosscheck") or {}
|
|
@@ -7092,11 +6638,11 @@ def savings_report(days=None, as_json=None):
|
|
|
7092
6638
|
if isinstance(gap, (int, float)) else "")
|
|
7093
6639
|
if _measure_facade._crosscheck_verdict(wp):
|
|
7094
6640
|
print(f" Cross-check on {cross_unit}: "
|
|
7095
|
-
f"{_measure_facade._signed_usd(cross_usd)}
|
|
6641
|
+
f"{_measure_facade._signed_usd(cross_usd)} this period "
|
|
7096
6642
|
f"(independent unit, agrees within ~10%{gap_txt}).")
|
|
7097
6643
|
else:
|
|
7098
6644
|
print(f" Cross-check on {cross_unit}: "
|
|
7099
|
-
f"{_measure_facade._signed_usd(cross_usd)}
|
|
6645
|
+
f"{_measure_facade._signed_usd(cross_usd)} this period "
|
|
7100
6646
|
f"(independent unit, does not agree{gap_txt}).")
|
|
7101
6647
|
else:
|
|
7102
6648
|
print(f" Had you worked the way you did before Token Optimizer "
|
|
@@ -7111,7 +6657,7 @@ def savings_report(days=None, as_json=None):
|
|
|
7111
6657
|
for lev in ba_breakdown:
|
|
7112
6658
|
amt = float(lev.get("monthly_usd", 0) or 0)
|
|
7113
6659
|
sign = "-" if amt < 0 else " "
|
|
7114
|
-
print(f" {sign}${abs(amt):>8,.0f}
|
|
6660
|
+
print(f" {sign}${abs(amt):>8,.0f} this period {lev.get('label', lev.get('key', ''))}")
|
|
7115
6661
|
caveat = ba.get("breakdown_caveat") or ""
|
|
7116
6662
|
if caveat:
|
|
7117
6663
|
# Wrap the caveat so the CLI surfaces the same disclosure as the dashboard.
|
|
@@ -7122,7 +6668,7 @@ def savings_report(days=None, as_json=None):
|
|
|
7122
6668
|
# session-weight pool delegated work is excluded from the headline entirely.
|
|
7123
6669
|
prem = float(ba.get("premium_delegation_cost_usd", 0.0) or 0.0)
|
|
7124
6670
|
if prem > 0:
|
|
7125
|
-
print(f" Costlier delegation: ${prem:,.0f}
|
|
6671
|
+
print(f" Costlier delegation: ${prem:,.0f} this period of premium-model "
|
|
7126
6672
|
f"subagent spend. "
|
|
7127
6673
|
+ ("Not in the headline above (delegated work is measured separately)."
|
|
7128
6674
|
if wp else "Included in the sidechain net above."))
|
|
@@ -7132,16 +6678,16 @@ def savings_report(days=None, as_json=None):
|
|
|
7132
6678
|
print()
|
|
7133
6679
|
print(" YOUR TRANSFORMATION: none to headline this period")
|
|
7134
6680
|
print(f" Each request now carries more context than at your baseline "
|
|
7135
|
-
f"(est. ${ba.get('actual_monthly_usd', 0):,.0f}
|
|
7136
|
-
f"${ba.get('counterfactual_monthly_usd', 0):,.0f}
|
|
6681
|
+
f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs "
|
|
6682
|
+
f"${ba.get('counterfactual_monthly_usd', 0):,.0f} this period at the baseline's cost "
|
|
7137
6683
|
f"per request), so there is no whole-workload saving to headline. "
|
|
7138
6684
|
f"The measured savings below are real and counted.")
|
|
7139
6685
|
elif ba.get("reason") == "flat":
|
|
7140
6686
|
print()
|
|
7141
6687
|
print(" YOUR TRANSFORMATION: no measurable change this period")
|
|
7142
6688
|
print(f" Cost per unit of work is about the same as before install "
|
|
7143
|
-
f"(est. ${ba.get('actual_monthly_usd', 0):,.0f}
|
|
7144
|
-
f"${ba.get('counterfactual_monthly_usd', 0):,.0f}
|
|
6689
|
+
f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs "
|
|
6690
|
+
f"${ba.get('counterfactual_monthly_usd', 0):,.0f} this period the old way). "
|
|
7145
6691
|
f"The savings below are counted action by action.")
|
|
7146
6692
|
elif ba.get("reason") == "methods_disagree":
|
|
7147
6693
|
# The two independent work-unit methods could not be reconciled, so the
|
|
@@ -7157,29 +6703,18 @@ def savings_report(days=None, as_json=None):
|
|
|
7157
6703
|
print()
|
|
7158
6704
|
print(" YOUR TRANSFORMATION: not headlined this period")
|
|
7159
6705
|
print(f" The {main_unit} and {cross_unit} methods disagree "
|
|
7160
|
-
f"({_measure_facade._signed_usd(main_usd)}
|
|
6706
|
+
f"({_measure_facade._signed_usd(main_usd)} vs {_measure_facade._signed_usd(cross_usd)} this period), "
|
|
7161
6707
|
f"so neither is headlined. The measured savings below are real "
|
|
7162
6708
|
f"and counted.")
|
|
7163
6709
|
|
|
7164
6710
|
print(" Pricing: known model rates, API equivalent")
|
|
7165
6711
|
|
|
7166
6712
|
struct = summary.get("structural_detail") or {}
|
|
7167
|
-
|
|
7168
|
-
|
|
7169
|
-
|
|
7170
|
-
delta = struct.get("overhead_delta", 0)
|
|
7171
|
-
# Labelled "Prefix baseline" (not just "Baseline") to distinguish from
|
|
7172
|
-
# the transformation card's session-cost anchors (2026-06-23 etc.).
|
|
7173
|
-
# These are two different baselines with two different jobs: this one
|
|
7174
|
-
# measures prefix token reduction (structural savings), the anchors
|
|
7175
|
-
# measure per-call cost drift. Calling both "baseline" on the same
|
|
7176
|
-
# screen caused the zero-cards confusion.
|
|
7177
|
-
if delta > 0:
|
|
7178
|
-
print(f" Prefix baseline: snapshot {b_date} (prefix trimmed {delta:,} tokens, compounding [est])")
|
|
7179
|
-
else:
|
|
7180
|
-
print(f" Prefix baseline: snapshot {b_date} (no prefix trimmed below baseline yet -> realized $0)")
|
|
6713
|
+
if struct.get("baseline_source") == "trim_ledger":
|
|
6714
|
+
print(f" Setup trims: {len(struct.get('trims') or [])} recorded since "
|
|
6715
|
+
f"{(struct.get('baseline_date') or '')[:10]} ({struct.get('overhead_delta', 0):,} tokens per call still trimmed)")
|
|
7181
6716
|
else:
|
|
7182
|
-
print("
|
|
6717
|
+
print(f" Setup trims: {struct.get('message') or 'no trims recorded yet'}")
|
|
7183
6718
|
|
|
7184
6719
|
print()
|
|
7185
6720
|
print(f" {'Category':<28s} {'Events':>8s} {'Tokens Saved':>14s} {'Cost Saved':>11s}")
|
|
@@ -7196,10 +6731,10 @@ def savings_report(days=None, as_json=None):
|
|
|
7196
6731
|
# measured table (that was the A1/A3 double-count). Without verbosity_steer
|
|
7197
6732
|
# here, the row shows "0 events" in the measured table even though the
|
|
7198
6733
|
# feature fires thousands of times/month — the raw nudge injection count is
|
|
7199
|
-
# an estimated-tier metric
|
|
7200
|
-
#
|
|
6734
|
+
# an estimated-tier metric. verbosity_steer_measured is an uncontrolled
|
|
6735
|
+
# before/after; its net-of-control figure prints in the estimated tier.
|
|
7201
6736
|
_RELOCATED = {"setup_optimization", "mcp_cap", "verbosity_steer", "resume_lean",
|
|
7202
|
-
"checkpoint_restore"}
|
|
6737
|
+
"checkpoint_restore", "verbosity_steer_measured"}
|
|
7203
6738
|
|
|
7204
6739
|
# Known measured categories (even if zero), then any unknown ones in the data.
|
|
7205
6740
|
table_rows = [(label, by_cat.get(key, {}))
|
|
@@ -7247,11 +6782,9 @@ def savings_report(days=None, as_json=None):
|
|
|
7247
6782
|
oneshot = summary.get("oneshot_pricing") or {}
|
|
7248
6783
|
if oneshot.get("removal_events"):
|
|
7249
6784
|
print(" Initial removals above are priced at the input rate, a minimum.")
|
|
7250
|
-
|
|
7251
|
-
if premium >= 0.005:
|
|
6785
|
+
if _cents.get("class_premium"):
|
|
7252
6786
|
print(f" The next call billed new context at a cache-write rate for "
|
|
7253
|
-
f"{int(oneshot.get('class_events', 0)):,} removals
|
|
7254
|
-
f"not in the total.")
|
|
6787
|
+
f"{int(oneshot.get('class_events', 0)):,} removals; that premium is its own line below.")
|
|
7255
6788
|
trip = _measure_facade._headline_tripwire(total_cost + rr_usd, total_events, days)
|
|
7256
6789
|
if trip:
|
|
7257
6790
|
print()
|
|
@@ -7263,21 +6796,30 @@ def savings_report(days=None, as_json=None):
|
|
|
7263
6796
|
print(f" Estimated monthly: ${_money(_cents['logged'])} (measured)")
|
|
7264
6797
|
else:
|
|
7265
6798
|
print(f" Total so far ({tracked} day{'' if tracked == 1 else 's'} tracked): ${_money(_cents['logged'])} (measured)")
|
|
6799
|
+
if _cents.get("class_premium"):
|
|
6800
|
+
print(f" + write-class premium: ~${_money(_cents['class_premium'])}{per} ({_act.get('class_premium_events', 0):,} "
|
|
6801
|
+
"removals whose next call wrote to the cache, priced at that write rate) [measured]")
|
|
7266
6802
|
|
|
7267
|
-
#
|
|
6803
|
+
# Model routing is an assumption, shown on its own line and kept out of ALL IN.
|
|
7268
6804
|
routing = summary.get("model_routing") or {}
|
|
7269
6805
|
routing_realized = float(routing.get("realized_cost_usd", 0.0) or 0.0)
|
|
7270
6806
|
routing_pending = int(routing.get("pending_sessions", 0) or 0) if routing.get("evidence") == "pending" else 0
|
|
7271
6807
|
if routing_pending:
|
|
7272
|
-
print(f"
|
|
7273
|
-
f"session{'' if routing_pending == 1 else 's'} left), not in ALL IN
|
|
6808
|
+
print(f" i model routing: re-measuring ({routing_pending:,} "
|
|
6809
|
+
f"session{'' if routing_pending == 1 else 's'} left), not in ALL IN")
|
|
7274
6810
|
if routing_realized > 0:
|
|
7275
|
-
|
|
6811
|
+
r_cents, _ = _measure_facade._allocate_cents([_mo(routing_realized)])
|
|
6812
|
+
r_monthly = _money(r_cents[0])
|
|
7276
6813
|
b_share = routing.get("baseline_opus_share", 0.0) * 100
|
|
7277
6814
|
c_share = routing.get("current_opus_share", 0.0) * 100
|
|
7278
6815
|
routing_label = "estimated" if routing.get("evidence") == "estimated" else "measured"
|
|
7279
|
-
|
|
7280
|
-
|
|
6816
|
+
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")
|
|
6817
|
+
print(f" i Model routing (not in ALL IN): ~${r_monthly}{per} "
|
|
6818
|
+
f"{basis} (now {c_share:.0f}%) [{routing_label}]")
|
|
6819
|
+
mb_share = routing.get("measured_baseline_opus_share")
|
|
6820
|
+
if mb_share is not None:
|
|
6821
|
+
mb_cents, _ = _measure_facade._allocate_cents([_mo(float(routing.get("measured_baseline_realized_cost_usd") or 0.0))])
|
|
6822
|
+
print(f" i measured alternative: your earliest tracked month had {float(mb_share) * 100:.1f}% Opus -> ~${_money(mb_cents[0])}{per}")
|
|
7281
6823
|
ref_priced = [str(f)[:1].upper() + str(f)[1:] for f in routing.get("baseline_reference_priced") or []]
|
|
7282
6824
|
if ref_priced:
|
|
7283
6825
|
print(f" i routing compares your earlier and current mix on one price list, the newest card of each "
|
|
@@ -7336,24 +6878,6 @@ def savings_report(days=None, as_json=None):
|
|
|
7336
6878
|
# cache_drop + output_waste are OPPORTUNITY (avoidable waste TO does not yet
|
|
7337
6879
|
# prevent), shown in the COULD SAVE block below, never in the estimated total.
|
|
7338
6880
|
|
|
7339
|
-
# Estimated tier — MCP-cap (relocated from measured; Claude Code's own
|
|
7340
|
-
# truncation, inferred not observed).
|
|
7341
|
-
mcp_cap_est = summary.get("mcp_cap_estimated") or {}
|
|
7342
|
-
mce_cost = float(mcp_cap_est.get("cost_saved_usd", 0.0) or 0.0)
|
|
7343
|
-
if mce_cost > 0:
|
|
7344
|
-
mce_monthly = _money(_est_cents["mcp_cap_estimated"])
|
|
7345
|
-
print(f" + est. MCP output cap: ~${mce_monthly}{per} "
|
|
7346
|
-
f"({mcp_cap_est.get('events', 0)} capped MCP results) [estimated]")
|
|
7347
|
-
|
|
7348
|
-
# Estimated tier — lean resumes (cold `--resume` reload avoided; the trigger
|
|
7349
|
-
# is a counterfactual, the magnitude is the target's real last-turn context).
|
|
7350
|
-
rl_est = summary.get("resume_lean_estimated") or {}
|
|
7351
|
-
rle_cost = float(rl_est.get("cost_saved_usd", 0.0) or 0.0)
|
|
7352
|
-
if rle_cost > 0:
|
|
7353
|
-
rle_monthly = _money(_est_cents["resume_lean_estimated"])
|
|
7354
|
-
print(f" + est. lean resumes: ~${rle_monthly}{per} "
|
|
7355
|
-
f"({rl_est.get('events', 0)} cold-resume reloads avoided) [estimated]")
|
|
7356
|
-
|
|
7357
6881
|
# Estimated tier — checkpoint restores (avoided working-set re-reads; the
|
|
7358
6882
|
# restore is observed, the credited re-read is inferred, never metered).
|
|
7359
6883
|
cr_est = summary.get("checkpoint_restore_estimated") or {}
|
|
@@ -7393,15 +6917,9 @@ def savings_report(days=None, as_json=None):
|
|
|
7393
6917
|
print(f" + est. avoided search ({label}): ~${_money(_est_cents[avoided_source])}{per} "
|
|
7394
6918
|
f"({detail}) [estimated]")
|
|
7395
6919
|
|
|
7396
|
-
verbosity = summary.get("verbosity_steer") or {}
|
|
7397
|
-
verbosity_cost = summary["action_savings"]["estimates_usd"]["verbosity_steer"]
|
|
7398
|
-
if verbosity_cost > 0:
|
|
7399
|
-
print(f" + est. concise output nudges: ~${_money(_est_cents['verbosity_steer'])}{per} "
|
|
7400
|
-
f"({verbosity.get('events', 0)} nudges) [estimated]")
|
|
7401
|
-
|
|
7402
6920
|
print(f" = ALL IN: ~${all_in}{per} (measured + modeled + estimated)")
|
|
7403
6921
|
if routing_pending:
|
|
7404
|
-
print(" i ALL IN leaves out model routing
|
|
6922
|
+
print(" i ALL IN leaves out model routing; the assumption stays separate.")
|
|
7405
6923
|
if summary["action_savings"].get("reread_pricing_complete") is False:
|
|
7406
6924
|
print(" i ALL IN is a priced subtotal; unpriced repeat-read credits and debits are not included.")
|
|
7407
6925
|
if summary["action_savings"]["total_clamped"]:
|
|
@@ -7416,7 +6934,7 @@ def savings_report(days=None, as_json=None):
|
|
|
7416
6934
|
if float(since_all_in.get("total_usd") or 0) > 0:
|
|
7417
6935
|
so_far = " so far" if since_all_in.get("routing_pending") or since_all_in.get("remeasuring") else ""
|
|
7418
6936
|
print(f" = SINCE INSTALL ({since['install_date']}, {since['days']} days): "
|
|
7419
|
-
f"~${since_all_in['total_usd']:,.2f}{so_far} (same
|
|
6937
|
+
f"~${since_all_in['total_usd']:,.2f}{so_far} (same parts, added up)")
|
|
7420
6938
|
|
|
7421
6939
|
# Informational (not summed): one-time first-trim + progressive disclosure.
|
|
7422
6940
|
one_time = summary.get("one_time_setup") or {}
|
|
@@ -7462,14 +6980,14 @@ def savings_report(days=None, as_json=None):
|
|
|
7462
6980
|
f"re-reads across {reclaimable.get('sessions', 0)} sessions — avoid re-reading or use .contextignore.")
|
|
7463
6981
|
if len(concrete_items) > 1:
|
|
7464
6982
|
print(f" = ~${_measure_facade._format_cents(items_total_cents)}{per} from the items above (API-rate equivalent)")
|
|
7465
|
-
if cd_tokens > 0:
|
|
7466
|
-
|
|
7467
|
-
|
|
6983
|
+
if cd_tokens > 0: # an opportunity at API rates: own line, never folded into the total above
|
|
6984
|
+
ttl = float(cache_drop.get("ttl_seconds") or 0) # the TTL the user's own cache writes show
|
|
6985
|
+
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")
|
|
7468
6986
|
cd_dollars = f", about ${_mo(cd_cost):.2f}{per} at API rates" if cd_cost > 0 else ""
|
|
7469
6987
|
print()
|
|
7470
6988
|
print(f" Cache drops (an opportunity, not a measurement): {cache_drop.get('drop_sessions', 0)} sessions idled "
|
|
7471
|
-
f"past
|
|
7472
|
-
f"
|
|
6989
|
+
f"past {cache_name} and re-wrote ~{int(_mo(cd_tokens)):,} tokens{per} of prefix{cd_dollars}. "
|
|
6990
|
+
f"Resume within {resume}, or batch related work before stepping away.")
|
|
7473
6991
|
if routing_potential > 0:
|
|
7474
6992
|
# Routing is an assumption about the user's own Opus work, so it sits
|
|
7475
6993
|
# on its own line and is never folded into the total above.
|