cctally 1.114.0 → 1.116.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 (86) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/bin/_cctally_account.py +32 -8
  3. package/bin/_cctally_cache.py +4491 -295
  4. package/bin/_cctally_completion.py +1355 -0
  5. package/bin/_cctally_config.py +37 -0
  6. package/bin/_cctally_core.py +282 -9
  7. package/bin/_cctally_dashboard.py +8 -11
  8. package/bin/_cctally_dashboard_conversation.py +292 -23
  9. package/bin/_cctally_dashboard_envelope.py +42 -35
  10. package/bin/_cctally_dashboard_sources.py +18 -9
  11. package/bin/_cctally_db.py +401 -9
  12. package/bin/_cctally_doctor.py +469 -27
  13. package/bin/_cctally_five_hour.py +166 -1049
  14. package/bin/_cctally_forecast.py +81 -9
  15. package/bin/_cctally_journal.py +5076 -177
  16. package/bin/_cctally_journal_repair.py +110 -19
  17. package/bin/_cctally_oauth_samples.py +280 -0
  18. package/bin/_cctally_parser.py +47 -0
  19. package/bin/_cctally_project.py +8 -2
  20. package/bin/_cctally_quarantine.py +662 -0
  21. package/bin/_cctally_quota.py +96 -12
  22. package/bin/_cctally_quota_model.py +391 -83
  23. package/bin/_cctally_record.py +1088 -269
  24. package/bin/_cctally_rederive.py +854 -192
  25. package/bin/_cctally_refresh.py +113 -13
  26. package/bin/_cctally_source_analytics.py +23 -2
  27. package/bin/_cctally_statusline.py +7062 -505
  28. package/bin/_cctally_store.py +1244 -91
  29. package/bin/_cctally_transcript.py +8 -7
  30. package/bin/_cctally_tui.py +119 -60
  31. package/bin/_cctally_update.py +25 -0
  32. package/bin/_lib_account_binding.py +152 -0
  33. package/bin/_lib_account_protocol.py +569 -0
  34. package/bin/_lib_aggregators.py +4 -0
  35. package/bin/_lib_cache_coverage.py +13 -1
  36. package/bin/_lib_cache_writer_lock.py +19 -3
  37. package/bin/_lib_clone_copy.py +177 -0
  38. package/bin/_lib_codex_conversation_query.py +133 -19
  39. package/bin/_lib_codex_conversation_watch.py +59 -14
  40. package/bin/_lib_codex_drain_admission.py +214 -0
  41. package/bin/_lib_codex_metadata.py +18 -1
  42. package/bin/_lib_codex_publication_barrier.py +277 -0
  43. package/bin/_lib_codex_rollout_container.py +502 -0
  44. package/bin/_lib_conversation_dispatch.py +3 -0
  45. package/bin/_lib_conversation_query.py +11 -3
  46. package/bin/_lib_dashboard_sources.py +57 -15
  47. package/bin/_lib_detector_access_registry.py +4038 -0
  48. package/bin/_lib_doctor.py +753 -1
  49. package/bin/_lib_five_hour.py +126 -0
  50. package/bin/_lib_ingest_frontier.py +414 -20
  51. package/bin/_lib_journal.py +261 -10
  52. package/bin/_lib_journal_router.py +166 -48
  53. package/bin/_lib_jsonl.py +5 -4
  54. package/bin/_lib_legacy_spool.py +126 -0
  55. package/bin/_lib_legacy_writer_evidence.py +136 -0
  56. package/bin/_lib_meter_rate_change.py +10 -0
  57. package/bin/_lib_oauth_samples.py +238 -0
  58. package/bin/_lib_outcome_quarantine.py +690 -0
  59. package/bin/_lib_pricing.py +7 -2
  60. package/bin/_lib_pricing_check.py +0 -12
  61. package/bin/_lib_provider_activity.py +770 -0
  62. package/bin/_lib_quarantine.py +155 -0
  63. package/bin/_lib_quota_calibration.py +53 -8
  64. package/bin/_lib_quota_copy.py +2 -1
  65. package/bin/_lib_quota_model.py +384 -52
  66. package/bin/_lib_rebuild_progress.py +146 -0
  67. package/bin/_lib_record.py +22 -0
  68. package/bin/_lib_rederive.py +393 -8
  69. package/bin/_lib_segment_summary.py +35 -2
  70. package/bin/_lib_snapshot_cache.py +43 -1
  71. package/bin/_lib_stale_proof.py +708 -0
  72. package/bin/_lib_statusline_candidates.py +356 -27
  73. package/bin/_lib_worker_launches.py +315 -0
  74. package/bin/cctally +29 -12
  75. package/dashboard/static/assets/{ConversationsView-Bc8LCOAZ.js → ConversationsView-Dflb_myA.js} +1 -1
  76. package/dashboard/static/assets/DoctorModal-DFX5CfIs.js +1 -0
  77. package/dashboard/static/assets/{ModalRoot-DLPgyAM_.js → ModalRoot-HlxoagIa.js} +1 -1
  78. package/dashboard/static/assets/{ProjectsDrillPanel-z53a4v4M.js → ProjectsDrillPanel-C3PJy1xx.js} +1 -1
  79. package/dashboard/static/assets/{SourceDetailModal-Bw0T8W-W.js → SourceDetailModal-BczsWKhD.js} +1 -1
  80. package/dashboard/static/assets/{UpdateModal-D5AKx4Yw.js → UpdateModal-Os-Lo5cs.js} +1 -1
  81. package/dashboard/static/assets/{index-BXDOzSng.js → index-CYZ3NLqF.js} +3 -3
  82. package/dashboard/static/assets/{outlineNavigation-JObY7cUY.js → outlineNavigation-k-zIif6W.js} +1 -1
  83. package/dashboard/static/dashboard.html +1 -1
  84. package/package.json +20 -2
  85. package/bin/_lib_merge_gate.py +0 -725
  86. package/dashboard/static/assets/DoctorModal-D--qVBwe.js +0 -1
