@alexgreensh/token-optimizer 5.13.64 → 5.13.66
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 +62 -13
- package/hooks/userpromptsubmit_runner.py +13 -1
- package/package.json +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +16 -0
- package/skills/token-optimizer/scripts/_measure/_compat.py +200 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +6949 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +6997 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +2722 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +4630 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +6773 -0
- package/skills/token-optimizer/scripts/_measure/dashboard.py +4358 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +5952 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +2101 -0
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +7138 -0
- package/skills/token-optimizer/scripts/_measure/runtime.py +1231 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +7702 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +4784 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +2432 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +7 -8
- package/skills/token-optimizer/scripts/codex_doctor.py +14 -0
- package/skills/token-optimizer/scripts/devin_source.py +1 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +13 -0
- package/skills/token-optimizer/scripts/hermes_install.py +11 -0
- package/skills/token-optimizer/scripts/measure.py +2428 -60928
|
@@ -0,0 +1,2432 @@
|
|
|
1
|
+
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from . import _compat
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _classify_jsonl_is_sidechain(filepath, max_lines=None):
|
|
7
|
+
"""Return ``(is_sidechain, reason)`` using only authoritative signals."""
|
|
8
|
+
_measure_facade = _compat.facade()
|
|
9
|
+
path_reason = _measure_facade._sidechain_path_reason(filepath)
|
|
10
|
+
if path_reason:
|
|
11
|
+
return (True, path_reason)
|
|
12
|
+
try:
|
|
13
|
+
parsed = 0
|
|
14
|
+
first_user_record_seen = False
|
|
15
|
+
with open(filepath, "r", encoding="utf-8", errors="replace") as f:
|
|
16
|
+
for line in f:
|
|
17
|
+
# Cap on parsed records, not raw lines, so blank/garbage lines
|
|
18
|
+
# do not consume the scan budget before a real record is seen.
|
|
19
|
+
if parsed >= max_lines:
|
|
20
|
+
break
|
|
21
|
+
line = line.strip()
|
|
22
|
+
if not line:
|
|
23
|
+
continue
|
|
24
|
+
try:
|
|
25
|
+
rec = _measure_facade.json.loads(line)
|
|
26
|
+
except _measure_facade.json.JSONDecodeError:
|
|
27
|
+
continue
|
|
28
|
+
parsed += 1
|
|
29
|
+
if rec.get("isSidechain") is True:
|
|
30
|
+
return (True, "isSidechain")
|
|
31
|
+
# The OSRC protocol is meaningful only in the first real user
|
|
32
|
+
# prompt. Tool-result transport and later assistant/user echoes
|
|
33
|
+
# are orchestrator activity, not proof of a delegated worker.
|
|
34
|
+
if rec.get("type") == "user" and not first_user_record_seen:
|
|
35
|
+
prompt = _measure_facade._osrc_prompt_text(rec)
|
|
36
|
+
if prompt:
|
|
37
|
+
first_user_record_seen = True
|
|
38
|
+
if prompt and ("OSRC::PROGRESS" in prompt or "OSRC::DONE" in prompt):
|
|
39
|
+
return (True, "osrc_prompt")
|
|
40
|
+
return (False, None)
|
|
41
|
+
except (OSError, ValueError):
|
|
42
|
+
return (None, None)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _scan_jsonl_is_sidechain(filepath, max_lines=None):
|
|
46
|
+
"""Return True/False for a readable transcript, otherwise None."""
|
|
47
|
+
_measure_facade = _compat.facade()
|
|
48
|
+
verdict, _reason = _measure_facade._classify_jsonl_is_sidechain(filepath, max_lines=max_lines)
|
|
49
|
+
return verdict
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _backfill_is_sidechain(conn, batch_limit=None):
|
|
53
|
+
"""Reclassify legacy rows once with the corrected classifier.
|
|
54
|
+
|
|
55
|
+
The persistent gate is required because ``sidechain_reason`` is NULL for a
|
|
56
|
+
legitimate human row after repair, so NULL alone cannot be a durable
|
|
57
|
+
unclassified sentinel. Missing transcripts remain unchanged and are counted
|
|
58
|
+
rather than guessed.
|
|
59
|
+
|
|
60
|
+
Batched with a resume cursor: if the process is killed mid-backfill (hook
|
|
61
|
+
timeout), the next _init_trends_db resumes from the last-processed id
|
|
62
|
+
instead of re-reading every row from scratch. The done-marker is only
|
|
63
|
+
written when the cursor reaches the end.
|
|
64
|
+
"""
|
|
65
|
+
_measure_facade = _compat.facade()
|
|
66
|
+
conn.execute(
|
|
67
|
+
"CREATE TABLE IF NOT EXISTS token_optimizer_meta "
|
|
68
|
+
"(key TEXT PRIMARY KEY, value TEXT)"
|
|
69
|
+
)
|
|
70
|
+
if conn.execute(
|
|
71
|
+
"SELECT 1 FROM token_optimizer_meta WHERE key = 'sidechain_classifier_v2_done'"
|
|
72
|
+
).fetchone() is not None:
|
|
73
|
+
return (0, 0)
|
|
74
|
+
|
|
75
|
+
cols = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
|
|
76
|
+
has_reason = "sidechain_reason" in cols
|
|
77
|
+
# Resume from the last-processed id if a prior pass was interrupted.
|
|
78
|
+
cursor_row = conn.execute(
|
|
79
|
+
"SELECT value FROM token_optimizer_meta WHERE key = 'sidechain_classifier_v2_cursor'"
|
|
80
|
+
).fetchone()
|
|
81
|
+
cursor_id = int(cursor_row[0]) if cursor_row else 0
|
|
82
|
+
rows = conn.execute(
|
|
83
|
+
"SELECT id, jsonl_path FROM session_log "
|
|
84
|
+
"WHERE jsonl_path IS NOT NULL AND id > ? "
|
|
85
|
+
"ORDER BY id LIMIT ?",
|
|
86
|
+
(cursor_id, batch_limit),
|
|
87
|
+
).fetchall()
|
|
88
|
+
if not rows:
|
|
89
|
+
# No more rows to process: mark done and clear the cursor.
|
|
90
|
+
conn.execute(
|
|
91
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
92
|
+
"VALUES ('sidechain_classifier_v2_done', datetime('now'))"
|
|
93
|
+
)
|
|
94
|
+
conn.execute(
|
|
95
|
+
"DELETE FROM token_optimizer_meta WHERE key = 'sidechain_classifier_v2_cursor'"
|
|
96
|
+
)
|
|
97
|
+
conn.commit()
|
|
98
|
+
return (0, 0)
|
|
99
|
+
updates = []
|
|
100
|
+
missing = 0
|
|
101
|
+
last_id = cursor_id
|
|
102
|
+
for row_id, jpath in rows:
|
|
103
|
+
verdict, reason = _measure_facade._classify_jsonl_is_sidechain(jpath)
|
|
104
|
+
last_id = row_id
|
|
105
|
+
if verdict is None:
|
|
106
|
+
missing += 1
|
|
107
|
+
continue
|
|
108
|
+
if has_reason:
|
|
109
|
+
updates.append((1 if verdict else 0, reason, row_id))
|
|
110
|
+
else:
|
|
111
|
+
updates.append((1 if verdict else 0, row_id))
|
|
112
|
+
if updates:
|
|
113
|
+
if has_reason:
|
|
114
|
+
conn.executemany(
|
|
115
|
+
"UPDATE session_log SET is_sidechain = ?, sidechain_reason = ? WHERE id = ?",
|
|
116
|
+
updates,
|
|
117
|
+
)
|
|
118
|
+
else:
|
|
119
|
+
conn.executemany(
|
|
120
|
+
"UPDATE session_log SET is_sidechain = ? WHERE id = ?", updates
|
|
121
|
+
)
|
|
122
|
+
# Persist the cursor so a killed process resumes here next time.
|
|
123
|
+
conn.execute(
|
|
124
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
125
|
+
"VALUES ('sidechain_classifier_v2_cursor', ?)",
|
|
126
|
+
(str(last_id),),
|
|
127
|
+
)
|
|
128
|
+
# If we processed fewer than batch_limit rows, we've reached the end.
|
|
129
|
+
if len(rows) < batch_limit:
|
|
130
|
+
conn.execute(
|
|
131
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
132
|
+
"VALUES ('sidechain_classifier_v2_done', datetime('now'))"
|
|
133
|
+
)
|
|
134
|
+
conn.execute(
|
|
135
|
+
"DELETE FROM token_optimizer_meta WHERE key = 'sidechain_classifier_v2_cursor'"
|
|
136
|
+
)
|
|
137
|
+
conn.commit()
|
|
138
|
+
return (len(updates), missing)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _backfill_reported_token_usage(conn, batch_limit=None):
|
|
142
|
+
"""Persist the official-compatible, non-deduped usage basis for old rows.
|
|
143
|
+
|
|
144
|
+
Batched with a resume cursor (see _backfill_is_sidechain for rationale).
|
|
145
|
+
"""
|
|
146
|
+
_measure_facade = _compat.facade()
|
|
147
|
+
conn.execute(
|
|
148
|
+
"CREATE TABLE IF NOT EXISTS token_optimizer_meta "
|
|
149
|
+
"(key TEXT PRIMARY KEY, value TEXT)"
|
|
150
|
+
)
|
|
151
|
+
if conn.execute(
|
|
152
|
+
"SELECT 1 FROM token_optimizer_meta WHERE key = 'reported_token_backfill_done'"
|
|
153
|
+
).fetchone() is not None:
|
|
154
|
+
return 0
|
|
155
|
+
|
|
156
|
+
cursor_row = conn.execute(
|
|
157
|
+
"SELECT value FROM token_optimizer_meta WHERE key = 'reported_token_backfill_cursor'"
|
|
158
|
+
).fetchone()
|
|
159
|
+
cursor_id = int(cursor_row[0]) if cursor_row else 0
|
|
160
|
+
rows = conn.execute(
|
|
161
|
+
"SELECT id, jsonl_path FROM session_log "
|
|
162
|
+
"WHERE jsonl_path IS NOT NULL AND id > ? "
|
|
163
|
+
"ORDER BY id LIMIT ?",
|
|
164
|
+
(cursor_id, batch_limit),
|
|
165
|
+
).fetchall()
|
|
166
|
+
if not rows:
|
|
167
|
+
conn.execute(
|
|
168
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
169
|
+
"VALUES ('reported_token_backfill_done', datetime('now'))"
|
|
170
|
+
)
|
|
171
|
+
conn.execute(
|
|
172
|
+
"DELETE FROM token_optimizer_meta WHERE key = 'reported_token_backfill_cursor'"
|
|
173
|
+
)
|
|
174
|
+
conn.commit()
|
|
175
|
+
return 0
|
|
176
|
+
updates = []
|
|
177
|
+
last_id = cursor_id
|
|
178
|
+
for row_id, jpath in rows:
|
|
179
|
+
parsed = _measure_facade._parse_session_jsonl(jpath)
|
|
180
|
+
last_id = row_id
|
|
181
|
+
if not parsed:
|
|
182
|
+
continue
|
|
183
|
+
updates.append((
|
|
184
|
+
int(parsed.get("reported_input_tokens", 0) or 0),
|
|
185
|
+
int(parsed.get("reported_output_tokens", 0) or 0),
|
|
186
|
+
_measure_facade.json.dumps(parsed.get("reported_model_usage", {})),
|
|
187
|
+
row_id,
|
|
188
|
+
))
|
|
189
|
+
if updates:
|
|
190
|
+
conn.executemany(
|
|
191
|
+
"UPDATE session_log SET reported_input_tokens = ?, "
|
|
192
|
+
"reported_output_tokens = ?, reported_model_usage_json = ? WHERE id = ?",
|
|
193
|
+
updates,
|
|
194
|
+
)
|
|
195
|
+
conn.execute(
|
|
196
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
197
|
+
"VALUES ('reported_token_backfill_cursor', ?)",
|
|
198
|
+
(str(last_id),),
|
|
199
|
+
)
|
|
200
|
+
if len(rows) < batch_limit:
|
|
201
|
+
conn.execute(
|
|
202
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
203
|
+
"VALUES ('reported_token_backfill_done', datetime('now'))"
|
|
204
|
+
)
|
|
205
|
+
conn.execute(
|
|
206
|
+
"DELETE FROM token_optimizer_meta WHERE key = 'reported_token_backfill_cursor'"
|
|
207
|
+
)
|
|
208
|
+
conn.commit()
|
|
209
|
+
return len(updates)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _backfill_outsourcerer_sidechain(conn):
|
|
213
|
+
"""Reclassify existing outsourcerer delegation sessions as is_sidechain=1.
|
|
214
|
+
|
|
215
|
+
One-time migration for rows collected before content-based detection existed.
|
|
216
|
+
Scans each already-human (is_sidechain=0) row's JSONL for the OSRC::PROGRESS
|
|
217
|
+
marker injected by the outsourcerer skill and flips true matches to 1.
|
|
218
|
+
|
|
219
|
+
Gated by a persistent completion marker so it content-scans transcripts at
|
|
220
|
+
most ONCE. Without the gate the `is_sidechain = 0` predicate matches every
|
|
221
|
+
human session forever (non-matches are never updated, so they never drain),
|
|
222
|
+
which re-opened and re-read up to 200 lines of every human transcript on
|
|
223
|
+
every _init_trends_db() call (~38 call sites; twice per SessionEnd). New
|
|
224
|
+
sessions are classified at collect time, so a single pass over the
|
|
225
|
+
pre-existing rows is sufficient. Returns count of reclassified rows.
|
|
226
|
+
"""
|
|
227
|
+
# One-time gate. On any error establishing it, skip the scan entirely rather
|
|
228
|
+
# than risk re-reading the whole history (fail toward NOT rescanning).
|
|
229
|
+
_measure_facade = _compat.facade()
|
|
230
|
+
try:
|
|
231
|
+
conn.execute(
|
|
232
|
+
"CREATE TABLE IF NOT EXISTS token_optimizer_meta "
|
|
233
|
+
"(key TEXT PRIMARY KEY, value TEXT)"
|
|
234
|
+
)
|
|
235
|
+
if conn.execute(
|
|
236
|
+
"SELECT 1 FROM token_optimizer_meta WHERE key = 'osrc_backfill_done'"
|
|
237
|
+
).fetchone() is not None:
|
|
238
|
+
return 0
|
|
239
|
+
except _measure_facade.sqlite3.Error:
|
|
240
|
+
return 0
|
|
241
|
+
|
|
242
|
+
rows = conn.execute(
|
|
243
|
+
"SELECT id, jsonl_path FROM session_log "
|
|
244
|
+
"WHERE is_sidechain = 0 AND jsonl_path IS NOT NULL"
|
|
245
|
+
).fetchall()
|
|
246
|
+
updates = []
|
|
247
|
+
for row_id, jpath in rows:
|
|
248
|
+
verdict = _measure_facade._scan_jsonl_is_sidechain(jpath)
|
|
249
|
+
if verdict is True:
|
|
250
|
+
updates.append((1, row_id))
|
|
251
|
+
if updates:
|
|
252
|
+
conn.executemany(
|
|
253
|
+
"UPDATE session_log SET is_sidechain = ? WHERE id = ?", updates
|
|
254
|
+
)
|
|
255
|
+
# Mark the pass complete regardless of match count so it never re-scans.
|
|
256
|
+
conn.execute(
|
|
257
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
258
|
+
"VALUES ('osrc_backfill_done', datetime('now'))"
|
|
259
|
+
)
|
|
260
|
+
conn.commit()
|
|
261
|
+
return len(updates)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _repair_osrc_sidechain_misflag(conn):
|
|
265
|
+
"""Undo rows the OLD, over-broad OSRC marker test wrongly flagged.
|
|
266
|
+
|
|
267
|
+
Until this fix, both marker tests searched the WHOLE record (and the raw
|
|
268
|
+
line) for OSRC::PROGRESS / OSRC::DONE. The marker therefore matched inside
|
|
269
|
+
tool RESULTS, so a human session that merely *watched* a delegate (running
|
|
270
|
+
`outsourcerer.sh status/watch/result`, whose output echoes the marker)
|
|
271
|
+
classified itself as the delegation it was watching. On the author's own
|
|
272
|
+
machine that mislabelled 234 of 3,312 30-day rows holding 8.87B of 15.5B
|
|
273
|
+
input tokens (57%) -- the longest genuine working sessions -- and removed
|
|
274
|
+
them from the human pool every cost comparison runs on.
|
|
275
|
+
|
|
276
|
+
Fixing the classifier is not enough: `_backfill_outsourcerer_sidechain` is
|
|
277
|
+
gated by a persistent `osrc_backfill_done` marker, so the corrected code
|
|
278
|
+
would never revisit the rows the buggy code already wrote. Code fixed, data
|
|
279
|
+
still wrong. This pass re-tests only rows currently flagged is_sidechain=1
|
|
280
|
+
with the corrected scanner and flips back the ones that no longer qualify.
|
|
281
|
+
|
|
282
|
+
Direction is deliberately one-way: it can only move 1 -> 0. A row that still
|
|
283
|
+
matches under the corrected rule is left alone, and no row is ever newly
|
|
284
|
+
flagged here, so a bug in this pass cannot manufacture sidechains.
|
|
285
|
+
|
|
286
|
+
Gated by its own marker so it runs at most once, matching the discipline of
|
|
287
|
+
`_backfill_outsourcerer_sidechain` (an ungated content-scan re-reads every
|
|
288
|
+
flagged transcript on every _init_trends_db call). Returns count repaired.
|
|
289
|
+
"""
|
|
290
|
+
_measure_facade = _compat.facade()
|
|
291
|
+
try:
|
|
292
|
+
conn.execute(
|
|
293
|
+
"CREATE TABLE IF NOT EXISTS token_optimizer_meta "
|
|
294
|
+
"(key TEXT PRIMARY KEY, value TEXT)"
|
|
295
|
+
)
|
|
296
|
+
if conn.execute(
|
|
297
|
+
"SELECT 1 FROM token_optimizer_meta WHERE key = 'osrc_misflag_repair_done'"
|
|
298
|
+
).fetchone() is not None:
|
|
299
|
+
return 0
|
|
300
|
+
except _measure_facade.sqlite3.Error:
|
|
301
|
+
return 0
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
rows = conn.execute(
|
|
305
|
+
"SELECT id, jsonl_path FROM session_log "
|
|
306
|
+
"WHERE is_sidechain = 1 AND jsonl_path IS NOT NULL"
|
|
307
|
+
).fetchall()
|
|
308
|
+
except _measure_facade.sqlite3.Error:
|
|
309
|
+
return 0
|
|
310
|
+
|
|
311
|
+
updates = []
|
|
312
|
+
for row_id, jpath in rows:
|
|
313
|
+
verdict = _measure_facade._scan_jsonl_is_sidechain(jpath)
|
|
314
|
+
# Only an explicit False repairs. None (file gone/unreadable) leaves the
|
|
315
|
+
# row as-is: we cannot prove it was misflagged, so we do not guess.
|
|
316
|
+
if verdict is False:
|
|
317
|
+
updates.append((0, row_id))
|
|
318
|
+
if updates:
|
|
319
|
+
conn.executemany(
|
|
320
|
+
"UPDATE session_log SET is_sidechain = ? WHERE id = ?", updates
|
|
321
|
+
)
|
|
322
|
+
conn.execute(
|
|
323
|
+
"INSERT OR REPLACE INTO token_optimizer_meta (key, value) "
|
|
324
|
+
"VALUES ('osrc_misflag_repair_done', datetime('now'))"
|
|
325
|
+
)
|
|
326
|
+
conn.commit()
|
|
327
|
+
return len(updates)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _recompute_session_tokens(conn, rel_tol=None, limit=None):
|
|
331
|
+
"""Re-parse stored sessions with the CURRENT collector and refresh stale token columns.
|
|
332
|
+
|
|
333
|
+
Rows collected by older collector versions (before the streaming-aware
|
|
334
|
+
per-requestId dedup) carry token counts that disagree with a fresh parse —
|
|
335
|
+
some over-counted (summed streaming chunks), some under-counted. Because rows
|
|
336
|
+
are written INSERT OR IGNORE and never updated, that staleness persists and
|
|
337
|
+
skews every per-session cost derived from session_log. This re-parses each
|
|
338
|
+
row whose transcript still exists and UPDATEs input_tokens / output_tokens /
|
|
339
|
+
cache_create_* / cache_hit_rate when they differ by more than `rel_tol`.
|
|
340
|
+
|
|
341
|
+
Idempotent: a row already matching the current parse is skipped. Rows whose
|
|
342
|
+
transcript is gone are left untouched (their stored values are the best we
|
|
343
|
+
have). Returns (refreshed, checked, missing). NOT run from _init_trends_db
|
|
344
|
+
(a full re-parse of every transcript is expensive); invoke via the
|
|
345
|
+
`recompute-tokens` command or a maintenance pass.
|
|
346
|
+
"""
|
|
347
|
+
_measure_facade = _compat.facade()
|
|
348
|
+
rows = conn.execute(
|
|
349
|
+
"SELECT id, jsonl_path, input_tokens FROM session_log "
|
|
350
|
+
"WHERE jsonl_path IS NOT NULL ORDER BY id DESC"
|
|
351
|
+
).fetchall()
|
|
352
|
+
if limit:
|
|
353
|
+
rows = rows[:limit]
|
|
354
|
+
refreshed = checked = missing = 0
|
|
355
|
+
updates = []
|
|
356
|
+
for row_id, jpath, stored_input in rows:
|
|
357
|
+
if not jpath or not _measure_facade.os.path.exists(jpath):
|
|
358
|
+
missing += 1
|
|
359
|
+
continue
|
|
360
|
+
parsed = _measure_facade._parse_session_jsonl(jpath)
|
|
361
|
+
if not parsed:
|
|
362
|
+
missing += 1
|
|
363
|
+
continue
|
|
364
|
+
checked += 1
|
|
365
|
+
new_input = int(parsed.get("total_input_tokens", 0) or 0)
|
|
366
|
+
stored = int(stored_input or 0)
|
|
367
|
+
# Only update when the fresh parse has a positive input. The old condition
|
|
368
|
+
# `stored <= 0 or ...` fired for stored==0 even when the new parse was also 0,
|
|
369
|
+
# overwriting valid cache_create_* on legitimately zero-input rows (e.g. the
|
|
370
|
+
# Codex path, where input_tokens can be 0 but cache_create is real). Requiring
|
|
371
|
+
# new_input > 0 keeps those rows intact while still catching every stale row.
|
|
372
|
+
if new_input > 0 and (stored <= 0 or abs(new_input - stored) > stored * rel_tol):
|
|
373
|
+
updates.append((
|
|
374
|
+
new_input,
|
|
375
|
+
int(parsed.get("total_output_tokens", 0) or 0),
|
|
376
|
+
int(parsed.get("total_cache_create_1h", 0) or 0),
|
|
377
|
+
int(parsed.get("total_cache_create_5m", 0) or 0),
|
|
378
|
+
float(parsed.get("cache_hit_rate", 0.0) or 0.0),
|
|
379
|
+
# Refresh the model-usage JSON columns too. Downstream cost calcs
|
|
380
|
+
# read BOTH input_tokens and these breakdowns; updating tokens without
|
|
381
|
+
# the breakdown leaves the row internally inconsistent.
|
|
382
|
+
_measure_facade.json.dumps(parsed.get("model_usage", {})),
|
|
383
|
+
_measure_facade.json.dumps(parsed.get("model_usage", {})), # all_model_usage = {model:int}
|
|
384
|
+
_measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
|
|
385
|
+
row_id,
|
|
386
|
+
))
|
|
387
|
+
refreshed += 1
|
|
388
|
+
if updates:
|
|
389
|
+
conn.executemany(
|
|
390
|
+
"UPDATE session_log SET input_tokens = ?, output_tokens = ?, "
|
|
391
|
+
"cache_create_1h_tokens = ?, cache_create_5m_tokens = ?, cache_hit_rate = ?, "
|
|
392
|
+
"model_usage_json = ?, all_model_usage_json = ?, model_usage_breakdown_json = ? "
|
|
393
|
+
"WHERE id = ?",
|
|
394
|
+
updates,
|
|
395
|
+
)
|
|
396
|
+
conn.commit()
|
|
397
|
+
return (refreshed, checked, missing)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _log_migration_error(step, exc):
|
|
401
|
+
"""Log a trends-DB migration error, suppressing benign 'duplicate column' /
|
|
402
|
+
'table already exists' cases that are expected under concurrent init.
|
|
403
|
+
|
|
404
|
+
The migration blocks in _init_trends_db are guarded by PRAGMA table_info
|
|
405
|
+
checks, so a 'duplicate column name' error means a concurrent process won
|
|
406
|
+
the race — benign and idempotent. Any other sqlite3.Error (disk full,
|
|
407
|
+
corruption, I/O error) would otherwise be silently swallowed, leaving the
|
|
408
|
+
column missing and causing confusing downstream crashes far from the root
|
|
409
|
+
cause. Log those to stderr so they are discoverable.
|
|
410
|
+
"""
|
|
411
|
+
_measure_facade = _compat.facade()
|
|
412
|
+
msg = str(exc)
|
|
413
|
+
benign = (
|
|
414
|
+
"duplicate column" in msg
|
|
415
|
+
or "already exists" in msg
|
|
416
|
+
)
|
|
417
|
+
if not benign:
|
|
418
|
+
try:
|
|
419
|
+
_measure_facade.sys.stderr.write(
|
|
420
|
+
"[Token Optimizer] trends DB migration '%s' failed: %s\n"
|
|
421
|
+
% (step, msg)
|
|
422
|
+
)
|
|
423
|
+
except Exception:
|
|
424
|
+
pass
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
class _SkipMigration(Exception):
|
|
428
|
+
"""Nothing to migrate; leave the step without touching the write lock."""
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _origin_insert_parts(conn, table):
|
|
432
|
+
"""(column SQL, placeholder SQL, values) that add ``origin`` to an INSERT
|
|
433
|
+
into ``table`` -- or three empties when the column is missing (a migration
|
|
434
|
+
that could not run yet), so the row still lands without it instead of the
|
|
435
|
+
whole event being lost to an "no such column" error."""
|
|
436
|
+
_measure_facade = _compat.facade()
|
|
437
|
+
try:
|
|
438
|
+
cols = {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
|
439
|
+
except Exception:
|
|
440
|
+
cols = set()
|
|
441
|
+
if "origin" in cols:
|
|
442
|
+
return ", origin", ", ?", (_measure_facade.run_origin(),)
|
|
443
|
+
return "", "", ()
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _claude_projects_like_patterns() -> tuple:
|
|
447
|
+
"""Prefix LIKE patterns (ESCAPE '!') for transcripts under the resolved
|
|
448
|
+
Claude config's projects/ dir, or () when that is the default ~/.claude
|
|
449
|
+
(the literal pattern already covers it) or unresolvable.
|
|
450
|
+
|
|
451
|
+
Anchored at the start of the path, so a "copilot:"/"hermes:" dedup key or
|
|
452
|
+
a path that merely contains the folder name further down never matches.
|
|
453
|
+
Forward slashes only: callers match it against _PLATFORM_PATH_SQL, which
|
|
454
|
+
folds the backslashes of rows written on Windows to forward slashes.
|
|
455
|
+
"""
|
|
456
|
+
_measure_facade = _compat.facade()
|
|
457
|
+
try:
|
|
458
|
+
projects = _measure_facade.Path(_measure_facade.CLAUDE_DIR) / "projects"
|
|
459
|
+
if projects == _measure_facade.Path(_measure_facade.HOME) / ".claude" / "projects":
|
|
460
|
+
return ()
|
|
461
|
+
form = str(projects).replace("\\", "/")
|
|
462
|
+
esc = form.replace("!", "!!").replace("%", "!%").replace("_", "!_")
|
|
463
|
+
return (esc + "/%",)
|
|
464
|
+
except Exception:
|
|
465
|
+
return ()
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _sql_quote(value):
|
|
469
|
+
_measure_facade = _compat.facade()
|
|
470
|
+
return "'" + str(value).replace("'", "''") + "'"
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _fixture_session_sql(col=None):
|
|
474
|
+
_measure_facade = _compat.facade()
|
|
475
|
+
globs = " OR ".join(f"{col} GLOB {_measure_facade._sql_quote(g)}" for g in _measure_facade._FIXTURE_SESSION_GLOBS)
|
|
476
|
+
numeric_codex = (f"({col} GLOB 'codex-sess-[0-9]*' "
|
|
477
|
+
f"AND substr({col}, 12) NOT GLOB '*[^0-9]*')")
|
|
478
|
+
return f"({col} IS NOT NULL AND ({globs} OR {numeric_codex}))"
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _is_fixture_session_id(session_id):
|
|
482
|
+
"""Python mirror of _fixture_session_sql, for callers outside SQL."""
|
|
483
|
+
_measure_facade = _compat.facade()
|
|
484
|
+
import fnmatch
|
|
485
|
+
if not session_id:
|
|
486
|
+
return False
|
|
487
|
+
sid = str(session_id)
|
|
488
|
+
if _measure_facade.re.fullmatch(r"codex-sess-[0-9]+", sid):
|
|
489
|
+
return True
|
|
490
|
+
return any(fnmatch.fnmatchcase(sid, g) for g in _measure_facade._FIXTURE_SESSION_GLOBS)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _sql_variants(template, **fragments):
|
|
494
|
+
"""Every statement *template* can become, built once at import.
|
|
495
|
+
|
|
496
|
+
Each keyword names a ``{field}`` in the template and maps a key to one of the
|
|
497
|
+
author's own fixed SQL fragments. The result is keyed by one key per field (in
|
|
498
|
+
keyword order), so a call site selects a prebuilt statement and never assembles
|
|
499
|
+
SQL text at runtime."""
|
|
500
|
+
_measure_facade = _compat.facade()
|
|
501
|
+
names = tuple(fragments)
|
|
502
|
+
return {
|
|
503
|
+
keys: template.format(**{n: fragments[n][k] for n, k in zip(names, keys)})
|
|
504
|
+
for keys in _measure_facade.itertools.product(*fragments.values())
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _counted_twin_sql(alias, table, kind_col, same):
|
|
509
|
+
"""Twin check: an earlier row of the same shape in the same session within
|
|
510
|
+
the window. Correlated EXISTS (not a window function) so a query with a
|
|
511
|
+
timestamp filter only looks at the rows it reads; the lookup is served by
|
|
512
|
+
the (session_id, kind, timestamp) indexes created in _init_trends_db."""
|
|
513
|
+
_measure_facade = _compat.facade()
|
|
514
|
+
win = _measure_facade._COUNTED_TWIN_WINDOW_SECONDS
|
|
515
|
+
return (
|
|
516
|
+
f"EXISTS (SELECT 1 FROM main.{table} p WHERE p.session_id = {alias}.session_id "
|
|
517
|
+
f"AND p.{kind_col} = {alias}.{kind_col} AND {same} "
|
|
518
|
+
f"AND p.timestamp <= {alias}.timestamp "
|
|
519
|
+
f"AND p.timestamp >= strftime('%Y-%m-%dT%H:%M:%S', julianday({alias}.timestamp) - {win + 1.0} / 86400.0) "
|
|
520
|
+
f"AND (p.timestamp < {alias}.timestamp OR p.id < {alias}.id) "
|
|
521
|
+
f"AND (julianday({alias}.timestamp) - julianday(p.timestamp)) * 86400.0 <= {win})"
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _media_reexpand_pair_sql(alias):
|
|
526
|
+
"""A re-expansion whose paired archive row is a media result. Its archive
|
|
527
|
+
credit is left out as media, so its debit is left out too."""
|
|
528
|
+
_measure_facade = _compat.facade()
|
|
529
|
+
media = " OR ".join(f"a.detail GLOB {_measure_facade._sql_quote(g)}" for g in _measure_facade._MEDIA_TOOL_GLOBS)
|
|
530
|
+
win = _measure_facade._REEXPAND_PAIR_WINDOW_SECONDS
|
|
531
|
+
return (
|
|
532
|
+
f"EXISTS (SELECT 1 FROM main.savings_events a WHERE a.session_id = {alias}.session_id "
|
|
533
|
+
f"AND a.event_type = 'tool_archive' AND a.detail IS NOT NULL AND ({media}) "
|
|
534
|
+
f"AND a.timestamp <= {alias}.timestamp "
|
|
535
|
+
f"AND a.timestamp >= strftime('%Y-%m-%dT%H:%M:%S', julianday({alias}.timestamp) - {win}.0 / 86400.0) "
|
|
536
|
+
f"AND {alias}.tokens_saved - a.tokens_saved BETWEEN 0 AND {_measure_facade._REEXPAND_PAIR_STUB_TOKENS} "
|
|
537
|
+
f"AND NOT EXISTS (SELECT 1 FROM main.savings_events b WHERE b.session_id = {alias}.session_id "
|
|
538
|
+
f"AND b.event_type = 'tool_archive' AND b.timestamp <= {alias}.timestamp AND b.timestamp > a.timestamp "
|
|
539
|
+
f"AND {alias}.tokens_saved - b.tokens_saved BETWEEN 0 AND {_measure_facade._REEXPAND_PAIR_STUB_TOKENS}))"
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _counted_view_statements():
|
|
544
|
+
"""The two CREATE TEMP VIEW statements, composed once from the fixed rules above."""
|
|
545
|
+
_measure_facade = _compat.facade()
|
|
546
|
+
media = " OR ".join(f"e.detail GLOB {_measure_facade._sql_quote(g)}" for g in _measure_facade._MEDIA_TOOL_GLOBS)
|
|
547
|
+
media_types = ", ".join(_measure_facade._sql_quote(t) for t in _measure_facade._MEDIA_ARCHIVE_EVENT_TYPES)
|
|
548
|
+
media_pair = _measure_facade._media_reexpand_pair_sql("e")
|
|
549
|
+
se_twin = _measure_facade._counted_twin_sql(
|
|
550
|
+
"e", "savings_events", "event_type",
|
|
551
|
+
"p.tokens_saved = e.tokens_saved AND COALESCE(p.detail, '') = COALESCE(e.detail, '')")
|
|
552
|
+
ce_twin = _measure_facade._counted_twin_sql(
|
|
553
|
+
"c", "compression_events", "feature",
|
|
554
|
+
"p.original_tokens = c.original_tokens AND p.compressed_tokens = c.compressed_tokens "
|
|
555
|
+
"AND COALESCE(p.command_pattern, '') = COALESCE(c.command_pattern, '')")
|
|
556
|
+
return (
|
|
557
|
+
"CREATE TEMP VIEW IF NOT EXISTS counted_savings_events AS "
|
|
558
|
+
"SELECT e.* FROM main.savings_events e "
|
|
559
|
+
f"WHERE NOT {_measure_facade._fixture_session_sql('e.session_id')}"
|
|
560
|
+
f" AND NOT (e.event_type IN ({media_types}) AND e.detail IS NOT NULL AND ({media}))"
|
|
561
|
+
f" AND NOT (e.event_type = 'tool_archive_reexpand' AND COALESCE(e.session_id, '') != '' AND {media_pair})"
|
|
562
|
+
f" AND NOT (e.tokens_saved > 0 AND COALESCE(e.session_id, '') != '' AND {se_twin})",
|
|
563
|
+
"CREATE TEMP VIEW IF NOT EXISTS counted_compression_events AS "
|
|
564
|
+
"SELECT c.* FROM main.compression_events c "
|
|
565
|
+
f"WHERE NOT {_measure_facade._fixture_session_sql('c.session_id')}"
|
|
566
|
+
f" AND NOT (c.original_tokens > c.compressed_tokens AND COALESCE(c.session_id, '') != '' AND {ce_twin})",
|
|
567
|
+
)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _counted_media_candidate_statement():
|
|
571
|
+
"""Media archive events that pass every other counted-view rule."""
|
|
572
|
+
_measure_facade = _compat.facade()
|
|
573
|
+
media = " OR ".join(f"e.detail GLOB {_measure_facade._sql_quote(g)}" for g in _measure_facade._MEDIA_TOOL_GLOBS)
|
|
574
|
+
se_twin = _measure_facade._counted_twin_sql(
|
|
575
|
+
"e", "savings_events", "event_type",
|
|
576
|
+
"p.tokens_saved = e.tokens_saved AND COALESCE(p.detail, '') = COALESCE(e.detail, '')")
|
|
577
|
+
return (
|
|
578
|
+
"SELECT 'md:'||e.id, e.session_uuid, e.timestamp, 0, NULL, e.model "
|
|
579
|
+
"FROM main.savings_events e WHERE e.event_type = 'tool_archive' AND e.timestamp >= ? "
|
|
580
|
+
f"AND e.detail IS NOT NULL AND ({media}) "
|
|
581
|
+
f"AND NOT {_measure_facade._fixture_session_sql('e.session_id')} "
|
|
582
|
+
f"AND NOT (e.tokens_saved > 0 AND COALESCE(e.session_id, '') != '' AND {se_twin})"
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _ensure_counted_views(conn):
|
|
587
|
+
"""Create the per-connection counted views (idempotent, TEMP, read-only).
|
|
588
|
+
|
|
589
|
+
counted_savings_events and counted_compression_events have the same
|
|
590
|
+
columns as the tables they read. Safe to call on any trends.db connection;
|
|
591
|
+
returns False (and callers fall back to the raw table) only if the tables
|
|
592
|
+
are missing or the SQLite build lacks window functions."""
|
|
593
|
+
_measure_facade = _compat.facade()
|
|
594
|
+
try:
|
|
595
|
+
have = {r[0] for r in conn.execute(
|
|
596
|
+
"SELECT name FROM sqlite_temp_master WHERE type='view'").fetchall()}
|
|
597
|
+
if {"counted_savings_events", "counted_compression_events"} <= have:
|
|
598
|
+
return True
|
|
599
|
+
for statement in _measure_facade._COUNTED_VIEW_SQL:
|
|
600
|
+
conn.execute(statement)
|
|
601
|
+
# SQLite resolves view columns lazily: a database missing a column the
|
|
602
|
+
# filters use (very old installs, minimal schemas) only fails on first
|
|
603
|
+
# read. Probe now and fall back to the raw tables instead.
|
|
604
|
+
conn.execute("SELECT 1 FROM counted_savings_events LIMIT 0").fetchall()
|
|
605
|
+
conn.execute("SELECT 1 FROM counted_compression_events LIMIT 0").fetchall()
|
|
606
|
+
return True
|
|
607
|
+
except _measure_facade.sqlite3.Error:
|
|
608
|
+
for drop in ("DROP VIEW IF EXISTS temp.counted_savings_events",
|
|
609
|
+
"DROP VIEW IF EXISTS temp.counted_compression_events"):
|
|
610
|
+
try:
|
|
611
|
+
conn.execute(drop)
|
|
612
|
+
except _measure_facade.sqlite3.Error:
|
|
613
|
+
pass
|
|
614
|
+
return False
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def _counted_table(conn, table):
|
|
618
|
+
"""Name of the counted view for *table*, or the raw table if views fail."""
|
|
619
|
+
_measure_facade = _compat.facade()
|
|
620
|
+
return _measure_facade._COUNTED_SOURCES[table][0] if _measure_facade._ensure_counted_views(conn) else table
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _counted_sql(table, template):
|
|
624
|
+
"""Statement for every source _counted_table(conn, table) can return, keyed by
|
|
625
|
+
that name. The template's ``{table}`` field is the only thing that varies."""
|
|
626
|
+
_measure_facade = _compat.facade()
|
|
627
|
+
variants = _measure_facade._sql_variants(template, table={name: name for name in _measure_facade._COUNTED_SOURCES[table]})
|
|
628
|
+
return {name: sql for (name,), sql in variants.items()}
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _connect_trends_db():
|
|
632
|
+
"""Open the trends DB with the standard pragmas (no migrations run)."""
|
|
633
|
+
_measure_facade = _compat.facade()
|
|
634
|
+
conn = _measure_facade.sqlite3.connect(str(_measure_facade.TRENDS_DB))
|
|
635
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
636
|
+
conn.execute("PRAGMA busy_timeout=5000")
|
|
637
|
+
# Auto-checkpoint every 100 pages (~400 KiB) instead of 1000 (~4 MiB).
|
|
638
|
+
# A single large transaction (e.g. _rebuild_aggregate_tables) cannot
|
|
639
|
+
# checkpoint mid-flight, so a smaller threshold bounds the WAL growth
|
|
640
|
+
# between transactions to ~400 KiB instead of ~4 MiB, keeping the
|
|
641
|
+
# post-checkpoint WAL closer to the 64 MiB journal_size_limit.
|
|
642
|
+
conn.execute("PRAGMA wal_autocheckpoint=100")
|
|
643
|
+
conn.execute("PRAGMA journal_size_limit=67108864")
|
|
644
|
+
return conn
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _snapshot_activity_dating_prestate(conn, old_rows):
|
|
648
|
+
"""Journal pre-migration session dates/calls and copy the aggregate tables
|
|
649
|
+
aside, inside the caller's open transaction. ``old_rows`` holds
|
|
650
|
+
``(jsonl_path, date, first_activity_day, last_activity_day, daily_calls_json)`` read before
|
|
651
|
+
``repair_activity_dates`` rewrote the dates, so rollback restores the
|
|
652
|
+
values the migration replaced rather than the repaired ones."""
|
|
653
|
+
_measure_facade = _compat.facade()
|
|
654
|
+
conn.execute(f"DROP TABLE IF EXISTS {_measure_facade._ACTIVITY_DATING_JOURNAL}")
|
|
655
|
+
conn.execute(
|
|
656
|
+
f"CREATE TABLE {_measure_facade._ACTIVITY_DATING_JOURNAL} ("
|
|
657
|
+
"jsonl_path TEXT PRIMARY KEY, old_date TEXT, "
|
|
658
|
+
"old_first_activity_day TEXT, old_last_activity_day TEXT, old_daily_calls_json TEXT)")
|
|
659
|
+
conn.executemany(
|
|
660
|
+
f"INSERT INTO {_measure_facade._ACTIVITY_DATING_JOURNAL} "
|
|
661
|
+
"(jsonl_path, old_date, old_first_activity_day, old_last_activity_day, old_daily_calls_json) "
|
|
662
|
+
"VALUES (?, ?, ?, ?, ?)", old_rows)
|
|
663
|
+
for table in _measure_facade._ACTIVITY_AGGREGATE_TABLES:
|
|
664
|
+
backup = f"{table}_pre_activity_v1"
|
|
665
|
+
conn.execute(f"DROP TABLE IF EXISTS {backup}")
|
|
666
|
+
conn.execute(f"CREATE TABLE {backup} AS SELECT * FROM {table}")
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _archive_pre_activity_state_files():
|
|
670
|
+
"""Move every pre-activity derived state file off its live name.
|
|
671
|
+
|
|
672
|
+
The first archive keeps the ``.pre-activity-v1`` suffix; when that name is
|
|
673
|
+
already taken (an interrupted earlier run, a restored backup) the active
|
|
674
|
+
copy moves to the next free ``.pre-activity-v1.N`` instead. The stale file
|
|
675
|
+
therefore always leaves its live name — it cannot keep serving as an
|
|
676
|
+
anchor — and no earlier archive is overwritten. Files already stamped
|
|
677
|
+
``activity_basis == 1`` were rebuilt under activity dating and stay."""
|
|
678
|
+
_measure_facade = _compat.facade()
|
|
679
|
+
for name in ("baseline_state.json", "workload_anchor.json", "workload_anchor_pretool.json",
|
|
680
|
+
"weekly_full_value.json", "subagent_pool.json", "compact_advice_cache.json"):
|
|
681
|
+
path = _measure_facade.SNAPSHOT_DIR / name
|
|
682
|
+
if not path.exists():
|
|
683
|
+
continue
|
|
684
|
+
try:
|
|
685
|
+
if _measure_facade.json.loads(path.read_text()).get("activity_basis") == 1:
|
|
686
|
+
continue
|
|
687
|
+
except (OSError, ValueError, AttributeError):
|
|
688
|
+
pass
|
|
689
|
+
retained = path.with_name(path.name + ".pre-activity-v1")
|
|
690
|
+
suffix = 2
|
|
691
|
+
while retained.exists():
|
|
692
|
+
retained = path.with_name(f"{path.name}.pre-activity-v1.{suffix}")
|
|
693
|
+
suffix += 1
|
|
694
|
+
path.rename(retained)
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def rollback_activity_dating(conn):
|
|
698
|
+
"""Developer-only safety net for immediately checking a migration on a copy.
|
|
699
|
+
|
|
700
|
+
No CLI is exposed. Use before any recollection or new writes: this restores
|
|
701
|
+
snapshot dates/calls and aggregates, so later changes would be overwritten
|
|
702
|
+
or lost. It is not a downgrade or live-database recovery mechanism.
|
|
703
|
+
Restores the session dates/calls journaled by jsonl_path before the rewrite, copies the
|
|
704
|
+
``*_pre_activity_v1`` aggregate backups back over the rebuilt tables and
|
|
705
|
+
clears the migration marker, so the next ``_init_trends_db`` re-runs the
|
|
706
|
+
migration. The ``.pre-activity-v1`` JSON archives are left in place: they
|
|
707
|
+
are retained evidence, and derived files regenerate on their own. Returns
|
|
708
|
+
True when pre-migration state was restored, False when there was nothing
|
|
709
|
+
to undo. Caller owns the connection; this commits on success.
|
|
710
|
+
"""
|
|
711
|
+
# Only a committed migration is reversible: without the marker the journal
|
|
712
|
+
# and backups (if any) belong to an earlier run or a rolled-back attempt,
|
|
713
|
+
# and restoring them could overwrite newer state with stale snapshots.
|
|
714
|
+
_measure_facade = _compat.facade()
|
|
715
|
+
if not conn.execute(
|
|
716
|
+
"SELECT 1 FROM schema_migrations WHERE name='activity_dating_v1'").fetchone():
|
|
717
|
+
return False
|
|
718
|
+
tables = {r[0] for r in conn.execute(
|
|
719
|
+
"SELECT name FROM sqlite_master WHERE type='table'")}
|
|
720
|
+
journal = _measure_facade._ACTIVITY_DATING_JOURNAL in tables
|
|
721
|
+
backups = [t for t in _measure_facade._ACTIVITY_AGGREGATE_TABLES
|
|
722
|
+
if f"{t}_pre_activity_v1" in tables]
|
|
723
|
+
if not journal and not backups:
|
|
724
|
+
return False
|
|
725
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
726
|
+
try:
|
|
727
|
+
if journal:
|
|
728
|
+
rows = conn.execute(
|
|
729
|
+
f"SELECT jsonl_path, old_date, old_first_activity_day, "
|
|
730
|
+
f"old_last_activity_day, old_daily_calls_json FROM {_measure_facade._ACTIVITY_DATING_JOURNAL}").fetchall()
|
|
731
|
+
conn.executemany(
|
|
732
|
+
"UPDATE session_log SET date=?, first_activity_day=?, "
|
|
733
|
+
"last_activity_day=?, daily_calls_json=? WHERE jsonl_path=?",
|
|
734
|
+
[(old_date, first, last, calls, path)
|
|
735
|
+
for path, old_date, first, last, calls in rows])
|
|
736
|
+
for table in backups:
|
|
737
|
+
backup = f"{table}_pre_activity_v1"
|
|
738
|
+
live_cols = [r[1] for r in conn.execute(f"PRAGMA table_info({table})")]
|
|
739
|
+
backup_cols = {r[1] for r in conn.execute(f"PRAGMA table_info({backup})")}
|
|
740
|
+
cols = [c for c in live_cols if c in backup_cols]
|
|
741
|
+
if cols:
|
|
742
|
+
conn.execute(f"DELETE FROM {table}")
|
|
743
|
+
conn.execute(
|
|
744
|
+
f"INSERT INTO {table} ({', '.join(cols)}) "
|
|
745
|
+
f"SELECT {', '.join(cols)} FROM {backup}")
|
|
746
|
+
conn.execute(f"DROP TABLE {backup}")
|
|
747
|
+
if journal:
|
|
748
|
+
conn.execute(f"DROP TABLE {_measure_facade._ACTIVITY_DATING_JOURNAL}")
|
|
749
|
+
conn.execute("DELETE FROM schema_migrations WHERE name='activity_dating_v1'")
|
|
750
|
+
conn.commit()
|
|
751
|
+
except Exception:
|
|
752
|
+
conn.rollback()
|
|
753
|
+
raise
|
|
754
|
+
return True
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _init_trends_db():
|
|
758
|
+
"""Initialize the trends SQLite DB. Returns a connection.
|
|
759
|
+
|
|
760
|
+
Uses Total Recall's DB-lock pattern: WAL mode + 5s busy_timeout + retry.
|
|
761
|
+
"""
|
|
762
|
+
_measure_facade = _compat.facade()
|
|
763
|
+
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
764
|
+
conn = _measure_facade._connect_trends_db()
|
|
765
|
+
conn.executescript(_measure_facade._SCHEMA)
|
|
766
|
+
# Migrate existing DBs: add slug/topic columns if missing
|
|
767
|
+
try:
|
|
768
|
+
cols = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
|
|
769
|
+
if "slug" not in cols:
|
|
770
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN slug TEXT")
|
|
771
|
+
if "topic" not in cols:
|
|
772
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN topic TEXT")
|
|
773
|
+
if "cache_create_1h_tokens" not in cols:
|
|
774
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN cache_create_1h_tokens INTEGER DEFAULT 0")
|
|
775
|
+
if "cache_create_5m_tokens" not in cols:
|
|
776
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN cache_create_5m_tokens INTEGER DEFAULT 0")
|
|
777
|
+
if "cache_ttl_scanned" not in cols:
|
|
778
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN cache_ttl_scanned INTEGER DEFAULT 0")
|
|
779
|
+
if "avg_call_gap_seconds" not in cols:
|
|
780
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN avg_call_gap_seconds REAL")
|
|
781
|
+
if "max_call_gap_seconds" not in cols:
|
|
782
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN max_call_gap_seconds REAL")
|
|
783
|
+
if "p95_call_gap_seconds" not in cols:
|
|
784
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN p95_call_gap_seconds REAL")
|
|
785
|
+
if "model_usage_breakdown_json" not in cols:
|
|
786
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN model_usage_breakdown_json TEXT")
|
|
787
|
+
if "all_model_usage_json" not in cols:
|
|
788
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN all_model_usage_json TEXT")
|
|
789
|
+
if "quality_score" not in cols:
|
|
790
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN quality_score REAL")
|
|
791
|
+
if "quality_grade" not in cols:
|
|
792
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN quality_grade TEXT")
|
|
793
|
+
# B1: per-session reclaimable stale-read waste (opportunity tier only,
|
|
794
|
+
# never summed into realized savings). Defaults 0 for pre-existing rows.
|
|
795
|
+
if "stale_waste_tokens" not in cols:
|
|
796
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN stale_waste_tokens INTEGER DEFAULT 0")
|
|
797
|
+
# Stable UUID-keyed join column so savings/compression events can
|
|
798
|
+
# join to their originating session without LIKE-scanning jsonl_path.
|
|
799
|
+
# The session UUID is the JSONL file stem (the Claude session UUID).
|
|
800
|
+
if "session_uuid" not in cols:
|
|
801
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN session_uuid TEXT")
|
|
802
|
+
# Copilot cost is platform-reported (AI credits / premium requests) and
|
|
803
|
+
# CANNOT be re-derived from token counts the way Claude/Codex cost is,
|
|
804
|
+
# so it must be persisted. Also carry the source discriminator + plane
|
|
805
|
+
# so the credits-led dashboard keeps CLI and VS Code sessions distinct.
|
|
806
|
+
if "cost_usd" not in cols:
|
|
807
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN cost_usd REAL")
|
|
808
|
+
if "cost_source" not in cols:
|
|
809
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN cost_source TEXT")
|
|
810
|
+
if "credits" not in cols:
|
|
811
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN credits REAL")
|
|
812
|
+
if "platform" not in cols:
|
|
813
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN platform TEXT")
|
|
814
|
+
# Marks a session whose totals are partial (crashed / still-active at
|
|
815
|
+
# rollup time). Lets a later rollup UPGRADE the row once real shutdown
|
|
816
|
+
# totals arrive, instead of INSERT-OR-IGNORE freezing the partial data.
|
|
817
|
+
if "incomplete" not in cols:
|
|
818
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN incomplete INTEGER DEFAULT 0")
|
|
819
|
+
# Subagent sidechains (isSidechain:true in the JSONL) are not human working
|
|
820
|
+
# sessions; flagging them lets the before/after cost comparison filter to
|
|
821
|
+
# human sessions on both sides instead of diluting "after" with cheap
|
|
822
|
+
# sidechain rows. Added WITHOUT a default so existing rows are NULL =
|
|
823
|
+
# "not yet classified" — the sentinel _backfill_is_sidechain targets. New
|
|
824
|
+
# collection always writes an explicit 0/1. Queries treat NULL as human.
|
|
825
|
+
if "is_sidechain" not in cols:
|
|
826
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN is_sidechain INTEGER")
|
|
827
|
+
if "sidechain_reason" not in cols:
|
|
828
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN sidechain_reason TEXT")
|
|
829
|
+
# Official /stats-compatible usage is captured without streaming dedup
|
|
830
|
+
# and without cache classes. Legacy rows are filled by a one-time scan.
|
|
831
|
+
if "reported_input_tokens" not in cols:
|
|
832
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN reported_input_tokens INTEGER")
|
|
833
|
+
if "reported_output_tokens" not in cols:
|
|
834
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN reported_output_tokens INTEGER")
|
|
835
|
+
if "reported_model_usage_json" not in cols:
|
|
836
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN reported_model_usage_json TEXT")
|
|
837
|
+
# Per-local-day, per-model token buckets for the whole session INCLUDING
|
|
838
|
+
# its subagents. The daily cost rollup prices from this so each day bills
|
|
839
|
+
# its own requests and delegated work is not dropped (#200).
|
|
840
|
+
if "daily_usage_json" not in cols:
|
|
841
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN daily_usage_json TEXT")
|
|
842
|
+
# Where the collecting process ran: 'local', 'cloud' (Claude Code cloud
|
|
843
|
+
# VM) or 'cowork'. NULL on rows collected before the column existed,
|
|
844
|
+
# which were all local. Groundwork for importing a cloud VM's rows or a
|
|
845
|
+
# teleported transcript without counting the session twice: the dedupe
|
|
846
|
+
# key stays session_uuid (the transcript's session id); origin records
|
|
847
|
+
# which side a row came from.
|
|
848
|
+
if "origin" not in cols:
|
|
849
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN origin TEXT")
|
|
850
|
+
# Which usage-attribution version stored the row. NULL = stored before
|
|
851
|
+
# versioning; collect re-parses such rows from their transcript.
|
|
852
|
+
if "usage_parser_version" not in cols:
|
|
853
|
+
conn.execute("ALTER TABLE session_log ADD COLUMN usage_parser_version INTEGER")
|
|
854
|
+
conn.commit()
|
|
855
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
856
|
+
_measure_facade._log_migration_error("session_log columns", _e)
|
|
857
|
+
# Shares already recorded are usage evidence: a claims table from before the
|
|
858
|
+
# model and day columns keeps its counters and gains the columns. Only a
|
|
859
|
+
# table that never held counters (nothing to keep) is recreated.
|
|
860
|
+
try:
|
|
861
|
+
_claim_cols = {r[1] for r in conn.execute("PRAGMA table_info(usage_request_claims)").fetchall()}
|
|
862
|
+
if _claim_cols and "inp" not in _claim_cols:
|
|
863
|
+
conn.execute("DROP TABLE usage_request_claims")
|
|
864
|
+
conn.executescript(_measure_facade._SCHEMA)
|
|
865
|
+
else:
|
|
866
|
+
for _col in ("model", "day"):
|
|
867
|
+
if _claim_cols and _col not in _claim_cols:
|
|
868
|
+
conn.execute(f"ALTER TABLE usage_request_claims ADD COLUMN {_col} TEXT")
|
|
869
|
+
conn.commit()
|
|
870
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
871
|
+
_measure_facade._log_migration_error("usage_request_claims", _e)
|
|
872
|
+
# Same origin column on the per-event savings tables (NULL = legacy/local).
|
|
873
|
+
for _origin_table in ("savings_events", "compression_events"):
|
|
874
|
+
try:
|
|
875
|
+
_ocols = {r[1] for r in conn.execute(f"PRAGMA table_info({_origin_table})").fetchall()}
|
|
876
|
+
if _ocols and "origin" not in _ocols:
|
|
877
|
+
conn.execute(f"ALTER TABLE {_origin_table} ADD COLUMN origin TEXT")
|
|
878
|
+
conn.commit()
|
|
879
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
880
|
+
_measure_facade._log_migration_error(f"{_origin_table} origin column", _e)
|
|
881
|
+
_measure_facade.ensure_activity_schema(conn)
|
|
882
|
+
# Backfill session_uuid from jsonl_path basename stem for existing rows,
|
|
883
|
+
# then create an index so joins are O(log n) instead of full-table LIKE scans.
|
|
884
|
+
# Done in Python (not a single SQL UPDATE) because SQLite lacks a basename
|
|
885
|
+
# function and the path separator can vary on Windows.
|
|
886
|
+
try:
|
|
887
|
+
conn.execute(
|
|
888
|
+
"CREATE INDEX IF NOT EXISTS idx_session_log_uuid ON session_log (session_uuid)"
|
|
889
|
+
)
|
|
890
|
+
rows = conn.execute(
|
|
891
|
+
"SELECT id, jsonl_path FROM session_log "
|
|
892
|
+
"WHERE (session_uuid IS NULL OR session_uuid LIKE 'rollout-%') AND jsonl_path IS NOT NULL"
|
|
893
|
+
).fetchall()
|
|
894
|
+
if rows:
|
|
895
|
+
updates = []
|
|
896
|
+
for row_id, jpath in rows:
|
|
897
|
+
stem = _measure_facade.Path(jpath).stem # strips directory and .jsonl suffix
|
|
898
|
+
if stem and stem != "unknown":
|
|
899
|
+
canonical, _ = _measure_facade._extract_session_uuid(stem)
|
|
900
|
+
updates.append((canonical or stem, row_id))
|
|
901
|
+
if updates:
|
|
902
|
+
conn.executemany(
|
|
903
|
+
"UPDATE session_log SET session_uuid = ? WHERE id = ?", updates
|
|
904
|
+
)
|
|
905
|
+
conn.commit()
|
|
906
|
+
except (_measure_facade.sqlite3.Error, OSError, ValueError) as _e:
|
|
907
|
+
_measure_facade._log_migration_error("session_uuid backfill", _e)
|
|
908
|
+
# One-time backfill of the corrected sidechain classifier. It revisits old
|
|
909
|
+
# rows, including the 1-valued rows the broad marker test misclassified.
|
|
910
|
+
sidechain_changed = 0
|
|
911
|
+
try:
|
|
912
|
+
sidechain_changed, _sidechain_missing = _measure_facade._backfill_is_sidechain(conn)
|
|
913
|
+
except (_measure_facade.sqlite3.Error, OSError) as _e:
|
|
914
|
+
_measure_facade._log_migration_error("sidechain backfill", _e)
|
|
915
|
+
# One-time backfill of official-compatible usage for existing rows. New
|
|
916
|
+
# collection writes these fields directly from every assistant record.
|
|
917
|
+
try:
|
|
918
|
+
_measure_facade._backfill_reported_token_usage(conn)
|
|
919
|
+
except (_measure_facade.sqlite3.Error, OSError) as _e:
|
|
920
|
+
_measure_facade._log_migration_error("reported token backfill", _e)
|
|
921
|
+
if sidechain_changed:
|
|
922
|
+
try:
|
|
923
|
+
_measure_facade._rebuild_aggregate_tables(conn)
|
|
924
|
+
conn.commit()
|
|
925
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
926
|
+
_measure_facade._log_migration_error("aggregate rebuild", _e)
|
|
927
|
+
# Backfill platform for rows collected before the column was wired into the
|
|
928
|
+
# INSERT paths. The jsonl_path discriminator is definitive: Claude sessions
|
|
929
|
+
# live under ~/.claude/projects/, Codex under ~/.codex/sessions/, Hermes
|
|
930
|
+
# uses "hermes:" dedup keys, and Copilot uses "copilot:" dedup keys. Only
|
|
931
|
+
# infer when the path unambiguously identifies one platform; anything else
|
|
932
|
+
# stays NULL. Idempotent (gated by platform IS NULL). An UPDATE takes the
|
|
933
|
+
# write lock even when it matches nothing, so check with a read first: on
|
|
934
|
+
# every dashboard open this would otherwise wait out busy_timeout behind a
|
|
935
|
+
# running collector.
|
|
936
|
+
_platform_patterns = ("%/.claude/projects/%", "%/.codex/sessions/%", "%/.codex/archived_sessions/%",
|
|
937
|
+
"hermes:%", "copilot:%", "cursor:%", "antigravity:%")
|
|
938
|
+
# A relocated Claude config (CLAUDE_CONFIG_DIR) keeps its transcripts under
|
|
939
|
+
# <config>/projects/, which the literal ~/.claude pattern above misses.
|
|
940
|
+
_claude_cfg_patterns = _measure_facade._claude_projects_like_patterns()
|
|
941
|
+
# Paths are matched with backslashes folded to '/', so a row written on
|
|
942
|
+
# Windows (C:\Users\me\.claude\projects\...) is tagged like a POSIX one.
|
|
943
|
+
_p = _measure_facade._PLATFORM_PATH_SQL
|
|
944
|
+
_cfg_where = " OR ".join([f"{_p} LIKE ? ESCAPE '!'"] * len(_claude_cfg_patterns))
|
|
945
|
+
try:
|
|
946
|
+
_needs_platform = conn.execute(
|
|
947
|
+
"SELECT 1 FROM session_log WHERE platform IS NULL AND ("
|
|
948
|
+
+ " OR ".join([f"{_p} LIKE ?"] * len(_platform_patterns))
|
|
949
|
+
+ (" OR " + _cfg_where if _cfg_where else "") + ") LIMIT 1",
|
|
950
|
+
_platform_patterns + _claude_cfg_patterns,
|
|
951
|
+
).fetchone()
|
|
952
|
+
except _measure_facade.sqlite3.Error:
|
|
953
|
+
_needs_platform = True
|
|
954
|
+
try:
|
|
955
|
+
if not _needs_platform:
|
|
956
|
+
raise _measure_facade._SkipMigration
|
|
957
|
+
for _platform, _pattern in (("claude", "%/.claude/projects/%"),
|
|
958
|
+
("codex", "%/.codex/sessions/%"),
|
|
959
|
+
("codex", "%/.codex/archived_sessions/%"),
|
|
960
|
+
("hermes", "hermes:%"),
|
|
961
|
+
("copilot", "copilot:%"),
|
|
962
|
+
("cursor", "cursor:%"),
|
|
963
|
+
("antigravity", "antigravity:%")):
|
|
964
|
+
conn.execute(
|
|
965
|
+
f"UPDATE session_log SET platform = ? WHERE platform IS NULL AND {_p} LIKE ?",
|
|
966
|
+
(_platform, _pattern),
|
|
967
|
+
)
|
|
968
|
+
# Last, so every other runtime's definitive pattern has claimed its rows
|
|
969
|
+
# first; the Codex path patterns are excluded again so a config dir
|
|
970
|
+
# that happens to sit inside a Codex home can never tag a Codex file.
|
|
971
|
+
if _cfg_where:
|
|
972
|
+
conn.execute(
|
|
973
|
+
"UPDATE session_log SET platform = 'claude' "
|
|
974
|
+
"WHERE platform IS NULL AND (" + _cfg_where + ") "
|
|
975
|
+
f"AND {_p} NOT LIKE '%/.codex/sessions/%' "
|
|
976
|
+
f"AND {_p} NOT LIKE '%/.codex/archived_sessions/%'",
|
|
977
|
+
_claude_cfg_patterns,
|
|
978
|
+
)
|
|
979
|
+
conn.commit()
|
|
980
|
+
except _measure_facade._SkipMigration:
|
|
981
|
+
pass
|
|
982
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
983
|
+
_measure_facade._log_migration_error("platform backfill", _e)
|
|
984
|
+
# Migrate: add quality columns to daily_stats for existing DBs
|
|
985
|
+
try:
|
|
986
|
+
ds_cols = {r[1] for r in conn.execute("PRAGMA table_info(daily_stats)").fetchall()}
|
|
987
|
+
for name, kind in (("session_count", "INTEGER"), ("total_input", "INTEGER"),
|
|
988
|
+
("total_output", "INTEGER"), ("total_duration", "REAL"), ("avg_cache_hit", "REAL")):
|
|
989
|
+
if name not in ds_cols:
|
|
990
|
+
conn.execute(f"ALTER TABLE daily_stats ADD COLUMN {name} {kind}")
|
|
991
|
+
if "avg_quality_score" not in ds_cols:
|
|
992
|
+
conn.execute("ALTER TABLE daily_stats ADD COLUMN avg_quality_score REAL")
|
|
993
|
+
if "worst_grade" not in ds_cols:
|
|
994
|
+
conn.execute("ALTER TABLE daily_stats ADD COLUMN worst_grade TEXT")
|
|
995
|
+
conn.commit()
|
|
996
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
997
|
+
_measure_facade._log_migration_error("daily_stats columns", _e)
|
|
998
|
+
# Migrate: add per-event model column to savings_events (v5.9+). Lets the
|
|
999
|
+
# savings view reprice historical events at the rate that was actually in
|
|
1000
|
+
# effect when they were logged, instead of today's active-model rate.
|
|
1001
|
+
try:
|
|
1002
|
+
se_cols = {r[1] for r in conn.execute("PRAGMA table_info(savings_events)").fetchall()}
|
|
1003
|
+
if "model" not in se_cols:
|
|
1004
|
+
conn.execute("ALTER TABLE savings_events ADD COLUMN model TEXT")
|
|
1005
|
+
# Session_uuid + unjoinable columns for direct session joins (no LIKE scan).
|
|
1006
|
+
# session_uuid = the Claude session UUID (= JSONL basename stem).
|
|
1007
|
+
# unjoinable = 1 when session_id is a short agent_id that cannot be resolved.
|
|
1008
|
+
if "session_uuid" not in se_cols:
|
|
1009
|
+
conn.execute("ALTER TABLE savings_events ADD COLUMN session_uuid TEXT")
|
|
1010
|
+
if "unjoinable" not in se_cols:
|
|
1011
|
+
conn.execute("ALTER TABLE savings_events ADD COLUMN unjoinable INTEGER DEFAULT 0")
|
|
1012
|
+
# Keep-warm idempotency: pause_key uniquely identifies one (session, pause)
|
|
1013
|
+
# realized booking. The UNIQUE index makes SQLite the dedup authority so a
|
|
1014
|
+
# lost ledger marker (or a re-detect across ticks) can never double-book the
|
|
1015
|
+
# same warm resume. Partial index (WHERE pause_key IS NOT NULL) leaves every
|
|
1016
|
+
# legacy/non-keepwarm row -- all NULL here -- unconstrained.
|
|
1017
|
+
if "pause_key" not in se_cols:
|
|
1018
|
+
conn.execute("ALTER TABLE savings_events ADD COLUMN pause_key TEXT")
|
|
1019
|
+
conn.execute(
|
|
1020
|
+
"CREATE INDEX IF NOT EXISTS idx_savings_events_uuid "
|
|
1021
|
+
"ON savings_events (session_uuid)"
|
|
1022
|
+
)
|
|
1023
|
+
conn.execute(
|
|
1024
|
+
"CREATE UNIQUE INDEX IF NOT EXISTS idx_savings_events_pause_key "
|
|
1025
|
+
"ON savings_events (pause_key) WHERE pause_key IS NOT NULL"
|
|
1026
|
+
)
|
|
1027
|
+
conn.commit()
|
|
1028
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
1029
|
+
_measure_facade._log_migration_error("savings_events columns", _e)
|
|
1030
|
+
# Backfill session_uuid on savings_events from session_id where it looks
|
|
1031
|
+
# like a UUID (8-4-4-4-12 hex pattern). Short agent_ids (<=17 chars without
|
|
1032
|
+
# dashes) are flagged unjoinable=1 rather than silently treated as Sonnet.
|
|
1033
|
+
try:
|
|
1034
|
+
import re as _re
|
|
1035
|
+
_UUID_PAT = _re.compile(
|
|
1036
|
+
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
|
1037
|
+
_re.IGNORECASE,
|
|
1038
|
+
)
|
|
1039
|
+
rows = conn.execute(
|
|
1040
|
+
"SELECT id, session_id FROM savings_events "
|
|
1041
|
+
"WHERE session_uuid IS NULL AND session_id IS NOT NULL"
|
|
1042
|
+
).fetchall()
|
|
1043
|
+
if rows:
|
|
1044
|
+
uuid_updates = []
|
|
1045
|
+
unjoinable_updates = []
|
|
1046
|
+
for row_id, sid in rows:
|
|
1047
|
+
canonical, _ = _measure_facade._extract_session_uuid(sid)
|
|
1048
|
+
if canonical:
|
|
1049
|
+
uuid_updates.append((canonical, row_id))
|
|
1050
|
+
elif sid and len(sid) <= 20 and "-" not in sid and sid not in (
|
|
1051
|
+
"unknown", "test-123", "perf_test", "regtest", "demo"
|
|
1052
|
+
):
|
|
1053
|
+
# Short opaque hex agent_id — cannot be resolved to a session_log row
|
|
1054
|
+
unjoinable_updates.append((row_id,))
|
|
1055
|
+
if uuid_updates:
|
|
1056
|
+
conn.executemany(
|
|
1057
|
+
"UPDATE savings_events SET session_uuid = ? WHERE id = ?",
|
|
1058
|
+
uuid_updates,
|
|
1059
|
+
)
|
|
1060
|
+
if unjoinable_updates:
|
|
1061
|
+
conn.executemany(
|
|
1062
|
+
"UPDATE savings_events SET unjoinable = 1 WHERE id = ?",
|
|
1063
|
+
unjoinable_updates,
|
|
1064
|
+
)
|
|
1065
|
+
conn.commit()
|
|
1066
|
+
except (_measure_facade.sqlite3.Error, OSError) as _e:
|
|
1067
|
+
_measure_facade._log_migration_error("savings_events uuid backfill", _e)
|
|
1068
|
+
# Migrate: ensure compression_events table exists for upgrades from v4.x
|
|
1069
|
+
try:
|
|
1070
|
+
conn.execute("SELECT 1 FROM compression_events LIMIT 1")
|
|
1071
|
+
except _measure_facade.sqlite3.OperationalError:
|
|
1072
|
+
try:
|
|
1073
|
+
conn.executescript("""
|
|
1074
|
+
CREATE TABLE IF NOT EXISTS compression_events (
|
|
1075
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1076
|
+
timestamp TEXT NOT NULL,
|
|
1077
|
+
session_id TEXT,
|
|
1078
|
+
session_uuid TEXT,
|
|
1079
|
+
feature TEXT NOT NULL,
|
|
1080
|
+
command_pattern TEXT,
|
|
1081
|
+
original_tokens INTEGER DEFAULT 0,
|
|
1082
|
+
compressed_tokens INTEGER DEFAULT 0,
|
|
1083
|
+
compression_ratio REAL DEFAULT 0.0,
|
|
1084
|
+
quality_preserved INTEGER DEFAULT 1,
|
|
1085
|
+
verified INTEGER DEFAULT 0,
|
|
1086
|
+
detail TEXT,
|
|
1087
|
+
model TEXT
|
|
1088
|
+
);
|
|
1089
|
+
""")
|
|
1090
|
+
conn.commit()
|
|
1091
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
1092
|
+
_measure_facade._log_migration_error("compression_events table", _e)
|
|
1093
|
+
# Idempotent migrations for session_uuid + model on compression_events.
|
|
1094
|
+
# These columns enable per-event session joins and correct model attribution.
|
|
1095
|
+
try:
|
|
1096
|
+
ce_cols = {r[1] for r in conn.execute("PRAGMA table_info(compression_events)").fetchall()}
|
|
1097
|
+
if "session_uuid" not in ce_cols:
|
|
1098
|
+
conn.execute("ALTER TABLE compression_events ADD COLUMN session_uuid TEXT")
|
|
1099
|
+
if "model" not in ce_cols:
|
|
1100
|
+
conn.execute("ALTER TABLE compression_events ADD COLUMN model TEXT")
|
|
1101
|
+
if "tier" not in ce_cols:
|
|
1102
|
+
# Three-tier accounting tag (measured/estimated/
|
|
1103
|
+
# opportunity). Nullable: pre-existing rows stay NULL and keep their
|
|
1104
|
+
# current headline treatment; only new coverage events set a tier.
|
|
1105
|
+
conn.execute("ALTER TABLE compression_events ADD COLUMN tier TEXT")
|
|
1106
|
+
conn.execute(
|
|
1107
|
+
"CREATE INDEX IF NOT EXISTS idx_compression_events_uuid "
|
|
1108
|
+
"ON compression_events (session_uuid)"
|
|
1109
|
+
)
|
|
1110
|
+
# T6: the tripwire edit-rate query filters on (feature, tier); index it so
|
|
1111
|
+
# the per-cohort skeleton/follow-up scans stay cheap as the table grows.
|
|
1112
|
+
# Idempotent (IF NOT EXISTS) — safe on every init.
|
|
1113
|
+
conn.execute(
|
|
1114
|
+
"CREATE INDEX IF NOT EXISTS idx_compression_events_feature_tier "
|
|
1115
|
+
"ON compression_events (feature, tier)"
|
|
1116
|
+
)
|
|
1117
|
+
# Serves the counted views' same-session twin lookup.
|
|
1118
|
+
conn.execute(
|
|
1119
|
+
"CREATE INDEX IF NOT EXISTS idx_compression_events_session_feature_ts "
|
|
1120
|
+
"ON compression_events (session_id, feature, timestamp)"
|
|
1121
|
+
)
|
|
1122
|
+
conn.execute(
|
|
1123
|
+
"CREATE INDEX IF NOT EXISTS idx_savings_events_session_type_ts "
|
|
1124
|
+
"ON savings_events (session_id, event_type, timestamp)"
|
|
1125
|
+
)
|
|
1126
|
+
conn.commit()
|
|
1127
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
1128
|
+
_measure_facade._log_migration_error("compression_events columns", _e)
|
|
1129
|
+
# Backfill session_uuid on compression_events from session_id where UUID pattern.
|
|
1130
|
+
try:
|
|
1131
|
+
import re as _re
|
|
1132
|
+
_UUID_PAT2 = _re.compile(
|
|
1133
|
+
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
|
1134
|
+
_re.IGNORECASE,
|
|
1135
|
+
)
|
|
1136
|
+
ce_rows = conn.execute(
|
|
1137
|
+
"SELECT id, session_id FROM compression_events "
|
|
1138
|
+
"WHERE session_uuid IS NULL AND session_id IS NOT NULL"
|
|
1139
|
+
).fetchall()
|
|
1140
|
+
if ce_rows:
|
|
1141
|
+
ce_updates = [
|
|
1142
|
+
(_measure_facade._extract_session_uuid(sid)[0], row_id)
|
|
1143
|
+
for row_id, sid in ce_rows
|
|
1144
|
+
if _measure_facade._extract_session_uuid(sid)[0]
|
|
1145
|
+
]
|
|
1146
|
+
if ce_updates:
|
|
1147
|
+
conn.executemany(
|
|
1148
|
+
"UPDATE compression_events SET session_uuid = ? WHERE id = ?",
|
|
1149
|
+
ce_updates,
|
|
1150
|
+
)
|
|
1151
|
+
conn.commit()
|
|
1152
|
+
except (_measure_facade.sqlite3.Error, OSError) as _e:
|
|
1153
|
+
_measure_facade._log_migration_error("compression_events uuid backfill", _e)
|
|
1154
|
+
conn.commit()
|
|
1155
|
+
# Journal the pre-rewrite dates before repair_activity_dates opens its
|
|
1156
|
+
# transaction; the journal, aggregate backups, rebuild, archives and
|
|
1157
|
+
# marker then commit or roll back together.
|
|
1158
|
+
pre_activity_rows = []
|
|
1159
|
+
if not conn.execute(
|
|
1160
|
+
"SELECT 1 FROM schema_migrations WHERE name='activity_dating_v1'").fetchone():
|
|
1161
|
+
pre_activity_rows = conn.execute(
|
|
1162
|
+
"SELECT jsonl_path,date,first_activity_day,last_activity_day,daily_calls_json FROM session_log").fetchall()
|
|
1163
|
+
try:
|
|
1164
|
+
if _measure_facade.repair_activity_dates(conn):
|
|
1165
|
+
_measure_facade._snapshot_activity_dating_prestate(conn, pre_activity_rows)
|
|
1166
|
+
_measure_facade._rebuild_aggregate_tables(conn)
|
|
1167
|
+
# Keep original evidence recoverable. These derived comparisons used
|
|
1168
|
+
# session-date windows and must be rebuilt against dated activity.
|
|
1169
|
+
_measure_facade._archive_pre_activity_state_files()
|
|
1170
|
+
conn.execute("INSERT INTO schema_migrations(name) VALUES ('activity_dating_v1')")
|
|
1171
|
+
conn.commit()
|
|
1172
|
+
except Exception as _e:
|
|
1173
|
+
# Includes BEGIN IMMEDIATE lock failures. Roll back any partial work
|
|
1174
|
+
# and return a fresh, usable connection; retry migration on next init.
|
|
1175
|
+
try:
|
|
1176
|
+
conn.rollback()
|
|
1177
|
+
finally:
|
|
1178
|
+
conn.close()
|
|
1179
|
+
_measure_facade._log_migration_error("activity_dating_v1 migration", _e)
|
|
1180
|
+
return _measure_facade._connect_trends_db()
|
|
1181
|
+
return conn
|
|
1182
|
+
|
|
1183
|
+
|
|
1184
|
+
def _compute_call_gap_stats(api_call_timestamps):
|
|
1185
|
+
"""Compute avg/max/p95 gaps between assistant API calls within a session."""
|
|
1186
|
+
_measure_facade = _compat.facade()
|
|
1187
|
+
if len(api_call_timestamps) < 2:
|
|
1188
|
+
return {"avg": None, "max": None, "p95": None}
|
|
1189
|
+
|
|
1190
|
+
gaps = []
|
|
1191
|
+
prev_ts = None
|
|
1192
|
+
for ts in api_call_timestamps:
|
|
1193
|
+
if prev_ts is None:
|
|
1194
|
+
prev_ts = ts
|
|
1195
|
+
continue
|
|
1196
|
+
delta = (ts - prev_ts).total_seconds()
|
|
1197
|
+
if delta >= 0:
|
|
1198
|
+
gaps.append(delta)
|
|
1199
|
+
prev_ts = ts
|
|
1200
|
+
|
|
1201
|
+
if not gaps:
|
|
1202
|
+
return {"avg": None, "max": None, "p95": None}
|
|
1203
|
+
|
|
1204
|
+
sorted_gaps = sorted(gaps)
|
|
1205
|
+
p95_index = max(0, min(len(sorted_gaps) - 1, _measure_facade.math.ceil(len(sorted_gaps) * 0.95) - 1))
|
|
1206
|
+
return {
|
|
1207
|
+
"avg": sum(gaps) / len(gaps),
|
|
1208
|
+
"max": max(gaps),
|
|
1209
|
+
"p95": sorted_gaps[p95_index],
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
def _make_session_key(jsonl_path):
|
|
1214
|
+
"""Generate a stable opaque session key from a JSONL path."""
|
|
1215
|
+
_measure_facade = _compat.facade()
|
|
1216
|
+
if not jsonl_path:
|
|
1217
|
+
return None
|
|
1218
|
+
normalized = str(_measure_facade.Path(jsonl_path).resolve())
|
|
1219
|
+
return _measure_facade.hashlib.sha1(normalized.encode("utf-8")).hexdigest()[:16]
|
|
1220
|
+
|
|
1221
|
+
|
|
1222
|
+
def _retry_db_operation(conn, operation, max_retries=None, initial_backoff=None):
|
|
1223
|
+
"""Retry a database operation with exponential backoff on lock errors.
|
|
1224
|
+
|
|
1225
|
+
Mirrors Total Recall's DB-lock pattern: busy_timeout + retry with backoff.
|
|
1226
|
+
Fails open on persistent lock errors (returns None, caller handles gracefully).
|
|
1227
|
+
Non-lock OperationalErrors are re-raised so real bugs aren't silently swallowed.
|
|
1228
|
+
"""
|
|
1229
|
+
_measure_facade = _compat.facade()
|
|
1230
|
+
for attempt in range(max_retries):
|
|
1231
|
+
try:
|
|
1232
|
+
return operation()
|
|
1233
|
+
except _measure_facade.sqlite3.OperationalError as e:
|
|
1234
|
+
if "database is locked" in str(e) or "unable to open database" in str(e):
|
|
1235
|
+
if attempt < max_retries - 1:
|
|
1236
|
+
backoff = initial_backoff * (2 ** attempt)
|
|
1237
|
+
_measure_facade.time.sleep(backoff)
|
|
1238
|
+
continue
|
|
1239
|
+
return None # exhausted retries on lock error — fail open
|
|
1240
|
+
raise # non-lock error — propagate, don't swallow
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
def _backfill_session_metrics(conn, days=None, limit=None):
|
|
1244
|
+
"""Populate derived session metrics for rows collected before fields existed.
|
|
1245
|
+
|
|
1246
|
+
Bounded per-flush work (limit=50) to prevent re-parse storms. Batched
|
|
1247
|
+
UPDATEs in single transaction to minimize lock duration. Retry with backoff
|
|
1248
|
+
on DB lock errors (mirrors Total Recall's pattern).
|
|
1249
|
+
"""
|
|
1250
|
+
_measure_facade = _compat.facade()
|
|
1251
|
+
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
|
|
1252
|
+
|
|
1253
|
+
def fetch_rows():
|
|
1254
|
+
_measure_facade = _compat.facade()
|
|
1255
|
+
return conn.execute(
|
|
1256
|
+
"""SELECT jsonl_path
|
|
1257
|
+
FROM session_log
|
|
1258
|
+
WHERE date >= ?
|
|
1259
|
+
AND (
|
|
1260
|
+
IFNULL(cache_ttl_scanned, 0) = 0
|
|
1261
|
+
OR avg_call_gap_seconds IS NULL
|
|
1262
|
+
OR max_call_gap_seconds IS NULL
|
|
1263
|
+
OR p95_call_gap_seconds IS NULL
|
|
1264
|
+
OR quality_score IS NULL
|
|
1265
|
+
)
|
|
1266
|
+
ORDER BY date DESC, collected_at DESC
|
|
1267
|
+
LIMIT ?""",
|
|
1268
|
+
(cutoff, limit),
|
|
1269
|
+
).fetchall()
|
|
1270
|
+
|
|
1271
|
+
rows = _measure_facade._retry_db_operation(conn, fetch_rows)
|
|
1272
|
+
if rows is None:
|
|
1273
|
+
return 0
|
|
1274
|
+
|
|
1275
|
+
updates = []
|
|
1276
|
+
for row in rows:
|
|
1277
|
+
jsonl_path = row[0]
|
|
1278
|
+
ttl_1h = 0
|
|
1279
|
+
ttl_5m = 0
|
|
1280
|
+
avg_gap = None
|
|
1281
|
+
max_gap = None
|
|
1282
|
+
p95_gap = None
|
|
1283
|
+
q_score = None
|
|
1284
|
+
q_grade = None
|
|
1285
|
+
parsed = _measure_facade._parse_session_jsonl(jsonl_path) if jsonl_path and _measure_facade.os.path.exists(jsonl_path) else None
|
|
1286
|
+
if not parsed:
|
|
1287
|
+
continue
|
|
1288
|
+
if parsed:
|
|
1289
|
+
ttl_1h = int(parsed.get("total_cache_create_1h", 0) or 0)
|
|
1290
|
+
ttl_5m = int(parsed.get("total_cache_create_5m", 0) or 0)
|
|
1291
|
+
avg_gap = parsed.get("avg_call_gap_seconds")
|
|
1292
|
+
max_gap = parsed.get("max_call_gap_seconds")
|
|
1293
|
+
p95_gap = parsed.get("p95_call_gap_seconds")
|
|
1294
|
+
sq = _measure_facade.score_session_quality(parsed)
|
|
1295
|
+
q_score = sq["score"]
|
|
1296
|
+
q_grade = sq["grade"]
|
|
1297
|
+
updates.append((ttl_1h, ttl_5m, avg_gap, max_gap, p95_gap, q_score, q_grade, str(jsonl_path)))
|
|
1298
|
+
|
|
1299
|
+
if not updates:
|
|
1300
|
+
return 0
|
|
1301
|
+
|
|
1302
|
+
def batch_update():
|
|
1303
|
+
# Batch all UPDATEs into one commit to minimize lock duration (Total
|
|
1304
|
+
# Recall's small-chunk pattern). Deliberately NO explicit BEGIN IMMEDIATE:
|
|
1305
|
+
# a caller (collect_sessions) may have uncommitted inserts on this same
|
|
1306
|
+
# conn — an explicit BEGIN would raise "transaction within a transaction",
|
|
1307
|
+
# and rolling back on that error would DISCARD the caller's pending work.
|
|
1308
|
+
# Sharing the implicit transaction commits our updates and theirs together.
|
|
1309
|
+
_measure_facade = _compat.facade()
|
|
1310
|
+
conn.executemany(
|
|
1311
|
+
"""UPDATE session_log
|
|
1312
|
+
SET cache_create_1h_tokens = ?,
|
|
1313
|
+
cache_create_5m_tokens = ?,
|
|
1314
|
+
cache_ttl_scanned = 1,
|
|
1315
|
+
avg_call_gap_seconds = ?,
|
|
1316
|
+
max_call_gap_seconds = ?,
|
|
1317
|
+
p95_call_gap_seconds = ?,
|
|
1318
|
+
quality_score = COALESCE(quality_score, ?),
|
|
1319
|
+
quality_grade = COALESCE(quality_grade, ?)
|
|
1320
|
+
WHERE jsonl_path = ?""",
|
|
1321
|
+
updates,
|
|
1322
|
+
)
|
|
1323
|
+
conn.commit()
|
|
1324
|
+
return len(updates)
|
|
1325
|
+
|
|
1326
|
+
result = _measure_facade._retry_db_operation(conn, batch_update)
|
|
1327
|
+
return result if result is not None else 0
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
def _backfill_daily_usage(conn, days=None, budget_seconds=None):
|
|
1331
|
+
"""Fill daily_usage_json for rows collected before per-day attribution.
|
|
1332
|
+
|
|
1333
|
+
Time-boxed rather than count-capped: parses are memoized and most rows are
|
|
1334
|
+
small, so the window usually converges in one pass, and a huge history
|
|
1335
|
+
simply finishes on later flushes. Hook rollups without day evidence stay
|
|
1336
|
+
incomplete; missing transcripts can be filled when their files return.
|
|
1337
|
+
"""
|
|
1338
|
+
_measure_facade = _compat.facade()
|
|
1339
|
+
rows = _measure_facade._retry_db_operation(conn, lambda: conn.execute(
|
|
1340
|
+
"""SELECT jsonl_path, date FROM session_log
|
|
1341
|
+
WHERE daily_usage_json IS NULL
|
|
1342
|
+
ORDER BY collected_at DESC"""
|
|
1343
|
+
).fetchall())
|
|
1344
|
+
if not rows:
|
|
1345
|
+
return 0
|
|
1346
|
+
deadline = _measure_facade.time.monotonic() + budget_seconds
|
|
1347
|
+
updates = []
|
|
1348
|
+
live_owners = _measure_facade._live_usage_owners(conn)
|
|
1349
|
+
for jsonl_path, stored_date in rows:
|
|
1350
|
+
if _measure_facade.time.monotonic() > deadline:
|
|
1351
|
+
break
|
|
1352
|
+
if not (jsonl_path and str(jsonl_path).endswith(".jsonl")):
|
|
1353
|
+
# A hook-rollup adapter row has no transcript to split by day:
|
|
1354
|
+
# settle it now so it is never rescanned. The other daily fields
|
|
1355
|
+
# stay NULL: no evidence was produced, so nothing is claimed.
|
|
1356
|
+
updates.append(("{}", None, None, None, "", None, None, None, jsonl_path))
|
|
1357
|
+
continue
|
|
1358
|
+
if not _measure_facade.os.path.exists(jsonl_path):
|
|
1359
|
+
# Transcript missing, maybe only for now (a synced folder not yet
|
|
1360
|
+
# downloaded, an unmounted drive): stay NULL so it fills in when the
|
|
1361
|
+
# file returns, even with an old mtime that collect would skip.
|
|
1362
|
+
continue
|
|
1363
|
+
try:
|
|
1364
|
+
evidence = _measure_facade._session_activity_evidence(jsonl_path, conn=conn, live_owners=live_owners)
|
|
1365
|
+
except Exception:
|
|
1366
|
+
evidence = None
|
|
1367
|
+
if evidence is None:
|
|
1368
|
+
updates.append(("{}", _measure_facade._canonical_session_uuid(jsonl_path) if jsonl_path else None,
|
|
1369
|
+
None, None, "", None, None, None, jsonl_path))
|
|
1370
|
+
continue
|
|
1371
|
+
bounds = evidence["bounds"]
|
|
1372
|
+
updates.append((_measure_facade.json.dumps(evidence["daily_usage"]),
|
|
1373
|
+
_measure_facade._canonical_session_uuid(jsonl_path) if jsonl_path else None,
|
|
1374
|
+
bounds[0] if bounds else None, bounds[-1] if bounds else None,
|
|
1375
|
+
bounds[-1] or "",
|
|
1376
|
+
_measure_facade.json.dumps(evidence["parent_usage"]),
|
|
1377
|
+
_measure_facade.json.dumps(evidence["calls"]),
|
|
1378
|
+
_measure_facade.json.dumps(evidence["metrics"]),
|
|
1379
|
+
jsonl_path))
|
|
1380
|
+
if not updates:
|
|
1381
|
+
return 0
|
|
1382
|
+
|
|
1383
|
+
def batch_update():
|
|
1384
|
+
_measure_facade = _compat.facade()
|
|
1385
|
+
conn.executemany(
|
|
1386
|
+
"""UPDATE session_log
|
|
1387
|
+
SET daily_usage_json = ?,
|
|
1388
|
+
session_uuid = COALESCE(session_uuid, ?),
|
|
1389
|
+
first_activity_day = ?, last_activity_day = ?, date = ?,
|
|
1390
|
+
parent_daily_usage_json = ?, daily_calls_json = ?,
|
|
1391
|
+
daily_metrics_json = ?
|
|
1392
|
+
WHERE jsonl_path = ?""",
|
|
1393
|
+
updates,
|
|
1394
|
+
)
|
|
1395
|
+
conn.commit()
|
|
1396
|
+
return len(updates)
|
|
1397
|
+
|
|
1398
|
+
result = _measure_facade._retry_db_operation(conn, batch_update)
|
|
1399
|
+
return result if result is not None else 0
|
|
1400
|
+
|
|
1401
|
+
|
|
1402
|
+
def _extract_session_uuid(session_id):
|
|
1403
|
+
"""Return (session_uuid, unjoinable) for a session_id string.
|
|
1404
|
+
|
|
1405
|
+
A valid Claude session UUID has the 8-4-4-4-12 hex pattern and maps to a
|
|
1406
|
+
JSONL file basename. Short opaque hex agent_ids (<=20 chars, no dashes,
|
|
1407
|
+
no UUID pattern) cannot be resolved to a session_log row; they are flagged
|
|
1408
|
+
unjoinable=1 so callers never silently price them at the Sonnet fallback.
|
|
1409
|
+
|
|
1410
|
+
Returns:
|
|
1411
|
+
(uuid_str, False) — session_id IS a UUID and is safe to join on.
|
|
1412
|
+
(None, True) — short agent_id, cannot join.
|
|
1413
|
+
(None, False) — empty/unknown/test id, not an error, just no UUID.
|
|
1414
|
+
"""
|
|
1415
|
+
_measure_facade = _compat.facade()
|
|
1416
|
+
import re as _re
|
|
1417
|
+
_UUID_PAT = _re.compile(
|
|
1418
|
+
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
|
1419
|
+
_re.IGNORECASE,
|
|
1420
|
+
)
|
|
1421
|
+
if not session_id or session_id in ("unknown", "test-123", "perf_test", "regtest", "demo"):
|
|
1422
|
+
return None, False
|
|
1423
|
+
if session_id.startswith('rollout-'):
|
|
1424
|
+
match = _measure_facade.re.search(r'([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$', session_id, _measure_facade.re.I)
|
|
1425
|
+
if match:
|
|
1426
|
+
return match.group(1), False
|
|
1427
|
+
if _UUID_PAT.match(session_id):
|
|
1428
|
+
return session_id, False
|
|
1429
|
+
# Short opaque hex without dashes (17-char agent_ids from Claude Code)
|
|
1430
|
+
if len(session_id) <= 20 and "-" not in session_id:
|
|
1431
|
+
return None, True
|
|
1432
|
+
return None, False
|
|
1433
|
+
|
|
1434
|
+
|
|
1435
|
+
def _log_spawn_failure(msg):
|
|
1436
|
+
"""Append a durable breadcrumb when a detached spawn returns None.
|
|
1437
|
+
|
|
1438
|
+
spawn_detached swallows OSError and returns None; every caller ignores it,
|
|
1439
|
+
so a silent spawn failure leaves no trace. This writes one line to the
|
|
1440
|
+
daemon log dir so the failure is discoverable post-hoc. Never raises.
|
|
1441
|
+
"""
|
|
1442
|
+
_measure_facade = _compat.facade()
|
|
1443
|
+
try:
|
|
1444
|
+
_measure_facade.DAEMON_LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
1445
|
+
_measure_facade._cap_append_log(_measure_facade.DAEMON_LOG_DIR / "spawn-failures.log")
|
|
1446
|
+
with open(_measure_facade.DAEMON_LOG_DIR / "spawn-failures.log", "a", encoding="utf-8") as f:
|
|
1447
|
+
f.write("%s %s\n" % (_measure_facade.time.strftime("%Y-%m-%dT%H:%M:%S"), msg))
|
|
1448
|
+
except OSError:
|
|
1449
|
+
pass
|
|
1450
|
+
|
|
1451
|
+
|
|
1452
|
+
def _log_savings_event(event_type, tokens_saved, session_id=None, detail=None, model=None,
|
|
1453
|
+
cost_per_mtok=None):
|
|
1454
|
+
"""Log a savings event to the trends database.
|
|
1455
|
+
|
|
1456
|
+
Cost is calculated at the session's actual model rate. Resolution order:
|
|
1457
|
+
explicit `model` arg → session JSONL (via session_id) → CLAUDE_MODEL env →
|
|
1458
|
+
trends DB dominant → Sonnet fallback. See `_resolve_session_model`.
|
|
1459
|
+
|
|
1460
|
+
`cost_per_mtok` overrides the default input-rate pricing for event classes
|
|
1461
|
+
whose avoided token is NOT an input-class token (e.g. resume_lean prices at
|
|
1462
|
+
the cache-read / 1h cache-write rate of the avoided reload). When given, the
|
|
1463
|
+
stored cost is tokens_saved * cost_per_mtok / 1e6 at the caller's rate.
|
|
1464
|
+
|
|
1465
|
+
Also writes session_uuid (the Claude UUID = JSONL stem) so aggregation
|
|
1466
|
+
joins directly on session_log.session_uuid rather than LIKE-scanning
|
|
1467
|
+
jsonl_path. Agent_ids that cannot be joined are flagged unjoinable=1 so
|
|
1468
|
+
the reprice logic skips them instead of silently attributing them to Sonnet.
|
|
1469
|
+
"""
|
|
1470
|
+
_measure_facade = _compat.facade()
|
|
1471
|
+
try:
|
|
1472
|
+
# Derive the stable join key before opening the DB connection.
|
|
1473
|
+
session_uuid, unjoinable = _measure_facade._extract_session_uuid(session_id)
|
|
1474
|
+
|
|
1475
|
+
# Calculate cost saved using input token rate for the active model.
|
|
1476
|
+
# Unjoinable rows still get priced via env/recent fallback so the stored
|
|
1477
|
+
# cost_saved_usd is a reasonable estimate; the unjoinable flag tells the
|
|
1478
|
+
# aggregation layer not to use the stored model for reprice attribution.
|
|
1479
|
+
tier = _measure_facade._load_pricing_tier()
|
|
1480
|
+
tier_data = _measure_facade.PRICING_TIERS.get(tier, _measure_facade.PRICING_TIERS["anthropic"])
|
|
1481
|
+
# Output-class events (a measured verbosity reduction) avoid output tokens,
|
|
1482
|
+
# so they are priced at the output rate rather than the input rate.
|
|
1483
|
+
output_class = _measure_facade._EVENT_RATE_CLASS.get(event_type) == "output"
|
|
1484
|
+
if _measure_facade.detect_runtime() == 'codex':
|
|
1485
|
+
normalized = model or _measure_facade._resolve_session_model(session_id)
|
|
1486
|
+
rates = _measure_facade._input_and_cached_read_rates(normalized)
|
|
1487
|
+
if cost_per_mtok is None:
|
|
1488
|
+
if output_class:
|
|
1489
|
+
out_rate = _measure_facade._get_model_cost(normalized, 0, 1) * 1e6 if rates else 0.0
|
|
1490
|
+
cost_per_mtok = out_rate or None
|
|
1491
|
+
else:
|
|
1492
|
+
cost_per_mtok = rates[0] if rates else None
|
|
1493
|
+
elif model:
|
|
1494
|
+
normalized = _measure_facade._claude_price_key(model, tier_data["claude_models"]) or "sonnet"
|
|
1495
|
+
else:
|
|
1496
|
+
normalized = _measure_facade._resolve_session_model(session_id)
|
|
1497
|
+
if _measure_facade.detect_runtime() != 'codex':
|
|
1498
|
+
rates = tier_data["claude_models"].get(normalized, tier_data["claude_models"].get("sonnet", {}))
|
|
1499
|
+
if cost_per_mtok is None:
|
|
1500
|
+
cost_per_mtok = (rates.get("output", 15.0) if output_class
|
|
1501
|
+
else rates.get("input", 3.0))
|
|
1502
|
+
cost_saved = tokens_saved * cost_per_mtok / 1e6 if cost_per_mtok is not None else None
|
|
1503
|
+
|
|
1504
|
+
conn = _measure_facade._init_trends_db()
|
|
1505
|
+
try:
|
|
1506
|
+
o_col, o_mark, o_val = _measure_facade._origin_insert_parts(conn, "savings_events")
|
|
1507
|
+
conn.execute(
|
|
1508
|
+
"INSERT INTO savings_events "
|
|
1509
|
+
"(timestamp, event_type, tokens_saved, cost_saved_usd, session_id, session_uuid, detail, model, unjoinable"
|
|
1510
|
+
+ o_col + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?" + o_mark + ")",
|
|
1511
|
+
(_measure_facade.datetime.now().isoformat(), event_type, tokens_saved, cost_saved,
|
|
1512
|
+
session_id, session_uuid, detail, normalized, 1 if unjoinable else 0) + o_val,
|
|
1513
|
+
)
|
|
1514
|
+
conn.commit()
|
|
1515
|
+
finally:
|
|
1516
|
+
conn.close()
|
|
1517
|
+
except Exception:
|
|
1518
|
+
pass # Never crash the caller over savings tracking
|
|
1519
|
+
|
|
1520
|
+
|
|
1521
|
+
def _estimate_tokens(text):
|
|
1522
|
+
"""Estimate token count via the shared calibrated estimator (token_estimate.py).
|
|
1523
|
+
|
|
1524
|
+
Falls back to bytes/4 only if the shared estimator is unavailable.
|
|
1525
|
+
"""
|
|
1526
|
+
_measure_facade = _compat.facade()
|
|
1527
|
+
pass
|
|
1528
|
+
if not text:
|
|
1529
|
+
return 0
|
|
1530
|
+
if _measure_facade._cached_estimate_fn is None:
|
|
1531
|
+
try:
|
|
1532
|
+
from token_estimate import estimate_tokens as _fn
|
|
1533
|
+
_measure_facade._cached_estimate_fn = _fn
|
|
1534
|
+
except Exception:
|
|
1535
|
+
_measure_facade._cached_estimate_fn = lambda t: len(t.encode("utf-8", errors="replace")) // 4
|
|
1536
|
+
return _measure_facade._cached_estimate_fn(text)
|
|
1537
|
+
|
|
1538
|
+
|
|
1539
|
+
def _log_compression_event(feature, original_text=None, compressed_text=None,
|
|
1540
|
+
session_id=None, command_pattern=None,
|
|
1541
|
+
quality_preserved=None, verified=None, detail=None,
|
|
1542
|
+
tier=None):
|
|
1543
|
+
"""Log a compression event to the trends database.
|
|
1544
|
+
|
|
1545
|
+
Token counts come from the shared calibrated estimator (_estimate_tokens ->
|
|
1546
|
+
token_estimate.py); it falls back to a bytes/4 proxy only if that module is
|
|
1547
|
+
unavailable. Never crashes the caller -- all errors silently caught.
|
|
1548
|
+
|
|
1549
|
+
Writes session_uuid (the stable join key) and resolves + stores model
|
|
1550
|
+
at event-time so _get_merged_savings can reprice at the session's real
|
|
1551
|
+
model rate instead of the current dashboard session model (anachronistic).
|
|
1552
|
+
"""
|
|
1553
|
+
_measure_facade = _compat.facade()
|
|
1554
|
+
try:
|
|
1555
|
+
original_tokens = _measure_facade._estimate_tokens(original_text)
|
|
1556
|
+
compressed_tokens = _measure_facade._estimate_tokens(compressed_text)
|
|
1557
|
+
ratio = 0.0
|
|
1558
|
+
if original_tokens > 0:
|
|
1559
|
+
ratio = round(1.0 - compressed_tokens / original_tokens, 4)
|
|
1560
|
+
|
|
1561
|
+
# DB boundary: command_pattern/detail can embed a file name or label
|
|
1562
|
+
# that carries a credential shape. Redact here so NO caller (present
|
|
1563
|
+
# or future) can persist them raw; on a redactor refusal the text
|
|
1564
|
+
# columns go NULL while token counts still land. feature/session_id
|
|
1565
|
+
# are caller text too — a no-op on real inputs (constant feature
|
|
1566
|
+
# names, host-generated ids, so joins still hold), but a tainted
|
|
1567
|
+
# value can no longer reach disk verbatim.
|
|
1568
|
+
try:
|
|
1569
|
+
from credential_patterns import redact_credentials as _ce_redact
|
|
1570
|
+
if feature:
|
|
1571
|
+
feature = _ce_redact(feature)
|
|
1572
|
+
if session_id:
|
|
1573
|
+
session_id = _ce_redact(session_id)
|
|
1574
|
+
if command_pattern:
|
|
1575
|
+
command_pattern = _ce_redact(command_pattern)
|
|
1576
|
+
if detail:
|
|
1577
|
+
detail = _ce_redact(detail)
|
|
1578
|
+
except Exception:
|
|
1579
|
+
feature = "unknown"
|
|
1580
|
+
session_id = None
|
|
1581
|
+
command_pattern = None
|
|
1582
|
+
detail = None
|
|
1583
|
+
|
|
1584
|
+
# Derive stable join key and resolve event-time model.
|
|
1585
|
+
session_uuid, _ = _measure_facade._extract_session_uuid(session_id)
|
|
1586
|
+
resolved_model = _measure_facade._resolve_session_model(session_id)
|
|
1587
|
+
|
|
1588
|
+
conn = _measure_facade._init_trends_db()
|
|
1589
|
+
try:
|
|
1590
|
+
o_col, o_mark, o_val = _measure_facade._origin_insert_parts(conn, "compression_events")
|
|
1591
|
+
conn.execute(
|
|
1592
|
+
"INSERT INTO compression_events "
|
|
1593
|
+
"(timestamp, session_id, session_uuid, feature, command_pattern, original_tokens, "
|
|
1594
|
+
"compressed_tokens, compression_ratio, quality_preserved, verified, detail, model, tier"
|
|
1595
|
+
+ o_col + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" + o_mark + ")",
|
|
1596
|
+
(_measure_facade.datetime.now().isoformat(), session_id, session_uuid, feature, command_pattern,
|
|
1597
|
+
original_tokens, compressed_tokens, ratio,
|
|
1598
|
+
1 if quality_preserved else 0,
|
|
1599
|
+
1 if verified else 0,
|
|
1600
|
+
detail, resolved_model, tier) + o_val,
|
|
1601
|
+
)
|
|
1602
|
+
conn.commit()
|
|
1603
|
+
finally:
|
|
1604
|
+
conn.close()
|
|
1605
|
+
except Exception:
|
|
1606
|
+
pass
|
|
1607
|
+
|
|
1608
|
+
|
|
1609
|
+
def _compression_known_model(model):
|
|
1610
|
+
"""Reject an unknown Claude generation even when its family has a card."""
|
|
1611
|
+
_measure_facade = _compat.facade()
|
|
1612
|
+
if not isinstance(model, str) or not _measure_facade._is_priced_model(model):
|
|
1613
|
+
return False
|
|
1614
|
+
value = _measure_facade._strip_provider_prefixes(model)
|
|
1615
|
+
if value.startswith(("gpt-", "gemini-")):
|
|
1616
|
+
return _measure_facade._foreign_savings_card_exact(model)
|
|
1617
|
+
generation = _measure_facade._CLAUDE_GENERATION_RE.search(model.lower())
|
|
1618
|
+
legacy = _measure_facade._CLAUDE_LEGACY_ID_RE.search(model.lower())
|
|
1619
|
+
if legacy:
|
|
1620
|
+
major, minor, family = legacy.groups()
|
|
1621
|
+
if major == "3" and family == "sonnet" and minor in (None, "5", "7"):
|
|
1622
|
+
return True
|
|
1623
|
+
elif generation:
|
|
1624
|
+
family, major, minor = generation.groups()
|
|
1625
|
+
else:
|
|
1626
|
+
return True
|
|
1627
|
+
family = "fable" if family == "mythos" else family
|
|
1628
|
+
key = f"{family}_{major}" + (f"_{minor}" if minor else "")
|
|
1629
|
+
return key in _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"]).get("claude_models", {})
|
|
1630
|
+
|
|
1631
|
+
|
|
1632
|
+
def _compression_row_rate(model, fallback_rate, tier_data):
|
|
1633
|
+
"""Input price per million tokens, or zero when no rate card is known."""
|
|
1634
|
+
_measure_facade = _compat.facade()
|
|
1635
|
+
if not _measure_facade._compression_known_model(model):
|
|
1636
|
+
return 0.0
|
|
1637
|
+
return _measure_facade._get_model_cost(model, 1, 0) * 1_000_000
|
|
1638
|
+
|
|
1639
|
+
|
|
1640
|
+
def _compression_session_rates(conn, session_uuids, session_ids=None):
|
|
1641
|
+
"""{session_uuid: [(share, input_rate)]} from each session's own model mix.
|
|
1642
|
+
|
|
1643
|
+
Used for compression rows logged without a usable model stamp: the hook
|
|
1644
|
+
often cannot read the live transcript, so it writes "unknown". Each row is
|
|
1645
|
+
priced at ITS OWN session's mix (never a window average), the same rule
|
|
1646
|
+
_session_model_reprice applies to savings_events."""
|
|
1647
|
+
_measure_facade = _compat.facade()
|
|
1648
|
+
out = {}
|
|
1649
|
+
ids = [u for u in set(session_uuids) if u]
|
|
1650
|
+
foreign_ids = [s for s in set(session_ids) if s]
|
|
1651
|
+
if not ids and not foreign_ids:
|
|
1652
|
+
return out
|
|
1653
|
+
try:
|
|
1654
|
+
sl_cols = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
|
|
1655
|
+
mu = "model_usage_json" if "model_usage_json" in sl_cols else "NULL"
|
|
1656
|
+
amu = "all_model_usage_json" if "all_model_usage_json" in sl_cols else "NULL"
|
|
1657
|
+
breakdown = "model_usage_breakdown_json" if "model_usage_breakdown_json" in sl_cols else "NULL"
|
|
1658
|
+
for i in range(0, len(ids) if "session_uuid" in sl_cols else 0, 500):
|
|
1659
|
+
chunk = ids[i:i + 500]
|
|
1660
|
+
marks = ",".join("?" for _ in chunk)
|
|
1661
|
+
for uuid, detail_json, mu_json, amu_json in conn.execute(
|
|
1662
|
+
f"SELECT session_uuid, {breakdown}, {mu}, {amu} FROM session_log "
|
|
1663
|
+
f"WHERE session_uuid IN ({marks}) ORDER BY id", chunk):
|
|
1664
|
+
terms = _measure_facade._compression_mix_input_terms(detail_json, mu_json, amu_json)
|
|
1665
|
+
if terms:
|
|
1666
|
+
out[uuid] = terms
|
|
1667
|
+
prefixes = ("hermes:", "copilot:", "cursor:", "grok:",
|
|
1668
|
+
"antigravity:antigravity:", "antigravity:antigravity-cli:",
|
|
1669
|
+
"antigravity:antigravity-ide:")
|
|
1670
|
+
for i in range(0, len(foreign_ids), 50):
|
|
1671
|
+
paths = {prefix + sid: sid for sid in foreign_ids[i:i + 50] for prefix in prefixes}
|
|
1672
|
+
marks = ",".join("?" for _ in paths)
|
|
1673
|
+
matches = {}
|
|
1674
|
+
for path, detail_json, mu_json, amu_json in conn.execute(
|
|
1675
|
+
f"SELECT jsonl_path, {breakdown}, {mu}, {amu} FROM session_log WHERE jsonl_path IN ({marks})", tuple(paths)):
|
|
1676
|
+
matches.setdefault(paths[path], []).append((detail_json, mu_json, amu_json))
|
|
1677
|
+
for sid, records in matches.items():
|
|
1678
|
+
if len(records) == 1:
|
|
1679
|
+
terms = _measure_facade._compression_mix_input_terms(*records[0])
|
|
1680
|
+
if terms:
|
|
1681
|
+
out[("session_id", sid)] = terms
|
|
1682
|
+
except (_measure_facade.sqlite3.Error, TypeError, ValueError):
|
|
1683
|
+
return {}
|
|
1684
|
+
return out
|
|
1685
|
+
|
|
1686
|
+
|
|
1687
|
+
def _compression_mix_input_terms(*blobs):
|
|
1688
|
+
"""Known input rates weighted by all models in one session, including unknowns."""
|
|
1689
|
+
_measure_facade = _compat.facade()
|
|
1690
|
+
for blob in blobs:
|
|
1691
|
+
try:
|
|
1692
|
+
values = _measure_facade.json.loads(blob) if blob else None
|
|
1693
|
+
except (TypeError, ValueError):
|
|
1694
|
+
continue
|
|
1695
|
+
if not isinstance(values, dict) or not values:
|
|
1696
|
+
continue
|
|
1697
|
+
weights = []
|
|
1698
|
+
for name, value in values.items():
|
|
1699
|
+
if isinstance(value, dict):
|
|
1700
|
+
try:
|
|
1701
|
+
value = sum(float(value.get(field) or 0) for field in
|
|
1702
|
+
("fresh_input", "cache_create", "output"))
|
|
1703
|
+
except (TypeError, ValueError):
|
|
1704
|
+
continue
|
|
1705
|
+
try:
|
|
1706
|
+
weight = float(value)
|
|
1707
|
+
except (TypeError, ValueError):
|
|
1708
|
+
continue
|
|
1709
|
+
if _measure_facade.math.isfinite(weight) and weight > 0:
|
|
1710
|
+
weights.append((name, weight))
|
|
1711
|
+
total = sum(weight for _, weight in weights)
|
|
1712
|
+
if total:
|
|
1713
|
+
return [(weight / total, _measure_facade._get_model_cost(name, 1, 0) * 1_000_000)
|
|
1714
|
+
for name, weight in weights if _measure_facade._compression_known_model(name)]
|
|
1715
|
+
return []
|
|
1716
|
+
|
|
1717
|
+
|
|
1718
|
+
def _compression_rate_coverage(model, session_uuid, session_rates, fallback_rate, tier_data):
|
|
1719
|
+
"""Return the known input price and the fraction of saved tokens priced."""
|
|
1720
|
+
_measure_facade = _compat.facade()
|
|
1721
|
+
if _measure_facade._compression_known_model(model):
|
|
1722
|
+
return _measure_facade._compression_row_rate(model, fallback_rate, tier_data), 1.0
|
|
1723
|
+
terms = session_rates.get(session_uuid, [])
|
|
1724
|
+
return sum(sh * rate for sh, rate in terms), min(1.0, sum(sh for sh, _ in terms))
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
def _compression_priced_rate(model, session_uuid, session_rates, fallback_rate, tier_data):
|
|
1728
|
+
_measure_facade = _compat.facade()
|
|
1729
|
+
return _measure_facade._compression_rate_coverage(model, session_uuid, session_rates, fallback_rate, tier_data)[0]
|
|
1730
|
+
|
|
1731
|
+
|
|
1732
|
+
def _get_compression_summary(days=None, since=None):
|
|
1733
|
+
"""Query compression events and return a summary dict.
|
|
1734
|
+
|
|
1735
|
+
When *since* is a non-empty ISO-8601 timestamp string, it is used directly
|
|
1736
|
+
as the cutoff (``timestamp >= since``) instead of the rolling ``now - days``
|
|
1737
|
+
cutoff. When *since* is None / empty, the rolling cutoff is computed from
|
|
1738
|
+
*days* as before.
|
|
1739
|
+
|
|
1740
|
+
Price known model stamps or the known share of the event's own session mix.
|
|
1741
|
+
Keep tokens with no known rate in the count and disclose them as unpriced.
|
|
1742
|
+
"""
|
|
1743
|
+
_measure_facade = _compat.facade()
|
|
1744
|
+
try:
|
|
1745
|
+
conn = _measure_facade._init_trends_db()
|
|
1746
|
+
try:
|
|
1747
|
+
if since:
|
|
1748
|
+
cutoff = since
|
|
1749
|
+
else:
|
|
1750
|
+
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
1751
|
+
# Pull model alongside aggregates so we can reprice by event-time model.
|
|
1752
|
+
# NULLs land as None in Python; fallback handled below.
|
|
1753
|
+
# REALIZED tiers only: opportunity (shadow) and estimated rows are
|
|
1754
|
+
# diagnostic and MUST NEVER reach the savings headline (three-tier
|
|
1755
|
+
# rule). Legacy rows predate the tier column (NULL) and stay counted.
|
|
1756
|
+
rows = conn.execute(
|
|
1757
|
+
"SELECT feature, COUNT(*) as cnt, "
|
|
1758
|
+
"SUM(original_tokens) as orig, SUM(compressed_tokens) as comp, "
|
|
1759
|
+
"AVG(compression_ratio) as avg_ratio, "
|
|
1760
|
+
"SUM(CASE WHEN quality_preserved = 1 THEN 1 ELSE 0 END) as quality_ok, "
|
|
1761
|
+
"SUM(CASE WHEN verified = 1 THEN 1 ELSE 0 END) as verified_cnt, "
|
|
1762
|
+
"model, session_uuid, session_id, "
|
|
1763
|
+
"SUM(CASE WHEN original_tokens > compressed_tokens "
|
|
1764
|
+
" THEN original_tokens - compressed_tokens ELSE 0 END) as gross_credit, "
|
|
1765
|
+
"SUM(CASE WHEN compressed_tokens > original_tokens "
|
|
1766
|
+
" THEN compressed_tokens - original_tokens ELSE 0 END) as gross_debit "
|
|
1767
|
+
"FROM " + _measure_facade._counted_table(conn, "compression_events") + " WHERE timestamp >= ? "
|
|
1768
|
+
"AND (tier IS NULL OR tier = 'measured') "
|
|
1769
|
+
"GROUP BY feature, model, session_uuid, session_id ORDER BY orig DESC",
|
|
1770
|
+
(cutoff,),
|
|
1771
|
+
).fetchall()
|
|
1772
|
+
session_rates = _measure_facade._compression_session_rates(
|
|
1773
|
+
conn, [r[8] for r in rows
|
|
1774
|
+
if not _measure_facade._compression_known_model(r[7])],
|
|
1775
|
+
[r[9] for r in rows if not _measure_facade._compression_known_model(r[7])])
|
|
1776
|
+
finally:
|
|
1777
|
+
conn.close()
|
|
1778
|
+
|
|
1779
|
+
# Merge rows with the same feature (may appear once per model after the
|
|
1780
|
+
# GROUP BY feature, model). Accumulate cost using per-row model rate.
|
|
1781
|
+
by_feature: dict = {}
|
|
1782
|
+
total_original = 0
|
|
1783
|
+
total_compressed = 0
|
|
1784
|
+
total_events = 0
|
|
1785
|
+
fallback_rate = _measure_facade._estimate_compression_cost_per_mtok()
|
|
1786
|
+
tier = _measure_facade._load_pricing_tier()
|
|
1787
|
+
tier_data = _measure_facade.PRICING_TIERS.get(tier, _measure_facade.PRICING_TIERS["anthropic"])
|
|
1788
|
+
|
|
1789
|
+
for (feature, cnt, orig, comp, avg_ratio, quality_ok, verified_cnt, model, s_uuid, sid,
|
|
1790
|
+
gross_credit, gross_debit) in rows:
|
|
1791
|
+
orig = orig or 0
|
|
1792
|
+
comp = comp or 0
|
|
1793
|
+
cnt = cnt or 0
|
|
1794
|
+
key = s_uuid if s_uuid in session_rates else ("session_id", sid)
|
|
1795
|
+
rate, priced_share = _measure_facade._compression_rate_coverage(model, key, session_rates, fallback_rate, tier_data)
|
|
1796
|
+
tokens_saved = orig - comp
|
|
1797
|
+
cost_saved = round(tokens_saved * rate / 1_000_000, 6)
|
|
1798
|
+
# Gross credits and debits are kept apart (summed per event in SQL), so
|
|
1799
|
+
# an unknown-model expansion is disclosed rather than netted away.
|
|
1800
|
+
uncovered = max(0.0, 1.0 - priced_share)
|
|
1801
|
+
unpriced_credit = (gross_credit or 0) * uncovered
|
|
1802
|
+
unpriced_debit = (gross_debit or 0) * uncovered
|
|
1803
|
+
|
|
1804
|
+
if feature in by_feature:
|
|
1805
|
+
# Merge with existing entry for this feature (multi-model rows)
|
|
1806
|
+
entry = by_feature[feature]
|
|
1807
|
+
entry["events"] += cnt
|
|
1808
|
+
entry["original_tokens"] += orig
|
|
1809
|
+
entry["compressed_tokens"] += comp
|
|
1810
|
+
entry["tokens_saved"] += tokens_saved
|
|
1811
|
+
entry["cost_saved_usd"] = round(entry["cost_saved_usd"] + cost_saved, 6)
|
|
1812
|
+
entry["unpriced_credit_tokens"] += unpriced_credit
|
|
1813
|
+
entry["unpriced_debit_tokens"] += unpriced_debit
|
|
1814
|
+
# avg_ratio and quality_pcts are approximate after merging; acceptable.
|
|
1815
|
+
entry["quality_preserved_pct"] = round(
|
|
1816
|
+
(entry["quality_preserved_pct"] * (entry["events"] - cnt) + 100 * (quality_ok or 0))
|
|
1817
|
+
/ max(entry["events"], 1),
|
|
1818
|
+
1,
|
|
1819
|
+
)
|
|
1820
|
+
else:
|
|
1821
|
+
by_feature[feature] = {
|
|
1822
|
+
"events": cnt,
|
|
1823
|
+
"original_tokens": orig,
|
|
1824
|
+
"compressed_tokens": comp,
|
|
1825
|
+
"avg_ratio": round(avg_ratio or 0.0, 4),
|
|
1826
|
+
"tokens_saved": tokens_saved,
|
|
1827
|
+
"cost_saved_usd": cost_saved,
|
|
1828
|
+
"unpriced_credit_tokens": unpriced_credit,
|
|
1829
|
+
"unpriced_debit_tokens": unpriced_debit,
|
|
1830
|
+
"quality_preserved_pct": round(100 * (quality_ok or 0) / max(cnt, 1), 1),
|
|
1831
|
+
"verified_pct": round(100 * (verified_cnt or 0) / max(cnt, 1), 1),
|
|
1832
|
+
}
|
|
1833
|
+
total_original += orig
|
|
1834
|
+
total_compressed += comp
|
|
1835
|
+
total_events += cnt
|
|
1836
|
+
|
|
1837
|
+
overall_ratio = round(1.0 - total_compressed / max(total_original, 1), 4)
|
|
1838
|
+
tokens_saved = total_original - total_compressed
|
|
1839
|
+
for entry in by_feature.values():
|
|
1840
|
+
entry["unpriced_credit_tokens"] = round(entry["unpriced_credit_tokens"])
|
|
1841
|
+
entry["unpriced_debit_tokens"] = round(entry["unpriced_debit_tokens"])
|
|
1842
|
+
entry["unpriced_tokens"] = entry["unpriced_credit_tokens"] + entry["unpriced_debit_tokens"]
|
|
1843
|
+
|
|
1844
|
+
return {
|
|
1845
|
+
"total_events": total_events,
|
|
1846
|
+
"total_original_tokens": total_original,
|
|
1847
|
+
"total_compressed_tokens": total_compressed,
|
|
1848
|
+
"total_tokens_saved": tokens_saved,
|
|
1849
|
+
"unpriced_tokens": sum(entry["unpriced_tokens"] for entry in by_feature.values()),
|
|
1850
|
+
"unpriced_credit_tokens": sum(e["unpriced_credit_tokens"] for e in by_feature.values()),
|
|
1851
|
+
"unpriced_debit_tokens": sum(e["unpriced_debit_tokens"] for e in by_feature.values()),
|
|
1852
|
+
"overall_ratio": overall_ratio,
|
|
1853
|
+
"by_feature": by_feature,
|
|
1854
|
+
"period_days": days,
|
|
1855
|
+
}
|
|
1856
|
+
except Exception:
|
|
1857
|
+
return {"total_events": 0, "total_tokens_saved": 0, "by_feature": {}, "period_days": days}
|
|
1858
|
+
|
|
1859
|
+
|
|
1860
|
+
def _coverage_feature_label(feature):
|
|
1861
|
+
"""Display label for a coverage feature (falls back through the v5 labels)."""
|
|
1862
|
+
_measure_facade = _compat.facade()
|
|
1863
|
+
return (
|
|
1864
|
+
_measure_facade._COVERAGE_FEATURE_LABELS.get(feature)
|
|
1865
|
+
or _measure_facade._V5_COMPRESSION_LABELS.get(feature)
|
|
1866
|
+
or feature
|
|
1867
|
+
)
|
|
1868
|
+
|
|
1869
|
+
|
|
1870
|
+
def _get_compression_coverage(days=None):
|
|
1871
|
+
"""Tiered compression-coverage view. Diagnostic only, never summed.
|
|
1872
|
+
|
|
1873
|
+
Groups compression_events by feature into measured / estimated / opportunity
|
|
1874
|
+
buckets and reports per-feature events, would-be (shadow) or realized
|
|
1875
|
+
(active) avg ratio, and verified %. Tiers are kept strictly separate so a
|
|
1876
|
+
shadow opportunity can never be read as realized savings. These numbers do
|
|
1877
|
+
NOT feed _get_merged_savings (only _V5_COMPRESSION_CATEGORIES features do).
|
|
1878
|
+
|
|
1879
|
+
Also surfaces the first-read shadow quality proxy: edit_rate =
|
|
1880
|
+
edits-after-shadow-read / shadow-reads. It is the promotion gate: a low
|
|
1881
|
+
rate means the model rarely needed the full file, so a skeleton would have
|
|
1882
|
+
been safe. Fail-open: returns an empty (but well-formed) structure on error.
|
|
1883
|
+
"""
|
|
1884
|
+
_measure_facade = _compat.facade()
|
|
1885
|
+
out = {
|
|
1886
|
+
"period_days": days,
|
|
1887
|
+
"tiers": {t: [] for t in _measure_facade._COMPRESSION_TIERS},
|
|
1888
|
+
"first_read_proxy": None,
|
|
1889
|
+
"available": False,
|
|
1890
|
+
}
|
|
1891
|
+
try:
|
|
1892
|
+
conn = _measure_facade._init_trends_db()
|
|
1893
|
+
try:
|
|
1894
|
+
cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).isoformat()
|
|
1895
|
+
rows = conn.execute(
|
|
1896
|
+
"SELECT feature, tier, COUNT(*) as cnt, "
|
|
1897
|
+
"SUM(original_tokens) as orig, SUM(compressed_tokens) as comp, "
|
|
1898
|
+
"AVG(compression_ratio) as avg_ratio, "
|
|
1899
|
+
"SUM(CASE WHEN verified = 1 THEN 1 ELSE 0 END) as vcnt "
|
|
1900
|
+
"FROM " + _measure_facade._counted_table(conn, "compression_events") + " WHERE timestamp >= ? "
|
|
1901
|
+
"GROUP BY feature, tier",
|
|
1902
|
+
(cutoff,),
|
|
1903
|
+
).fetchall()
|
|
1904
|
+
finally:
|
|
1905
|
+
conn.close()
|
|
1906
|
+
except Exception as exc:
|
|
1907
|
+
# Distinguish a broken query from a legitimately empty DB so the
|
|
1908
|
+
# dashboard/CLI can show "unavailable (error)" rather than "no data yet".
|
|
1909
|
+
out["error"] = str(exc)
|
|
1910
|
+
return out
|
|
1911
|
+
|
|
1912
|
+
# Proxy denominator is the shadow-tier skeletons only; the numerator is their
|
|
1913
|
+
# edit follow-ups. Both must come from the same opportunity cohort.
|
|
1914
|
+
skeleton_cnt = 0
|
|
1915
|
+
followup_cnt = 0
|
|
1916
|
+
for feature, tier, cnt, _orig, _comp, _avg, _vcnt in rows:
|
|
1917
|
+
if feature == _measure_facade._FEATURE_FIRST_READ_SKELETON and tier == "opportunity":
|
|
1918
|
+
skeleton_cnt += cnt or 0
|
|
1919
|
+
elif feature == _measure_facade._FEATURE_FIRST_READ_EDIT_FOLLOWUP and tier == "opportunity":
|
|
1920
|
+
followup_cnt += cnt or 0
|
|
1921
|
+
|
|
1922
|
+
for feature, tier, cnt, orig, comp, avg_ratio, vcnt in rows:
|
|
1923
|
+
if feature in _measure_facade._NON_SAVINGS_COMPRESSION_FEATURES:
|
|
1924
|
+
continue
|
|
1925
|
+
cnt = cnt or 0
|
|
1926
|
+
orig = orig or 0
|
|
1927
|
+
comp = comp or 0
|
|
1928
|
+
safe_tier = tier if tier in _measure_facade._COMPRESSION_TIERS else "estimated"
|
|
1929
|
+
realized = safe_tier == "measured"
|
|
1930
|
+
out["tiers"][safe_tier].append({
|
|
1931
|
+
"feature": feature,
|
|
1932
|
+
"label": _measure_facade._coverage_feature_label(feature),
|
|
1933
|
+
"events": cnt,
|
|
1934
|
+
"tokens_saved": max(orig - comp, 0),
|
|
1935
|
+
"ratio": round(avg_ratio or 0.0, 4),
|
|
1936
|
+
"ratio_kind": "realized" if realized else "would_be",
|
|
1937
|
+
"verified_pct": round(100 * (vcnt or 0) / max(cnt, 1), 1),
|
|
1938
|
+
"shadow": not realized,
|
|
1939
|
+
})
|
|
1940
|
+
out["available"] = True
|
|
1941
|
+
|
|
1942
|
+
if skeleton_cnt > 0:
|
|
1943
|
+
edit_rate = followup_cnt / skeleton_cnt
|
|
1944
|
+
out["first_read_proxy"] = {
|
|
1945
|
+
"shadow_reads": skeleton_cnt,
|
|
1946
|
+
"edits_after_read": followup_cnt,
|
|
1947
|
+
"edit_rate_pct": round(100 * edit_rate, 1),
|
|
1948
|
+
"promotion_gate_pct": round(100 * _measure_facade._FIRST_READ_PROMOTION_EDIT_RATE, 1),
|
|
1949
|
+
"promotion_ready": edit_rate < _measure_facade._FIRST_READ_PROMOTION_EDIT_RATE,
|
|
1950
|
+
}
|
|
1951
|
+
out["available"] = True
|
|
1952
|
+
|
|
1953
|
+
for bucket in out["tiers"].values():
|
|
1954
|
+
bucket.sort(key=lambda e: e["events"], reverse=True)
|
|
1955
|
+
return out
|
|
1956
|
+
|
|
1957
|
+
|
|
1958
|
+
def _resolve_active_cohorts():
|
|
1959
|
+
"""The canonical active-cohort set, preferring read_cache's live constant.
|
|
1960
|
+
|
|
1961
|
+
C2: lazily import read_cache.FIRST_READ_ACTIVE_COHORTS (the hot-path source
|
|
1962
|
+
of truth) so this CLI/dashboard module follows the read hook without a hard
|
|
1963
|
+
import at module load. Falls back to the local mirror if the import fails,
|
|
1964
|
+
and emits a one-line stderr drift warning (once) if the two ever disagree —
|
|
1965
|
+
the drift test then fails loudly instead of the tripwire silently judging a
|
|
1966
|
+
cohort the read hook no longer serves.
|
|
1967
|
+
"""
|
|
1968
|
+
_measure_facade = _compat.facade()
|
|
1969
|
+
pass
|
|
1970
|
+
try:
|
|
1971
|
+
from read_cache import FIRST_READ_ACTIVE_COHORTS as _live
|
|
1972
|
+
live = frozenset(_live)
|
|
1973
|
+
except Exception:
|
|
1974
|
+
return _measure_facade._FIRST_READ_ACTIVE_COHORTS
|
|
1975
|
+
if live != _measure_facade._FIRST_READ_ACTIVE_COHORTS and not _measure_facade._active_cohorts_drift_warned:
|
|
1976
|
+
_measure_facade._active_cohorts_drift_warned = True
|
|
1977
|
+
try:
|
|
1978
|
+
print(
|
|
1979
|
+
"[Token Optimizer] WARNING: active-cohort drift between "
|
|
1980
|
+
"measure._FIRST_READ_ACTIVE_COHORTS and "
|
|
1981
|
+
"read_cache.FIRST_READ_ACTIVE_COHORTS; using the read-hook set.",
|
|
1982
|
+
file=_measure_facade.sys.stderr,
|
|
1983
|
+
)
|
|
1984
|
+
except Exception:
|
|
1985
|
+
pass
|
|
1986
|
+
return live
|
|
1987
|
+
|
|
1988
|
+
|
|
1989
|
+
def _tripwire_min_samples(cohort) -> int:
|
|
1990
|
+
"""Sample floor before a cohort can be auto-demoted (T9).
|
|
1991
|
+
|
|
1992
|
+
Interpolated cohorts (thin historical sample) use the tighter floor so a bad
|
|
1993
|
+
live signal surfaces faster; full-gate cohorts use the standard floor.
|
|
1994
|
+
"""
|
|
1995
|
+
_measure_facade = _compat.facade()
|
|
1996
|
+
return (_measure_facade._TRIPWIRE_MIN_SAMPLES_INTERP if cohort in _measure_facade._INTERPOLATED_COHORTS
|
|
1997
|
+
else _measure_facade._TRIPWIRE_MIN_SAMPLES)
|
|
1998
|
+
|
|
1999
|
+
|
|
2000
|
+
def _cohort_basis(cohort) -> str:
|
|
2001
|
+
"""'interpolated' (adjacent-band graduation) or 'full_gate' (sidecar label)."""
|
|
2002
|
+
_measure_facade = _compat.facade()
|
|
2003
|
+
return "interpolated" if cohort in _measure_facade._INTERPOLATED_COHORTS else "full_gate"
|
|
2004
|
+
|
|
2005
|
+
|
|
2006
|
+
def _cohort_from_pattern(pattern):
|
|
2007
|
+
"""Recover a (language, band) cohort from a `lang|band` command_pattern."""
|
|
2008
|
+
_measure_facade = _compat.facade()
|
|
2009
|
+
if not pattern or "|" not in pattern:
|
|
2010
|
+
return None
|
|
2011
|
+
lang, band = pattern.split("|", 1)
|
|
2012
|
+
lang, band = lang.strip(), band.strip()
|
|
2013
|
+
if not lang or not band:
|
|
2014
|
+
return None
|
|
2015
|
+
return (lang, band)
|
|
2016
|
+
|
|
2017
|
+
|
|
2018
|
+
def _compute_cohort_edit_rates(conn, promoted_at=None):
|
|
2019
|
+
"""Per-cohort live edit-rate over the last _TRIPWIRE_WINDOW active skeletons.
|
|
2020
|
+
|
|
2021
|
+
Returns {(lang, band): {"skeletons": n, "followups": m, "edit_rate": r}} for
|
|
2022
|
+
every active cohort that has at least one measured skeleton. The skeleton
|
|
2023
|
+
window is bounded per cohort (most recent N) so an old run of bad edits ages
|
|
2024
|
+
out.
|
|
2025
|
+
|
|
2026
|
+
Promote fence (hysteresis hole): for any cohort with a `promoted_at`
|
|
2027
|
+
timestamp, BOTH skeleton and follow-up events older than that promotion are
|
|
2028
|
+
filtered out, so a re-promoted cohort is judged only on POST-promote history
|
|
2029
|
+
and cannot immediately re-demote on the pre-promote edits that demoted it.
|
|
2030
|
+
|
|
2031
|
+
Follow-up window (T6): a global `timestamp >= oldest active-skeleton ts`
|
|
2032
|
+
filter is pushed into SQL, then per-cohort follow-ups are bounded to
|
|
2033
|
+
oldest(cohort skeleton ts) <= t <= newest(cohort skeleton ts) so an edit
|
|
2034
|
+
attributed to an aged-out OR a not-yet-served skeleton can't inflate the rate.
|
|
2035
|
+
"""
|
|
2036
|
+
_measure_facade = _compat.facade()
|
|
2037
|
+
promoted_at = promoted_at or {}
|
|
2038
|
+
|
|
2039
|
+
def _fence(cohort):
|
|
2040
|
+
_measure_facade = _compat.facade()
|
|
2041
|
+
return promoted_at.get(f"{cohort[0]}|{cohort[1]}")
|
|
2042
|
+
|
|
2043
|
+
rates = {}
|
|
2044
|
+
# Most-recent measured skeleton events per cohort (id DESC == recency).
|
|
2045
|
+
sk_rows = conn.execute(
|
|
2046
|
+
"SELECT command_pattern, timestamp FROM compression_events "
|
|
2047
|
+
"WHERE feature = ? AND tier = 'measured' AND command_pattern LIKE '%|%' "
|
|
2048
|
+
"ORDER BY id DESC",
|
|
2049
|
+
(_measure_facade._FEATURE_FIRST_READ_SKELETON,),
|
|
2050
|
+
).fetchall()
|
|
2051
|
+
per_cohort_ts = {}
|
|
2052
|
+
for pattern, ts in sk_rows:
|
|
2053
|
+
cohort = _measure_facade._cohort_from_pattern(pattern)
|
|
2054
|
+
if cohort is None:
|
|
2055
|
+
continue
|
|
2056
|
+
fence = _fence(cohort)
|
|
2057
|
+
if fence is not None and ts is not None and ts < fence:
|
|
2058
|
+
continue # pre-promote skeleton: fenced out (T5)
|
|
2059
|
+
bucket = per_cohort_ts.setdefault(cohort, [])
|
|
2060
|
+
if len(bucket) < _measure_facade._TRIPWIRE_WINDOW:
|
|
2061
|
+
bucket.append(ts)
|
|
2062
|
+
if not per_cohort_ts:
|
|
2063
|
+
return rates
|
|
2064
|
+
|
|
2065
|
+
# T6: oldest in-window skeleton ts across ALL cohorts bounds the follow-up
|
|
2066
|
+
# scan, so the query never reads follow-ups that predate every live window.
|
|
2067
|
+
all_ts = [t for ts_list in per_cohort_ts.values() for t in ts_list if t is not None]
|
|
2068
|
+
global_oldest = min(all_ts) if all_ts else None
|
|
2069
|
+
if global_oldest is not None:
|
|
2070
|
+
fu_rows = conn.execute(
|
|
2071
|
+
"SELECT command_pattern, timestamp FROM compression_events "
|
|
2072
|
+
"WHERE feature = ? AND tier = 'measured' AND command_pattern LIKE '%|%' "
|
|
2073
|
+
"AND timestamp >= ?",
|
|
2074
|
+
(_measure_facade._FEATURE_FIRST_READ_EDIT_FOLLOWUP, global_oldest),
|
|
2075
|
+
).fetchall()
|
|
2076
|
+
else:
|
|
2077
|
+
fu_rows = conn.execute(
|
|
2078
|
+
"SELECT command_pattern, timestamp FROM compression_events "
|
|
2079
|
+
"WHERE feature = ? AND tier = 'measured' AND command_pattern LIKE '%|%'",
|
|
2080
|
+
(_measure_facade._FEATURE_FIRST_READ_EDIT_FOLLOWUP,),
|
|
2081
|
+
).fetchall()
|
|
2082
|
+
followups = {}
|
|
2083
|
+
for pattern, ts in fu_rows:
|
|
2084
|
+
cohort = _measure_facade._cohort_from_pattern(pattern)
|
|
2085
|
+
if cohort is None:
|
|
2086
|
+
continue
|
|
2087
|
+
fence = _fence(cohort)
|
|
2088
|
+
if fence is not None and ts is not None and ts < fence:
|
|
2089
|
+
continue # pre-promote follow-up: fenced out (T5)
|
|
2090
|
+
followups.setdefault(cohort, []).append(ts)
|
|
2091
|
+
|
|
2092
|
+
for cohort, ts_list in per_cohort_ts.items():
|
|
2093
|
+
skeletons = len(ts_list)
|
|
2094
|
+
# Window bounds: oldest skeleton ts (aged-out floor) and newest skeleton
|
|
2095
|
+
# ts (a follow-up after the newest served skeleton cannot belong to it).
|
|
2096
|
+
valid_ts = [t for t in ts_list if t is not None]
|
|
2097
|
+
oldest = min(valid_ts) if valid_ts else None
|
|
2098
|
+
newest = max(valid_ts) if valid_ts else None
|
|
2099
|
+
fu = followups.get(cohort, [])
|
|
2100
|
+
fu_in_window = sum(
|
|
2101
|
+
1 for t in fu
|
|
2102
|
+
if (oldest is None or t is None or t >= oldest)
|
|
2103
|
+
and (newest is None or t is None or t <= newest)
|
|
2104
|
+
)
|
|
2105
|
+
# Cap follow-ups at the skeleton count (one edit per served skeleton).
|
|
2106
|
+
fu_in_window = min(fu_in_window, skeletons)
|
|
2107
|
+
edit_rate = (fu_in_window / skeletons) if skeletons else 0.0
|
|
2108
|
+
rates[cohort] = {
|
|
2109
|
+
"skeletons": skeletons,
|
|
2110
|
+
"followups": fu_in_window,
|
|
2111
|
+
"edit_rate": round(edit_rate, 4),
|
|
2112
|
+
"basis": _measure_facade._cohort_basis(cohort),
|
|
2113
|
+
}
|
|
2114
|
+
return rates
|
|
2115
|
+
|
|
2116
|
+
|
|
2117
|
+
def _valid_tripwire_payload(data):
|
|
2118
|
+
"""Schema-check the tripwire sidecar (parity with read_cache).
|
|
2119
|
+
|
|
2120
|
+
`demoted` must be a list of 2-element string pairs; `edit_rates`/`promoted_at`
|
|
2121
|
+
(when present) dicts. Used to decide corrupt-vs-valid so a malformed sidecar
|
|
2122
|
+
forces a recompute instead of being trusted.
|
|
2123
|
+
"""
|
|
2124
|
+
_measure_facade = _compat.facade()
|
|
2125
|
+
if not isinstance(data, dict):
|
|
2126
|
+
return False
|
|
2127
|
+
demoted = data.get("demoted", [])
|
|
2128
|
+
if not isinstance(demoted, list):
|
|
2129
|
+
return False
|
|
2130
|
+
for pair in demoted:
|
|
2131
|
+
if not isinstance(pair, (list, tuple)) or len(pair) != 2:
|
|
2132
|
+
return False
|
|
2133
|
+
if not all(isinstance(x, str) for x in pair):
|
|
2134
|
+
return False
|
|
2135
|
+
if not isinstance(data.get("edit_rates", {}), dict):
|
|
2136
|
+
return False
|
|
2137
|
+
if not isinstance(data.get("promoted_at", {}), dict):
|
|
2138
|
+
return False
|
|
2139
|
+
return True
|
|
2140
|
+
|
|
2141
|
+
|
|
2142
|
+
def _read_tripwire_sidecar(return_corrupt=None):
|
|
2143
|
+
"""Load the demoted-cohort sidecar.
|
|
2144
|
+
|
|
2145
|
+
Returns the parsed dict, or {} when missing/unreadable. When the file EXISTS
|
|
2146
|
+
but is corrupt/malformed and `return_corrupt=True`, returns the sentinel
|
|
2147
|
+
string ``"__corrupt__"`` so the caller (evaluate_cohort_tripwire) can force a
|
|
2148
|
+
fresh recompute rather than trust an unparseable verdict (T1). Default
|
|
2149
|
+
behavior (return_corrupt=False) keeps the historical empty-dict fail-open for
|
|
2150
|
+
read-only consumers (_cohort_tripwire_state / cohorts_promote).
|
|
2151
|
+
"""
|
|
2152
|
+
_measure_facade = _compat.facade()
|
|
2153
|
+
path = _measure_facade.SNAPSHOT_DIR / _measure_facade._TRIPWIRE_SIDECAR_NAME
|
|
2154
|
+
try:
|
|
2155
|
+
if not path.exists():
|
|
2156
|
+
return {}
|
|
2157
|
+
data = _measure_facade.json.loads(path.read_text(encoding="utf-8"))
|
|
2158
|
+
except (_measure_facade.json.JSONDecodeError, OSError, ValueError):
|
|
2159
|
+
return "__corrupt__" if return_corrupt else {}
|
|
2160
|
+
if not _measure_facade._valid_tripwire_payload(data):
|
|
2161
|
+
return "__corrupt__" if return_corrupt else {}
|
|
2162
|
+
return data
|
|
2163
|
+
|
|
2164
|
+
|
|
2165
|
+
def _write_tripwire_sidecar(demoted, rates, promoted_at=None):
|
|
2166
|
+
"""Atomically write the demoted-cohort sidecar (0600).
|
|
2167
|
+
|
|
2168
|
+
`promoted_at` is a {lang|band: epoch_ts} map (hysteresis fence): when a
|
|
2169
|
+
cohort is re-promoted, its pre-promote skeleton/follow-up history is fenced
|
|
2170
|
+
out of the live edit-rate so it cannot immediately re-demote. Each cohort
|
|
2171
|
+
also carries its `basis` (full_gate|interpolated) for the dashboard label.
|
|
2172
|
+
"""
|
|
2173
|
+
_measure_facade = _compat.facade()
|
|
2174
|
+
path = _measure_facade.SNAPSHOT_DIR / _measure_facade._TRIPWIRE_SIDECAR_NAME
|
|
2175
|
+
promoted_at = promoted_at or {}
|
|
2176
|
+
record = {
|
|
2177
|
+
"demoted": [list(c) for c in sorted(demoted)],
|
|
2178
|
+
"edit_rates": {f"{c[0]}|{c[1]}": rates.get(c, {}) for c in rates},
|
|
2179
|
+
"promoted_at": dict(promoted_at),
|
|
2180
|
+
"basis": {f"{c[0]}|{c[1]}": _measure_facade._cohort_basis(c) for c in rates},
|
|
2181
|
+
"_cached_ts": _measure_facade.time.time(),
|
|
2182
|
+
}
|
|
2183
|
+
try:
|
|
2184
|
+
_measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
2185
|
+
fd, tmp_name = _measure_facade.tempfile.mkstemp(
|
|
2186
|
+
prefix=".cohort_tripwire.", suffix=".tmp", dir=str(_measure_facade.SNAPSHOT_DIR))
|
|
2187
|
+
try:
|
|
2188
|
+
if hasattr(_measure_facade.os, "fchmod"):
|
|
2189
|
+
_measure_facade.os.fchmod(fd, 0o600)
|
|
2190
|
+
with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
2191
|
+
_measure_facade.json.dump(record, fh)
|
|
2192
|
+
_measure_facade.os.replace(tmp_name, str(path))
|
|
2193
|
+
except OSError:
|
|
2194
|
+
try:
|
|
2195
|
+
_measure_facade.os.unlink(tmp_name)
|
|
2196
|
+
except OSError:
|
|
2197
|
+
pass
|
|
2198
|
+
raise
|
|
2199
|
+
except OSError:
|
|
2200
|
+
pass
|
|
2201
|
+
|
|
2202
|
+
|
|
2203
|
+
def _tripwire_lock():
|
|
2204
|
+
"""Bounded portable lease serializing tripwire recompute+write (T4)."""
|
|
2205
|
+
_measure_facade = _compat.facade()
|
|
2206
|
+
lock_path = _measure_facade.SNAPSHOT_DIR / f"{_measure_facade._TRIPWIRE_LOCK_NAME}.lease"
|
|
2207
|
+
with _measure_facade.lease_lock(
|
|
2208
|
+
lock_path,
|
|
2209
|
+
deadline=_measure_facade.current_deadline(),
|
|
2210
|
+
acquire_timeout=0.075,
|
|
2211
|
+
) as acquired:
|
|
2212
|
+
yield acquired
|
|
2213
|
+
|
|
2214
|
+
|
|
2215
|
+
def evaluate_cohort_tripwire(force=None):
|
|
2216
|
+
"""Recompute per-cohort live edit-rates and auto-demote breaches.
|
|
2217
|
+
|
|
2218
|
+
Cheap, mtime-gated: returns the cached sidecar verdict unless it is older
|
|
2219
|
+
than _TRIPWIRE_CACHE_TTL_SECONDS (or `force`). On a fresh compute, any active
|
|
2220
|
+
cohort whose live edit-rate exceeds _TRIPWIRE_EDIT_RATE (with at least
|
|
2221
|
+
_TRIPWIRE_MIN_SAMPLES active reads) is added to the demoted set. Demotions
|
|
2222
|
+
are STICKY (hysteresis): a cohort already demoted stays demoted regardless of
|
|
2223
|
+
a later dip — only the CLI promote / next backfill clears it. Each NEW
|
|
2224
|
+
demotion logs one `cohort_demoted` event. Fail-open: returns {} on error.
|
|
2225
|
+
"""
|
|
2226
|
+
# T1: read_corrupt distinguishes a malformed sidecar (force recompute) from a
|
|
2227
|
+
# fresh valid one. A corrupt verdict must never satisfy the TTL fast path.
|
|
2228
|
+
_measure_facade = _compat.facade()
|
|
2229
|
+
sidecar = _measure_facade._read_tripwire_sidecar(return_corrupt=True)
|
|
2230
|
+
corrupt = sidecar == "__corrupt__"
|
|
2231
|
+
if corrupt:
|
|
2232
|
+
sidecar = {}
|
|
2233
|
+
if not force and not corrupt:
|
|
2234
|
+
try:
|
|
2235
|
+
age = _measure_facade.time.time() - float(sidecar.get("_cached_ts", 0))
|
|
2236
|
+
if sidecar and age < _measure_facade._TRIPWIRE_CACHE_TTL_SECONDS:
|
|
2237
|
+
return sidecar
|
|
2238
|
+
except (TypeError, ValueError):
|
|
2239
|
+
pass
|
|
2240
|
+
|
|
2241
|
+
# T4: serialize the recompute+write branch under a portable bounded lease.
|
|
2242
|
+
# Contenders fail open by skipping this mutation, never by running unlocked.
|
|
2243
|
+
with _measure_facade._tripwire_lock() as acquired:
|
|
2244
|
+
if not acquired:
|
|
2245
|
+
return sidecar or {}
|
|
2246
|
+
# Re-read INSIDE the lock: another process may have just recomputed.
|
|
2247
|
+
sidecar = _measure_facade._read_tripwire_sidecar(return_corrupt=True)
|
|
2248
|
+
if sidecar == "__corrupt__":
|
|
2249
|
+
sidecar = {}
|
|
2250
|
+
elif not force:
|
|
2251
|
+
try:
|
|
2252
|
+
age = _measure_facade.time.time() - float(sidecar.get("_cached_ts", 0))
|
|
2253
|
+
if sidecar and age < _measure_facade._TRIPWIRE_CACHE_TTL_SECONDS:
|
|
2254
|
+
return sidecar
|
|
2255
|
+
except (TypeError, ValueError):
|
|
2256
|
+
pass
|
|
2257
|
+
|
|
2258
|
+
prev_demoted = set(
|
|
2259
|
+
tuple(c) for c in sidecar.get("demoted", [])
|
|
2260
|
+
if isinstance(c, (list, tuple)) and len(c) == 2
|
|
2261
|
+
)
|
|
2262
|
+
promoted_at = sidecar.get("promoted_at", {})
|
|
2263
|
+
if not isinstance(promoted_at, dict):
|
|
2264
|
+
promoted_at = {}
|
|
2265
|
+
try:
|
|
2266
|
+
conn = _measure_facade._init_trends_db()
|
|
2267
|
+
try:
|
|
2268
|
+
rates = _measure_facade._compute_cohort_edit_rates(conn, promoted_at=promoted_at)
|
|
2269
|
+
finally:
|
|
2270
|
+
conn.close()
|
|
2271
|
+
except Exception:
|
|
2272
|
+
return sidecar or {}
|
|
2273
|
+
|
|
2274
|
+
demoted = set(prev_demoted) # hysteresis: never un-demote here
|
|
2275
|
+
newly_demoted = []
|
|
2276
|
+
for cohort, r in rates.items():
|
|
2277
|
+
if cohort in demoted:
|
|
2278
|
+
continue
|
|
2279
|
+
# T9: interpolated cohorts use a tighter sample floor.
|
|
2280
|
+
if (
|
|
2281
|
+
r["skeletons"] >= _measure_facade._tripwire_min_samples(cohort)
|
|
2282
|
+
and r["edit_rate"] > _measure_facade._TRIPWIRE_EDIT_RATE
|
|
2283
|
+
):
|
|
2284
|
+
demoted.add(cohort)
|
|
2285
|
+
newly_demoted.append((cohort, r))
|
|
2286
|
+
|
|
2287
|
+
# Drop demotions for cohorts no longer in the active set (e.g. removed
|
|
2288
|
+
# from FIRST_READ_ACTIVE_COHORTS) so the sidecar cannot pin a stale one.
|
|
2289
|
+
active_cohorts = _measure_facade._resolve_active_cohorts()
|
|
2290
|
+
demoted = {c for c in demoted if c in active_cohorts}
|
|
2291
|
+
|
|
2292
|
+
_measure_facade._write_tripwire_sidecar(demoted, rates, promoted_at=promoted_at)
|
|
2293
|
+
|
|
2294
|
+
for cohort, r in newly_demoted:
|
|
2295
|
+
try:
|
|
2296
|
+
_measure_facade._log_compression_event(
|
|
2297
|
+
feature=_measure_facade._FEATURE_COHORT_DEMOTED,
|
|
2298
|
+
original_text="",
|
|
2299
|
+
compressed_text="",
|
|
2300
|
+
command_pattern=f"{cohort[0]}|{cohort[1]}",
|
|
2301
|
+
tier="opportunity",
|
|
2302
|
+
verified=False,
|
|
2303
|
+
quality_preserved=False,
|
|
2304
|
+
detail=(
|
|
2305
|
+
f"auto-demoted: live edit-rate {r['edit_rate']*100:.1f}% "
|
|
2306
|
+
f"(> {_measure_facade._TRIPWIRE_EDIT_RATE*100:.0f}% gate) over "
|
|
2307
|
+
f"{r['skeletons']} active reads"
|
|
2308
|
+
),
|
|
2309
|
+
)
|
|
2310
|
+
except Exception:
|
|
2311
|
+
pass
|
|
2312
|
+
# T8: push one rate-limited warn line to stderr naming the cohort, its
|
|
2313
|
+
# live edit rate, and the exact re-promote command. Operators watching
|
|
2314
|
+
# hook stderr learn about a silent quality demotion immediately instead
|
|
2315
|
+
# of only on the next compression-stats render.
|
|
2316
|
+
key = f"{cohort[0]}|{cohort[1]}"
|
|
2317
|
+
if key not in _measure_facade._tripwire_warned_cohorts:
|
|
2318
|
+
_measure_facade._tripwire_warned_cohorts.add(key)
|
|
2319
|
+
try:
|
|
2320
|
+
print(
|
|
2321
|
+
f"[Token Optimizer] cohort auto-demoted to measure-only: "
|
|
2322
|
+
f"{cohort[0]}:{cohort[1]} (live edit-rate "
|
|
2323
|
+
f"{r['edit_rate']*100:.1f}% > {_measure_facade._TRIPWIRE_EDIT_RATE*100:.0f}% "
|
|
2324
|
+
f"gate). Re-promote: measure.py cohorts promote "
|
|
2325
|
+
f"{cohort[0]}:{cohort[1]}",
|
|
2326
|
+
file=_measure_facade.sys.stderr,
|
|
2327
|
+
)
|
|
2328
|
+
except Exception:
|
|
2329
|
+
pass
|
|
2330
|
+
|
|
2331
|
+
# T3: build the verdict from the in-memory demoted set + freshly-computed
|
|
2332
|
+
# rates rather than re-reading the file. A concurrent writer (or our own
|
|
2333
|
+
# not-yet-flushed page cache) could otherwise hand back a stale/ghost verdict.
|
|
2334
|
+
return {
|
|
2335
|
+
"demoted": [list(c) for c in sorted(demoted)],
|
|
2336
|
+
"edit_rates": {f"{c[0]}|{c[1]}": rates.get(c, {}) for c in rates},
|
|
2337
|
+
"promoted_at": dict(promoted_at),
|
|
2338
|
+
"basis": {f"{c[0]}|{c[1]}": _measure_facade._cohort_basis(c) for c in rates},
|
|
2339
|
+
"_cached_ts": _measure_facade.time.time(),
|
|
2340
|
+
}
|
|
2341
|
+
|
|
2342
|
+
|
|
2343
|
+
def _cohort_tripwire_state():
|
|
2344
|
+
"""Read-only tripwire view for compression-stats + the dashboard.
|
|
2345
|
+
|
|
2346
|
+
Returns {"cohorts": [...], "demoted": [[lang,band],...]}. Each cohort row
|
|
2347
|
+
carries its live edit-rate and a `demoted` flag. Does NOT recompute or
|
|
2348
|
+
demote — it reads the sidecar verdict (kept fresh by the Edit-hook
|
|
2349
|
+
evaluation) plus the current edit-rates for display. Fail-open: empty on
|
|
2350
|
+
error.
|
|
2351
|
+
"""
|
|
2352
|
+
_measure_facade = _compat.facade()
|
|
2353
|
+
out = {"cohorts": [], "demoted": []}
|
|
2354
|
+
sidecar = _measure_facade._read_tripwire_sidecar()
|
|
2355
|
+
demoted = set(
|
|
2356
|
+
tuple(c) for c in sidecar.get("demoted", [])
|
|
2357
|
+
if isinstance(c, (list, tuple)) and len(c) == 2
|
|
2358
|
+
)
|
|
2359
|
+
promoted_at = sidecar.get("promoted_at", {})
|
|
2360
|
+
if not isinstance(promoted_at, dict):
|
|
2361
|
+
promoted_at = {}
|
|
2362
|
+
out["demoted"] = [list(c) for c in sorted(demoted)]
|
|
2363
|
+
try:
|
|
2364
|
+
conn = _measure_facade._init_trends_db()
|
|
2365
|
+
try:
|
|
2366
|
+
rates = _measure_facade._compute_cohort_edit_rates(conn, promoted_at=promoted_at)
|
|
2367
|
+
finally:
|
|
2368
|
+
conn.close()
|
|
2369
|
+
except Exception:
|
|
2370
|
+
return out
|
|
2371
|
+
for cohort, r in sorted(rates.items()):
|
|
2372
|
+
out["cohorts"].append({
|
|
2373
|
+
"language": cohort[0],
|
|
2374
|
+
"band": cohort[1],
|
|
2375
|
+
# T9: full_gate | interpolated, so the dashboard/CLI can flag the
|
|
2376
|
+
# thinner-sample (higher-exposure) interpolated cohorts honestly.
|
|
2377
|
+
"basis": r.get("basis", _measure_facade._cohort_basis(cohort)),
|
|
2378
|
+
"skeletons": r["skeletons"],
|
|
2379
|
+
"followups": r["followups"],
|
|
2380
|
+
"edit_rate_pct": round(100 * r["edit_rate"], 1),
|
|
2381
|
+
"demoted": cohort in demoted,
|
|
2382
|
+
})
|
|
2383
|
+
return out
|
|
2384
|
+
|
|
2385
|
+
|
|
2386
|
+
def cohorts_promote(cohort_args):
|
|
2387
|
+
"""CLI: clear a tripwire demotion for one or more `lang:band` cohorts.
|
|
2388
|
+
|
|
2389
|
+
The ONLY runtime path that re-promotes a demoted cohort (hysteresis). Returns
|
|
2390
|
+
the count cleared. Unknown cohorts are ignored with a note.
|
|
2391
|
+
"""
|
|
2392
|
+
_measure_facade = _compat.facade()
|
|
2393
|
+
sidecar = _measure_facade._read_tripwire_sidecar()
|
|
2394
|
+
demoted = set(
|
|
2395
|
+
tuple(c) for c in sidecar.get("demoted", [])
|
|
2396
|
+
if isinstance(c, (list, tuple)) and len(c) == 2
|
|
2397
|
+
)
|
|
2398
|
+
promoted_at = sidecar.get("promoted_at", {})
|
|
2399
|
+
if not isinstance(promoted_at, dict):
|
|
2400
|
+
promoted_at = {}
|
|
2401
|
+
promoted_at = dict(promoted_at)
|
|
2402
|
+
cleared = 0
|
|
2403
|
+
now = _measure_facade.time.time()
|
|
2404
|
+
for arg in cohort_args:
|
|
2405
|
+
if ":" not in arg:
|
|
2406
|
+
# T7: a malformed arg (missing the lang:band separator) is almost
|
|
2407
|
+
# always a typo; warn rather than silently skip so the operator
|
|
2408
|
+
# learns nothing was re-promoted.
|
|
2409
|
+
print(f" [warn] ignoring malformed cohort arg '{arg}' "
|
|
2410
|
+
"(expected lang:band, e.g. python:64-256KB)", file=_measure_facade.sys.stderr)
|
|
2411
|
+
continue
|
|
2412
|
+
lang, band = arg.split(":", 1)
|
|
2413
|
+
cohort = (lang.strip(), band.strip())
|
|
2414
|
+
if cohort in demoted:
|
|
2415
|
+
demoted.discard(cohort)
|
|
2416
|
+
cleared += 1
|
|
2417
|
+
# T5: stamp the promotion time so pre-promote skeleton/follow-up
|
|
2418
|
+
# history is fenced out of the live edit-rate and the cohort cannot
|
|
2419
|
+
# immediately re-demote on the very edits that demoted it.
|
|
2420
|
+
promoted_at[f"{cohort[0]}|{cohort[1]}"] = now
|
|
2421
|
+
if cleared:
|
|
2422
|
+
rates = {}
|
|
2423
|
+
try:
|
|
2424
|
+
conn = _measure_facade._init_trends_db()
|
|
2425
|
+
try:
|
|
2426
|
+
rates = _measure_facade._compute_cohort_edit_rates(conn, promoted_at=promoted_at)
|
|
2427
|
+
finally:
|
|
2428
|
+
conn.close()
|
|
2429
|
+
except Exception:
|
|
2430
|
+
pass
|
|
2431
|
+
_measure_facade._write_tripwire_sidecar(demoted, rates, promoted_at=promoted_at)
|
|
2432
|
+
return cleared
|