@alexgreensh/token-optimizer 5.13.73 → 5.13.75
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 -8
- package/hooks/sessionstart_runner.py +25 -0
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +20 -7
- package/skills/token-optimizer/assets/savings_story.js +10 -6
- package/skills/token-optimizer/references/cli-reference.md +9 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -2
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +3 -1
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +2 -79
- package/skills/token-optimizer/scripts/_measure/cli.py +24 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +77 -15
- package/skills/token-optimizer/scripts/_measure/install_baseline.py +157 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +16 -3
- package/skills/token-optimizer/scripts/_measure/mod_action_diagnostics.py +24 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_selftest.py +33 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +4 -4
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +2 -2
- package/skills/token-optimizer/scripts/_measure/nudge_followthrough.py +334 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +3 -0
- package/skills/token-optimizer/scripts/_measure/pilot_report.py +349 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +15 -414
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +5 -10
- package/skills/token-optimizer/scripts/_measure/routing_credit.py +60 -0
- package/skills/token-optimizer/scripts/_measure/routing_default.py +374 -0
- package/skills/token-optimizer/scripts/_measure/routing_savings.py +368 -0
- package/skills/token-optimizer/scripts/_measure/runway_all_in.py +42 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +33 -247
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_activity.py +128 -0
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +59 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -4
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -10
- package/skills/token-optimizer/scripts/hermes_doctor.py +1 -10
- package/skills/token-optimizer/scripts/hermes_install.py +1 -10
- package/skills/token-optimizer/scripts/injection.py +5 -2
- package/skills/token-optimizer/scripts/measure.py +4 -4
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
2
|
from __future__ import annotations
|
|
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
|
|
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
|
|
4
4
|
|
|
5
5
|
def _counted_event_utc(ts):
|
|
6
6
|
"""Convert local event timestamps to UTC, respecting local DST."""
|
|
@@ -1297,7 +1297,7 @@ def _net_realized_savings(rows, reprice_deltas):
|
|
|
1297
1297
|
# a counterfactual (file not read within the follow-up window).
|
|
1298
1298
|
for name in ("setup_optimization", "mcp_cap", "hint_followed", "verbosity_steer",
|
|
1299
1299
|
"resume_lean", "checkpoint_restore", "verbosity_steer_measured",
|
|
1300
|
-
"codemap_lookup", "keepwarm_estimated"):
|
|
1300
|
+
"codemap_lookup", "keepwarm_estimated", "nudge_followed"):
|
|
1301
1301
|
entry = popped[name] = by_category.pop(name, None)
|
|
1302
1302
|
if entry:
|
|
1303
1303
|
total_tokens -= int(entry.get("tokens_saved", 0) or 0)
|
|
@@ -1350,14 +1350,12 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1350
1350
|
boundary (e.g. the subscription limit reset). When *since* is None / empty,
|
|
1351
1351
|
the rolling cutoff is computed from *days* as before.
|
|
1352
1352
|
"""
|
|
1353
|
-
_measure_facade = _compat.facade(); from . import keepwarm_economics, mod_fresh_booking, mod_compaction_booking
|
|
1353
|
+
_measure_facade = _compat.facade(); from . import keepwarm_economics, mod_fresh_booking, mod_compaction_booking, nudge_followthrough
|
|
1354
1354
|
try:
|
|
1355
1355
|
conn = _measure_facade._init_trends_db()
|
|
1356
1356
|
try:
|
|
1357
|
-
if since
|
|
1358
|
-
|
|
1359
|
-
else:
|
|
1360
|
-
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
1357
|
+
import sqlite3; nudge_followthrough.resolve(_measure_facade, conn) if isinstance(conn, sqlite3.Connection) else None; cutoff = since
|
|
1358
|
+
if not since: cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
1361
1359
|
table = _measure_facade._counted_table(conn, "savings_events")
|
|
1362
1360
|
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"
|
|
1363
1361
|
rows = conn.execute(
|
|
@@ -1370,7 +1368,7 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1370
1368
|
# _session_model_reprice.
|
|
1371
1369
|
unpriced_reprice = {}
|
|
1372
1370
|
reprice_deltas, repriced_tokens, unmeasured_tokens = _measure_facade._session_model_reprice(
|
|
1373
|
-
conn, cutoff, unpriced_out=unpriced_reprice)
|
|
1371
|
+
conn, cutoff, unpriced_out=unpriced_reprice); reprice_deltas.pop("nudge_followed", None)
|
|
1374
1372
|
tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
|
|
1375
1373
|
resume_fix = _measure_facade._counted_pricing_v5.resume_lean_reprice(conn, _measure_facade._counted_table(conn, "savings_events"), cutoff,
|
|
1376
1374
|
lambda model: _measure_facade._counted_exact_card(model, tier_data))
|
|
@@ -1404,7 +1402,7 @@ def _get_savings_summary(days=None, since=None):
|
|
|
1404
1402
|
"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),
|
|
1405
1403
|
# U-G: observed-trigger / estimated-magnitude avoided-search from
|
|
1406
1404
|
# proactive hints. Estimated tier, never in the realized total.
|
|
1407
|
-
"hint_followed_estimated": hint_followed_est,
|
|
1405
|
+
"hint_followed_estimated": hint_followed_est, "nudge_followed": popped["nudge_followed"],
|
|
1408
1406
|
# Code map lookups: observed lookup, counterfactual avoided read. Estimated tier.
|
|
1409
1407
|
"codemap_lookup_estimated": codemap_lookup_est,
|
|
1410
1408
|
# Verbosity-steer: estimated output-token reduction from conciseness
|
|
@@ -2299,6 +2297,9 @@ def runway_snapshot(days=None, now=None, token_headline=None):
|
|
|
2299
2297
|
token_parts = token_headline
|
|
2300
2298
|
except Exception:
|
|
2301
2299
|
token_parts = _compat.facade()._headline.token_headline({})
|
|
2300
|
+
from . import runway_all_in; conn = _measure_facade._init_trends_db()
|
|
2301
|
+
try: direct_pct = runway_all_in.safe_extra_work(_measure_facade, conn, days)
|
|
2302
|
+
finally: conn.close()
|
|
2302
2303
|
context_saved = token_parts["total_tokens"]
|
|
2303
2304
|
context_mult = (consumed + context_saved) / consumed if consumed > 0 else 1.0
|
|
2304
2305
|
|
|
@@ -2308,12 +2309,9 @@ def runway_snapshot(days=None, now=None, token_headline=None):
|
|
|
2308
2309
|
routing_state = routing.get("state")
|
|
2309
2310
|
routing_mult = routing.get("factor")
|
|
2310
2311
|
|
|
2311
|
-
# A heavier model mix is the user's choice, not a cost Token Optimizer
|
|
2312
|
-
# caused, so it never shrinks what TO hands back (or hides the card).
|
|
2313
|
-
# The raw factor is still reported as routing_multiplier below.
|
|
2314
2312
|
mult = context_mult * max(1.0, routing_mult if routing_mult is not None else 1.0)
|
|
2315
2313
|
# Hide immaterial changes unless weekly savings are available.
|
|
2316
|
-
if mult < 1.02 and not weekly_signal:
|
|
2314
|
+
if mult + (direct_pct or 0) / 100 < 1.02 and not weekly_signal:
|
|
2317
2315
|
return None
|
|
2318
2316
|
|
|
2319
2317
|
# --- USD-per-window: API-credit OVERAGE over each window's OWN real span ---
|
|
@@ -2559,7 +2557,7 @@ def runway_snapshot(days=None, now=None, token_headline=None):
|
|
|
2559
2557
|
"routing_unsplit_tokens": routing.get("unsplit_tokens", 0),
|
|
2560
2558
|
"routing_standardized_baseline_cost_usd": routing.get("standardized_baseline_cost_usd"),
|
|
2561
2559
|
"routing_standardized_actual_cost_usd": routing.get("standardized_actual_cost_usd"),
|
|
2562
|
-
"extra_work_pct": round((mult - 1) * 100, 1),
|
|
2560
|
+
"extra_work_pct": round((mult - 1) * 100 + (direct_pct or 0), 1), "estimated_work_pct": round(direct_pct or 0, 1),
|
|
2563
2561
|
"tokens_consumed": int(consumed),
|
|
2564
2562
|
"tokens_consumed_basis": traffic["basis"] if traffic else None,
|
|
2565
2563
|
"tokens_consumed_basis_complete": bool(traffic and traffic["complete"]),
|
|
@@ -3509,99 +3507,7 @@ def _compute_baseline_state():
|
|
|
3509
3507
|
opus_share, opus_share_source, window {start,end,sessions_used,sessions_total,
|
|
3510
3508
|
elapsed}, method, winsor_pct, structural_overhead_tokens, source}.
|
|
3511
3509
|
"""
|
|
3512
|
-
|
|
3513
|
-
try:
|
|
3514
|
-
if not _measure_facade.TRENDS_DB.exists():
|
|
3515
|
-
return None
|
|
3516
|
-
conn = _measure_facade._init_trends_db()
|
|
3517
|
-
_measure_facade.ensure_activity_view(conn)
|
|
3518
|
-
try:
|
|
3519
|
-
rows = conn.execute(
|
|
3520
|
-
"SELECT date, id, input_tokens, output_tokens, cache_create_5m_tokens, "
|
|
3521
|
-
"cache_create_1h_tokens, cache_hit_rate FROM session_activity "
|
|
3522
|
-
# Human sessions only -- the baseline anchor must count the same population
|
|
3523
|
-
# as _baseline_progress (the "ready" signal) and _mix_from_session_rows, so
|
|
3524
|
-
# heavy sidechain/subagent volume can't inflate the frozen typical-session
|
|
3525
|
-
# vector or qualify the window before the human-session count is actually met.
|
|
3526
|
-
# Quality filter REMOVED (audit 2026-08-29): the filter inflated the
|
|
3527
|
-
# frozen anchor by 69% on the real ledger (mean input 28.4M filtered vs
|
|
3528
|
-
# 16.8M all). The winsorization already trims outliers; the filter was a
|
|
3529
|
-
# second population-shrinking gate that hid the real session-count collapse.
|
|
3530
|
-
"WHERE input_tokens IS NOT NULL AND COALESCE(is_sidechain, 0) = 0 "
|
|
3531
|
-
"ORDER BY date, id"
|
|
3532
|
-
).fetchall()
|
|
3533
|
-
finally:
|
|
3534
|
-
conn.close()
|
|
3535
|
-
if not rows:
|
|
3536
|
-
return None
|
|
3537
|
-
first = _measure_facade.datetime.fromisoformat(str(rows[0][0])[:10])
|
|
3538
|
-
win_start = first + _measure_facade.timedelta(days=_measure_facade._BASELINE_ONBOARDING_DAYS)
|
|
3539
|
-
win_end = win_start + _measure_facade.timedelta(days=_measure_facade._BASELINE_EARLY_WINDOW_DAYS)
|
|
3540
|
-
vectors = {}
|
|
3541
|
-
for row in rows:
|
|
3542
|
-
if not win_start <= _measure_facade.datetime.fromisoformat(str(row[0])[:10]) < win_end:
|
|
3543
|
-
continue
|
|
3544
|
-
acc = vectors.setdefault(row[1], [0.0] * 5)
|
|
3545
|
-
for index in range(4):
|
|
3546
|
-
acc[index] += row[index + 2] or 0
|
|
3547
|
-
acc[4] += (row[2] or 0) * (row[6] or 0)
|
|
3548
|
-
window_rows = [(*v[:4], v[4] / v[0] if v[0] else 0.0) for v in vectors.values()]
|
|
3549
|
-
if len(window_rows) < _measure_facade._BASELINE_MIN_STABLE_SESSIONS:
|
|
3550
|
-
return None
|
|
3551
|
-
vec, used, total = _measure_facade._winsorized_mean_session(window_rows)
|
|
3552
|
-
# Guard against a corrupt DB row poisoning the frozen anchor with a non-finite
|
|
3553
|
-
# value (json would persist `Infinity`, then int() raises later). Bail to None.
|
|
3554
|
-
if not all(_measure_facade.math.isfinite(x) for x in vec):
|
|
3555
|
-
return None
|
|
3556
|
-
|
|
3557
|
-
# Pre-TO Opus share: explicit per-user baseline if set, else the earliest measured
|
|
3558
|
-
# mix over the SAME window as the token vector (aligned so the blend is honest;
|
|
3559
|
-
# a 14-day mix on a 30-day vector would overstate if the user routed off Opus in
|
|
3560
|
-
# weeks 3-4).
|
|
3561
|
-
baseline = _measure_facade._pretool_baseline_mix()
|
|
3562
|
-
if baseline:
|
|
3563
|
-
model_shares = dict(baseline) # {"opus": x, "sonnet": 1-x}
|
|
3564
|
-
opus_share = float(baseline.get("opus", 0.0))
|
|
3565
|
-
opus_source = "pretool_baseline"
|
|
3566
|
-
else:
|
|
3567
|
-
early = _measure_facade._earliest_model_mix(lookback_days=_measure_facade._BASELINE_EARLY_WINDOW_DAYS)
|
|
3568
|
-
model_shares = dict((early.get("shares") or {})) if early else {}
|
|
3569
|
-
opus_share = float(model_shares.get("opus", 0.0))
|
|
3570
|
-
opus_source = "robust_earliest"
|
|
3571
|
-
|
|
3572
|
-
struct_overhead = 0
|
|
3573
|
-
try:
|
|
3574
|
-
snap = _measure_facade.SNAPSHOT_DIR / "snapshot_before.json"
|
|
3575
|
-
if snap.exists():
|
|
3576
|
-
struct_overhead = int(
|
|
3577
|
-
_measure_facade.json.loads(snap.read_text(encoding="utf-8"))
|
|
3578
|
-
.get("totals", {}).get("estimated_total", 0) or 0
|
|
3579
|
-
)
|
|
3580
|
-
except (_measure_facade.json.JSONDecodeError, OSError, ValueError, TypeError):
|
|
3581
|
-
struct_overhead = 0
|
|
3582
|
-
|
|
3583
|
-
return {
|
|
3584
|
-
"version": _measure_facade._BASELINE_VERSION,
|
|
3585
|
-
"activity_basis": 1,
|
|
3586
|
-
"typical_session": {
|
|
3587
|
-
"fresh_input": round(vec[0], 1), "cache_write": round(vec[1], 1),
|
|
3588
|
-
"cache_read": round(vec[2], 1), "output": round(vec[3], 1),
|
|
3589
|
-
},
|
|
3590
|
-
"opus_share": round(opus_share, 4),
|
|
3591
|
-
"opus_share_source": opus_source,
|
|
3592
|
-
"model_shares": {k: round(float(v), 4) for k, v in model_shares.items() if v},
|
|
3593
|
-
"window": {
|
|
3594
|
-
"start": win_start.strftime("%Y-%m-%d"),
|
|
3595
|
-
"end": win_end.strftime("%Y-%m-%d"),
|
|
3596
|
-
"sessions_used": used, "sessions_total": total,
|
|
3597
|
-
"elapsed": _measure_facade.datetime.now() >= win_end,
|
|
3598
|
-
},
|
|
3599
|
-
"method": "winsorized_mean",
|
|
3600
|
-
"winsor_pct": _measure_facade._BASELINE_WINSOR_PCT,
|
|
3601
|
-
"structural_overhead_tokens": struct_overhead,
|
|
3602
|
-
}
|
|
3603
|
-
except (_measure_facade.sqlite3.Error, OSError, ValueError, TypeError, OverflowError):
|
|
3604
|
-
return None
|
|
3510
|
+
return install_baseline.compute()
|
|
3605
3511
|
|
|
3606
3512
|
|
|
3607
3513
|
def _write_baseline_state(path, data):
|
|
@@ -3688,13 +3594,13 @@ def _migrate_baseline(data):
|
|
|
3688
3594
|
v = data.get("version")
|
|
3689
3595
|
if v == _measure_facade._BASELINE_VERSION:
|
|
3690
3596
|
return dict(data)
|
|
3691
|
-
if v
|
|
3597
|
+
if v in (3, 4):
|
|
3692
3598
|
# v3 -> v4 added `structural_overhead_tokens`. Absent means "not measured
|
|
3693
3599
|
# at capture time", which is 0 contribution, NOT a smaller baseline.
|
|
3694
3600
|
out = dict(data)
|
|
3695
3601
|
out.setdefault("structural_overhead_tokens", 0)
|
|
3696
3602
|
out["version"] = _measure_facade._BASELINE_VERSION
|
|
3697
|
-
out["migrated_from_version"] =
|
|
3603
|
+
out["migrated_from_version"] = v
|
|
3698
3604
|
return out
|
|
3699
3605
|
return None
|
|
3700
3606
|
|
|
@@ -3833,104 +3739,7 @@ def _get_baseline_state(freeze=None):
|
|
|
3833
3739
|
then returns the live computation (or None), so a new user sees no transformation
|
|
3834
3740
|
until a real, stable anchor exists. Never raises.
|
|
3835
3741
|
"""
|
|
3836
|
-
|
|
3837
|
-
bpath = _measure_facade.SNAPSHOT_DIR / "baseline_state.json"
|
|
3838
|
-
incumbent = None
|
|
3839
|
-
try:
|
|
3840
|
-
if bpath.exists():
|
|
3841
|
-
data = _measure_facade.json.loads(bpath.read_text(encoding="utf-8"))
|
|
3842
|
-
if (isinstance(data, dict) and data.get("typical_session")
|
|
3843
|
-
and data.get("version") == _measure_facade._BASELINE_VERSION and data.get("activity_basis") == 1):
|
|
3844
|
-
return data
|
|
3845
|
-
# Never unlink. The old code deleted a mismatched baseline and
|
|
3846
|
-
# re-captured, so a single bump of _BASELINE_VERSION would destroy EVERY
|
|
3847
|
-
# user's only record of their pre-TO cost, on our release schedule, with
|
|
3848
|
-
# no way back. Migrate forward when we can; otherwise RETAIN the file
|
|
3849
|
-
# under a versioned name so it stays recoverable and can still act as
|
|
3850
|
-
# the incumbent for the shrink guard below.
|
|
3851
|
-
if isinstance(data, dict):
|
|
3852
|
-
migrated = _measure_facade._migrate_baseline(data) if data.get("activity_basis") == 1 else None
|
|
3853
|
-
if migrated is not None and _measure_facade._baseline_is_well_formed(migrated):
|
|
3854
|
-
try:
|
|
3855
|
-
_measure_facade._write_baseline_state(bpath, migrated)
|
|
3856
|
-
except OSError:
|
|
3857
|
-
pass
|
|
3858
|
-
return migrated
|
|
3859
|
-
if _measure_facade._baseline_is_well_formed(data) and data.get("activity_basis") == 1:
|
|
3860
|
-
incumbent = data
|
|
3861
|
-
try:
|
|
3862
|
-
retained = bpath.with_name(
|
|
3863
|
-
f"baseline_state.v{data.get('version', 'unknown')}.json")
|
|
3864
|
-
if not retained.exists():
|
|
3865
|
-
_measure_facade.shutil.copy2(str(bpath), str(retained))
|
|
3866
|
-
except (OSError, _measure_facade.shutil.Error):
|
|
3867
|
-
pass
|
|
3868
|
-
except (_measure_facade.json.JSONDecodeError, OSError, ValueError):
|
|
3869
|
-
pass
|
|
3870
|
-
|
|
3871
|
-
# Before re-capturing from scratch, look for an orphaned baseline left
|
|
3872
|
-
# behind by a previous plugin identity. A re-install under a new marketplace id
|
|
3873
|
-
# gets a fresh data dir; the old anchor is stranded, not deleted. Re-capturing
|
|
3874
|
-
# months later reads a thinned history and yields a smaller, wronger anchor.
|
|
3875
|
-
adopted = _measure_facade._adopt_orphaned_baseline()
|
|
3876
|
-
if adopted is not None and adopted.get("activity_basis") == 1:
|
|
3877
|
-
if incumbent is not None and _measure_facade._baseline_shrink_is_material(incumbent, adopted):
|
|
3878
|
-
adopted = None # never adopt DOWNWARD past the guard
|
|
3879
|
-
else:
|
|
3880
|
-
try:
|
|
3881
|
-
_measure_facade._write_baseline_state(bpath, adopted)
|
|
3882
|
-
except OSError:
|
|
3883
|
-
pass
|
|
3884
|
-
return adopted
|
|
3885
|
-
|
|
3886
|
-
state = _measure_facade._compute_baseline_state()
|
|
3887
|
-
if not state:
|
|
3888
|
-
return None
|
|
3889
|
-
|
|
3890
|
-
# Refuse to silently replace a good anchor with a materially smaller one.
|
|
3891
|
-
# A shrinking baseline means the HISTORY thinned, not that the user got cheaper.
|
|
3892
|
-
# Keep the incumbent, park the candidate beside it, and surface it rather than
|
|
3893
|
-
# letting the reported saving quietly collapse.
|
|
3894
|
-
if incumbent is not None and _measure_facade._baseline_shrink_is_material(incumbent, state):
|
|
3895
|
-
try:
|
|
3896
|
-
cand = bpath.with_name("baseline_state.candidate.json")
|
|
3897
|
-
_measure_facade._write_baseline_state(cand, dict(
|
|
3898
|
-
state,
|
|
3899
|
-
rejected_reason="materially smaller than the existing baseline",
|
|
3900
|
-
rejected_at=_measure_facade.datetime.now().isoformat(),
|
|
3901
|
-
incumbent_cost_usd=round(_measure_facade._baseline_priced_cost(incumbent), 4),
|
|
3902
|
-
candidate_cost_usd=round(_measure_facade._baseline_priced_cost(state), 4),
|
|
3903
|
-
))
|
|
3904
|
-
except OSError:
|
|
3905
|
-
pass
|
|
3906
|
-
return incumbent
|
|
3907
|
-
if freeze and (state.get("window") or {}).get("elapsed"):
|
|
3908
|
-
try:
|
|
3909
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
3910
|
-
frozen = dict(state)
|
|
3911
|
-
frozen["captured_at"] = _measure_facade.datetime.now().isoformat()
|
|
3912
|
-
frozen["source"] = "frozen_from_history"
|
|
3913
|
-
# Atomic write: unique temp via mkstemp + os.replace, with try/finally
|
|
3914
|
-
# cleanup so a crash mid-write never leaks a stale temp file (matches the
|
|
3915
|
-
# config-writer pattern used elsewhere in this file).
|
|
3916
|
-
tmp_fd, tmp_path = _measure_facade.tempfile.mkstemp(
|
|
3917
|
-
dir=str(_measure_facade.SNAPSHOT_DIR), prefix=".baseline_state-", suffix=".tmp")
|
|
3918
|
-
try:
|
|
3919
|
-
with _measure_facade.os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
|
|
3920
|
-
_measure_facade.json.dump(frozen, f, indent=2, default=str)
|
|
3921
|
-
_measure_facade.os.chmod(tmp_path, 0o600)
|
|
3922
|
-
_measure_facade.os.replace(tmp_path, str(bpath))
|
|
3923
|
-
tmp_path = None
|
|
3924
|
-
finally:
|
|
3925
|
-
if tmp_path is not None:
|
|
3926
|
-
try:
|
|
3927
|
-
_measure_facade.os.unlink(tmp_path)
|
|
3928
|
-
except OSError:
|
|
3929
|
-
pass
|
|
3930
|
-
return frozen
|
|
3931
|
-
except OSError:
|
|
3932
|
-
return state
|
|
3933
|
-
return state
|
|
3742
|
+
return install_baseline.get(True if freeze is None else freeze)
|
|
3934
3743
|
|
|
3935
3744
|
|
|
3936
3745
|
def _cost_per_session(fi, cw, cr, out, shares, tier):
|
|
@@ -4530,7 +4339,7 @@ def _pinned_workload_anchor():
|
|
|
4530
4339
|
m = data.get("metrics") if isinstance(data, dict) else None
|
|
4531
4340
|
if (data.get("status") == "pinned" and data.get("activity_basis") == 1
|
|
4532
4341
|
and isinstance(m, dict)
|
|
4533
|
-
and data.get("rates") == _measure_facade._WEIGHT_POOL_FLAT_RATES
|
|
4342
|
+
and data.get("rates") == _measure_facade._WEIGHT_POOL_FLAT_RATES and (not _measure_facade._pretool_window() or all(d in str(data.get("label") or "") for d in _measure_facade._pretool_window()))
|
|
4534
4343
|
and all(isinstance(m.get(k), (int, float)) and _measure_facade.math.isfinite(m[k]) and m[k] >= 0
|
|
4535
4344
|
for k in ("sessions", "usd", "tokens", "flat_usd", "api_calls", "messages"))
|
|
4536
4345
|
and m["sessions"] >= _measure_facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
|
|
@@ -4727,7 +4536,8 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
|
|
|
4727
4536
|
).fetchall() if r and r[0]
|
|
4728
4537
|
]
|
|
4729
4538
|
pinned = _measure_facade._pinned_workload_anchor()
|
|
4730
|
-
|
|
4539
|
+
pinned = pinned or install_baseline.workload_anchor(_measure_facade, conn, tier)
|
|
4540
|
+
if not pinned and (len(months) < 2 or install_baseline.has_install_anchor(_measure_facade)):
|
|
4731
4541
|
return None
|
|
4732
4542
|
first_day = conn.execute(
|
|
4733
4543
|
"SELECT MIN(date) FROM session_activity WHERE input_tokens IS NOT NULL "
|
|
@@ -5137,33 +4947,12 @@ def _estimate_before_after_savings(days=None, estimated_pools=None, model_routin
|
|
|
5137
4947
|
# Anthropic runtime; with none, the current mix. A frozen share is trusted as-is;
|
|
5138
4948
|
# a non-Anthropic user is priced at their own measured mix, never fabricated Opus.
|
|
5139
4949
|
anthropic = _measure_facade.detect_runtime() not in {"codex", "hermes", "copilot", "opencode", "cursor", "antigravity", "grok"}
|
|
5140
|
-
|
|
5141
|
-
|
|
5142
|
-
|
|
5143
|
-
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
# Opus against an after arm priced at the user's real non-Anthropic
|
|
5147
|
-
# mix, fabricating a routing lever that never existed and OVERSTATING
|
|
5148
|
-
# savings. Such a user falls through to before_shares = after_shares,
|
|
5149
|
-
# which zeroes the routing lever instead of inventing one.
|
|
5150
|
-
baseline_opus_share = frozen_opus
|
|
5151
|
-
before_shares = {"opus": baseline_opus_share,
|
|
5152
|
-
"sonnet": round(1.0 - baseline_opus_share, 4)}
|
|
5153
|
-
elif anthropic:
|
|
5154
|
-
# Anthropic user with no MEASURED baseline. The pre-Token-Optimizer model
|
|
5155
|
-
# mix is not knowable here, and a mix we cannot measure is a mix we do not
|
|
5156
|
-
# claim: any assumed Opus share would directly scale the routing lever and
|
|
5157
|
-
# inflate the _compat.facade()._headline. Price the before-arm at the user's real current mix
|
|
5158
|
-
# so the routing lever is exactly zero until a baseline is measured.
|
|
5159
|
-
baseline_opus_share = float(after_shares.get("opus", 0.0))
|
|
5160
|
-
before_shares = dict(after_shares)
|
|
5161
|
-
else:
|
|
5162
|
-
# Non-Anthropic (Codex/Hermes/Copilot/OpenCode) with no baseline -> price the
|
|
5163
|
-
# before-arm at the user's real current mix. Never inject Opus they never used;
|
|
5164
|
-
# with no routing lever the transformation falls to the caching lever alone.
|
|
5165
|
-
baseline_opus_share = float(after_shares.get("opus", 0.0))
|
|
5166
|
-
before_shares = dict(after_shares)
|
|
4950
|
+
# Older baseline files carry only opus_share (no model_shares); keep honoring it.
|
|
4951
|
+
legacy_shares = ({"opus": frozen_opus, "sonnet": round(1.0 - frozen_opus, 4)}
|
|
4952
|
+
if frozen_opus > 0 else None)
|
|
4953
|
+
before_shares = dict((baseline.get("model_shares") or legacy_shares if anthropic else None)
|
|
4954
|
+
or after_shares)
|
|
4955
|
+
baseline_opus_share = float(before_shares.get("opus", 0.0))
|
|
5167
4956
|
# Baseline cache-hit pattern, defined over the FRESH+CACHE_READ POOL only (cache
|
|
5168
4957
|
# write excluded). C1/C2: the counterfactual redistributes caching over the pool,
|
|
5169
4958
|
# not over total_in (which includes CW); a total_in-based hit prices MORE volume on
|
|
@@ -6108,6 +5897,7 @@ def _action_savings_components(summary, reread=None):
|
|
|
6108
5897
|
"checkpoint_restore_estimated", "verbosity_steer", "verbosity_output_estimated", "structural_estimated", "keepwarm_estimated",
|
|
6109
5898
|
)
|
|
6110
5899
|
}
|
|
5900
|
+
if summary.get("nudge_followed") is not None: estimates["nudge_followed"] = float((summary.get("nudge_followed") or {}).get("cost_saved_usd", 0) or 0)
|
|
6111
5901
|
overhead = ((summary.get("session_effect") or {}).get("overhead") or {}); estimates["mod_fresh_estimated"] = mod_fresh_booking.additive(summary.get("mod_fresh_estimated"), summary.get("handover_rerun"))
|
|
6112
5902
|
estimates["expand_overhead"] = -max(0.0, float(overhead.get("expand_usd") or 0))
|
|
6113
5903
|
hints = summary.get("hint_followed") or {}
|
|
@@ -6165,6 +5955,7 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6165
5955
|
wins — compression_events rows are skipped for that key.
|
|
6166
5956
|
"""
|
|
6167
5957
|
_measure_facade = _compat.facade()
|
|
5958
|
+
since = since or savings_story.install_anchor()
|
|
6168
5959
|
savings = _measure_facade._get_savings_summary(days=days, since=since)
|
|
6169
5960
|
compression = _measure_facade._get_compression_summary(days=days, since=since)
|
|
6170
5961
|
|
|
@@ -6298,7 +6089,7 @@ def _get_merged_savings(days=None, since=None):
|
|
|
6298
6089
|
"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"),
|
|
6299
6090
|
# U-G: deterministically-triggered avoided-search from proactive hints
|
|
6300
6091
|
# (observed hint->read), estimated magnitude. Estimated tier, never realized.
|
|
6301
|
-
"hint_followed": savings.get("hint_followed_estimated"),
|
|
6092
|
+
"hint_followed": savings.get("hint_followed_estimated"), "nudge_followed": savings.get("nudge_followed"),
|
|
6302
6093
|
# Verbosity-steer: estimated output-token reduction from conciseness
|
|
6303
6094
|
# nudges. Estimated tier, never in the realized total. Surfaced for
|
|
6304
6095
|
# the dashboard's estimated-tier display.
|
|
@@ -6339,21 +6130,16 @@ def _savings_since_install():
|
|
|
6339
6130
|
return None
|
|
6340
6131
|
days = (_measure_facade.datetime.now() - _measure_facade.datetime.fromisoformat(d)).days + 1
|
|
6341
6132
|
days = max(1, min(days, 3650))
|
|
6342
|
-
full = savings_story.since_install_summary(_measure_facade._get_merged_savings, days)
|
|
6133
|
+
full = savings_story.since_install_summary(_measure_facade._get_merged_savings, days, since=d)
|
|
6343
6134
|
try:
|
|
6344
6135
|
from . import session_effect
|
|
6345
6136
|
full["session_effect"] = session_effect.summary(days)
|
|
6346
6137
|
except Exception:
|
|
6347
6138
|
full["session_effect"] = {}
|
|
6348
|
-
# Measured = logged runtime + realized structural
|
|
6349
|
-
# assumption and stays out of every savings total.
|
|
6139
|
+
# Measured = logged runtime + realized structural; routing is separate.
|
|
6350
6140
|
measured = float(full.get("total_cost_usd", 0) or 0) - savings_story.verbosity_logged(full)
|
|
6351
6141
|
full_routing = full.get("model_routing") or {}
|
|
6352
|
-
#
|
|
6353
|
-
# (pretool_baseline.json / TOKEN_OPTIMIZER_BASELINE_OPUS_SHARE) wins,
|
|
6354
|
-
# else the model mix measured at install (snapshot or earliest
|
|
6355
|
-
# history). Same pricing either way; no baseline, a non-Anthropic
|
|
6356
|
-
# runtime, or no Opus in the baseline means $0, never invented Opus.
|
|
6142
|
+
# A usable baseline supplies a separate estimated routing contribution.
|
|
6357
6143
|
routing_source = savings_story.routing_baseline_kind(full_routing, _measure_facade.detect_runtime())
|
|
6358
6144
|
stated = routing_source is not None
|
|
6359
6145
|
stated_routing = max(0.0, float(full_routing.get("realized_cost_usd") or 0)) if stated else 0.0
|
|
@@ -6377,7 +6163,7 @@ def _savings_since_install():
|
|
|
6377
6163
|
hf = full.get("hint_followed") or {}
|
|
6378
6164
|
rs = full.get("retrieval_serve") or {}
|
|
6379
6165
|
avoided = hf if int(hf.get("events") or 0) > 0 else rs
|
|
6380
|
-
estimated += float(avoided.get("cost_saved_usd", 0) or 0) + float(((full.get("structural_detail") or {}).get("estimated") or {}).get("cost_saved_usd") or 0)
|
|
6166
|
+
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) - max(0.0, float(((full.get("session_effect") or {}).get("overhead") or {}).get("expand_usd") or 0))
|
|
6381
6167
|
# The all-in since install uses the monthly headline's own recipe
|
|
6382
6168
|
# (logged + repeat reads + estimates); routing stays out of both.
|
|
6383
6169
|
all_in = None
|
|
@@ -6418,7 +6204,7 @@ def _savings_since_install():
|
|
|
6418
6204
|
"excluded_usd": dict(savings_story.excluded_since_install(full), routing=None) if stated else savings_story.excluded_since_install(full),
|
|
6419
6205
|
"measured_usd": round(measured, 2),
|
|
6420
6206
|
"estimated_usd": round(estimated, 2),
|
|
6421
|
-
"total_usd": round(measured + estimated, 2),
|
|
6207
|
+
"total_usd": all_in["total_usd"] if all_in is not None else round(measured + estimated, 2),
|
|
6422
6208
|
"all_in": all_in,
|
|
6423
6209
|
# measured_usd is no longer a pure event-time meter once the
|
|
6424
6210
|
# model-mix repair has moved a rate (see _session_model_reprice), so
|
|
@@ -2,20 +2,27 @@
|
|
|
2
2
|
from contextvars import ContextVar
|
|
3
3
|
|
|
4
4
|
_SKIP_COMPARISON = ContextVar('skip_since_install_comparison', default=False)
|
|
5
|
+
_INSTALL_ANCHOR = ContextVar('since_install_anchor', default=None)
|
|
5
6
|
|
|
6
7
|
|
|
7
|
-
def since_install_summary(builder, days):
|
|
8
|
+
def since_install_summary(builder, days, since=None):
|
|
8
9
|
"""Skip an expensive comparison that the since-install card never reads."""
|
|
9
10
|
token = _SKIP_COMPARISON.set(True)
|
|
11
|
+
anchor_token = _INSTALL_ANCHOR.set(since)
|
|
10
12
|
try:
|
|
11
13
|
return builder(days=days)
|
|
12
14
|
finally:
|
|
15
|
+
_INSTALL_ANCHOR.reset(anchor_token)
|
|
13
16
|
_SKIP_COMPARISON.reset(token)
|
|
14
17
|
|
|
15
18
|
|
|
16
19
|
def skip_comparison():
|
|
17
20
|
return _SKIP_COMPARISON.get()
|
|
18
21
|
|
|
22
|
+
|
|
23
|
+
def install_anchor():
|
|
24
|
+
return _INSTALL_ANCHOR.get()
|
|
25
|
+
|
|
19
26
|
def _number(value):
|
|
20
27
|
try:
|
|
21
28
|
return int(float(value or 0))
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Live-session activity from Claude Code's ``sessions/<pid>.json`` records.
|
|
2
|
+
|
|
3
|
+
Process age cannot tell a busy orchestrator apart from an abandoned one;
|
|
4
|
+
the record's ``status`` and timestamps can. Claude Code writes one JSON
|
|
5
|
+
record per live session under ``$CLAUDE_CONFIG_DIR/sessions/`` (default
|
|
6
|
+
``~/.claude/sessions/``) and the transcript under
|
|
7
|
+
``projects/<encoded-cwd>/<sessionId>.jsonl``.
|
|
8
|
+
|
|
9
|
+
Everything fails open: a missing or unreadable record returns
|
|
10
|
+
``source="none"`` so callers keep their elapsed-time behavior.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
# Process start (ps elapsed, whole seconds) vs the record startedAt.
|
|
21
|
+
START_TOLERANCE_SECONDS = 10
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _config_dir(config_dir=None):
|
|
25
|
+
"""Claude Code's config dir: explicit override, else claude_home() ($CLAUDE_CONFIG_DIR or ~/.claude)."""
|
|
26
|
+
if config_dir is not None:
|
|
27
|
+
return Path(config_dir)
|
|
28
|
+
from runtime_env import claude_home
|
|
29
|
+
return claude_home()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ms(value):
|
|
33
|
+
"""Epoch-milliseconds field to epoch seconds, or None."""
|
|
34
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
35
|
+
return None
|
|
36
|
+
try:
|
|
37
|
+
return float(value) / 1000.0
|
|
38
|
+
except (OverflowError, ValueError):
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _project_dir_name(cwd):
|
|
43
|
+
"""Claude Code's projects/ encoding: every non-alphanumeric character becomes '-'."""
|
|
44
|
+
return re.sub(r"[^A-Za-z0-9]", "-", cwd)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _transcript_mtime(config_dir, record):
|
|
48
|
+
"""mtime of the session's transcript JSONL, or None when it cannot be located."""
|
|
49
|
+
session_id = record.get("sessionId")
|
|
50
|
+
cwd = record.get("cwd")
|
|
51
|
+
if not (isinstance(session_id, str) and session_id
|
|
52
|
+
and isinstance(cwd, str) and cwd):
|
|
53
|
+
return None
|
|
54
|
+
path = Path(config_dir) / "projects" / _project_dir_name(cwd) / f"{session_id}.jsonl"
|
|
55
|
+
try:
|
|
56
|
+
return path.stat().st_mtime
|
|
57
|
+
except OSError:
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def activity(pid, now=None, config_dir=None, elapsed_seconds=None):
|
|
62
|
+
"""Activity snapshot for one live session pid.
|
|
63
|
+
|
|
64
|
+
Returns ``{"status", "last_active_ts", "idle_seconds", "tmux", "source"}``:
|
|
65
|
+
``status`` is the record's busy/idle (None when unknown),
|
|
66
|
+
``last_active_ts`` the newest of ``statusUpdatedAt``/``updatedAt`` and the
|
|
67
|
+
transcript mtime in epoch seconds (None when unknowable),
|
|
68
|
+
``idle_seconds`` ``now - last_active_ts`` clamped at 0 (None when
|
|
69
|
+
unknowable), ``tmux`` the orchestrator's tmux target when the record has
|
|
70
|
+
one, and ``source`` "record" or "none".
|
|
71
|
+
"""
|
|
72
|
+
if now is None:
|
|
73
|
+
now = time.time()
|
|
74
|
+
def _none(reason):
|
|
75
|
+
return {"status": None, "last_active_ts": None, "idle_seconds": None,
|
|
76
|
+
"tmux": None, "source": "none", "reason": reason, "verified": False}
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
base = _config_dir(config_dir)
|
|
80
|
+
path = base / "sessions" / f"{pid}.json"
|
|
81
|
+
except Exception:
|
|
82
|
+
# Resolve again with plain strings. "missing" (old behavior allowed)
|
|
83
|
+
# only when that proves no record exists; any doubt is "unresolved",
|
|
84
|
+
# which kill-stale never acts on.
|
|
85
|
+
try:
|
|
86
|
+
root = str(config_dir) if config_dir is not None else (
|
|
87
|
+
os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join(os.path.expanduser("~"), ".claude"))
|
|
88
|
+
if os.path.exists(os.path.join(root, "sessions", f"{pid}.json")):
|
|
89
|
+
return _none("unreadable")
|
|
90
|
+
return _none("missing")
|
|
91
|
+
except Exception:
|
|
92
|
+
return _none("unresolved")
|
|
93
|
+
if not path.exists():
|
|
94
|
+
return _none("missing")
|
|
95
|
+
try:
|
|
96
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
97
|
+
except (OSError, ValueError):
|
|
98
|
+
return _none("unreadable")
|
|
99
|
+
if not isinstance(record, dict):
|
|
100
|
+
return _none("unreadable")
|
|
101
|
+
# A record left by a dead session whose pid was reused describes another
|
|
102
|
+
# process: it counts only when its pid and start time match the live one.
|
|
103
|
+
if record.get("pid") not in (None, pid):
|
|
104
|
+
return _none("pid_mismatch")
|
|
105
|
+
started = _ms(record.get("startedAt"))
|
|
106
|
+
lifetime = float(elapsed_seconds) if isinstance(elapsed_seconds, (int, float)) and elapsed_seconds >= 0 else None
|
|
107
|
+
if started is not None and lifetime is not None and abs((now - lifetime) - started) > START_TOLERANCE_SECONDS:
|
|
108
|
+
return _none("start_mismatch")
|
|
109
|
+
verified = record.get("pid") == pid and started is not None and lifetime is not None
|
|
110
|
+
|
|
111
|
+
stamps = [ts for ts in (_ms(record.get("statusUpdatedAt")),
|
|
112
|
+
_ms(record.get("updatedAt")),
|
|
113
|
+
_transcript_mtime(base, record)) if ts is not None]
|
|
114
|
+
last_active = max(stamps) if stamps else None
|
|
115
|
+
idle = max(0.0, now - last_active) if last_active is not None else None
|
|
116
|
+
if idle is not None and lifetime is not None:
|
|
117
|
+
idle = min(idle, lifetime) # never idle longer than the process has lived
|
|
118
|
+
status = record.get("status")
|
|
119
|
+
tmux = record.get("tmux")
|
|
120
|
+
return {
|
|
121
|
+
"status": status if status in ("busy", "idle") else None,
|
|
122
|
+
"last_active_ts": last_active,
|
|
123
|
+
"idle_seconds": int(idle) if idle is not None else None,
|
|
124
|
+
"tmux": tmux if isinstance(tmux, str) and tmux else None,
|
|
125
|
+
"source": "record",
|
|
126
|
+
"reason": "ok",
|
|
127
|
+
"verified": verified,
|
|
128
|
+
}
|
|
@@ -4,3 +4,62 @@
|
|
|
4
4
|
def base_trends(facade, days):
|
|
5
5
|
result = facade._collect_trends_from_db(days)
|
|
6
6
|
return facade._collect_trends_from_jsonl(days) if result is None else result
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def cache_health(f, days, fresh):
|
|
10
|
+
"""Cache each window and runtime without discarding legacy sidecars."""
|
|
11
|
+
path = f.SNAPSHOT_DIR / 'cache_health.json'
|
|
12
|
+
runtime = f.detect_runtime()
|
|
13
|
+
key = f'{days}:{runtime}'
|
|
14
|
+
payload = {}
|
|
15
|
+
try:
|
|
16
|
+
mtime = path.stat().st_mtime
|
|
17
|
+
memo = f._cache_health_memo
|
|
18
|
+
if memo is not None and memo[0] == mtime:
|
|
19
|
+
payload = memo[1]
|
|
20
|
+
else:
|
|
21
|
+
payload = f.json.loads(path.read_text(encoding='utf-8'))
|
|
22
|
+
f._cache_health_memo = (mtime, payload)
|
|
23
|
+
if not isinstance(payload, dict):
|
|
24
|
+
payload = {}
|
|
25
|
+
except (f.json.JSONDecodeError, OSError, ValueError, TypeError, IndexError):
|
|
26
|
+
payload = {}
|
|
27
|
+
|
|
28
|
+
stored = payload.get('entries')
|
|
29
|
+
entries = dict(stored) if isinstance(stored, dict) else {}
|
|
30
|
+
if 'period_days' in payload and 'platform' in payload:
|
|
31
|
+
legacy_key = f"{payload['period_days']}:{payload['platform']}"
|
|
32
|
+
entries.setdefault(legacy_key, {k: v for k, v in payload.items() if k != 'entries'})
|
|
33
|
+
candidate = entries.get(key)
|
|
34
|
+
if not fresh and isinstance(candidate, dict):
|
|
35
|
+
try:
|
|
36
|
+
if (int(candidate.get('period_days', -1)) == int(days)
|
|
37
|
+
and candidate.get('platform') == runtime and candidate.get('engine') == 2
|
|
38
|
+
and f.time.time() - float(candidate.get('_cached_ts', 0)) < f._CACHE_HEALTH_CACHE_TTL_SECONDS):
|
|
39
|
+
return candidate
|
|
40
|
+
except (TypeError, ValueError):
|
|
41
|
+
pass
|
|
42
|
+
result = f._get_cache_ttl_waste(days=days)
|
|
43
|
+
try:
|
|
44
|
+
record = dict(result)
|
|
45
|
+
record['_cached_ts'] = f.time.time()
|
|
46
|
+
entries[key] = record
|
|
47
|
+
sidecar = {**record, 'entries': entries}
|
|
48
|
+
f.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
fd, tmp_name = f.tempfile.mkstemp(prefix='.cache_health.', suffix='.tmp', dir=str(f.SNAPSHOT_DIR))
|
|
50
|
+
try:
|
|
51
|
+
if hasattr(f.os, 'fchmod'):
|
|
52
|
+
f.os.fchmod(fd, 0o600)
|
|
53
|
+
with f.os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
|
54
|
+
f.json.dump(sidecar, stream)
|
|
55
|
+
f.os.replace(tmp_name, str(path))
|
|
56
|
+
f._cache_health_memo = (f.os.stat(path).st_mtime, sidecar)
|
|
57
|
+
except Exception:
|
|
58
|
+
try:
|
|
59
|
+
f.os.unlink(tmp_name)
|
|
60
|
+
except OSError:
|
|
61
|
+
pass
|
|
62
|
+
raise
|
|
63
|
+
except Exception:
|
|
64
|
+
pass
|
|
65
|
+
return result
|