@@ -21,12 +21,14 @@ from __future__ import annotations
21
21
  import bisect
22
22
  import dataclasses
23
23
  import datetime as dt
24
+ import decimal
24
25
  import enum
25
26
  import hashlib
26
27
  import json
27
28
  import math
28
29
  import re
29
30
  import statistics
31
+ import typing
30
32
 
31
33
  from _lib_pricing import _strip_anthropic_model_prefix
32
34
 
@@ -36,14 +38,9 @@ from _lib_pricing import _strip_anthropic_model_prefix
36
38
  # fitted under a different fingerprint is `stale`.
37
39
  # ---------------------------------------------------------------------------
38
40
 
39
- #: Weights in "fresh input token" equivalents. Calibrated on Opus-5-dominated
40
- #: traffic; the five-minute cache-write quantity is weighted as fresh input.
41
- TOKEN_CLASS_WEIGHTS: dict[str, float] = {
42
- "fresh": 1.0,
43
- "output": 4.73,
44
- "cache_1h": 1.03,
45
- "cache_read": 0.0031,
46
- }
41
+ #: The four weighted token classes, in the order every era states its
42
+ #: weights. The five-minute cache-write quantity is weighted as fresh input.
43
+ TOKEN_CLASSES: tuple[str, ...] = ("fresh", "output", "cache_1h", "cache_read")
47
44
 
48
45
  #: Recognized model spellings (case-folded, provider prefix stripped, anchored
49
46
  #: terminal -YYYYMMDD removed) resolved to their canonical family. An
@@ -87,6 +84,12 @@ FAMILY_ALIASES: dict[str, str] = {
87
84
  "claude-mythos-5": "claude-mythos-5",
88
85
  "claude-mythos-5-1": "claude-mythos-5-1",
89
86
  "claude-mythos-preview": "claude-mythos-5",
87
+ # The 5.5 generation (#978). Each is its OWN canonical family, on the
88
+ # #704 precedent: pooling one into the family it follows would assert
89
+ # equal per-unit consumption, which nothing here establishes.
90
+ "claude-opus-5-5": "claude-opus-5-5",
91
+ "claude-sonnet-5-5": "claude-sonnet-5-5",
92
+ "claude-haiku-5-5": "claude-haiku-5-5",
90
93
  }
91
94
 
92
95
  #: Whether a canonical family drains the general weekly quota, drains a
@@ -114,6 +117,9 @@ FAMILY_PARTICIPATION: dict[str, str] = {
114
117
  "claude-fable-5-1": "general",
115
118
  "claude-mythos-5": "general",
116
119
  "claude-mythos-5-1": "general",
120
+ "claude-opus-5-5": "general",
121
+ "claude-sonnet-5-5": "general",
122
+ "claude-haiku-5-5": "general",
117
123
  }
118
124
 
119
125
  #: Where each classification came from, so a later reader can re-test it
