cctally 1.113.0 → 1.114.0

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +4 -6
  3. package/bin/_cctally_cache.py +1683 -485
  4. package/bin/_cctally_core.py +223 -1
  5. package/bin/_cctally_dashboard.py +96 -18
  6. package/bin/_cctally_dashboard_perf.py +128 -9
  7. package/bin/_cctally_dashboard_sources.py +267 -204
  8. package/bin/_cctally_db.py +861 -18
  9. package/bin/_cctally_diagnosis_sources.py +22 -4
  10. package/bin/_cctally_doctor.py +136 -18
  11. package/bin/_cctally_five_hour.py +2 -2
  12. package/bin/_cctally_forecast.py +27 -6
  13. package/bin/_cctally_journal.py +67 -5
  14. package/bin/_cctally_milestone_history.py +82 -9
  15. package/bin/_cctally_percent_breakdown.py +3 -2
  16. package/bin/_cctally_quota.py +201 -33
  17. package/bin/_cctally_record.py +14 -0
  18. package/bin/_cctally_rederive.py +23 -9
  19. package/bin/_cctally_source_analytics.py +60 -15
  20. package/bin/_cctally_statusline.py +17 -0
  21. package/bin/_cctally_store.py +80 -5
  22. package/bin/_cctally_tui.py +4 -3
  23. package/bin/_cctally_weekrefs.py +128 -21
  24. package/bin/_lib_cache_report.py +35 -6
  25. package/bin/_lib_codex_conversation.py +32 -0
  26. package/bin/_lib_codex_conversation_query.py +164 -30
  27. package/bin/_lib_conversation_query.py +95 -56
  28. package/bin/_lib_conversation_retention.py +1605 -640
  29. package/bin/_lib_cost_provenance.py +53 -2
  30. package/bin/_lib_doctor.py +263 -69
  31. package/bin/_lib_fmt.py +11 -0
  32. package/bin/_lib_merge_gate.py +469 -51
  33. package/bin/_lib_perf.py +27 -1
  34. package/bin/_lib_pricing.py +193 -8
  35. package/bin/_lib_pricing_check.py +20 -4
  36. package/bin/_lib_reclaim_planner.py +792 -0
  37. package/bin/_lib_rederive.py +225 -77
  38. package/bin/_lib_snapshot_cache.py +21 -0
  39. package/bin/_lib_sqlite_close.py +81 -0
  40. package/bin/_lib_subscription_weeks.py +100 -17
  41. package/bin/_lib_tick_stats.py +217 -17
  42. package/bin/_lib_wal_checkpoint.py +1077 -0
  43. package/bin/_lib_write_budget.py +483 -0
  44. package/bin/_lib_write_io.py +703 -0
  45. package/bin/cctally +8 -0
  46. package/dashboard/static/assets/{ConversationsView-CEZ-BUyi.js → ConversationsView-Bc8LCOAZ.js} +1 -1
  47. package/dashboard/static/assets/{DoctorModal-CE1oH_Zy.js → DoctorModal-D--qVBwe.js} +1 -1
  48. package/dashboard/static/assets/ModalRoot-DLPgyAM_.js +1 -0
  49. package/dashboard/static/assets/{ProjectsDrillPanel-B3DZoCeD.js → ProjectsDrillPanel-z53a4v4M.js} +1 -1
  50. package/dashboard/static/assets/{SourceDetailModal-CHp9EgLP.js → SourceDetailModal-Bw0T8W-W.js} +1 -1
  51. package/dashboard/static/assets/{UpdateModal-5iKST6jo.js → UpdateModal-D5AKx4Yw.js} +1 -1
  52. package/dashboard/static/assets/index-BKITk1CT.css +1 -0
  53. package/dashboard/static/assets/{index-Cm0VTxJC.js → index-BXDOzSng.js} +3 -3
  54. package/dashboard/static/assets/{outlineNavigation-DkXGL8J6.js → outlineNavigation-JObY7cUY.js} +1 -1
  55. package/dashboard/static/dashboard.html +2 -2
  56. package/package.json +6 -1
  57. package/dashboard/static/assets/ModalRoot-D5Y8IFUG.js +0 -1
  58. package/dashboard/static/assets/index-Dt4tqf43.css +0 -1
