@alexgreensh/token-optimizer 5.13.81 → 5.13.82
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/hooks/module_runner.py +1 -1
- package/package.json +1 -1
- package/skills/token-optimizer/assets/savings_story.js +6 -4
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/continuity.py +30 -3
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +32 -15
- package/skills/token-optimizer/scripts/_measure/daemon.py +25 -2
- package/skills/token-optimizer/scripts/_measure/dashboard.py +2 -1
- package/skills/token-optimizer/scripts/_measure/feature_health.py +14 -5
- package/skills/token-optimizer/scripts/_measure/install_baseline.py +2 -1
- package/skills/token-optimizer/scripts/_measure/like_for_like.py +329 -0
- package/skills/token-optimizer/scripts/_measure/limit_units.py +39 -0
- package/skills/token-optimizer/scripts/_measure/model_families.py +133 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +38 -14
- package/skills/token-optimizer/scripts/_measure/pilot_report.py +197 -48
- package/skills/token-optimizer/scripts/_measure/pricing.py +7 -2
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +41 -19
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +2 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +155 -80
- package/skills/token-optimizer/scripts/_measure/sessions.py +7 -2
- package/skills/token-optimizer/scripts/_measure/trends.py +20 -2
- package/skills/token-optimizer/scripts/_measure/weekly_activity.py +37 -4
- package/skills/token-optimizer/scripts/antigravity_doctor.py +42 -6
- package/skills/token-optimizer/scripts/antigravity_install.py +18 -9
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/cursor_coach.py +5 -4
- package/skills/token-optimizer/scripts/cursor_install.py +1 -0
- package/skills/token-optimizer/scripts/delta_serve.py +174 -0
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +2 -1
- package/skills/token-optimizer/scripts/hermes_install.py +2 -1
- package/skills/token-optimizer/scripts/measure.py +14 -21
- package/skills/token-optimizer/scripts/read_cache.py +19 -76
- package/skills/token-optimizer/scripts/reset_epoch.py +5 -3
- package/skills/token-optimizer/scripts/session_activity.py +1 -1
- package/skills/token-optimizer/scripts/session_store.py +5 -6
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
2
|
from __future__ import annotations
|
|
3
|
-
from . import _compat, install_baseline, baseline_provenance, own_price_card, counted_orphans, counted_subagents, headline, structural_report, savings_story, transcript_stream, token_type_split, upgrade_drain_control
|
|
3
|
+
from . import _compat, install_baseline, baseline_provenance, own_price_card, like_for_like, counted_orphans, counted_subagents, headline, structural_report, savings_story, transcript_stream, token_type_split, upgrade_drain_control, limit_units
|
|
4
4
|
|
|
5
5
|
def _counted_event_utc(ts):
|
|
6
6
|
"""Convert local event timestamps to UTC, respecting local DST."""
|
|
@@ -398,7 +398,7 @@ def _counted_candidate_events(conn):
|
|
|
398
398
|
ce_excl = ",".join("?" for _ in _measure_facade._COUNTED_CE_EXCLUDED_FEATURES)
|
|
399
399
|
rows = conn.execute(
|
|
400
400
|
"SELECT 'se:'||id, session_uuid, timestamp, "
|
|
401
|
-
" CASE WHEN event_type
|
|
401
|
+
" CASE WHEN event_type IN ('tool_archive_reexpand','delta_read_reread') THEN -tokens_saved "
|
|
402
402
|
" ELSE tokens_saved END, cost_saved_usd, model "
|
|
403
403
|
"FROM " + _measure_facade._counted_table(conn, "savings_events") + " "
|
|
404
404
|
"WHERE event_type IN (" + se_types + ") AND timestamp >= ? "
|
|
@@ -1310,29 +1310,18 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1310
1310
|
bash["tokens_saved"] = -int(bash.get("tokens_saved") or 0)
|
|
1311
1311
|
bash["cost_saved_usd"] = -float(bash.get("cost_saved_usd") or 0)
|
|
1312
1312
|
|
|
1313
|
-
# B6: net
|
|
1314
|
-
# re-
|
|
1315
|
-
# even if the result is negative.
|
|
1316
|
-
#
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
c_tok = int(ta["tokens_saved"]) if ta else 0
|
|
1326
|
-
c_cost = float(ta["cost_saved_usd"]) if ta else 0.0
|
|
1327
|
-
net_tok = c_tok - r_tok
|
|
1328
|
-
net_cost = c_cost - r_cost
|
|
1329
|
-
if ta:
|
|
1330
|
-
ta["tokens_saved"] = net_tok
|
|
1331
|
-
ta["cost_saved_usd"] = round(net_cost, 4)
|
|
1332
|
-
# Back out the debit's own positive AND the reversed over-credit.
|
|
1333
|
-
total_tokens += (net_tok - c_tok) - r_tok
|
|
1334
|
-
total_cost += (net_cost - c_cost) - r_cost
|
|
1335
|
-
total_events -= r_events # re-expand rows are not savings events
|
|
1313
|
+
# B6: net positive-magnitude debits out of their credit lines. A re-popped
|
|
1314
|
+
# archive result or post-delta full re-read didn't stay avoided, so its eager
|
|
1315
|
+
# credit is reversed even if the result is negative. Debit rows are never
|
|
1316
|
+
# savings lines or savings events of their own.
|
|
1317
|
+
for debit_key, credit_key in (
|
|
1318
|
+
("tool_archive_reexpand", "tool_archive"),
|
|
1319
|
+
("delta_read_reread", "delta_read"),
|
|
1320
|
+
):
|
|
1321
|
+
adj_tok, adj_cost, adj_events = limit_units.net_positive_debit(by_category, debit_key, credit_key)
|
|
1322
|
+
total_tokens += adj_tok
|
|
1323
|
+
total_cost += adj_cost
|
|
1324
|
+
total_events += adj_events
|
|
1336
1325
|
|
|
1337
1326
|
return (by_category, total_tokens, total_cost, total_events, popped,
|
|
1338
1327
|
repriced_to_session_mix)
|
|
@@ -1356,7 +1345,9 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1356
1345
|
table = _measure_facade._counted_table(conn, "savings_events")
|
|
1357
1346
|
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"
|
|
1358
1347
|
rows = conn.execute(
|
|
1359
|
-
"SELECT " + event_expr + ",
|
|
1348
|
+
"SELECT " + event_expr + ", "
|
|
1349
|
+
"SUM(CASE WHEN event_type = 'checkpoint_restore' AND COALESCE(tokens_saved, 0) <= 0 THEN 0 ELSE 1 END) as cnt, "
|
|
1350
|
+
"SUM(tokens_saved) as tok, SUM(cost_saved_usd) as cost "
|
|
1360
1351
|
"FROM " + table + " WHERE timestamp >= ? GROUP BY 1 ORDER BY tok DESC",
|
|
1361
1352
|
(cutoff,),
|
|
1362
1353
|
).fetchall()
|
|
@@ -2202,16 +2193,20 @@ def _runway_saved_tokens(conn, cutoff, include_estimated=None):
|
|
|
2202
2193
|
sql, (cutoff,))
|
|
2203
2194
|
if include_estimated or event_type not in _measure_facade._RUNWAY_ESTIMATED_EVENT_TYPES}
|
|
2204
2195
|
reexpanded = by_event.pop("tool_archive_reexpand", 0)
|
|
2196
|
+
delta_reread = by_event.pop("delta_read_reread", 0)
|
|
2205
2197
|
if "bash_archive_reexpand" in by_event: by_event["bash_archive_reexpand"] *= -1
|
|
2206
2198
|
if reexpanded:
|
|
2207
2199
|
by_event["tool_archive"] = by_event.get("tool_archive", 0) - reexpanded
|
|
2200
|
+
if delta_reread:
|
|
2201
|
+
by_event["delta_read"] = by_event.get("delta_read", 0) - delta_reread
|
|
2208
2202
|
saved = sum(by_event.values())
|
|
2209
2203
|
table = _measure_facade._counted_table(conn, "compression_events")
|
|
2210
2204
|
if "feature" not in {r[1] for r in conn.execute(f"PRAGMA table_info({table})")}:
|
|
2211
2205
|
# An install old enough to log no feature name cannot be split by owner.
|
|
2212
2206
|
return saved + int(conn.execute(
|
|
2213
2207
|
_measure_facade._RUNWAY_COMPRESSED_TOTAL_SQL[table], (cutoff,)).fetchone()[0] or 0)
|
|
2214
|
-
|
|
2208
|
+
compressed = limit_units.net_delta_reread_tokens(conn.execute(_measure_facade._RUNWAY_COMPRESSED_SQL[table], (cutoff,)))
|
|
2209
|
+
for feature, tokens in compressed.items():
|
|
2215
2210
|
if feature in _measure_facade._V5_COMPRESSION_CATEGORIES and feature not in by_event:
|
|
2216
2211
|
saved += int(tokens or 0)
|
|
2217
2212
|
return saved
|
|
@@ -3966,15 +3961,17 @@ def _subagent_pool_savings(baseline_opus_share, days=None, tier=None, fresh=None
|
|
|
3966
3961
|
baseline_mix_available=None):
|
|
3967
3962
|
"""Subagent (sidechain) routing pool — the big missing lever.
|
|
3968
3963
|
|
|
3969
|
-
Subagents run in sidechain transcripts (isSidechain:true)
|
|
3970
|
-
|
|
3971
|
-
|
|
3972
|
-
|
|
3964
|
+
Subagents run in sidechain transcripts (isSidechain:true). Modern collection
|
|
3965
|
+
merges nested delegated requests into the parent's combined usage map and can
|
|
3966
|
+
also store standalone sidechain rows net of request claims. Consequently this
|
|
3967
|
+
raw transcript scan overlaps the session-weight pool. When that pool exists the
|
|
3968
|
+
scan is diagnostic only; when the older ledger shape leaves no work-normalized
|
|
3969
|
+
pool, it remains the legacy additive subagent pool. They are real spend that
|
|
3970
|
+
Token Optimizer may route: a user's CLAUDE.md may route subagents to Haiku/Sonnet;
|
|
3973
3971
|
pre-TO they would have run on Opus. This pool prices that delta.
|
|
3974
3972
|
|
|
3975
|
-
Method (separate from, and summed with, the main pool
|
|
3976
|
-
|
|
3977
|
-
pools never price the same dollars):
|
|
3973
|
+
Method (separate from, and summed with, the legacy main pool only when the
|
|
3974
|
+
session-weight pool is unavailable):
|
|
3978
3975
|
1. Locate sidechain JSONL for the current `days` window. We scan project dirs
|
|
3979
3976
|
for both top-level transcripts AND the `{uuid}/subagents/*.jsonl` files,
|
|
3980
3977
|
filtered by mtime, then keep only files _parse_session_jsonl flags
|
|
@@ -4275,10 +4272,16 @@ def _baseline_progress():
|
|
|
4275
4272
|
return None
|
|
4276
4273
|
|
|
4277
4274
|
|
|
4278
|
-
def _price_parent_window(conn, where, params, tier):
|
|
4279
|
-
"""Sum USD over
|
|
4275
|
+
def _price_parent_window(conn, where, params, tier, include_sidechains=False):
|
|
4276
|
+
"""Sum USD over every session matching `where`, at each session's own mix
|
|
4280
4277
|
AND at one constant rate card, plus the work-unit counts (api_calls, messages).
|
|
4281
4278
|
|
|
4279
|
+
Sidechain rows are excluded by default for legacy callers. When
|
|
4280
|
+
include_sidechains is true, only rows stamped by the request-claiming usage
|
|
4281
|
+
parser are admitted: their stored usage is net of requests already claimed by
|
|
4282
|
+
a parent (and vice versa), so parent+sidechain rows partition billed work
|
|
4283
|
+
instead of double counting it.
|
|
4284
|
+
|
|
4282
4285
|
Deliberately does NOT apply _SESSION_QUALITY_FILTER. That filter
|
|
4283
4286
|
(`input_tokens >= 1000 AND duration_minutes >= 1.0`) exists to keep a per-session
|
|
4284
4287
|
ANCHOR clean, but using it to select the population being counted is what blinded
|
|
@@ -4293,22 +4296,31 @@ def _price_parent_window(conn, where, params, tier):
|
|
|
4293
4296
|
"""
|
|
4294
4297
|
_measure_facade = _compat.facade()
|
|
4295
4298
|
_measure_facade.ensure_activity_view(conn)
|
|
4299
|
+
population = "AND COALESCE(is_sidechain, 0) = 0 "
|
|
4300
|
+
if include_sidechains:
|
|
4301
|
+
population = ("AND (COALESCE(is_sidechain, 0) = 0 "
|
|
4302
|
+
"OR COALESCE(usage_parser_version, 0) >= ?) ")
|
|
4303
|
+
params = (_measure_facade._USAGE_PARSER_VERSION,) + tuple(params)
|
|
4296
4304
|
rows = conn.execute(
|
|
4297
4305
|
"SELECT input_tokens, output_tokens, cache_create_5m_tokens, "
|
|
4298
4306
|
"cache_create_1h_tokens, cache_hit_rate, model_usage_json, all_model_usage_json, "
|
|
4299
4307
|
"COALESCE(api_calls, 0), COALESCE(message_count, 0), model_usage_breakdown_json "
|
|
4300
4308
|
"FROM session_activity WHERE input_tokens IS NOT NULL "
|
|
4301
|
-
|
|
4309
|
+
+ population + where, params
|
|
4302
4310
|
).fetchall()
|
|
4303
4311
|
api_calls_unknown = conn.execute(
|
|
4304
4312
|
"SELECT COUNT(DISTINCT id) FROM session_activity WHERE input_tokens IS NOT NULL "
|
|
4305
|
-
"AND COALESCE(
|
|
4313
|
+
"AND COALESCE(api_calls_known,0)=0 " + population + where, params
|
|
4306
4314
|
).fetchone()[0]
|
|
4307
4315
|
result = _measure_facade._price_parent_rows(rows, tier, api_calls_unknown=api_calls_unknown)
|
|
4308
4316
|
if result:
|
|
4309
4317
|
result["sessions"] = conn.execute(
|
|
4310
4318
|
"SELECT COUNT(DISTINCT id) FROM session_activity WHERE input_tokens IS NOT NULL "
|
|
4311
|
-
|
|
4319
|
+
+ population + where, params).fetchone()[0]
|
|
4320
|
+
if include_sidechains:
|
|
4321
|
+
result["sidechain_sessions"] = conn.execute(
|
|
4322
|
+
"SELECT COUNT(DISTINCT id) FROM session_activity WHERE input_tokens IS NOT NULL "
|
|
4323
|
+
"AND COALESCE(is_sidechain, 0) != 0 " + population + where, params).fetchone()[0]
|
|
4312
4324
|
return result
|
|
4313
4325
|
|
|
4314
4326
|
|
|
@@ -4504,7 +4516,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4504
4516
|
per-session cost counts capacity gained as money saved, which is exactly the
|
|
4505
4517
|
inflation this pool exists to avoid. `transformation_usd` answers "what would this
|
|
4506
4518
|
period's dispatched work have cost at the anchor month's cost per unit of work",
|
|
4507
|
-
both arms at the
|
|
4519
|
+
both arms at the same CURRENT reference card per model family so generation/vendor price drift stays out (the
|
|
4508
4520
|
engine-priced variant, which includes that drift, is disclosed as
|
|
4509
4521
|
`engine_priced_transformation_usd` / `price_mix_drift_usd`, never headline-claimed).
|
|
4510
4522
|
|
|
@@ -4527,6 +4539,17 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4527
4539
|
).fetchall() if r and r[0]
|
|
4528
4540
|
]
|
|
4529
4541
|
pinned = _measure_facade._pinned_workload_anchor()
|
|
4542
|
+
if pinned and not (pinned["metrics"].get("model_classes") or {}):
|
|
4543
|
+
# Anchors pinned before per-model evidence existed otherwise bypass
|
|
4544
|
+
# current-family pricing forever. When the ledger still retains the
|
|
4545
|
+
# anchor window, lend the detailed classes in memory (no write here);
|
|
4546
|
+
# transcript rebuild remains the fallback for aged-out windows.
|
|
4547
|
+
window = _measure_facade._pretool_window()
|
|
4548
|
+
if window:
|
|
4549
|
+
fresh_anchor = _measure_facade._price_parent_window(
|
|
4550
|
+
conn, "AND date BETWEEN ? AND ?", (window[0], window[1]), tier,
|
|
4551
|
+
include_sidechains=True)
|
|
4552
|
+
own_price_card.lend_classes(pinned["metrics"], fresh_anchor)
|
|
4530
4553
|
pinned = pinned or install_baseline.workload_anchor(_measure_facade, conn, tier)
|
|
4531
4554
|
if not pinned and (len(months) < 2 or install_baseline.has_install_anchor(_measure_facade)):
|
|
4532
4555
|
return None
|
|
@@ -4552,11 +4575,13 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4552
4575
|
if not anchor_month:
|
|
4553
4576
|
return None
|
|
4554
4577
|
before = _measure_facade._price_parent_window(
|
|
4555
|
-
conn, "AND date LIKE ?", (anchor_month + "%",), tier
|
|
4578
|
+
conn, "AND date LIKE ?", (anchor_month + "%",), tier,
|
|
4579
|
+
include_sidechains=True)
|
|
4556
4580
|
before, anchor_month = _measure_facade._stable_workload_anchor(before, anchor_month)
|
|
4557
4581
|
now = (_measure_facade._price_parent_activity_window(conn, *activity_window, tier)
|
|
4558
4582
|
if activity_window else
|
|
4559
|
-
_measure_facade._price_parent_window(conn, "AND date >= ?", (cutoff,), tier
|
|
4583
|
+
_measure_facade._price_parent_window(conn, "AND date >= ?", (cutoff,), tier,
|
|
4584
|
+
include_sidechains=True))
|
|
4560
4585
|
finally:
|
|
4561
4586
|
conn.close()
|
|
4562
4587
|
if not before or not now:
|
|
@@ -4564,11 +4589,16 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4564
4589
|
b_n, b_usd, b_tok = before["sessions"], before["usd"], before["tokens"]
|
|
4565
4590
|
n_n, n_usd, n_tok = now["sessions"], now["usd"], now["tokens"]
|
|
4566
4591
|
b_flat, n_flat = before["flat_usd"], now["flat_usd"]
|
|
4567
|
-
#
|
|
4568
|
-
#
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4592
|
+
# Detailed per-model evidence prices both eras at today's reference card for
|
|
4593
|
+
# the family that did the work; older anchors degrade to the prior fallback.
|
|
4594
|
+
own_box = {}
|
|
4595
|
+
def lazy_own_price_card():
|
|
4596
|
+
if "value" not in own_box:
|
|
4597
|
+
own_box["value"] = own_price_card.apply(_measure_facade, before, now, days or 30)
|
|
4598
|
+
return own_box["value"]
|
|
4599
|
+
b_flat, n_flat, price_basis, price_detail = like_for_like.price_arms(
|
|
4600
|
+
_measure_facade, before, now, lazy_own_price_card)
|
|
4601
|
+
own = own_box.get("value")
|
|
4572
4602
|
if (b_n < _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
4573
4603
|
or n_n < _measure_facade._AFTER_MIN_SESSIONS or b_usd <= 0 or b_flat <= 0):
|
|
4574
4604
|
return None
|
|
@@ -4590,8 +4620,8 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4590
4620
|
# of work actually dispatched to the model:
|
|
4591
4621
|
# transformation = (anchor_cost_per_unit - current_cost_per_unit)
|
|
4592
4622
|
# x current_units
|
|
4593
|
-
# Both arms are priced at
|
|
4594
|
-
#
|
|
4623
|
+
# Both arms are priced at one current reference card per model family, so
|
|
4624
|
+
# generation/vendor price drift cannot leak into the claim; the engine-priced
|
|
4595
4625
|
# variant (which includes that drift) is disclosed separately below.
|
|
4596
4626
|
b_calls, n_calls = before["api_calls"], now["api_calls"]
|
|
4597
4627
|
b_msgs, n_msgs = before["messages"], now["messages"]
|
|
@@ -4641,15 +4671,17 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4641
4671
|
price_mix_drift = engine_transformation - transformation
|
|
4642
4672
|
# Capacity: real value, expressed as COUNTS, never dollars. The extra sessions
|
|
4643
4673
|
# and calls the lighter workflow made possible are upside, not savings.
|
|
4674
|
+
price_basis_label = like_for_like.price_basis_label(price_basis)
|
|
4644
4675
|
capacity_note = (
|
|
4645
4676
|
"Work-normalized: your {units:,} {unit_label} this period priced at the "
|
|
4646
|
-
"{month} anchor's cost per {unit_singular}, at
|
|
4677
|
+
"{month} anchor's cost per {unit_singular}, at " + price_basis_label + ". "
|
|
4647
4678
|
"Sessions are not a stable unit of work (you ran {now_n:,} this period vs "
|
|
4648
4679
|
"{then_n:,} in {month}, {growth:.1f}x, at about the same total spend) -- "
|
|
4649
4680
|
"that extra capacity is real, but it is capacity gained, not dollars saved, "
|
|
4650
|
-
"so it is not in the headline.
|
|
4651
|
-
"${drift:,.0f} this period is
|
|
4652
|
-
"Optimizer."
|
|
4681
|
+
"so it is not in the headline. Generation and vendor price drift worth about "
|
|
4682
|
+
"${drift:,.0f} this period is excluded: it would have happened without Token "
|
|
4683
|
+
"Optimizer. Movement between model families stays in the comparison because "
|
|
4684
|
+
"routing work is a real behavior change."
|
|
4653
4685
|
).format(units=n_units,
|
|
4654
4686
|
unit_label="API calls" if unit == "api_call" else "messages",
|
|
4655
4687
|
unit_singular="API call" if unit == "api_call" else "message",
|
|
@@ -4668,6 +4700,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4668
4700
|
"after_tokens_per_session": (n_tok / n_n) if n_n else 0.0,
|
|
4669
4701
|
"before_sessions": b_n,
|
|
4670
4702
|
"sessions": n_n,
|
|
4703
|
+
"sidechain_sessions": int(now.get("sidechain_sessions") or 0),
|
|
4671
4704
|
"actual_usd": n_flat,
|
|
4672
4705
|
"counterfactual_usd": counterfactual,
|
|
4673
4706
|
"transformation_usd": transformation,
|
|
@@ -4676,6 +4709,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4676
4709
|
"engine_priced_transformation_usd": engine_transformation,
|
|
4677
4710
|
"engine_priced_actual_usd": n_usd,
|
|
4678
4711
|
"price_mix_drift_usd": price_mix_drift, "price_card": own,
|
|
4712
|
+
"price_basis": price_basis, "price_detail": price_detail,
|
|
4679
4713
|
"capacity_assumption": capacity_note,
|
|
4680
4714
|
# Sessions in each window whose dated per-day call evidence was never
|
|
4681
4715
|
# recorded; api_calls above is a lower bound when either is nonzero.
|
|
@@ -4734,7 +4768,6 @@ def _weekly_full_savings(resets_at=None, now=None):
|
|
|
4734
4768
|
# whole-workload figure is not trustworthy enough to stand in for
|
|
4735
4769
|
# the metered one; the caller falls back to measured savings.
|
|
4736
4770
|
return None
|
|
4737
|
-
# Same conservative display cap as the Savings tab.
|
|
4738
4771
|
saving = max(0.0, min(pool["transformation_usd"], pool["actual_usd"]))
|
|
4739
4772
|
value = {"saved_usd": round(saving, 2), "start": start.isoformat(),
|
|
4740
4773
|
"end": end.isoformat(), "method": "full workload",
|
|
@@ -4776,7 +4809,7 @@ def _weight_pool_payload(pool):
|
|
|
4776
4809
|
cross = pool.get("crosscheck") or {}
|
|
4777
4810
|
cross_agrees, cross_gap = _measure_facade._crosscheck_agrees(
|
|
4778
4811
|
pool.get("transformation_usd"), cross.get("transformation_usd")) if cross else (True, None)
|
|
4779
|
-
|
|
4812
|
+
payload = {
|
|
4780
4813
|
"anchor_month": pool["anchor_month"],
|
|
4781
4814
|
"work_unit": pool.get("work_unit"),
|
|
4782
4815
|
"before_units": pool.get("before_units", 0),
|
|
@@ -4789,6 +4822,7 @@ def _weight_pool_payload(pool):
|
|
|
4789
4822
|
"after_tokens_per_session": int(pool["after_tokens_per_session"]),
|
|
4790
4823
|
"before_sessions": pool["before_sessions"],
|
|
4791
4824
|
"sessions": pool["sessions"],
|
|
4825
|
+
"sidechain_sessions": int(pool.get("sidechain_sessions") or 0),
|
|
4792
4826
|
"actual_usd": round(pool["actual_usd"], 2),
|
|
4793
4827
|
"counterfactual_usd": round(pool["counterfactual_usd"], 2),
|
|
4794
4828
|
"transformation_usd": round(pool["transformation_usd"], 2),
|
|
@@ -4802,9 +4836,15 @@ def _weight_pool_payload(pool):
|
|
|
4802
4836
|
float(pool.get("engine_priced_transformation_usd", 0.0)), 2),
|
|
4803
4837
|
"engine_priced_actual_usd": round(
|
|
4804
4838
|
float(pool.get("engine_priced_actual_usd", 0.0)), 2),
|
|
4805
|
-
"price_mix_drift_usd": round(float(pool.get("price_mix_drift_usd", 0.0)), 2),
|
|
4839
|
+
"price_mix_drift_usd": round(float(pool.get("price_mix_drift_usd", 0.0)), 2),
|
|
4840
|
+
"price_basis": pool.get("price_basis") or ("own_prices" if pool.get("price_card") else "fixed_card"),
|
|
4841
|
+
**like_for_like.pool_price_disclosures(pool),
|
|
4806
4842
|
"capacity_assumption": pool["capacity_assumption"],
|
|
4807
4843
|
}
|
|
4844
|
+
if payload["price_basis"] != "current_model_reference":
|
|
4845
|
+
payload["flat_rates"] = dict((pool.get("price_card") or {}).get("rates")
|
|
4846
|
+
or _measure_facade._WEIGHT_POOL_FLAT_RATES)
|
|
4847
|
+
return payload
|
|
4808
4848
|
|
|
4809
4849
|
|
|
4810
4850
|
def _estimate_before_after_savings(days=None, estimated_pools=None, model_routing=None, since=None):
|
|
@@ -4943,7 +4983,12 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
4943
4983
|
if frozen_opus > 0 else None)
|
|
4944
4984
|
before_shares = dict((baseline.get("model_shares") or legacy_shares if anthropic else None)
|
|
4945
4985
|
or after_shares)
|
|
4946
|
-
|
|
4986
|
+
|
|
4987
|
+
def _family_share(shares, family):
|
|
4988
|
+
return sum(float(share or 0.0) for model, share in (shares or {}).items()
|
|
4989
|
+
if _measure_facade._normalize_model_name(model) == family)
|
|
4990
|
+
|
|
4991
|
+
baseline_opus_share = _family_share(before_shares, "opus")
|
|
4947
4992
|
# Baseline cache-hit pattern, defined over the FRESH+CACHE_READ POOL only (cache
|
|
4948
4993
|
# write excluded). C1/C2: the counterfactual redistributes caching over the pool,
|
|
4949
4994
|
# not over total_in (which includes CW); a total_in-based hit prices MORE volume on
|
|
@@ -5042,9 +5087,10 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5042
5087
|
tracks_actual_mix = not (anthropic and frozen_opus and frozen_opus > 0) and (
|
|
5043
5088
|
not anthropic or not _measure_facade._opus_floor_consented())
|
|
5044
5089
|
if tracks_actual_mix:
|
|
5045
|
-
baseline_opus_share = float(after_shares.get("opus", 0.0))
|
|
5046
5090
|
before_shares = dict(after_shares)
|
|
5047
|
-
after_opus =
|
|
5091
|
+
after_opus = _family_share(after_shares, "opus")
|
|
5092
|
+
baseline_opus_share = (after_opus if before_shares == after_shares
|
|
5093
|
+
else _family_share(before_shares, "opus"))
|
|
5048
5094
|
tier = _measure_facade._load_pricing_tier() # resolve once; reused across the waterfall levers
|
|
5049
5095
|
|
|
5050
5096
|
# Whether a genuinely DISTINCT pre-TO mix exists for the per-bundle pools'
|
|
@@ -5255,6 +5301,7 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5255
5301
|
sub_actual = sub_window_actual
|
|
5256
5302
|
sub_cf = sub_window_cf
|
|
5257
5303
|
sub_delta = sub_cf - sub_actual
|
|
5304
|
+
sub_window_delta = sub_delta
|
|
5258
5305
|
premium_delegation_cost = float(
|
|
5259
5306
|
sub_pool.get("premium_delegation_usd", 0.0) or 0.0)
|
|
5260
5307
|
# --- SESSION-WEIGHT pool: the volume lever, over the WHOLE parent population ---
|
|
@@ -5267,12 +5314,14 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5267
5314
|
# count the same removed tokens twice (once inside the per-call delta, once
|
|
5268
5315
|
# as repriced events). The main frozen-anchor and short-session pools price
|
|
5269
5316
|
# the same parent ledger this pool covers completely (no quality gate), so
|
|
5270
|
-
# they are superseded rather than summed. Delegated
|
|
5271
|
-
#
|
|
5272
|
-
#
|
|
5273
|
-
#
|
|
5274
|
-
#
|
|
5275
|
-
#
|
|
5317
|
+
# they are superseded rather than summed. Delegated work is in this pool
|
|
5318
|
+
# exactly once through two mechanisms: nested delegated requests are merged
|
|
5319
|
+
# into the parent's combined usage/calls, while standalone sidechain rows
|
|
5320
|
+
# are admitted only when the request-claiming parser version proves their
|
|
5321
|
+
# stored usage is net of parent claims. The raw transcript scan behind the
|
|
5322
|
+
# separate sidechain window overlaps both mechanisms, so it remains
|
|
5323
|
+
# drill-down evidence only; adding its delta would double count. The
|
|
5324
|
+
# directly-metered compression floor still renders
|
|
5276
5325
|
# in its own card from _get_savings_summary, unaffected by this supersession.
|
|
5277
5326
|
if weight_pool:
|
|
5278
5327
|
main_transformation = float(weight_pool["transformation_usd"])
|
|
@@ -5378,6 +5427,18 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5378
5427
|
# was built from; surface them so the card explains itself.
|
|
5379
5428
|
"session_weight_pool": (_measure_facade._weight_pool_payload(weight_pool)
|
|
5380
5429
|
if weight_pool else None)}
|
|
5430
|
+
not_headlined.update(like_for_like.method_disclosures(
|
|
5431
|
+
weight_pool, {"actual_usd": sub_window_actual,
|
|
5432
|
+
"counterfactual_usd": sub_window_cf,
|
|
5433
|
+
"transformation_usd": sub_window_delta}))
|
|
5434
|
+
# Both work-unit methods inside a small band of spend means cost per
|
|
5435
|
+
# unit of work did not measurably change: say "flat" rather than call a
|
|
5436
|
+
# neutral generation upgrade a regression. This check must precede the
|
|
5437
|
+
# net-negative gate, which otherwise claims every exactly neutral period.
|
|
5438
|
+
if weight_pool and _measure_facade._crosscheck_flat(weight_pool, combined_cf):
|
|
5439
|
+
return {**not_headlined,
|
|
5440
|
+
"transformation_state": "flat",
|
|
5441
|
+
"reason": "flat"}
|
|
5381
5442
|
if net < 0.01:
|
|
5382
5443
|
return {**not_headlined,
|
|
5383
5444
|
"net_shortfall_usd": round(net, 2),
|
|
@@ -5389,13 +5450,6 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5389
5450
|
# zero), neither figure is trustworthy enough to headline: the card
|
|
5390
5451
|
# reports both instead of picking one. Same non-headlined shape as
|
|
5391
5452
|
# net_negative; both disputed figures ride on session_weight_pool.
|
|
5392
|
-
# Both work-unit methods inside a small band of spend means cost per
|
|
5393
|
-
# unit of work did not measurably change: say "flat" rather than show
|
|
5394
|
-
# two near-zero figures as a disagreement.
|
|
5395
|
-
if weight_pool and _measure_facade._crosscheck_flat(weight_pool, combined_cf):
|
|
5396
|
-
return {**not_headlined,
|
|
5397
|
-
"transformation_state": "flat",
|
|
5398
|
-
"reason": "flat"}
|
|
5399
5453
|
if weight_pool and not _measure_facade._crosscheck_verdict(weight_pool):
|
|
5400
5454
|
return {**not_headlined,
|
|
5401
5455
|
"transformation_state": "methods_disagree",
|
|
@@ -5621,6 +5675,10 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5621
5675
|
# exists to avoid.
|
|
5622
5676
|
"session_weight_pool": (_measure_facade._weight_pool_payload(weight_pool)
|
|
5623
5677
|
if weight_pool else None),
|
|
5678
|
+
**like_for_like.method_disclosures(
|
|
5679
|
+
weight_pool, {"actual_usd": sub_window_actual,
|
|
5680
|
+
"counterfactual_usd": sub_window_cf,
|
|
5681
|
+
"transformation_usd": sub_window_delta}),
|
|
5624
5682
|
"capacity_neutral_monthly_usd": None,
|
|
5625
5683
|
"baseline_opus_share": round(baseline_opus_share, 4),
|
|
5626
5684
|
"before_opus": round(baseline_opus_share, 4),
|
|
@@ -5778,6 +5836,7 @@ def _merge_v5_compression(by_category, by_feature, fallback_cost_per_mtok):
|
|
|
5778
5836
|
"""
|
|
5779
5837
|
_measure_facade = _compat.facade()
|
|
5780
5838
|
add_tok, add_cost, add_events = 0, 0.0, 0
|
|
5839
|
+
by_feature = limit_units.net_delta_reread_compression(by_feature)
|
|
5781
5840
|
for feature, fdata in by_feature.items():
|
|
5782
5841
|
if feature not in _measure_facade._V5_COMPRESSION_CATEGORIES:
|
|
5783
5842
|
continue # only merge known v5 features; experimental keys stay out
|
|
@@ -6463,12 +6522,13 @@ def savings_report(days=None, as_json=None):
|
|
|
6463
6522
|
print(f" {line}")
|
|
6464
6523
|
# Premium delegation disclosure is supplementary context. Under the legacy
|
|
6465
6524
|
# path its signed effect is in the sidechain pool's net above; under the
|
|
6466
|
-
# session-weight pool delegated work is
|
|
6525
|
+
# session-weight pool delegated work is already inside the combined
|
|
6526
|
+
# parent+delegated activity rows, so nothing is added a second time.
|
|
6467
6527
|
prem = float(ba.get("premium_delegation_cost_usd", 0.0) or 0.0)
|
|
6468
6528
|
if prem > 0:
|
|
6469
6529
|
print(f" Costlier delegation: ${prem:,.0f} this period of premium-model "
|
|
6470
6530
|
f"subagent spend. "
|
|
6471
|
-
+ ("Not
|
|
6531
|
+
+ ("Not added again above (delegated work is already in the work-normalized arms)."
|
|
6472
6532
|
if wp else "Included in the sidechain net above."))
|
|
6473
6533
|
elif ba.get("reason") == "net_negative":
|
|
6474
6534
|
# Distinguishable empty state: the math RAN and landed at/below baseline.
|
|
@@ -6890,7 +6950,9 @@ def validate_impact(strategy=None, days=None, as_json=None):
|
|
|
6890
6950
|
"input_tokens": total_input,
|
|
6891
6951
|
"output_tokens": parsed["total_output_tokens"],
|
|
6892
6952
|
"cache_hit_rate": chr_val,
|
|
6893
|
-
|
|
6953
|
+
# Unmeasured sessions contribute no quality point, never the
|
|
6954
|
+
# scorer's fallback (default 100) (#360).
|
|
6955
|
+
"quality_score": sq["score"] if sq.get("measured") else None,
|
|
6894
6956
|
"cost_usd": cost,
|
|
6895
6957
|
"duration_minutes": parsed.get("duration_minutes", 0),
|
|
6896
6958
|
})
|
|
@@ -6935,12 +6997,15 @@ def validate_impact(strategy=None, days=None, as_json=None):
|
|
|
6935
6997
|
_measure_facade = _compat.facade()
|
|
6936
6998
|
n = len(window)
|
|
6937
6999
|
if n == 0:
|
|
6938
|
-
|
|
7000
|
+
# Empty window: no measured quality signal, so None (never a
|
|
7001
|
+
# phantom 0) - same contract as an all-unmeasured window (#360).
|
|
7002
|
+
return {"count": 0, "avg_tokens": 0, "avg_cost": 0, "avg_quality": None, "avg_cache_hit": 0}
|
|
7003
|
+
quality = [s["quality_score"] for s in window if s["quality_score"] is not None]
|
|
6939
7004
|
return {
|
|
6940
7005
|
"count": n,
|
|
6941
7006
|
"avg_tokens": int(sum(s["input_tokens"] for s in window) / n),
|
|
6942
7007
|
"avg_cost": round(sum(s["cost_usd"] for s in window) / n, 4),
|
|
6943
|
-
"avg_quality": round(sum(
|
|
7008
|
+
"avg_quality": round(sum(quality) / len(quality), 1) if quality else None,
|
|
6944
7009
|
"avg_cache_hit": round(sum(s["cache_hit_rate"] for s in window) / n, 3),
|
|
6945
7010
|
}
|
|
6946
7011
|
|
|
@@ -6952,6 +7017,10 @@ def validate_impact(strategy=None, days=None, as_json=None):
|
|
|
6952
7017
|
_measure_facade = _compat.facade()
|
|
6953
7018
|
b = before_summary[metric]
|
|
6954
7019
|
a = after_summary[metric]
|
|
7020
|
+
# Unmeasured on either side (None) means the delta is unknown, not
|
|
7021
|
+
# zero: return None and let the verdict ignore it (#360).
|
|
7022
|
+
if a is None or b is None:
|
|
7023
|
+
return None
|
|
6955
7024
|
if b == 0:
|
|
6956
7025
|
return 0
|
|
6957
7026
|
raw_pct = ((a - b) / abs(b)) * 100
|
|
@@ -6965,8 +7034,8 @@ def validate_impact(strategy=None, days=None, as_json=None):
|
|
|
6965
7034
|
}
|
|
6966
7035
|
|
|
6967
7036
|
# Verdict: improved if at least 2 of 4 metrics show >10% improvement
|
|
6968
|
-
improved_count = sum(1 for v in deltas.values() if v > 10)
|
|
6969
|
-
regressed_count = sum(1 for v in deltas.values() if v < -10)
|
|
7037
|
+
improved_count = sum(1 for v in deltas.values() if v is not None and v > 10)
|
|
7038
|
+
regressed_count = sum(1 for v in deltas.values() if v is not None and v < -10)
|
|
6970
7039
|
|
|
6971
7040
|
if improved_count >= 2:
|
|
6972
7041
|
verdict = "improved"
|
|
@@ -6996,7 +7065,13 @@ def validate_impact(strategy=None, days=None, as_json=None):
|
|
|
6996
7065
|
after_cost_str = f"${after_summary['avg_cost']:.4f}"
|
|
6997
7066
|
print(f" {'Avg tokens/session':<20s} {before_summary['avg_tokens']:>10,} {after_summary['avg_tokens']:>10,} {deltas['tokens_pct']:>+9.1f}%")
|
|
6998
7067
|
print(f" {'Avg cost/session':<20s} {before_cost_str:>10s} {after_cost_str:>10s} {deltas['cost_pct']:>+9.1f}%")
|
|
6999
|
-
|
|
7068
|
+
def _q(v):
|
|
7069
|
+
return f"{v:>10.1f}" if v is not None else f"{'n/a':>10s}"
|
|
7070
|
+
|
|
7071
|
+
def _d(v):
|
|
7072
|
+
return f"{v:>+9.1f}%" if v is not None else f"{'n/a':>9s} "
|
|
7073
|
+
|
|
7074
|
+
print(f" {'Avg quality score':<20s} {_q(before_summary['avg_quality'])} {_q(after_summary['avg_quality'])} {_d(deltas['quality_pct'])}")
|
|
7000
7075
|
print(f" {'Avg cache hit rate':<20s} {before_summary['avg_cache_hit']:>10.3f} {after_summary['avg_cache_hit']:>10.3f} {deltas['cache_hit_pct']:>+9.1f}%")
|
|
7001
7076
|
|
|
7002
7077
|
verdict_emoji = {"improved": "UP", "regressed": "DOWN", "no_change": "FLAT"}
|
|
@@ -1513,7 +1513,9 @@ def _rebuild_aggregate_tables(conn):
|
|
|
1513
1513
|
COALESCE(SUM(output_tokens), 0),
|
|
1514
1514
|
COALESCE(SUM(duration_minutes), 0),
|
|
1515
1515
|
COALESCE(AVG(cache_hit_rate), 0),
|
|
1516
|
-
|
|
1516
|
+
-- NULL, never 0, when no session that day was measured: an
|
|
1517
|
+
-- all-'?' day has no quality signal, not a zero score (#360).
|
|
1518
|
+
AVG(CASE WHEN quality_grade = '?' THEN NULL ELSE quality_score END),
|
|
1517
1519
|
SUBSTR('FDCBAS', MIN(NULLIF(INSTR('FDCBAS', quality_grade),0)),1)
|
|
1518
1520
|
FROM session_activity
|
|
1519
1521
|
GROUP BY date"""
|
|
@@ -4412,7 +4414,10 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4412
4414
|
parsed.get("slug"),
|
|
4413
4415
|
parsed.get("topic"),
|
|
4414
4416
|
collection_started,
|
|
4415
|
-
|
|
4417
|
+
# Unmeasured sessions (grade "?") store NULL, never the
|
|
4418
|
+
# scorer's fallback (last_measured_score, default 100): a
|
|
4419
|
+
# stored 100 read as a perfect score in every average (#360).
|
|
4420
|
+
sq["score"] if sq.get("measured") else None,
|
|
4416
4421
|
sq["grade"],
|
|
4417
4422
|
int(stale_waste or 0),
|
|
4418
4423
|
1 if parsed.get("is_sidechain") else 0,
|
|
@@ -890,6 +890,21 @@ def _init_trends_db():
|
|
|
890
890
|
except _measure_facade.sqlite3.Error as _e:
|
|
891
891
|
_measure_facade._log_migration_error(f"{_origin_table} origin column", _e)
|
|
892
892
|
_measure_facade.ensure_activity_schema(conn)
|
|
893
|
+
# One-time data repair (#360): unmeasured sessions (grade '?') used to
|
|
894
|
+
# store the scorer's fallback score (last_measured_score, default 100),
|
|
895
|
+
# which then read as a perfect score in raw queries and any consumer that
|
|
896
|
+
# does not filter grade. Null those stored scores; when any row changed,
|
|
897
|
+
# rebuild daily_stats now so its stored quality average cannot stay stale.
|
|
898
|
+
try:
|
|
899
|
+
if not conn.execute("SELECT 1 FROM schema_migrations WHERE name='unmeasured_quality_null_v1'").fetchone():
|
|
900
|
+
cur = conn.execute(
|
|
901
|
+
"UPDATE session_log SET quality_score = NULL WHERE quality_grade = '?' AND quality_score IS NOT NULL")
|
|
902
|
+
if cur.rowcount > 0:
|
|
903
|
+
_measure_facade._rebuild_aggregate_tables(conn)
|
|
904
|
+
conn.execute("INSERT OR IGNORE INTO schema_migrations (name) VALUES ('unmeasured_quality_null_v1')")
|
|
905
|
+
conn.commit()
|
|
906
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
907
|
+
_measure_facade._log_migration_error("unmeasured quality scores", _e)
|
|
893
908
|
# Backfill session_uuid from jsonl_path basename stem for existing rows,
|
|
894
909
|
# then create an index so joins are O(log n) instead of full-table LIKE scans.
|
|
895
910
|
try:
|
|
@@ -1270,7 +1285,10 @@ def _backfill_session_metrics(conn, days=None, limit=None):
|
|
|
1270
1285
|
OR avg_call_gap_seconds IS NULL
|
|
1271
1286
|
OR max_call_gap_seconds IS NULL
|
|
1272
1287
|
OR p95_call_gap_seconds IS NULL
|
|
1273
|
-
|
|
1288
|
+
-- quality_score IS NULL on an unmeasured ('?') row is the
|
|
1289
|
+
-- stored truth, not a gap: re-parsing it every flush is a
|
|
1290
|
+
-- perpetual latency tax that can never fill (#360).
|
|
1291
|
+
OR (quality_score IS NULL AND IFNULL(quality_grade, '') != '?')
|
|
1274
1292
|
)
|
|
1275
1293
|
ORDER BY date DESC, collected_at DESC
|
|
1276
1294
|
LIMIT ?""",
|
|
@@ -1301,7 +1319,7 @@ def _backfill_session_metrics(conn, days=None, limit=None):
|
|
|
1301
1319
|
max_gap = parsed.get("max_call_gap_seconds")
|
|
1302
1320
|
p95_gap = parsed.get("p95_call_gap_seconds")
|
|
1303
1321
|
sq = _measure_facade.score_session_quality(parsed)
|
|
1304
|
-
q_score = sq["score"]
|
|
1322
|
+
q_score = sq["score"] if sq.get("measured") else None
|
|
1305
1323
|
q_grade = sq["grade"]
|
|
1306
1324
|
updates.append((ttl_1h, ttl_5m, avg_gap, max_gap, p95_gap, q_score, q_grade, str(jsonl_path)))
|
|
1307
1325
|
|