@@ -121,6 +127,12 @@ FAMILY_PARTICIPATION: dict[str, str] = {
121
127
  #: operator-supplied and are NOT derivable from this repository. No family is
122
128
  #: ever classified "unknown" on the strength of unfamiliarity with it: an
123
129
  #: unrecognized family is escalated to the operator instead.
130
+ _PROVENANCE_55: str = (
131
+ "operator-supplied in #978 (2026-10-18), confirmed by the 2026-10-20 "
132
+ "handoff: participates in the general weekly meter; modelled with the "
133
+ "selected coefficient era's shared token-class coefficients"
134
+ )
135
+
124
136
  FAMILY_PROVENANCE: dict[str, str] = {
125
137
  "claude-fable-5": (
126
138
  "operator-supplied 2026-08-28: drains a dedicated pool AND the "
@@ -143,6 +155,10 @@ FAMILY_PROVENANCE: dict[str, str] = {
143
155
  "general weekly meter on the same terms as claude-mythos-5; only "
144
156
  "the general draining is modelled"
145
157
  ),
158
+ # Participation is the operator's statement, never the API price card.
159
+ "claude-opus-5-5": _PROVENANCE_55,
160
+ "claude-sonnet-5-5": _PROVENANCE_55,
161
+ "claude-haiku-5-5": _PROVENANCE_55,
146
162
  }
147
163
 
148
164
  #: Eligibility fence parameters (section 5).
@@ -193,14 +209,70 @@ MIX_SUPPORT: dict[str, object] = {
193
209
  "token_class_max_relative_effect": 0.05,
194
210
  }
195
211
 
196
- #: Producer policy that changes which retained requests the fitted model
197
- #: represents. It is fingerprinted with the arithmetic because moving the era
198
- #: floor or admitting another billing class changes the fitted answer just as
199
- #: surely as editing a coefficient does.
200
- COEFFICIENT_SUPPORT: dict[str, str] = {
201
- "supportedCompositionFrom": "2026-07-25",
202
- "fastModeParticipation": "usage-credits-only-excluded",
203
- }
212
+ #: The fast-mode policy every validated era applies: fast-mode requests are
213
+ #: billed to usage credits only and never reach the weekly meter.
214
+ FAST_MODE_PARTICIPATION: str = "usage-credits-only-excluded"
215
+
216
+
217
+ @dataclasses.dataclass(frozen=True)
218
+ class CoefficientEra:
219
+ """One validated coefficient era: a half-open UTC date interval, the four
220
+ token-class weights fitted for it, its support policy and provenance.
221
+
222
+ `start` is inclusive and `end` exclusive, both at UTC midnight; an open
223
+ era has `end=None`. `weights` is a tuple of `(class, weight)` pairs in
224
+ `TOKEN_CLASSES` order, so the record stays immutable and hashable.
225
+ """
226
+
227
+ id: str
228
+ start: "dt.date"
229
+ end: "dt.date | None"
230
+ weights: tuple
231
+ fast_mode_participation: str
232
+ provenance: str
233
+
234
+ def weight_map(self) -> dict[str, float]:
235
+ """The weights as a fresh `{class: weight}` dict the caller may own."""
236
+ return {name: float(weight) for name, weight in self.weights}
237
+
238
+
239
+ #: The ordered, immutable table of validated coefficient eras (spec 4.2).
240
+ #: Exactly one era covers any instant from 2026-07-25 on; earlier history is
241
+ #: covered by none and stays unvalidated. There is deliberately no mutable
242
+ #: "current weights" global: every weighting path asks this table.
243
+ COEFFICIENT_ERAS: tuple = (
244
+ CoefficientEra(
245
+ id="opus-5",
246
+ start=dt.date(2026, 7, 25),
247
+ end=dt.date(2026, 9, 22),
248
+ weights=(("fresh", 1.0), ("output", 4.73), ("cache_1h", 1.03),
249
+ ("cache_read", 0.0031)),
250
+ fast_mode_participation=FAST_MODE_PARTICIPATION,
251
+ provenance='The Opus 5 calibration, docs/quota-model.md "The finding"',
252
+ ),
253
+ CoefficientEra(
254
+ id="opus-5-5",
255
+ start=dt.date(2026, 9, 22),
256
+ end=None,
257
+ weights=(("fresh", 1.0), ("output", 0.64), ("cache_1h", 1.0),
258
+ ("cache_read", 0.0148)),
259
+ fast_mode_participation=FAST_MODE_PARTICIPATION,
260
+ provenance=("The 2026-10-18 Opus 5.5 refit; output weakly identified "
261
+ "(95% CI 0.23\u20131.13), cache read sharp "
262
+ "(0.0128\u20130.0168)"),
263
+ ),
264
+ )
265
+
266
+
267
+ def _era_payload(era: CoefficientEra) -> dict:
268
+ return {
269
+ "id": era.id,
270
+ "from": era.start.isoformat(),
271
+ "until": None if era.end is None else era.end.isoformat(),
272
+ "tokenClassWeights": era.weight_map(),
273
+ "fastModeParticipation": era.fast_mode_participation,
274
+ "provenance": era.provenance,
275
+ }
204
276
 
205
277
  #: The reading-to-interval rule of section 4. Bumped when that rule changes.
206
278
  DISPLAY_RULE_REVISION: int = 1
@@ -229,8 +301,8 @@ DEDICATED_POOL_SCOPE_NOTE: str = (
229
301
  "only general-quota draining is modelled"
230
302
  )
231
303
 
232
- QUOTA_MODEL_ALGORITHM_REVISION: int = 3
233
- QUOTA_MODEL_VERIFIED_AT: str = "2026-08-29"
304
+ QUOTA_MODEL_ALGORITHM_REVISION: int = 4
305
+ QUOTA_MODEL_VERIFIED_AT: str = "2026-10-20"
234
306
 
235
307
 
236
308
  def constants_payload() -> dict:
@@ -244,7 +316,6 @@ def constants_payload() -> dict:
244
316
  "algorithmRevision": QUOTA_MODEL_ALGORITHM_REVISION,
245
317
  "verifiedAt": QUOTA_MODEL_VERIFIED_AT,
246
318
  "displayRuleRevision": DISPLAY_RULE_REVISION,
247
- "tokenClassWeights": dict(TOKEN_CLASS_WEIGHTS),
248
319
  "familyAliases": dict(FAMILY_ALIASES),
249
320
  "familyParticipation": dict(FAMILY_PARTICIPATION),
250
321
  "familyProvenance": dict(FAMILY_PROVENANCE),
@@ -252,7 +323,7 @@ def constants_payload() -> dict:
252
323
  "detector": dict(DETECTOR),
253
324
  "trust": dict(TRUST),
254
325
  "mixSupport": dict(MIX_SUPPORT),
255
- "coefficientSupport": dict(COEFFICIENT_SUPPORT),
326
+ "coefficientEras": [_era_payload(era) for era in COEFFICIENT_ERAS],
256
327
  }
257
328
 
258
329
 
@@ -268,7 +339,7 @@ def constants_fingerprint() -> str:
268
339
  #: constant above without re-pinning this line is caught rather than silently
269
340
  #: invalidating every persisted calibration.
270
341
  QUOTA_MODEL_CONSTANTS_FINGERPRINT: str = (
271
- "0cd932a7f8caa5d9bec7010ed5d800935e5c78332ae060c1142650943512a24a"
342
+ "5835b430978b2fc556c577d44c9e62d5d7807e62533b32819ed63d37e3af671a"
272
343
  )
273
344
 
274
345
 
@@ -735,12 +806,136 @@ def token_class_units(e: EntryRecord) -> dict[str, float] | None:
735
806
  }
736
807
 