package/bin/_lib_perf.py CHANGED
@@ -149,7 +149,8 @@ def _stack():
149
149
 
150
150
 
151
151
  class Phase:
152
- __slots__ = ("name", "elapsed_ms", "count", "meta", "children", "_start", "_stack")
152
+ __slots__ = ("name", "elapsed_ms", "count", "meta", "children", "_start",
153
+ "_stack", "write_bytes", "_write_start")
153
154
 
154
155
  def __init__(self, name, stack):
155
156
  self.name = name
@@ -159,6 +160,8 @@ class Phase:
159
160
  self.children = []
160
161
  self._start = 0.0
161
162
  self._stack = stack
163
+ self.write_bytes = None
164
+ self._write_start = None
162
165
 
163
166
  def set_count(self, n):
164
167
  self.count = int(n)
@@ -169,12 +172,17 @@ class Phase:
169
172
  self.meta.update(kw)
170
173
 
171
174
  def __enter__(self):
175
+ self._write_start = _write_counter_value()
172
176
  self._start = time.perf_counter()
173
177
  self._stack.append(self)
174
178
  return self
175
179
 
176
180
  def __exit__(self, *exc):
177
181
  self.elapsed_ms = (time.perf_counter() - self._start) * 1000.0
182
+ end = _write_counter_value()
183
+ if (self._write_start is not None and end is not None
184
+ and end >= self._write_start):
185
+ self.write_bytes = end - self._write_start
178
186
  # Identity-aware unwind. If a nested phase leaked (its __exit__ was
179
187
  # skipped — e.g. an exception escaped a manually CM-bracketed region),
180
188
  # drop the leaked frames sitting above us so we never append a phase to
@@ -203,6 +211,8 @@ class Phase:
203
211
  d["count"] = self.count
204
212
  if self.meta:
205
213
  d["meta"] = dict(self.meta)
214
+ if self.write_bytes is not None:
215
+ d["write_bytes"] = self.write_bytes
206
216
  if self.children:
207
217
  d["children"] = [c.to_dict() for c in self.children]
208
218
  return d
@@ -227,6 +237,22 @@ class _NullPhase:
227
237
  _NULL_PHASE = _NullPhase()
228
238
 
229
239
 
240
+ def _write_counter_value():
241
+ """The process write counter for an armed phase (#901 §5.5), or None.
242
+
243
+ Deep-phase samples are optional: they ride an armed trace only, and the
244
+ always-on totals never depend on them. The counter module is used only
245
+ when the process already loaded it, so this stays stdlib-only."""
246
+ module = sys.modules.get("_lib_write_io")
247
+ if module is None:
248
+ return None
249
+ try:
250
+ reading = module.read_counter()
251
+ except Exception: # noqa: BLE001 — a diagnostic must not raise
252
+ return None
253
+ return reading.value if reading.status == "ok" else None
254
+
255
+
230
256
  def phase(name):
231
257
  # Per-root capture (#583 S1 §2.2). `_ENABLED` is process-global and HTTP
232
258
  # handlers open their own roots on their own threads, so a flip landing
@@ -19,6 +19,7 @@ from __future__ import annotations
19
19
 
20
20
  import dataclasses
21
21
  import datetime as dt
22
+ import math
22
23
  import re
23
24
  import sys
24
25
  from typing import Any
@@ -30,6 +31,34 @@ def _eprint(*args: Any) -> None:
30
31
 
31
32
  TIERED_THRESHOLD = 200_000
32
33
 
