@alexgreensh/token-optimizer 5.13.69 → 5.13.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +729 -767
- package/skills/token-optimizer/assets/savings_story.js +765 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +34 -76
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +144 -30
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
2
|
from __future__ import annotations
|
|
3
|
-
from . import _compat
|
|
3
|
+
from . import _compat, transcript_stream, quality_continuity, upgrade_drain_control
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
def _find_all_jsonl_files(days=None):
|
|
@@ -82,15 +82,10 @@ def _extract_skills_and_agents_from_subagent(filepath):
|
|
|
82
82
|
skills = {}
|
|
83
83
|
subagents = {}
|
|
84
84
|
try:
|
|
85
|
-
|
|
86
|
-
return skills, subagents
|
|
87
|
-
except OSError:
|
|
88
|
-
return skills, subagents
|
|
89
|
-
try:
|
|
90
|
-
with open(filepath, "r", encoding="utf-8", errors="replace") as f:
|
|
85
|
+
with transcript_stream.open_transcript(filepath) as f:
|
|
91
86
|
for line in f:
|
|
92
87
|
if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
|
|
93
|
-
continue
|
|
88
|
+
continue # bounded per-line work, same limit as the Codex adapter
|
|
94
89
|
try:
|
|
95
90
|
record = _measure_facade.json.loads(line)
|
|
96
91
|
except _measure_facade.json.JSONDecodeError:
|
|
@@ -220,16 +215,10 @@ def _extract_costly_prompts(jsonl_path, tier=None, top_n=None):
|
|
|
220
215
|
pending_prompt = None
|
|
221
216
|
|
|
222
217
|
try:
|
|
223
|
-
|
|
224
|
-
return prompts
|
|
225
|
-
except OSError:
|
|
226
|
-
return prompts
|
|
227
|
-
|
|
228
|
-
try:
|
|
229
|
-
with open(jsonl_path, "r", encoding="utf-8", errors="replace") as f:
|
|
218
|
+
with transcript_stream.open_transcript(jsonl_path) as f:
|
|
230
219
|
for line in f:
|
|
231
220
|
if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
|
|
232
|
-
continue
|
|
221
|
+
continue # bounded per-line work, same limit as the Codex adapter
|
|
233
222
|
try:
|
|
234
223
|
record = _measure_facade.json.loads(line)
|
|
235
224
|
except _measure_facade.json.JSONDecodeError:
|
|
@@ -577,8 +566,8 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
|
|
|
577
566
|
_measure_facade = _compat.facade()
|
|
578
567
|
try:
|
|
579
568
|
st = _measure_facade.os.stat(filepath)
|
|
580
|
-
cache_key = (str(filepath), st.st_mtime_ns, st.st_size, window_start, window_end)
|
|
581
|
-
if cache_key in _measure_facade._parse_session_jsonl_cache:
|
|
569
|
+
cache_key = (str(filepath), st.st_mtime_ns, st.st_size, window_start, window_end) if st.st_size <= transcript_stream.LARGE_BYTES else None
|
|
570
|
+
if cache_key in _measure_facade._parse_session_jsonl_cache and not transcript_stream.needs_resume(filepath):
|
|
582
571
|
return _measure_facade._parse_session_jsonl_cache[cache_key]
|
|
583
572
|
except OSError:
|
|
584
573
|
cache_key = None # stat failed — parse without caching
|
|
@@ -625,18 +614,11 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
|
|
|
625
614
|
is_sidechain = sidechain_reason is not None
|
|
626
615
|
first_user_record_seen = False
|
|
627
616
|
|
|
628
|
-
# Bound the work like the Codex adapter's _iter_json_records: a multi-GB
|
|
629
|
-
# transcript or one pathological line must not dominate a parse. st is set
|
|
630
|
-
# when the initial os.stat above succeeded; skip oversized files outright
|
|
631
|
-
# and oversized lines individually.
|
|
632
|
-
if cache_key is not None and st.st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
|
|
633
|
-
return None
|
|
634
|
-
|
|
635
617
|
try:
|
|
636
|
-
with
|
|
618
|
+
with transcript_stream.open_transcript(filepath) as f:
|
|
637
619
|
for line in f:
|
|
638
620
|
if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
|
|
639
|
-
continue
|
|
621
|
+
continue # bounded per-line work, same limit as the Codex adapter
|
|
640
622
|
try:
|
|
641
623
|
record = _measure_facade.json.loads(line)
|
|
642
624
|
except _measure_facade.json.JSONDecodeError:
|
|
@@ -1034,19 +1016,11 @@ def parse_session_turns(filepath):
|
|
|
1034
1016
|
turn_by_key = {}
|
|
1035
1017
|
parts_by_key = {}
|
|
1036
1018
|
|
|
1037
|
-
# Bound the work like the Codex adapter's _iter_json_records (see
|
|
1038
|
-
# _parse_session_jsonl): skip oversized files and oversized lines.
|
|
1039
|
-
try:
|
|
1040
|
-
if _measure_facade.os.stat(filepath).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
|
|
1041
|
-
return turns
|
|
1042
|
-
except OSError:
|
|
1043
|
-
return turns
|
|
1044
|
-
|
|
1045
1019
|
try:
|
|
1046
|
-
with
|
|
1020
|
+
with transcript_stream.open_transcript(filepath) as f:
|
|
1047
1021
|
for line in f:
|
|
1048
1022
|
if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
|
|
1049
|
-
continue
|
|
1023
|
+
continue # bounded per-line work, same limit as the Codex adapter
|
|
1050
1024
|
try:
|
|
1051
1025
|
record = _measure_facade.json.loads(line)
|
|
1052
1026
|
except _measure_facade.json.JSONDecodeError:
|
|
@@ -1126,6 +1100,9 @@ def parse_session_turns(filepath):
|
|
|
1126
1100
|
"gap_since_prev_seconds": gap_since_prev_seconds,
|
|
1127
1101
|
"tools_used": tools,
|
|
1128
1102
|
"cost_usd": round(cost, 6),
|
|
1103
|
+
# Stable across copies of one transcript: cache health
|
|
1104
|
+
# dedupes a synced or copied session by it.
|
|
1105
|
+
"request_id": req_key,
|
|
1129
1106
|
}
|
|
1130
1107
|
ctx_usage = _measure_facade._context_usage(usage)
|
|
1131
1108
|
if ctx_usage is not usage:
|
|
@@ -1182,103 +1159,10 @@ def parse_session_turns(filepath):
|
|
|
1182
1159
|
|
|
1183
1160
|
|
|
1184
1161
|
def score_session_quality(session_data):
|
|
1185
|
-
"""Score
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
- Message count risk (25%)
|
|
1190
|
-
- Cache hit rate (20%)
|
|
1191
|
-
- Output/input ratio (15%)
|
|
1192
|
-
- Compaction events (15%)
|
|
1193
|
-
|
|
1194
|
-
session_data should include: total_input_tokens, total_output_tokens,
|
|
1195
|
-
message_count, cache_hit_rate, api_calls, and optionally total_cache_read.
|
|
1196
|
-
"""
|
|
1197
|
-
_measure_facade = _compat.facade()
|
|
1198
|
-
score = 0.0
|
|
1199
|
-
|
|
1200
|
-
# Signal 1: Context fill (25%)
|
|
1201
|
-
# Lower fill = better (more room for work)
|
|
1202
|
-
context_window = _measure_facade.detect_context_window()[0]
|
|
1203
|
-
total_input = session_data.get("total_input_tokens", 0)
|
|
1204
|
-
fill_ratio = total_input / context_window if context_window > 0 else 0
|
|
1205
|
-
if fill_ratio < 0.3:
|
|
1206
|
-
fill_score = 100
|
|
1207
|
-
elif fill_ratio < 0.5:
|
|
1208
|
-
fill_score = 80
|
|
1209
|
-
elif fill_ratio < 0.7:
|
|
1210
|
-
fill_score = 55
|
|
1211
|
-
elif fill_ratio < 0.85:
|
|
1212
|
-
fill_score = 30
|
|
1213
|
-
else:
|
|
1214
|
-
fill_score = 10
|
|
1215
|
-
score += fill_score * 0.25
|
|
1216
|
-
|
|
1217
|
-
# Signal 2: Message count risk (25%)
|
|
1218
|
-
# More messages = higher risk of quality degradation
|
|
1219
|
-
msg_count = session_data.get("message_count", 0)
|
|
1220
|
-
if msg_count <= 20:
|
|
1221
|
-
msg_score = 100
|
|
1222
|
-
elif msg_count <= 40:
|
|
1223
|
-
msg_score = 80
|
|
1224
|
-
elif msg_count <= 60:
|
|
1225
|
-
msg_score = 55
|
|
1226
|
-
elif msg_count <= 100:
|
|
1227
|
-
msg_score = 30
|
|
1228
|
-
else:
|
|
1229
|
-
msg_score = 10
|
|
1230
|
-
score += msg_score * 0.25
|
|
1231
|
-
|
|
1232
|
-
# Signal 3: Cache hit rate (20%)
|
|
1233
|
-
# Higher cache = better (reusing context efficiently)
|
|
1234
|
-
chr_ = session_data.get("cache_hit_rate", 0)
|
|
1235
|
-
if chr_ >= 0.8:
|
|
1236
|
-
cache_score = 100
|
|
1237
|
-
elif chr_ >= 0.6:
|
|
1238
|
-
cache_score = 80
|
|
1239
|
-
elif chr_ >= 0.4:
|
|
1240
|
-
cache_score = 55
|
|
1241
|
-
elif chr_ >= 0.2:
|
|
1242
|
-
cache_score = 30
|
|
1243
|
-
else:
|
|
1244
|
-
cache_score = 10
|
|
1245
|
-
score += cache_score * 0.20
|
|
1246
|
-
|
|
1247
|
-
# Signal 4: Output/input ratio (15%)
|
|
1248
|
-
# Very low ratio = wasteful (loading lots of context, producing little)
|
|
1249
|
-
total_output = session_data.get("total_output_tokens", 0)
|
|
1250
|
-
if total_input > 0:
|
|
1251
|
-
oi_ratio = total_output / total_input
|
|
1252
|
-
else:
|
|
1253
|
-
oi_ratio = 1.0
|
|
1254
|
-
if oi_ratio >= 0.05:
|
|
1255
|
-
oi_score = 100
|
|
1256
|
-
elif oi_ratio >= 0.02:
|
|
1257
|
-
oi_score = 70
|
|
1258
|
-
elif oi_ratio >= 0.01:
|
|
1259
|
-
oi_score = 40
|
|
1260
|
-
else:
|
|
1261
|
-
oi_score = 15
|
|
1262
|
-
score += oi_score * 0.15
|
|
1263
|
-
|
|
1264
|
-
# Signal 5: API calls vs messages (15%)
|
|
1265
|
-
# Healthy: roughly 1 API call per 2 messages
|
|
1266
|
-
api_calls = session_data.get("api_calls", 0)
|
|
1267
|
-
if msg_count > 0 and api_calls > 0:
|
|
1268
|
-
calls_per_msg = api_calls / msg_count
|
|
1269
|
-
if calls_per_msg <= 0.6:
|
|
1270
|
-
api_score = 100
|
|
1271
|
-
elif calls_per_msg <= 0.8:
|
|
1272
|
-
api_score = 75
|
|
1273
|
-
else:
|
|
1274
|
-
api_score = 50
|
|
1275
|
-
else:
|
|
1276
|
-
api_score = 50
|
|
1277
|
-
score += api_score * 0.15
|
|
1278
|
-
|
|
1279
|
-
final = int(round(min(100, max(0, score))))
|
|
1280
|
-
|
|
1281
|
-
return {"score": final, "band": _measure_facade.score_to_band(final), "grade": _measure_facade.score_to_grade(final)}
|
|
1162
|
+
"""Score observed current occupancy through the common v3 scorer."""
|
|
1163
|
+
return quality_continuity.session_quality(
|
|
1164
|
+
session_data.get("context_tokens"), session_data.get("model_context_window"),
|
|
1165
|
+
session_data.get("model"), session_data.get("compactions", 0))
|
|
1282
1166
|
|
|
1283
1167
|
|
|
1284
1168
|
def _record_model(msg):
|
|
@@ -1406,8 +1290,12 @@ def _is_file_collected(conn, jsonl_path, check_mtime=None):
|
|
|
1406
1290
|
try:
|
|
1407
1291
|
collected = _measure_facade.datetime.fromisoformat(row[0]).timestamp()
|
|
1408
1292
|
path = _measure_facade.Path(jsonl_path)
|
|
1293
|
+
if path.stat().st_size > transcript_stream.LARGE_BYTES:
|
|
1294
|
+
observed = conn.execute('SELECT transcript_mtime FROM session_log WHERE jsonl_path=?', (str(path),)).fetchone()
|
|
1295
|
+
if observed and observed[0] != path.stat().st_mtime:
|
|
1296
|
+
return False
|
|
1409
1297
|
paths = [path, *_measure_facade._find_subagent_jsonl_files(path)]
|
|
1410
|
-
return all(path.stat().st_mtime <= collected for path in paths)
|
|
1298
|
+
return all(path.stat().st_mtime <= collected and not transcript_stream.needs_resume(path) for path in paths)
|
|
1411
1299
|
except (OSError, TypeError, ValueError):
|
|
1412
1300
|
return False
|
|
1413
1301
|
|
|
@@ -1463,10 +1351,10 @@ def _store_adapter_activity(conn, dedup_key, parsed):
|
|
|
1463
1351
|
"FROM session_log WHERE jsonl_path=?", (dedup_key,)).fetchone()
|
|
1464
1352
|
if current and tuple(current) == params[:-1]:
|
|
1465
1353
|
return 0
|
|
1466
|
-
|
|
1354
|
+
changed = upgrade_drain_control.session_write(conn,
|
|
1467
1355
|
"UPDATE session_log SET first_activity_day=?,last_activity_day=?,date=?,daily_usage_json=?, "
|
|
1468
1356
|
"parent_daily_usage_json=?,daily_calls_json=? WHERE jsonl_path=?", params)
|
|
1469
|
-
return
|
|
1357
|
+
return int(changed is not None)
|
|
1470
1358
|
|
|
1471
1359
|
|
|
1472
1360
|
def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallback, quiet=None):
|
|
@@ -1539,7 +1427,7 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
|
|
|
1539
1427
|
if existing is not None and int(existing[0]) == is_incomplete:
|
|
1540
1428
|
return _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
|
|
1541
1429
|
try:
|
|
1542
|
-
|
|
1430
|
+
changed = upgrade_drain_control.session_write(conn,
|
|
1543
1431
|
"""UPDATE session_log SET
|
|
1544
1432
|
date=?, project=?, duration_minutes=?, input_tokens=?,
|
|
1545
1433
|
output_tokens=?, message_count=?, api_calls=?, cache_hit_rate=?,
|
|
@@ -1553,6 +1441,8 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
|
|
|
1553
1441
|
WHERE jsonl_path=?""",
|
|
1554
1442
|
values + (dedup_key,),
|
|
1555
1443
|
)
|
|
1444
|
+
if changed is None:
|
|
1445
|
+
return 0
|
|
1556
1446
|
_measure_facade._store_adapter_activity(conn, dedup_key, parsed)
|
|
1557
1447
|
return 1
|
|
1558
1448
|
except _measure_facade.sqlite3.Error as exc:
|
|
@@ -1561,7 +1451,7 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
|
|
|
1561
1451
|
return 0
|
|
1562
1452
|
|
|
1563
1453
|
try:
|
|
1564
|
-
cur =
|
|
1454
|
+
cur = upgrade_drain_control.session_write(conn,
|
|
1565
1455
|
"""INSERT OR IGNORE INTO session_log
|
|
1566
1456
|
(jsonl_path, date, project, duration_minutes, input_tokens,
|
|
1567
1457
|
output_tokens, message_count, api_calls, cache_hit_rate,
|
|
@@ -1578,7 +1468,7 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
|
|
|
1578
1468
|
if not quiet:
|
|
1579
1469
|
print(f"[Token Optimizer] skipped a {platform} session: {exc}")
|
|
1580
1470
|
return 0
|
|
1581
|
-
if cur.rowcount == 1:
|
|
1471
|
+
if cur is not None and cur.rowcount == 1:
|
|
1582
1472
|
_measure_facade._store_adapter_activity(conn, dedup_key, parsed)
|
|
1583
1473
|
return 1
|
|
1584
1474
|
return 0
|
|
@@ -1789,7 +1679,7 @@ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
|
|
|
1789
1679
|
old = tuple(int(v or 0) for v in stored)
|
|
1790
1680
|
if any(n < o for n, o in zip(new, old)) or new == old:
|
|
1791
1681
|
return False
|
|
1792
|
-
|
|
1682
|
+
changed = upgrade_drain_control.session_write(conn,
|
|
1793
1683
|
"""UPDATE session_log
|
|
1794
1684
|
SET duration_minutes = ?, input_tokens = ?, output_tokens = ?,
|
|
1795
1685
|
message_count = ?, api_calls = ?, cache_hit_rate = ?,
|
|
@@ -1799,7 +1689,9 @@ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
|
|
|
1799
1689
|
model_usage_json = ?, all_model_usage_json = ?,
|
|
1800
1690
|
model_usage_breakdown_json = ?, version = ?, topic = ?,
|
|
1801
1691
|
collected_at = ?
|
|
1802
|
-
WHERE jsonl_path = ?
|
|
1692
|
+
WHERE jsonl_path = ? AND COALESCE(message_count,0)<=? AND COALESCE(input_tokens,0)<=?
|
|
1693
|
+
AND COALESCE(output_tokens,0)<=? AND COALESCE(api_calls,0)<=?
|
|
1694
|
+
AND (COALESCE(message_count,0)<? OR COALESCE(input_tokens,0)<? OR COALESCE(output_tokens,0)<? OR COALESCE(api_calls,0)<?)""",
|
|
1803
1695
|
(
|
|
1804
1696
|
parsed["duration_minutes"],
|
|
1805
1697
|
parsed["total_input_tokens"],
|
|
@@ -1821,8 +1713,9 @@ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
|
|
|
1821
1713
|
parsed.get("topic"),
|
|
1822
1714
|
_measure_facade.datetime.now().isoformat(),
|
|
1823
1715
|
dedup_key,
|
|
1824
|
-
),
|
|
1716
|
+
) + new + new,
|
|
1825
1717
|
)
|
|
1718
|
+
if changed is None or changed.rowcount != 1: return False
|
|
1826
1719
|
_measure_facade._store_adapter_activity(conn, dedup_key, parsed)
|
|
1827
1720
|
return True
|
|
1828
1721
|
|
|
@@ -3721,7 +3614,7 @@ def _stamp_usage_parser_version(conn, filepath):
|
|
|
3721
3614
|
re-parsed on every collect."""
|
|
3722
3615
|
_measure_facade = _compat.facade()
|
|
3723
3616
|
try:
|
|
3724
|
-
|
|
3617
|
+
upgrade_drain_control.session_write(conn,
|
|
3725
3618
|
"UPDATE session_log SET usage_parser_version = ? WHERE jsonl_path = ?",
|
|
3726
3619
|
(_measure_facade._USAGE_PARSER_VERSION, str(filepath)))
|
|
3727
3620
|
except _measure_facade.sqlite3.Error:
|
|
@@ -4062,20 +3955,22 @@ def _upgrade_drain_after_pass(conn, backlog):
|
|
|
4062
3955
|
if _measure_facade._upgrade_meta_get(conn, _measure_facade._UPGRADE_DRAIN_META) == key:
|
|
4063
3956
|
return False
|
|
4064
3957
|
if not backlog:
|
|
4065
|
-
|
|
3958
|
+
with upgrade_drain_control.running(_measure_facade) as held:
|
|
3959
|
+
if held: _measure_facade._upgrade_drain_mark_done(conn)
|
|
4066
3960
|
return False
|
|
4067
3961
|
# Under pytest the child would run against the real ~/.claude.
|
|
4068
3962
|
if _measure_facade.os.environ.get("PYTEST_CURRENT_TEST") and not _measure_facade.os.environ.get(
|
|
4069
3963
|
"TOKEN_OPTIMIZER_TEST_ALLOW_DRAIN_SPAWN"):
|
|
4070
3964
|
return False
|
|
4071
3965
|
raw = _measure_facade._upgrade_meta_get(conn, _measure_facade._UPGRADE_DRAIN_ATTEMPTS_META) or ""
|
|
4072
|
-
attempts =
|
|
4073
|
-
if
|
|
3966
|
+
ready, attempts = upgrade_drain_control.retry_ready(raw, key, _measure_facade.time.time())
|
|
3967
|
+
if not ready:
|
|
4074
3968
|
return False
|
|
4075
3969
|
if not _measure_facade._upgrade_drain_claim_lock():
|
|
4076
3970
|
return False
|
|
4077
|
-
|
|
4078
|
-
|
|
3971
|
+
started = _measure_facade._spawn_upgrade_drain()
|
|
3972
|
+
_measure_facade._upgrade_meta_set(conn, _measure_facade._UPGRADE_DRAIN_ATTEMPTS_META, f"{key}:{attempts + 1}:{_measure_facade.time.time()}")
|
|
3973
|
+
if started:
|
|
4079
3974
|
return True
|
|
4080
3975
|
_measure_facade._upgrade_drain_release_lock()
|
|
4081
3976
|
return False
|
|
@@ -4086,29 +3981,12 @@ def _upgrade_drain_after_pass(conn, backlog):
|
|
|
4086
3981
|
def _upgrade_drain_claim_lock():
|
|
4087
3982
|
"""Claim the drain lock file (O_EXCL); reclaim one left by a dead child."""
|
|
4088
3983
|
_measure_facade = _compat.facade()
|
|
4089
|
-
|
|
4090
|
-
try:
|
|
4091
|
-
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
4092
|
-
try:
|
|
4093
|
-
fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
4094
|
-
except FileExistsError:
|
|
4095
|
-
if _measure_facade.time.time() - marker.stat().st_mtime <= _measure_facade._UPGRADE_DRAIN_LOCK_STALE_SECONDS:
|
|
4096
|
-
return False
|
|
4097
|
-
_measure_facade.os.unlink(str(marker))
|
|
4098
|
-
fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
|
|
4099
|
-
with _measure_facade.os.fdopen(fd, "w") as handle:
|
|
4100
|
-
handle.write(str(_measure_facade.os.getpid()))
|
|
4101
|
-
return True
|
|
4102
|
-
except OSError:
|
|
4103
|
-
return False
|
|
3984
|
+
return upgrade_drain_control.claim(_measure_facade)
|
|
4104
3985
|
|
|
4105
3986
|
|
|
4106
3987
|
def _upgrade_drain_release_lock():
|
|
4107
3988
|
_measure_facade = _compat.facade()
|
|
4108
|
-
|
|
4109
|
-
(_measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME).unlink()
|
|
4110
|
-
except OSError:
|
|
4111
|
-
pass
|
|
3989
|
+
upgrade_drain_control.release(_measure_facade)
|
|
4112
3990
|
|
|
4113
3991
|
|
|
4114
3992
|
def _spawn_upgrade_drain():
|
|
@@ -4131,10 +4009,7 @@ def _spawn_upgrade_drain():
|
|
|
4131
4009
|
creationflags=(getattr(_measure_facade.subprocess, "DETACHED_PROCESS", 0) | _measure_facade._NO_WINDOW),
|
|
4132
4010
|
**popen_kw,
|
|
4133
4011
|
)
|
|
4134
|
-
|
|
4135
|
-
(_measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME).write_text(str(child.pid))
|
|
4136
|
-
except OSError:
|
|
4137
|
-
pass
|
|
4012
|
+
upgrade_drain_control.publish_child(_measure_facade, child.pid)
|
|
4138
4013
|
return True
|
|
4139
4014
|
except Exception as exc:
|
|
4140
4015
|
try:
|
|
@@ -4162,11 +4037,25 @@ def _run_upgrade_drain(days=None, quiet=None):
|
|
|
4162
4037
|
"""Body of `measure.py upgrade-drain`: one uncapped collect (usage re-parse,
|
|
4163
4038
|
per-day usage, counted ledger and markers), then release the lock."""
|
|
4164
4039
|
_measure_facade = _compat.facade()
|
|
4040
|
+
# Scoped to this run: the CLI exits right after, but an in-process caller (a test, an embedding host)
|
|
4041
|
+
# must not keep every later collect_sessions() in drain mode.
|
|
4042
|
+
previous_flag = _measure_facade.os.environ.get("TOKEN_OPTIMIZER_UPGRADE_DRAIN")
|
|
4165
4043
|
_measure_facade.os.environ["TOKEN_OPTIMIZER_UPGRADE_DRAIN"] = "1"
|
|
4166
4044
|
try:
|
|
4167
|
-
|
|
4045
|
+
with upgrade_drain_control.running(_measure_facade) as held:
|
|
4046
|
+
return _measure_facade.collect_sessions(days=days or _measure_facade._upgrade_drain_days(), quiet=quiet) if held else None
|
|
4047
|
+
except _measure_facade.sqlite3.OperationalError as exc:
|
|
4048
|
+
if "locked" not in str(exc).lower() and "busy" not in str(exc).lower():
|
|
4049
|
+
raise
|
|
4050
|
+
try: _measure_facade._log_spawn_failure("upgrade drain deferred after SQLite contention")
|
|
4051
|
+
except Exception: pass
|
|
4052
|
+
return 0
|
|
4168
4053
|
finally:
|
|
4169
4054
|
_measure_facade._upgrade_drain_release_lock()
|
|
4055
|
+
if previous_flag is None:
|
|
4056
|
+
_measure_facade.os.environ.pop("TOKEN_OPTIMIZER_UPGRADE_DRAIN", None)
|
|
4057
|
+
else:
|
|
4058
|
+
_measure_facade.os.environ["TOKEN_OPTIMIZER_UPGRADE_DRAIN"] = previous_flag
|
|
4170
4059
|
|
|
4171
4060
|
|
|
4172
4061
|
def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
@@ -4416,19 +4305,18 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4416
4305
|
# This copy changed since last seen and may hold requests the
|
|
4417
4306
|
# stored copy lacks; its per-day usage (merged across copies) is
|
|
4418
4307
|
# recomputed by the next backfill.
|
|
4419
|
-
|
|
4308
|
+
changed = upgrade_drain_control.session_write(conn,
|
|
4420
4309
|
"UPDATE session_log SET daily_usage_json = NULL WHERE session_uuid = ? AND jsonl_path != ?",
|
|
4421
4310
|
(session_uuid, str(filepath)))
|
|
4311
|
+
if changed is None:
|
|
4312
|
+
conn.rollback(); parse_truncated = True; break
|
|
4422
4313
|
_measure_facade._stamp_usage_parser_version(conn, filepath)
|
|
4423
4314
|
continue
|
|
4424
4315
|
else:
|
|
4425
4316
|
other = []
|
|
4426
4317
|
|
|
4427
|
-
# Compute quality score at collection time for persistence
|
|
4428
4318
|
sq = _measure_facade.score_session_quality(parsed)
|
|
4429
|
-
# B1: persist reclaimable stale-read waste (opportunity tier, not realized).
|
|
4430
4319
|
stale_waste = _measure_facade._session_stale_waste_tokens(filepath)
|
|
4431
|
-
|
|
4432
4320
|
# Resolve the platform for this session. Codex transcripts carry
|
|
4433
4321
|
# "runtime": "codex" in their parsed dict; Claude transcripts do not
|
|
4434
4322
|
# set the key, so detect_runtime() (which returns the active runtime,
|
|
@@ -4450,7 +4338,7 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4450
4338
|
o_mark += ", ?"
|
|
4451
4339
|
o_val += (_measure_facade._USAGE_PARSER_VERSION,)
|
|
4452
4340
|
o_upd += ",\n usage_parser_version=excluded.usage_parser_version"
|
|
4453
|
-
cur =
|
|
4341
|
+
cur = upgrade_drain_control.session_write(conn,
|
|
4454
4342
|
"""INSERT INTO session_log
|
|
4455
4343
|
(jsonl_path, date, project, duration_minutes, input_tokens,
|
|
4456
4344
|
output_tokens, message_count, api_calls, cache_hit_rate,
|
|
@@ -4537,6 +4425,8 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4537
4425
|
_measure_facade.json.dumps(daily_usage),
|
|
4538
4426
|
) + o_val,
|
|
4539
4427
|
)
|
|
4428
|
+
if cur is None:
|
|
4429
|
+
conn.rollback(); parse_truncated = True; break
|
|
4540
4430
|
if cur.rowcount != 1:
|
|
4541
4431
|
continue
|
|
4542
4432
|
calls = dict(parsed.get("daily_calls") or {})
|
|
@@ -4544,11 +4434,13 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4544
4434
|
if not u.get("advisor") and u.get("n", 1) and u.get("day"):
|
|
4545
4435
|
day = u["day"]
|
|
4546
4436
|
calls[day] = calls.get(day, 0) + 1
|
|
4547
|
-
|
|
4437
|
+
changed = upgrade_drain_control.session_write(conn,
|
|
4548
4438
|
"UPDATE session_log SET first_activity_day=?, last_activity_day=?, transcript_mtime=?, "
|
|
4549
4439
|
"parent_daily_usage_json=?, daily_calls_json=?, daily_metrics_json=? WHERE jsonl_path=?",
|
|
4550
4440
|
(activity_bounds[0] if activity_bounds else None, activity_bounds[-1] if activity_bounds else None, mtime,
|
|
4551
4441
|
_measure_facade.json.dumps(parent_daily), _measure_facade.json.dumps(calls), _measure_facade.json.dumps(session_daily_metrics), str(filepath)))
|
|
4442
|
+
if changed is None:
|
|
4443
|
+
conn.rollback(); parse_truncated = True; break
|
|
4552
4444
|
if merged is not None:
|
|
4553
4445
|
_measure_facade._claim_requests(conn, owner_id, merged)
|
|
4554
4446
|
live_owners.add(_measure_facade._stable_hash63(owner_id))
|
|
@@ -4565,7 +4457,8 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4565
4457
|
conn.executemany(
|
|
4566
4458
|
"INSERT OR REPLACE INTO session_log_aliases (jsonl_path, session_uuid, collected_at) "
|
|
4567
4459
|
"VALUES (?, ?, ?)", [(r[0], session_uuid, r[1]) for r in losers])
|
|
4568
|
-
|
|
4460
|
+
if upgrade_drain_control.session_write(conn, "DELETE FROM session_log WHERE id = ?", [(r[0],) for r in other], many=True) is None:
|
|
4461
|
+
conn.rollback(); parse_truncated = True; break
|
|
4569
4462
|
conn.execute("DELETE FROM session_log_aliases WHERE jsonl_path = ?", (str(filepath),))
|
|
4570
4463
|
|
|
4571
4464
|
new_count += 1
|
|
@@ -4595,9 +4488,9 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4595
4488
|
budget_seconds=budgets["daily_seconds"])
|
|
4596
4489
|
daily_truncated = _measure_facade.time.monotonic() - _daily_started >= budgets["daily_seconds"]
|
|
4597
4490
|
except Exception:
|
|
4598
|
-
|
|
4491
|
+
daily_truncated = True
|
|
4599
4492
|
try:
|
|
4600
|
-
_measure_facade._pretool_anchor_step(budget_seconds=5.0)
|
|
4493
|
+
_measure_facade._pretool_anchor_step(budget_seconds=3600.0 if drain == "full" else 5.0)
|
|
4601
4494
|
except Exception:
|
|
4602
4495
|
pass
|
|
4603
4496
|
|
|
@@ -4605,31 +4498,38 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4605
4498
|
# collect pass (never at dashboard-regen time). Both helpers carry their
|
|
4606
4499
|
# own per-pass caps + soft deadline and are fail-open, so a slow transcript
|
|
4607
4500
|
# can never hold the flush; the backlog converges over passes.
|
|
4608
|
-
counted_pending =
|
|
4501
|
+
counted_pending = 1
|
|
4609
4502
|
try:
|
|
4503
|
+
# Sessions where Token Optimizer ran elsewhere (cloud) and logged nothing
|
|
4504
|
+
# here: rebuild their events from its own transcript markers first.
|
|
4505
|
+
transcript_stats = _measure_facade._transcript_backfill.collect_pass(conn, _measure_facade, drain, budgets, quiet=quiet)
|
|
4610
4506
|
if drain == "full":
|
|
4611
|
-
|
|
4507
|
+
counted_stats = _measure_facade._counted_backfill_all(conn, quiet=quiet)
|
|
4508
|
+
counted_pending = int(counted_stats.get("pending_sessions", 0) or 0) + int(not counted_stats.get("marker_backfill_done"))
|
|
4612
4509
|
else:
|
|
4613
4510
|
counted_pending = int(_measure_facade._update_counted_cumulative(
|
|
4614
4511
|
conn, max_sessions=budgets["counted_sessions"],
|
|
4615
4512
|
deadline_seconds=budgets["counted_seconds"],
|
|
4616
4513
|
quiet=quiet).get("pending_sessions", 0) or 0)
|
|
4617
4514
|
if drain == "inline":
|
|
4618
|
-
_measure_facade._counted_marker_backfill(conn, max_files=None,
|
|
4515
|
+
marker_stats = _measure_facade._counted_marker_backfill(conn, max_files=None,
|
|
4619
4516
|
deadline_seconds=budgets["counted_seconds"], quiet=quiet)
|
|
4620
4517
|
else:
|
|
4621
|
-
_measure_facade._counted_marker_backfill(conn, quiet=quiet)
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
try:
|
|
4625
|
-
if drain == "full":
|
|
4626
|
-
_measure_facade._upgrade_drain_mark_done(conn)
|
|
4627
|
-
elif not rebuild:
|
|
4628
|
-
_measure_facade._upgrade_drain_after_pass(
|
|
4629
|
-
conn, backlog=bool(parse_truncated or daily_truncated or counted_pending))
|
|
4518
|
+
marker_stats = _measure_facade._counted_marker_backfill(conn, quiet=quiet)
|
|
4519
|
+
counted_pending += int(not marker_stats.get("done"))
|
|
4520
|
+
counted_pending += int(upgrade_drain_control.backfill_pending(transcript_stats))
|
|
4630
4521
|
except Exception:
|
|
4631
|
-
|
|
4632
|
-
|
|
4522
|
+
counted_pending = max(1, counted_pending)
|
|
4523
|
+
# Verbosity nudges against matched un-nudged replies (savings-truth U5).
|
|
4524
|
+
# Read-only on the DB, one derived JSON file, at most daily, and never on
|
|
4525
|
+
# the hook path: it walks every recent transcript.
|
|
4526
|
+
if drain in ("inline", "full"):
|
|
4527
|
+
try:
|
|
4528
|
+
_measure_facade._output_reread.refresh_study(conn, deadline=(
|
|
4529
|
+
None if drain == "full"
|
|
4530
|
+
else _measure_facade.time.monotonic() + budgets["counted_seconds"]))
|
|
4531
|
+
except Exception:
|
|
4532
|
+
pass
|
|
4633
4533
|
# ATOMICITY INVARIANT: _rebuild_aggregate_tables does DELETE-then-reINSERT and must
|
|
4634
4534
|
# NOT commit internally. The whole wipe+rebuild is one transaction that commits only on
|
|
4635
4535
|
# the next line, so a _HookTimeout (BaseException) mid-rebuild rolls back cleanly and the
|
|
@@ -4637,6 +4537,13 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
|
|
|
4637
4537
|
# re-INSERTs -- a half-applied commit would leave the dashboard reading empty aggregates.
|
|
4638
4538
|
_measure_facade._rebuild_aggregate_tables(conn)
|
|
4639
4539
|
conn.commit()
|
|
4540
|
+
try:
|
|
4541
|
+
if drain == "full" and not (parse_truncated or daily_truncated or counted_pending):
|
|
4542
|
+
_measure_facade._upgrade_drain_mark_done(conn)
|
|
4543
|
+
elif drain != "full" and not rebuild:
|
|
4544
|
+
_measure_facade._upgrade_drain_after_pass(conn, backlog=bool(parse_truncated or daily_truncated or counted_pending))
|
|
4545
|
+
except Exception:
|
|
4546
|
+
pass
|
|
4640
4547
|
# Ensure schema version is set (idempotent, also set in migration and rebuild)
|
|
4641
4548
|
conn.execute("PRAGMA user_version = 3")
|
|
4642
4549
|
conn.commit() # PRAGMA write must be committed explicitly
|