737
808
 
738
- def weighted_units(e: EntryRecord) -> float | None:
739
- """Weighted quota units for one entry, or None when the split is unknown."""
809
+ # ---------------------------------------------------------------------------
810
+ # Coefficient eras (#978, spec section 4.2).
811
+ #
812
+ # One covering era per instant, selected by the instant alone and never by
813
+ # the model name. The raw decomposition above is era-independent; everything
814
+ # that turns raw class quantities into units goes through `class_units`.
815
+ # ---------------------------------------------------------------------------
816
+ #: `weigh_entry`'s cause when no validated era covers the entry, or the
817
+ #: explicitly requested era does not. A member of `EVIDENCE_CODES`.
818
+ ERA_UNAVAILABLE: str = "unvalidated-coefficient-era"
819
+
820
+ #: `weigh_entry`'s cause when `token_class_units` cannot split the entry.
821
+ SPLIT_UNKNOWN: str = "token-split-unknown"
822
+
823
+
824
+ class CoefficientEraMismatch(ValueError):
825
+ """A population-level operation was handed an instant outside its era.
826
+
827
+ Units from two eras are never added together or divided by one budget
828
+ (spec section 4.2, invariant 5), so the refusal is loud rather than a
829
+ silent reweighting.
830
+ """
831
+
832
+
833
+ def _utc_midnight(date) -> "dt.datetime":
834
+ return dt.datetime.combine(date, dt.time(0, 0), tzinfo=dt.timezone.utc)
835
+
836
+
837
+ def era_bounds(era: CoefficientEra) -> tuple:
838
+ """`(start, end)` as aware UTC-midnight instants; `end` None when open."""
839
+ return (_utc_midnight(era.start),
840
+ None if era.end is None else _utc_midnight(era.end))
841
+
842
+
843
+ def era_contains(era: CoefficientEra, at: "dt.datetime") -> bool:
844
+ """`start <= at < end`, the half-open interval, for an aware instant."""
845
+ require_aware(at, "at")
846
+ start, end = era_bounds(era)
847
+ return at >= start and (end is None or at < end)
848
+
849
+
850
+ def era_for_instant(at: "dt.datetime") -> "CoefficientEra | None":
851
+ """The one validated era covering `at`, or None before 2026-07-25.
852
+
853
+ Raises on a naive datetime: a host-local reading would move the boundary
854
+ by the process's UTC offset.
855
+ """
856
+ require_aware(at, "at")
857
+ for era in COEFFICIENT_ERAS:
858
+ if era_contains(era, at):
859
+ return era
860
+ return None
861
+
862
+
863
+ def era_by_id(era_id: object) -> "CoefficientEra | None":
864
+ """The era whose identifier is exactly `era_id`, or None.
865
+
866
+ Anything that is not a known identifier string — None, a number, an
867
+ unknown name — is None, which a stored-regime reader treats as
868
+ malformed.
869
+ """
870
+ if not isinstance(era_id, str):
871
+ return None
872
+ for era in COEFFICIENT_ERAS:
873
+ if era.id == era_id:
874
+ return era
875
+ return None
876
+
877
+
878
+ def class_units(classes, era: CoefficientEra) -> float:
879
+ """Raw class quantities weighted by `era`'s coefficients.
880
+
881
+ The ONLY place in this module a quantity is multiplied by a weight, so
882
+ every aggregation path weights with the era it was given and none can keep
883
+ a multiplication of its own.
884
+ """
885
+ weights = era.weight_map()
886
+ return sum(float(classes.get(name, 0.0)) * weights[name]
887
+ for name in TOKEN_CLASSES)
888
+
889
+
890
+ class EntryWeighting(typing.NamedTuple):
891
+ """One entry's weighted units, or None with the typed reason why."""
892
+
893
+ units: "float | None"
894
+ cause: "str | None"
895
+
896
+
897
+ def weigh_entry(e: EntryRecord,
898
+ era: "CoefficientEra | None" = None) -> EntryWeighting:
899
+ """Weighted units for one entry under its covering era.
900
+
901
+ With `era=None` the era is the one covering the entry's instant. An
902
+ instant no validated era covers, or an explicit `era` that does not
903
+ contain it, is `ERA_UNAVAILABLE` — checked FIRST, so an uncovered entry is
904
+ never reported as a split problem. An unknown split is `SPLIT_UNKNOWN`.
905
+ """
906
+ covering = era_for_instant(e.at) if era is None else (
907
+ era if era_contains(era, e.at) else None)
908
+ if covering is None:
909
+ return EntryWeighting(None, ERA_UNAVAILABLE)
740
910
  classes = token_class_units(e)
741
911
  if classes is None:
742
- return None
743
- return sum(qty * TOKEN_CLASS_WEIGHTS[name] for name, qty in classes.items())
912
+ return EntryWeighting(None, SPLIT_UNKNOWN)
913
+ return EntryWeighting(class_units(classes, covering), None)
914
+
915
+
916
+ def weighted_units(e: EntryRecord,
917
+ era: "CoefficientEra | None" = None) -> float | None:
918
+ """Weighted quota units for one entry, or None when it cannot be weighted.
919
+
920
+ None covers both an unknown split and an instant outside every validated
921
+ era (or outside `era`); `weigh_entry` says which.
922
+ """
923
+ return weigh_entry(e, era).units
924
+
925
+
926
+ def _require_era(era) -> CoefficientEra:
927
+ if not isinstance(era, CoefficientEra):
928
+ raise TypeError(f"era must be a CoefficientEra, got {era!r}")
929
+ return era
930
+
931
+
932
+ def _require_in_era(era: CoefficientEra, instants, label: str) -> None:
933
+ """Raise `CoefficientEraMismatch` on the first instant outside `era`."""
934
+ for at in instants:
935
+ if not era_contains(era, at):
936
+ raise CoefficientEraMismatch(
937
+ f"{label} {at.isoformat()} lies outside coefficient era "
938
+ f"{era.id!r}")
744
939
 