34
+ # #929: Claude Haiku 5.5 is priced by prompt length. A card that declares
35
+ # `whole_request_prompt_threshold_tokens` selects ONE card per request from its
36
+ # prompt (input + flat cache creation + cache read): over the threshold every
37
+ # class of that request, output included, bills at the `_above_100k_tokens`
38
+ # rates. This is a different mechanism from the per-class MARGINAL
39
+ # `_above_200k_tokens` split older Sonnet cards carry, and a card never mixes
40
+ # the two. A legacy card carries neither the marker nor any 100K field.
41
+ CLAUDE_WHOLE_REQUEST_THRESHOLD_KEY = "whole_request_prompt_threshold_tokens"
42
+ CLAUDE_WHOLE_REQUEST_THRESHOLD = 100_000
43
+ CLAUDE_WHOLE_REQUEST_TIER_FIELDS = (
44
+ ("input_cost_per_token", "input_cost_per_token_above_100k_tokens"),
45
+ ("output_cost_per_token", "output_cost_per_token_above_100k_tokens"),
46
+ ("cache_creation_input_token_cost",
47
+ "cache_creation_input_token_cost_above_100k_tokens"),
48
+ ("cache_read_input_token_cost",
49
+ "cache_read_input_token_cost_above_100k_tokens"),
50
+ )
51
+ CLAUDE_WHOLE_REQUEST_TIER_SUFFIX = "_above_100k_tokens"
52
+ # The marker plus the four recognised tier fields. A card sharing none of them
53
+ # is legacy; the hot path decides that with one `isdisjoint` call. A card that
54
+ # carries some OTHER `_above_100k_tokens` field is malformed: the selector
55
+ # refuses it when the card is otherwise whole-request, and
56
+ # `check_table_shapes` refuses it on any card (`claude_whole_request_
57
+ # declaration_problems`), so it can never silently price at the base card.
58
+ _CLAUDE_WHOLE_REQUEST_KEYS = frozenset(
59
+ (CLAUDE_WHOLE_REQUEST_THRESHOLD_KEY,
60
+ *(tier for _, tier in CLAUDE_WHOLE_REQUEST_TIER_FIELDS)))
61
+
33
62
 
34
63
  def _chip_for_model(name: str) -> str:
35
64
  """Bucket a canonical model id into a small chip palette.
@@ -63,7 +92,7 @@ def _chip_for_model(name: str) -> str:
63
92
  # fingerprint a store recorded and refuses a write from an older process. That
64
93
  # comparison is day-granular by construction, so two revisions sharing a date
65
94
  # compare equal and the older process is authorized to write.
66
- PRICING_SNAPSHOT_DATE = "2026-09-30"
95
+ PRICING_SNAPSHOT_DATE = "2026-10-07"
67
96
  PRICING_STALENESS_DAYS = 60 # release pre-flight WARNs past this age
68
97
 
69
98
 
@@ -517,6 +546,21 @@ CLAUDE_MODEL_PRICING: dict[str, dict[str, Any]] = {
517
546
  "cache_creation_input_token_cost": 1.25e-06,
518
547
  "cache_read_input_token_cost": 1e-07,
519
548
  },
549
+ "claude-haiku-5-5": {
550
+ # Source: https://platform.claude.com/docs/en/models/haiku-5-5/overview
551
+ # Priced by prompt length (#929): over 100,000 prompt tokens the WHOLE
552
+ # request bills at the _above_100k_tokens card. The 1h write stays
553
+ # derived (selected input x CACHE_WRITE_1H_MULTIPLIER).
554
+ "input_cost_per_token": 1e-07,
555
+ "output_cost_per_token": 5e-07,
556
+ "cache_creation_input_token_cost": 1.25e-07,
557
+ "cache_read_input_token_cost": 1e-08,
558
+ "input_cost_per_token_above_100k_tokens": 5e-07,
559
+ "output_cost_per_token_above_100k_tokens": 2.5e-06,
560
+ "cache_creation_input_token_cost_above_100k_tokens": 6.25e-07,
561
+ "cache_read_input_token_cost_above_100k_tokens": 5e-08,
562
+ "whole_request_prompt_threshold_tokens": 100_000,
563
+ },
520
564
  "claude-mythos-5": {
521
565
  "input_cost_per_token": 1e-05,
522
566
  "output_cost_per_token": 5e-05,
@@ -1274,6 +1318,118 @@ def claude_usage_dict(*, cache_1h_tokens, speed, input_tokens=0, output_tokens=0
1274
1318
  return usage
1275
1319
 
1276
1320
 
1321
+ def _finite_positive_rate(value) -> bool:
1322
+ return (isinstance(value, (int, float)) and not isinstance(value, bool)
1323
+ and math.isfinite(value) and value > 0)
1324
+
1325
+
1326
+ def _is_whole_request_card(card) -> bool:
1327
+ """True when ``card`` declares (or half-declares) a whole-request tier:
1328
+ it carries the marker or one of the four recognised tier fields. This is
1329
+ on every Claude request's pricing path, so it is one set operation; the
1330
+ scan for unrecognised ``_above_100k_tokens`` fields lives in
1331
+ ``claude_whole_request_declaration_problems``."""
1332
+ return not _CLAUDE_WHOLE_REQUEST_KEYS.isdisjoint(card)
1333
+
1334
+
1335
+ def _unrecognised_whole_request_fields(card) -> list:
1336
+ return sorted(k for k in card
1337
+ if k.endswith(CLAUDE_WHOLE_REQUEST_TIER_SUFFIX)
1338
+ and k not in _CLAUDE_WHOLE_REQUEST_KEYS)
1339
+
1340
+
1341
+ def claude_whole_request_declaration_problems(card) -> list:
1342
+ """Every reason ``card``'s whole-request declaration is malformed (#929).
1343
+
1344
+ ``[]`` for a legacy card (neither the marker nor any
1345
+ ``_above_100k_tokens`` field) and for a well-formed declaration. Shared by
1346
+ the selector and ``check_table_shapes`` so the two can never disagree
1347
+ about what is well formed. Any ``_above_100k_tokens`` field other than the
1348
+ four recognised ones is a problem, with or without the marker.
1349
+ """
1350
+ unrecognised = _unrecognised_whole_request_fields(card)
1351
+ if not unrecognised and not _is_whole_request_card(card):
1352
+ return []
1353
+ problems = []
1354
+ key = CLAUDE_WHOLE_REQUEST_THRESHOLD_KEY
1355
+ threshold = card.get(key)
1356
+ if key not in card:
1357
+ problems.append(f"missing {key}")
1358
+ elif (isinstance(threshold, bool) or not isinstance(threshold, int)
1359
+ or threshold != CLAUDE_WHOLE_REQUEST_THRESHOLD):
1360
+ problems.append(
1361
+ f"{key} must be the integer {CLAUDE_WHOLE_REQUEST_THRESHOLD} the "
1362
+ f"_above_100k_tokens fields name (got {threshold!r})")
1363
+ for _, tier in CLAUDE_WHOLE_REQUEST_TIER_FIELDS:
1364
+ if tier not in card:
1365
+ problems.append(f"missing {tier}")
1366
+ elif not _finite_positive_rate(card[tier]):
1367
+ problems.append(
1368
+ f"{tier} not a finite positive number ({card[tier]!r})")
1369
+ mixed = sorted(k for k in card if k.endswith("_above_200k_tokens"))
1370
+ if mixed:
1371
+ problems.append("mixes whole-request and marginal tiers: "
1372
+ + ", ".join(mixed))
1373
+ if unrecognised:
1374
+ problems.append("unrecognised _above_100k_tokens fields: "
1375
+ + ", ".join(unrecognised))
1376
+ return problems
1377
+
1378
+
1379
+ def _select_claude_request_card(card, *, input_tokens, cache_creation_tokens,
1380
+ cache_read_tokens, prompt_tokens_for_tier=None):
1381
+ """The card that prices ONE request (#929). Pure: never writes ``card``.
1382
+
1383
+ A legacy card (neither the marker nor any of the four recognised tier
1384
+ fields) is returned unchanged (the same object) without reading a count.
1385
+ A whole-request card must be well formed, which includes carrying no
1386
+ unrecognised ``_above_100k_tokens`` field, or this raises
1387
+ ``ValueError``. Its prompt is ``prompt_tokens_for_tier`` when given (a
1388
+ caller pricing a synthetic subset of a real request), else input + FLAT
1389
+ cache creation + cache read; output and the 1h sub-split never count. At or
1390
+ under the threshold the stored card itself is returned; over it, a NEW dict
1391
+ whose four base slots hold the higher rates and which carries neither the
1392
+ marker nor any tier field.
1393
+ """
1394
+ if not _is_whole_request_card(card):
1395
+ return card
1396
+ problems = claude_whole_request_declaration_problems(card)
1397
+ if problems:
1398
+ raise ValueError("malformed whole-request pricing declaration: "
1399
+ + "; ".join(problems))
1400
+ if prompt_tokens_for_tier is None:
1401
+ prompt = ((input_tokens or 0) + (cache_creation_tokens or 0)
1402
+ + (cache_read_tokens or 0))
1403
+ else:
1404
+ prompt = prompt_tokens_for_tier
1405
+ if prompt <= card[CLAUDE_WHOLE_REQUEST_THRESHOLD_KEY]:
1406
+ return card
1407
+ # No marker and no `_above_100k_tokens` field survives into the selected
1408
+ # card (a well-formed card carries no unrecognised one, but the filter
1409
+ # does not rely on that).
1410
+ selected = {k: v for k, v in card.items()
1411
+ if k != CLAUDE_WHOLE_REQUEST_THRESHOLD_KEY
1412
+ and not k.endswith(CLAUDE_WHOLE_REQUEST_TIER_SUFFIX)}
1413
+ for base, tier in CLAUDE_WHOLE_REQUEST_TIER_FIELDS:
1414
+ selected[base] = card[tier]
1415
+ return selected
1416
+
1417
+
1418
+ def _whole_request_cache_create_cost(card, flat, h_raw) -> float:
1419
+ """Cache-creation USD on a whole-request card: direct flat arithmetic
1420
+ (#929 spec §5), never the legacy 200K band partition, which is not
1421
+ float-identical to it."""
1422
+ if flat <= 0:
1423
+ return 0.0
1424
+ rate_5m = card.get("cache_creation_input_token_cost", 0.0)
1425
+ h = 0 if h_raw is None else max(0, min(int(h_raw), flat))
1426
+ if h == 0:
1427
+ return flat * rate_5m
1428
+ rate_1h = (card.get("input_cost_per_token", 0.0)
1429
+ * current_pricing_snapshot().cache_write_1h_multiplier)
1430
+ return (flat - h) * rate_5m + h * rate_1h
1431
+
1432
+
1277
1433
  def _cache_create_cost(pricing: dict, flat: int, h_raw, tiered) -> float:
1278
1434
  """USD for one entry's cache-CREATION tokens, priced by TTL (#195).
1279
1435
 
@@ -1320,8 +1476,15 @@ def _calculate_entry_cost(
1320
1476
  usage: dict[str, Any],
1321
1477
  mode: str = "auto",
1322
1478
  cost_usd: float | None = None,
1479
+ *,
1480
+ prompt_tokens_for_tier: int | None = None,
1323
1481
  ) -> float:
1324
- """Calculate USD cost for a single API call entry."""
1482
+ """Calculate USD cost for a single API call entry.
1483
+
1484
+ ``prompt_tokens_for_tier`` only feeds whole-request card selection (#929):
1485
+ a caller pricing a synthetic subset of a real request passes that
1486
+ request's real prompt total so the subset bills at the request's card.
1487
+ """
1325
1488
  if mode == "display":
1326
1489
  return cost_usd if cost_usd is not None else 0.0
1327
1490
  if mode == "auto" and cost_usd is not None:
@@ -1330,6 +1493,18 @@ def _calculate_entry_cost(
1330
1493
  pricing = _resolve_model_pricing(model)
1331
1494
  if pricing is None:
1332
1495
  return 0.0
1496
+ # #929: a whole-request card selects ONE card for this request. A legacy
1497
+ # card skips selection entirely and runs the pre-#929 expressions below
1498
+ # byte-for-byte (the selector would return it unchanged anyway).
1499
+ whole_request = _is_whole_request_card(pricing)
1500
+ if whole_request:
1501
+ pricing = _select_claude_request_card(
1502
+ pricing,
1503
+ input_tokens=usage.get("input_tokens", 0),
1504
+ cache_creation_tokens=usage.get("cache_creation_input_tokens", 0),
1505
+ cache_read_tokens=usage.get("cache_read_input_tokens", 0),
1506
+ prompt_tokens_for_tier=prompt_tokens_for_tier,
1507
+ )
1333
1508
 
1334
1509
  def _tiered(tokens: int, base_key: str, tiered_key: str) -> float:
1335
1510
  base_rate = pricing.get(base_key, 0.0)
@@ -1361,12 +1536,22 @@ def _calculate_entry_cost(
1361
1536
  # arithmetic or comparison, and the `h_raw` side does its own `int()`
1362
1537
  # inside the clamp (which IS load-bearing there: `min(int(h_raw), flat)`
1363
1538
  # is what pins the 1h portion to whole tokens).
1364
- cache_create_cost = _cache_create_cost(
1365
- pricing,
1366
- usage.get("cache_creation_input_tokens", 0),
1367
- usage.get("cache_creation_1h_input_tokens"),
1368
- _tiered,
1369
- )
1539
+ if not whole_request:
1540
+ cache_create_cost = _cache_create_cost(
1541
+ pricing,
1542
+ usage.get("cache_creation_input_tokens", 0),
1543
+ usage.get("cache_creation_1h_input_tokens"),
1544
+ _tiered,
1545
+ )
1546
+ else:
1547
+ # The selected card has no `_above_200k_tokens` key, so `_tiered`
1548
+ # prices input, output and cache read as tokens x selected rate; cache
1549
+ # creation takes the direct flat form, not the 200K band partition.
1550
+ cache_create_cost = _whole_request_cache_create_cost(
1551
+ pricing,
1552
+ usage.get("cache_creation_input_tokens", 0),
1553
+ usage.get("cache_creation_1h_input_tokens"),
1554
+ )
1370
1555
  cache_read_cost = _tiered(
1371
1556
  usage.get("cache_read_input_tokens", 0),
1372
1557
  "cache_read_input_token_cost",
@@ -1,9 +1,12 @@
1
1
  """Pure-fn kernel for the pricing-freshness check (spec 2026-05-29).
2
2
 
3
- No I/O, no import of `cctally`/`_lib_pricing` at module scope — every
4
- dependency (pricing predicates, tables, observed rows, LiteLLM snapshot)
5
- is passed in by the I/O glue in bin/cctally. Re-exported there like the
6
- other _lib_* kernels.
3
+ No I/O, and no import of `cctally`/`_lib_pricing` at module scope. The
4
+ tables, observed rows and LiteLLM snapshot are passed in by the I/O glue in
5
+ bin/cctally, which re-exports this module like the other _lib_* kernels.
6
+ The one exception is `check_table_shapes`, which resolves the pure
7
+ `_lib_pricing` kernel per call through `_pricing()` (#929) so the
8
+ whole-request declaration rule has a single definition shared with the
9
+ cost engine's selector.
7
10
  """
8
11
  from __future__ import annotations
9
12
 
@@ -186,6 +189,13 @@ def expired_allowlist_entries(allowlist, as_of_date) -> list:
186
189
  ]
187
190
 
188
191
 
192
+ def _pricing():
193
+ """The pricing kernel, resolved per call (never bound at module scope —
194
+ see this module's docstring). Mirrors ``_lib_cost_provenance._pricing``."""
195
+ import _lib_pricing
196
+ return _lib_pricing
197
+
198
+
189
199
  _CLAUDE_REQUIRED = ("input_cost_per_token", "output_cost_per_token",
190
200
  "cache_creation_input_token_cost", "cache_read_input_token_cost")
191
201
  _CODEX_REQUIRED = ("input_cost_per_token", "cache_read_input_token_cost",
@@ -211,8 +221,14 @@ def check_table_shapes(claude_tbl, codex_tbl, zero_sentinels) -> list:
211
221
  if cost_fields and all(float(v) == 0.0 for v in cost_fields.values()) and not allow_zero:
212
222
  problems.append(f"{model}: all cost fields zero but not a documented sentinel")
213
223
 
224
+ # #929: a Claude whole-request (prompt-length) tier is all-or-nothing.
225
+ # The definition of "well formed" lives beside the selector that refuses a
226
+ # malformed card, so this check and the cost engine can never disagree.
227
+ declaration_problems = _pricing().claude_whole_request_declaration_problems
214
228
  for model, body in claude_tbl.items():
215
229
  _check(model, body, _CLAUDE_REQUIRED, allow_zero=False)
230
+ for p in declaration_problems(body):
231
+ problems.append(f"{model}: {p}")
216
232
  for model, body in codex_tbl.items():
217
233
  _check(model, body, _CODEX_REQUIRED, allow_zero=model in zero_sentinels)
218
234
  return problems