745
940
 
746
941
  def integer_percent(value: float) -> int:
@@ -1055,8 +1250,8 @@ def _day_slices(segments, now):
1055
1250
  )
1056
1251
 
1057
1252
 
1058
- def build_daily_series(segments, entries, *, now,
1059
- newest_entry_at) -> list[DailyObservation]:
1253
+ def build_daily_series(segments, entries, *, now, newest_entry_at,
1254
+ era: CoefficientEra) -> list[DailyObservation]:
1060
1255
  """One observation per complete UTC date, in date order.
1061
1256
 
1062
1257
  Within one day and one segment the observation runs from the first to the
@@ -1082,12 +1277,21 @@ def build_daily_series(segments, entries, *, now,
1082
1277
  unfinished, so reporting it as `no-local-history` asserts something false
1083
1278
  and, because it always falls on or after any split date, withheld every
1084
1279
  verdict at exit 3. `in_progress_dates` reports it as a diagnostic instead.
1280
+
1281
+ `era` is the ONE coefficient era the whole series is weighted with
1282
+ (#978). Every entry and every segment reading must lie inside it, and a
1283
+ population that does not raises `CoefficientEraMismatch` rather than
1284
+ summing units from two eras.
1085
1285
  """
1086
1286
  require_aware(now, "now")
1087
1287
  if newest_entry_at is not None:
1088
1288
  require_aware(newest_entry_at, "newest_entry_at")
1089
1289
  for entry in entries:
1090
1290
  require_aware(entry.at, "entry.at")
1291
+ _require_era(era)
1292
+ _require_in_era(era, (e.at for e in entries), "entry.at")
1293
+ _require_in_era(era, (r.at for seg in segments for r in seg.rows),
1294
+ "snapshot.at")
1091
1295
  ordered = sorted(entries, key=lambda e: e.at)
1092
1296
  instants = [e.at for e in ordered]
1093
1297
 
@@ -1122,7 +1326,7 @@ def build_daily_series(segments, entries, *, now,
1122
1326
  # token count per class, which is what the composition support vector
1123
1327
  # is (section 34) — a coefficient-weighted share cannot carry the
1124
1328
  # materiality floor derived from those same coefficients.
1125
- raw = {name: 0.0 for name in TOKEN_CLASS_WEIGHTS}
1329
+ raw = {name: 0.0 for name in TOKEN_CLASSES}
1126
1330
  units = 0.0
1127
1331
  families: dict = {}
1128
1332
  split_unknown = False
@@ -1136,10 +1340,9 @@ def build_daily_series(segments, entries, *, now,
1136
1340
  if quantities is None:
1137
1341
  split_unknown = True
1138
1342
  continue
1139
- entry_units = 0.0
1140
1343
  for name, qty in quantities.items():
1141
1344
  raw[name] += qty
1142
- entry_units += qty * TOKEN_CLASS_WEIGHTS[name]
1345
+ entry_units = class_units(quantities, era)
1143
1346
  units += entry_units
1144
1347
  families[family] = families.get(family, 0.0) + entry_units
1145
1348
  raw_total = sum(raw.values())
@@ -1186,7 +1389,8 @@ def in_progress_dates(segments, *, now) -> tuple:
1186
1389
  if sl.kind == "in-progress"}))
1187
1390
 
1188
1391
 
1189
- def unattributed_units(segments, entries, *, now) -> dict:
1392
+ def unattributed_units(segments, entries, *, now,
1393
+ era: CoefficientEra) -> dict:
1190
1394
  """Weighted units and entry count on NO observation's token interval.
1191
1395
 
1192
1396
  Section 14 requires this diagnostic rather than a silent discard. An
@@ -1203,7 +1407,17 @@ def unattributed_units(segments, entries, *, now) -> dict:
1203
1407
  the general-quota entries whose token split is known, because that is the
1204
1408
  quantity the fit would have used; a dedicated-pool entry is reported as
1205
1409
  present and contributes nothing, exactly as it would inside an interval.
1410
+
1411
+ `era` is the one coefficient era the series is weighted with, and the
1412
+ same out-of-era refusal applies as in `build_daily_series`.
1206
1413
  """
1414
+ _require_era(era)
1415
+ entries = list(entries)
1416
+ for entry in entries:
1417
+ require_aware(entry.at, "entry.at")
1418
+ _require_in_era(era, (e.at for e in entries), "entry.at")
1419
+ _require_in_era(era, (r.at for seg in segments for r in seg.rows),
1420
+ "snapshot.at")
1207
1421
  windows = sorted((s.first_at, s.last_at)
1208
1422
  for s in _day_slices(segments, now)
1209
1423
  if s.kind == "attributed")
@@ -1218,12 +1432,90 @@ def unattributed_units(segments, entries, *, now) -> dict:
1218
1432
  count += 1
1219
1433
  if family_participation(normalize_family(entry.model)) != "general":
1220
1434
  continue
1221
- units = weighted_units(entry)
1435
+ units = weighted_units(entry, era)
1222
1436
  if units is not None:
1223
1437
  total += units
1224
1438
  return {"units": total, "entries": count}
1225
1439
 
1226
1440
 
1441
+ # ---------------------------------------------------------------------------
1442
+ # Correctly rounded logarithms and exponentials.
1443
+ #
1444
+ # `math.log`, `math.log1p` and `math.expm1` call the platform C library, and
1445
+ # C does not require those to be correctly rounded. glibc 2.39's `log1p` and
1446
+ # `expm1` are off by one ULP on inputs the eligibility fence reaches, which
1447
+ # moved quota fixture 12's `eligibilityFence` between Linux and macOS. These
1448
+ # compute in `decimal`, whose `ln` and `exp` are correctly rounded at the
1449
+ # context precision, from the float's exact value, and round once to a
1450
+ # double. At 80 significant digits that double rounding can differ from a
1451
+ # direct one only if the true value lies within 1e-80 of a midpoint between
1452
+ # two doubles, far below what any double input can produce. Each call uses
1453
+ # its own context, never the thread's, and the edge cases the decimal path
1454
+ # does not model are delegated to `math`, whose answers there are exact.
1455
+ # ---------------------------------------------------------------------------
1456
+ _CR_DIGITS = 80
1457
+ #: The exact sum of 1 and any double needs at most 1075 significant digits.
1458
+ _CR_EXACT = decimal.Context(prec=1200, Emin=-999999, Emax=999999,
1459
+ traps=[decimal.InvalidOperation])
1460
+ _CR_ONE = decimal.Decimal(1)
1461
+
1462
+
1463
+ def _cr_context(prec: int = _CR_DIGITS) -> decimal.Context:
1464
+ return decimal.Context(prec=prec, rounding=decimal.ROUND_HALF_EVEN,
1465
+ Emin=-999999, Emax=999999,
1466
+ traps=[decimal.InvalidOperation,
1467
+ decimal.DivisionByZero, decimal.Overflow])
1468
+
1469
+
1470
+ def correctly_rounded_log(x) -> float:
1471
+ """`math.log(x)` correctly rounded on every platform.
1472
+
1473
+ Zero, negatives, infinities and NaN go to `math.log`, so the domain error
1474
+ and the non-finite results are exactly the standard library's.
1475
+ """
1476
+ x = float(x)
1477
+ if not math.isfinite(x) or x <= 0.0:
1478
+ return math.log(x)
1479
+ return float(_cr_context().ln(decimal.Decimal(x)))
1480
+
1481
+
1482
+ def correctly_rounded_log1p(x) -> float:
1483
+ """`math.log1p(x)` correctly rounded on every platform.
1484
+
1485
+ `1 + x` is formed exactly, so a tiny `x` keeps every digit. Signed zeros,
1486
+ `x <= -1` (the domain error), infinities and NaN go to `math.log1p`.
1487
+ """
1488
+ x = float(x)
1489
+ if not math.isfinite(x) or x == 0.0 or x <= -1.0:
1490
+ return math.log1p(x)
1491
+ one_plus = _CR_EXACT.add(_CR_ONE, decimal.Decimal(x))
1492
+ return float(_cr_context().ln(one_plus))
1493
+
1494
+
1495
+ def correctly_rounded_expm1(x) -> float:
1496
+ """`math.expm1(x)` correctly rounded on every platform.
1497
+
1498
+ The working precision grows with `1/|x|`, so the subtraction of one keeps
1499
+ 80 significant digits however small `x` is. Below -64 the true value is
1500
+ within 1.6e-28 of -1, which rounds to exactly -1. A finite result too
1501
+ large for a double raises `OverflowError`, as `math.expm1` does. Signed
1502
+ zeros, infinities and NaN go to `math.expm1`.
1503
+ """
1504
+ x = float(x)
1505
+ if not math.isfinite(x) or x == 0.0:
1506
+ return math.expm1(x)
1507
+ if x < -64.0:
1508
+ return -1.0
1509
+ if x > 710.0:
1510
+ return math.expm1(x) # raises OverflowError
1511
+ d = decimal.Decimal(x)
1512
+ ctx = _cr_context(_CR_DIGITS + max(0, -d.adjusted()))
1513
+ result = float(ctx.subtract(ctx.exp(d), _CR_ONE))
1514
+ if math.isinf(result):
1515
+ raise OverflowError("math range error")
1516
+ return result
1517
+
1518
+
1227
1519
  # ---------------------------------------------------------------------------
1228
1520
  # Robust statistics, the eligibility fence, and composition support (§5, §15).
1229
1521
  # ---------------------------------------------------------------------------
@@ -1263,14 +1555,16 @@ def eligibility_fence(days) -> float | None:
1263
1555
  which carried between 0.8 and 1.2 million weighted units against a
1264
1556
  message claiming no local token history at all.
1265
1557
  """
1266
- xs = [math.log1p(u) for u in days if u is not None and u > 0.0]
1558
+ xs = [correctly_rounded_log1p(u)
1559
+ for u in days if u is not None and u > 0.0]
1267
1560
  if len(xs) < 2:
1268
1561
  return None
1269
1562
  centre = median(xs)
1270
1563
  spread = scaled_mad(xs, centre)
1271
1564
  if not math.isfinite(spread) or spread == 0.0:
1272
1565
  return None
1273
- return math.expm1(centre - ELIGIBILITY["fence_mads"] * spread)
1566
+ return correctly_rounded_expm1(
1567
+ centre - ELIGIBILITY["fence_mads"] * spread)
1274
1568
 
1275
1569
 
1276
1570
  def composition_centre(vectors) -> dict[str, float] | None:
@@ -1293,9 +1587,16 @@ def composition_centre(vectors) -> dict[str, float] | None:
1293
1587
 
1294
1588
 
1295
1589
  def tv_distance(p, centre) -> float:
1296
- """Total-variation distance, `0.5 * sum(|p_i - c_i|)`."""
1590
+ """Total-variation distance, `0.5 * sum(|p_i - c_i|)`.
1591
+
1592
+ `math.fsum`, not `sum`: the keys come from a set, whose iteration order
1593
+ follows PYTHONHASHSEED, and Python 3.11's float `sum()` is uncompensated,
1594
+ so a plain sum moved the published radius by an ULP from one process to
1595
+ the next. `fsum` is correctly rounded, so the result is the same in every
1596
+ order and on every supported interpreter.
1597
+ """
1297
1598
  keys = set(p) | set(centre)
1298
- return 0.5 * sum(abs(p.get(k, 0.0) - centre.get(k, 0.0)) for k in keys)
1599
+ return 0.5 * math.fsum(abs(p.get(k, 0.0) - centre.get(k, 0.0)) for k in keys)
1299
1600
 
1300
1601
 
1301
1602
  def support_radius(vectors, centre) -> float | None:
@@ -1317,7 +1618,7 @@ def support_radius(vectors, centre) -> float | None:
1317
1618
  return median(distances) + MIX_SUPPORT["fence_mads"] * spread
1318
1619
 
1319
1620
 
1320
- def token_class_floor(centre) -> float | None:
1621
+ def token_class_floor(centre, *, era: CoefficientEra) -> float | None:
1321
1622
  """Materiality floor for the token-class radius, at `centre`.
1322
1623
 
1323
1624
  Derived, not asserted. For raw share distributions
@@ -1325,19 +1626,22 @@ def token_class_floor(centre) -> float | None:
1325
1626
  movement of the weighted-unit total at
1326
1627
  `MIX_SUPPORT["token_class_max_relative_effect"]` bounds the admissible
1327
1628
  total-variation distance at `effect * mu / spread`, where `mu` is the
1328
- centre's own weighted value and `spread` is the coefficient range. At the
1329
- shipped coefficients the spread is 4.73 - 0.0031 = 4.7269, so a fresh-only
1330
- centre admits about 0.01058 — half the 10% detection-width gate and a
1331
- third of the 15% prediction-width gate.
1629
+ centre's own weighted value and `spread` is the coefficient range of the
1630
+ selected `era` (#978). Under `opus-5` the spread is 4.73 - 0.0031 =
1631
+ 4.7269, so a fresh-only centre admits about 0.01058 — half the 10%
1632
+ detection-width gate and a third of the 15% prediction-width gate. Under
1633
+ `opus-5-5` it is 1.0 - 0.0148 = 0.9852, and a fresh-only centre admits
1634
+ about 0.0507511.
1332
1635
 
1333
1636
  None when the centre is undefined, which is a mix finding in its own right
1334
1637
  and never reaches here.
1335
1638
  """
1639
+ _require_era(era)
1336
1640
  if centre is None:
1337
1641
  return None
1338
- mu = sum(float(centre.get(name, 0.0)) * weight
1339
- for name, weight in TOKEN_CLASS_WEIGHTS.items())
1340
- spread = max(TOKEN_CLASS_WEIGHTS.values()) - min(TOKEN_CLASS_WEIGHTS.values())
1642
+ weights = era.weight_map()
1643
+ mu = class_units(centre, era)
1644
+ spread = max(weights.values()) - min(weights.values())
1341
1645
  if spread <= 0.0 or not math.isfinite(mu) or mu <= 0.0:
1342
1646
  return None
1343
1647
  return float(MIX_SUPPORT["token_class_max_relative_effect"]) * mu / spread
@@ -1364,7 +1668,7 @@ def effective_radius(empirical, floor) -> float | None:
1364
1668
  return max(empirical, floor)
1365
1669
 
1366
1670
 
1367
- def aggregate_composition(entries) -> tuple | None:
1671
+ def aggregate_composition(entries, *, era: CoefficientEra) -> tuple | None:
1368
1672
  """One `(family_shares, class_shares)` pair over a set of entries.
1369
1673
 
1370
1674
  The forecast population is a set of entries rather than a set of days
@@ -1374,8 +1678,16 @@ def aggregate_composition(entries) -> tuple | None:
1374
1678
 
1375
1679
  None when no general-quota entry with a known token split contributes,
1376
1680
  because an empty population supports no comparison.
1681
+
1682
+ `era` is the one coefficient era the population is weighted with; an
1683
+ entry outside it raises `CoefficientEraMismatch` (#978).
1377
1684
  """
1378
- raw = {name: 0.0 for name in TOKEN_CLASS_WEIGHTS}
1685
+ _require_era(era)
1686
+ entries = list(entries)
1687
+ for entry in entries:
1688
+ require_aware(entry.at, "entry.at")
1689
+ _require_in_era(era, (e.at for e in entries), "entry.at")
1690
+ raw = {name: 0.0 for name in TOKEN_CLASSES}
1379
1691
  families: dict = {}
1380
1692
  for entry in entries:
1381
1693
  family = normalize_family(entry.model)
@@ -1384,10 +1696,9 @@ def aggregate_composition(entries) -> tuple | None:
1384
1696
  quantities = token_class_units(entry)
1385
1697
  if quantities is None:
1386
1698
  continue
1387
- units = 0.0
1388
1699
  for name, qty in quantities.items():
1389
1700
  raw[name] += qty
1390
- units += qty * TOKEN_CLASS_WEIGHTS[name]
1701
+ units = class_units(quantities, era)
1391
1702
  families[family] = families.get(family, 0.0) + units
1392
1703
  raw_total = sum(raw.values())
1393
1704
  unit_total = sum(families.values())
@@ -1473,7 +1784,9 @@ def jackknife_fit(days) -> tuple[float, Interval] | None:
1473
1784
  return None
1474
1785
  replicates.append((total_units - row.units) / rest_meter)
1475
1786
  mean = sum(replicates) / n
1476
- se = math.sqrt((n - 1) / n * sum((v - mean) ** 2 for v in replicates))
1787
+ # A product, not `** 2`, which is the C library's `pow`.
1788
+ se = math.sqrt((n - 1) / n * sum((v - mean) * (v - mean)
1789
+ for v in replicates))
1477
1790
  half = t_quantile_975(n - 1) * se
1478
1791
  return point, Interval(max(0.0, point - half), point + half)
1479
1792
 
@@ -1707,7 +2020,7 @@ def detect_change(series, *, override_split=None) -> DetectorResult:
1707
2020
  total = len(days)
1708
2021
  truncated = input_days - total
1709
2022
  scan_start = days[0].date if days else None
1710
- stats = [math.log(o.units / o.meter_delta) for o in days]
2023
+ stats = [correctly_rounded_log(o.units / o.meter_delta) for o in days]
1711
2024
  min_base = int(TRUST["min_detect_baseline_days"])
1712
2025
  min_watch = int(DETECTOR["min_watch_days"])
1713
2026
  fence_mads = DETECTOR["fence_mads"]
@@ -2160,6 +2473,7 @@ def _composition_provenance(*, confirmed, reference_days, decisive_days,
2160
2473
 
2161
2474
 
2162
2475
  def analyse(series, *, now, newest_at, forecast_population,
2476
+ era: CoefficientEra, current_week_withheld: "str | None" = None,
2163
2477
  fingerprint_matches=True, observed_percent=None,
2164
2478
  current_week_units=None, current_week_start=None,
2165
2479
  current_week_end=None, override_split=None, extra_statuses=(),
@@ -2199,7 +2513,16 @@ def analyse(series, *, now, newest_at, forecast_population,
2199
2513
  non-finite or negative value withholds the evidence that depends on it
2200
2514
  with a typed code, because a NaN propagates through the headroom
2201
2515
  arithmetic into a published interval instead of raising.
2516
+
2517
+ `era` is the ONE coefficient era the analysis is fitted in (#978): the
2518
+ support floor uses its weights and the forecast probe aggregates under
2519
+ it, and a forecast entry outside it raises `CoefficientEraMismatch`.
2520
+ `current_week_withheld`, when set, is an `EVIDENCE_CODES` member that
2521
+ withholds the current week's consumption, headroom and projection while
2522
+ leaving `fitted` untouched — the glue's rule for a subscription week that
2523
+ spans the era boundary, whose units must never be summed across eras.
2202
2524
  """
2525
+ _require_era(era)
2203
2526
  require_aware(now, "now")
2204
2527
  for label, value in (("newest_at", newest_at),
2205
2528
  ("current_week_start", current_week_start),
@@ -2209,6 +2532,8 @@ def analyse(series, *, now, newest_at, forecast_population,
2209
2532
  forecast_entries = list(forecast_population)
2210
2533
  for entry in forecast_entries:
2211
2534
  require_aware(entry.at, "forecast_entry.at")
2535
+ _require_in_era(era, (e.at for e in forecast_entries),
2536
+ "forecast_entry.at")
2212
2537
 
2213
2538
  rejected: list[str] = []
2214
2539
  if current_week_units is not None and not _usable_quantity(
@@ -2278,7 +2603,7 @@ def analyse(series, *, now, newest_at, forecast_population,
2278
2603
  family_radius = effective_radius(
2279
2604
  family_radius, float(MIX_SUPPORT["family_tv_floor"]))
2280
2605
  class_radius = effective_radius(
2281
- class_radius, token_class_floor(class_centre))
2606
+ class_radius, token_class_floor(class_centre, era=era))
2282
2607
 
2283
2608
  # Section 35: after a confirmed change only the entries at or after the
2284
2609
  # successor boundary belong to the current regime, and they are measured
@@ -2289,7 +2614,7 @@ def analyse(series, *, now, newest_at, forecast_population,
2289
2614
  if e.at.astimezone(dt.timezone.utc).date() >= detector.split_date]
2290
2615
  else:
2291
2616
  probed_entries = forecast_entries
2292
- forecast_shares = (aggregate_composition(probed_entries)
2617
+ forecast_shares = (aggregate_composition(probed_entries, era=era)
2293
2618
  if probed_entries else None)
2294
2619
 
2295
2620
  contributed = list(extra_statuses)
@@ -2431,6 +2756,13 @@ def analyse(series, *, now, newest_at, forecast_population,
2431
2756
  week_start=current_week_start,
2432
2757
  week_end=current_week_end,
2433
2758
  qualifications=published_qualifications)
2759
+ if current_week_withheld is not None:
2760
+ consumption = evidence_withheld(current_week_withheld, population,
2761
+ published_qualifications)
2762
+ headroom = evidence_withheld(current_week_withheld, population,
2763
+ published_qualifications)
2764
+ projection = evidence_withheld(current_week_withheld, population,
2765
+ published_qualifications)
2434
2766
 
2435
2767
  merged = dict(diagnostics or {})
2436
2768
  merged.update({