compactlab 0.2.0__py3-none-any.whl

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 (67) hide show
  1. compactlab/__init__.py +3 -0
  2. compactlab/adapters/__init__.py +2 -0
  3. compactlab/adapters/base.py +212 -0
  4. compactlab/adapters/cache.py +396 -0
  5. compactlab/adapters/claude_code.py +226 -0
  6. compactlab/adapters/codex.py +298 -0
  7. compactlab/adapters/dsh.py +287 -0
  8. compactlab/adapters/gemini_cli.py +259 -0
  9. compactlab/adapters/opencode.py +375 -0
  10. compactlab/apply/__init__.py +582 -0
  11. compactlab/cli/__init__.py +5 -0
  12. compactlab/cli/main.py +2436 -0
  13. compactlab/data/config_knobs.json +158 -0
  14. compactlab/data/harness_defaults.json +72 -0
  15. compactlab/data/harness_formats.json +300 -0
  16. compactlab/data/pricing.json +51 -0
  17. compactlab/engine/__init__.py +138 -0
  18. compactlab/engine/live.py +306 -0
  19. compactlab/engine/settings.py +175 -0
  20. compactlab/engine/watch.py +82 -0
  21. compactlab/eval/__init__.py +1 -0
  22. compactlab/eval/deep.py +390 -0
  23. compactlab/eval/executors.py +84 -0
  24. compactlab/eval/factcheck.py +75 -0
  25. compactlab/lens.py +80 -0
  26. compactlab/model/__init__.py +285 -0
  27. compactlab/pricing/__init__.py +211 -0
  28. compactlab/pricing/auto.py +118 -0
  29. compactlab/pricing/ids.py +148 -0
  30. compactlab/pricing/refresh.py +299 -0
  31. compactlab/publish.py +125 -0
  32. compactlab/py.typed +0 -0
  33. compactlab/recommend/__init__.py +201 -0
  34. compactlab/recommend/claude_code.py +172 -0
  35. compactlab/recommend/codex.py +104 -0
  36. compactlab/recommend/dsh.py +89 -0
  37. compactlab/recommend/gemini_cli.py +85 -0
  38. compactlab/recommend/opencode.py +117 -0
  39. compactlab/recommend/units.py +63 -0
  40. compactlab/report/__init__.py +3 -0
  41. compactlab/report/html.py +27 -0
  42. compactlab/report/template.html +1189 -0
  43. compactlab/service/__init__.py +1 -0
  44. compactlab/service/core.py +220 -0
  45. compactlab/service/http.py +133 -0
  46. compactlab/service/lock.py +92 -0
  47. compactlab/service/policy.py +258 -0
  48. compactlab/service/schedule.py +212 -0
  49. compactlab/share.py +553 -0
  50. compactlab/sim/__init__.py +1 -0
  51. compactlab/sim/baseline.py +214 -0
  52. compactlab/sim/calibrate.py +108 -0
  53. compactlab/sim/engine.py +1130 -0
  54. compactlab/sim/select.py +238 -0
  55. compactlab/sim/timing.py +134 -0
  56. compactlab/synth.py +416 -0
  57. compactlab/term/__init__.py +0 -0
  58. compactlab/term/style.py +134 -0
  59. compactlab/term/top.py +531 -0
  60. compactlab/term/views.py +598 -0
  61. compactlab/term/widgets.py +238 -0
  62. compactlab/verify.py +462 -0
  63. compactlab-0.2.0.dist-info/METADATA +243 -0
  64. compactlab-0.2.0.dist-info/RECORD +67 -0
  65. compactlab-0.2.0.dist-info/WHEEL +4 -0
  66. compactlab-0.2.0.dist-info/entry_points.txt +2 -0
  67. compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
compactlab/share.py ADDED
@@ -0,0 +1,553 @@
1
+ """Anonymous, reviewable sharing record: what compactlab estimates it saves, with nothing that identifies a person.
2
+
3
+ `build` turns a result into a small record of aggregates per (harness, model, role) group: the settings compared,
4
+ the estimated change versus the harness default (and versus the current setting) per day, and the quality markers
5
+ a researcher needs to weigh it (history length, where the time model came from, replay vs logged cost). It never
6
+ copies session ids, paths, timestamps, project names, curves or transcript text, and it writes numbers and fixed
7
+ vocabulary only. `validate` accepts exactly that shape and nothing else, so the same check runs on the user's
8
+ machine before they post and in CI on whatever arrives. `aggregate` summarises many records.
9
+
10
+ The savings are replay estimates at list prices (see docs/METHODOLOGY.md), not measured savings.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import math
17
+ import re
18
+ import statistics
19
+ from collections.abc import Callable, Iterable
20
+ from typing import Any
21
+
22
+ from . import __version__
23
+ from .adapters import adapter_names
24
+ from .pricing import PricingTable
25
+ from .sim.select import PROFILE_NAMES, compare
26
+
27
+ SCHEMA_V1 = "compactlab.share/1"
28
+ SCHEMA = "compactlab.share/2" # /2 adds the optional per-group `verification` block
29
+ SCHEMAS = (SCHEMA_V1, SCHEMA)
30
+ ISSUE_URL = "https://github.com/LemonCANDY42/compactlab/issues/new?template=share_estimates.yml"
31
+ ROLES = ("main", "subagent")
32
+ CHANGING = ("set", "change")
33
+ ACTIONS = (*CHANGING, "keep default", "keep current", "no action needed")
34
+ MODES = ("lite", "deep")
35
+ VERDICTS = ("too_early", "already", "untouched", "unclear", "consistent", "less", "more")
36
+ IN_EFFECT = ("yes", "no", "none seen", "n/a")
37
+ SLUG = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,47}$")
38
+ VERSION = re.compile(r"^\d+\.\d+\.\d+((a|b|rc)\d+)?(\.dev\d+)?$")
39
+ MAX_GROUPS = 32
40
+ MAX_RECORD_BYTES = 64_000
41
+ MAX_BODY_CHARS = 200_000
42
+ # Free text never reaches a record: every string is one of these words (or "other").
43
+ FLAGS = ("min_window_unreachable", "wait_cap_unreachable", "guardrail_applied", "recall_floor_not_met",
44
+ "below_quarter_window", "wait_over_cap", "deep_recall_below_floor") # fmt: skip
45
+ TIME_SOURCES = ("own", "pooled", "prior")
46
+ PENALTY_SOURCES = ("observed", "prior")
47
+
48
+
49
+ class ShareError(Exception):
50
+ pass
51
+
52
+
53
+ def _sig(x: float | None, digits: int = 3) -> float | None:
54
+ """Round to a few significant figures: enough for a statistic, too coarse to fingerprint a history."""
55
+ if x is None:
56
+ return None
57
+ if x == 0 or not math.isfinite(x):
58
+ return 0.0 if x == 0 else None
59
+ return round(x, digits - 1 - math.floor(math.log10(abs(x))))
60
+
61
+
62
+ def _metrics(c: dict[str, Any]) -> dict[str, Any]:
63
+ """One comparison (profile or current setting vs a reference) as per-day figures. Negative = saved."""
64
+ im = c["impact"]
65
+ return {
66
+ "usd_per_day": _sig(im["usd"]["per_day"]),
67
+ "cost_pct": _sig(c["d_cost_pct"] * 100),
68
+ "minutes_per_day": _sig(im["minutes"]["per_day"]),
69
+ "wait_minutes_per_day": _sig(im["wait_minutes"]["per_day"]),
70
+ "compactions_per_day": _sig(im["compactions"]["per_day"]),
71
+ "ref_compactions_per_day": _sig(im["ref_compactions"]["per_day"]),
72
+ "recall_delta": _sig(c["d_recall"]),
73
+ }
74
+
75
+
76
+ def _vocab(s: Any, allowed: tuple[str, ...]) -> str:
77
+ return s if s in allowed else "other"
78
+
79
+
80
+ def _ttl_source(s: str) -> str:
81
+ return "override" if s.startswith("--") else "logs" if s.startswith("logs") else "default"
82
+
83
+
84
+ def _price_source(s: str) -> str:
85
+ return next((k for k in ("bundled", "refreshed", "user") if s.startswith(k)), "other")
86
+
87
+
88
+ def _group(g: dict[str, Any], public_models: set[str]) -> dict[str, Any]:
89
+ days, active = g.get("days"), g.get("active_days")
90
+ cur, default = g.get("current"), g["default"]
91
+ tm, pen = g.get("time_model") or {}, g.get("penalty_params") or {}
92
+ hist = g.get("history") or {}
93
+ profiles = {}
94
+ for n in PROFILE_NAMES:
95
+ cm = g["comparison"][n]
96
+ profiles[n] = {
97
+ "threshold": int(cm["threshold"]),
98
+ "action": cm["action"],
99
+ "flags": [_vocab(f, FLAGS) for f in g["profiles"][n].get("flags", [])][:8],
100
+ "vs_default": _metrics(cm["vs_default"]),
101
+ "vs_current": _metrics(cm["vs_current"]) if cm.get("vs_current") else None,
102
+ }
103
+ key = g.get("price_key")
104
+ return {
105
+ "harness": g["harness"],
106
+ "model": key if key in public_models else "other", # a custom name could say who you are
107
+ "role": g["role"],
108
+ "sessions": int(_sig(g["n_sessions"], 2) or 0),
109
+ "turns": int(_sig(g["n_turns"], 2) or 0),
110
+ "days": _sig(days, 2),
111
+ "active_days": _sig(active, 2),
112
+ "observed_compactions": int(_sig(g["observed_compactions"], 2) or 0),
113
+ "window": int(g["max_window"]),
114
+ "default_threshold": int(default["threshold"]),
115
+ "current_threshold": int(cur["configured"]) if cur else None,
116
+ "cache_ttl_s": int(g["cache_ttl"]),
117
+ "cache_ttl_source": _ttl_source(g.get("cache_ttl_source", "")),
118
+ "price_source": _price_source(g.get("price_source", "")),
119
+ "turn_source": _vocab(tm.get("turn_source"), TIME_SOURCES),
120
+ "compact_source": _vocab(tm.get("compact_source"), TIME_SOURCES),
121
+ "penalty_source": _vocab(pen.get("source"), PENALTY_SOURCES),
122
+ "no_action_needed": bool(g["no_action_needed"]),
123
+ # replay of the historical behaviour over what the logs priced at list price: how far to trust the replay
124
+ "replay_over_logged": _sig(hist["cost"] / g["actual_cost"]) if hist and g.get("actual_cost") else None,
125
+ "current_vs_default": _metrics(compare(cur, default, days or 1.0, active)) if cur else None,
126
+ "profiles": profiles,
127
+ }
128
+
129
+
130
+ def _verification(v: dict[str, Any]) -> dict[str, Any]:
131
+ """One `verify` group as flat, rounded figures: what was predicted, what the logs showed, and how much data."""
132
+ o, p, r = v["observed"], v["predicted"], v.get("replay_after") or {}
133
+ iv = o["cost_pct_interval"] or [None, None]
134
+ return {
135
+ "old_threshold": v["old"], # None = the harness default
136
+ "new_threshold": int(v["new"]),
137
+ "before_sessions": int(_sig(v["before"]["sessions"], 2) or 0),
138
+ "after_sessions": int(_sig(v["after"]["sessions"], 2) or 0),
139
+ "before_active_days": v["before"]["active_days"],
140
+ "after_active_days": v["after"]["active_days"],
141
+ "verdict": v["verdict"],
142
+ "in_effect": v["in_effect"],
143
+ "observed_cost_pct": _sig(o["cost_pct"]),
144
+ "observed_cost_pct_low": _sig(iv[0]),
145
+ "observed_cost_pct_high": _sig(iv[1]),
146
+ "observed_compactions_per_kturn": _sig(o["compactions_per_kturn"]),
147
+ "predicted_cost_pct": _sig(p["cost_pct"]),
148
+ "predicted_compactions_per_kturn": _sig(p["compactions_per_kturn"]),
149
+ "replay_after_cost_pct": _sig(r.get("cost_pct")),
150
+ "replay_after_compactions_per_kturn": _sig(r.get("compactions_per_kturn")),
151
+ }
152
+
153
+
154
+ def build(
155
+ result: dict[str, Any], *, allow_demo: bool = False, verification: dict[str, Any] | None = None
156
+ ) -> dict[str, Any]:
157
+ """The shareable record for a saved result. Refuses synthetic demo data (it would pollute the pool).
158
+ `verification` is a `verify.verify` result; each of its groups is attached to the matching result group."""
159
+ if result.get("demo") and not allow_demo:
160
+ raise ShareError("this result is synthetic demo data; run compactlab simulate on your own history")
161
+ public = set(PricingTable.bundled()["models"])
162
+ pairs = [(_group(rg, public), rg) for rg in result["groups"]]
163
+ for g, rg in pairs:
164
+ g["verification"] = None
165
+ for v in (verification or {}).get("groups", []):
166
+ if v["verdict"] != "no_data" and (v["harness"], v["model"], v["role"]) == (
167
+ rg["harness"],
168
+ rg["model"],
169
+ rg["role"],
170
+ ):
171
+ g["verification"] = _verification(v)
172
+ # Two raw model names (say a dated and an undated id) can share one public name; a record holds one group
173
+ # per harness, model and role, so the one with the most turns stands for them.
174
+ best: dict[tuple[str, str, str], dict[str, Any]] = {}
175
+ for g, _ in pairs:
176
+ ident = (g["harness"], g["model"], g["role"])
177
+ if ident not in best or g["turns"] > best[ident]["turns"]:
178
+ best[ident] = g
179
+ groups = list(best.values())
180
+ if not groups:
181
+ raise ShareError("the result has no groups to share")
182
+ rec = {
183
+ "schema": SCHEMA,
184
+ "compactlab": __version__,
185
+ "estimated": True,
186
+ "mode": result.get("mode", "lite"),
187
+ "groups": groups,
188
+ }
189
+ bad = validate(rec)
190
+ if bad: # a bug here must never reach a public issue
191
+ raise ShareError("internal error, record not valid: " + "; ".join(bad[:3]))
192
+ return rec
193
+
194
+
195
+ # ---------- validation: an allow-list, so anything unexpected is refused, not scrubbed ----------
196
+
197
+ _Check = Callable[[Any], bool]
198
+
199
+
200
+ def _num(lo: float, hi: float, nullable: bool = False) -> _Check:
201
+ def ok(x: Any) -> bool:
202
+ if x is None:
203
+ return nullable
204
+ if isinstance(x, bool) or not isinstance(x, (int, float)):
205
+ return False
206
+ # compare before any float conversion: a 400-digit integer must be refused, not raise
207
+ return (isinstance(x, int) or math.isfinite(x)) and lo <= x <= hi
208
+
209
+ return ok
210
+
211
+
212
+ def _rounded(check: _Check, digits: int) -> _Check:
213
+ """`check`, and the value is already rounded to `digits` significant figures (as `build` writes it)."""
214
+ return lambda x: check(x) and (x is None or _sig(x, digits) == x)
215
+
216
+
217
+ def _int(lo: int, hi: int, nullable: bool = False) -> _Check:
218
+ return lambda x: (x is None and nullable) or (isinstance(x, int) and not isinstance(x, bool) and lo <= x <= hi)
219
+
220
+
221
+ def _enum(*vals: str) -> _Check:
222
+ return lambda x: isinstance(x, str) and x in vals
223
+
224
+
225
+ def _slug_ok(x: Any) -> bool:
226
+ return isinstance(x, str) and bool(SLUG.match(x))
227
+
228
+
229
+ def _bool(x: Any) -> bool:
230
+ return isinstance(x, bool)
231
+
232
+
233
+ def _any(_: Any) -> bool:
234
+ return True
235
+
236
+
237
+ _METRIC_FIELDS: dict[str, _Check] = {
238
+ "usd_per_day": _rounded(_num(-1e7, 1e7), 3),
239
+ "cost_pct": _rounded(_num(-1000, 1000), 3),
240
+ "minutes_per_day": _rounded(_num(-1e5, 1e5), 3),
241
+ "wait_minutes_per_day": _rounded(_num(-1e5, 1e5), 3),
242
+ "compactions_per_day": _rounded(_num(0, 1e5), 3),
243
+ "ref_compactions_per_day": _rounded(_num(0, 1e5), 3),
244
+ "recall_delta": _rounded(_num(-1, 1), 3),
245
+ }
246
+ _PROFILE_FIELDS: dict[str, _Check] = {
247
+ "threshold": _int(1_000, 100_000_000),
248
+ "action": _enum(*ACTIONS),
249
+ "flags": lambda x: isinstance(x, list) and len(x) <= 8 and all(f in (*FLAGS, "other") for f in x),
250
+ }
251
+
252
+
253
+ def _check_fields(path: str, obj: Any, spec: dict[str, _Check], out: list[str], optional: Iterable[str] = ()) -> None:
254
+ if not isinstance(obj, dict):
255
+ out.append(f"{path}: expected an object")
256
+ return
257
+ extra = sorted(set(obj) - set(spec))
258
+ if extra:
259
+ out.append(f"{path}: {len(extra)} unexpected field(s)") # never repeat what was submitted
260
+ for k, ok in spec.items():
261
+ if k not in obj:
262
+ if k not in optional:
263
+ out.append(f"{path}.{k}: missing")
264
+ elif not ok(obj[k]):
265
+ out.append(f"{path}.{k}: value not allowed")
266
+
267
+
268
+ def _issues(path: str, obj: Any, spec: dict[str, _Check]) -> list[str]:
269
+ out: list[str] = []
270
+ _check_fields(path, obj, spec, out)
271
+ return out
272
+
273
+
274
+ _PCT = _rounded(_num(-1000, 1000, nullable=True), 3)
275
+ _PER_KTURN = _rounded(_num(-1e5, 1e5, nullable=True), 3)
276
+ _VERIFY_FIELDS: dict[str, _Check] = {
277
+ "old_threshold": _int(1_000, 100_000_000, nullable=True),
278
+ "new_threshold": _int(1_000, 100_000_000),
279
+ "before_sessions": _rounded(_int(0, 10_000_000), 2),
280
+ "after_sessions": _rounded(_int(0, 10_000_000), 2),
281
+ "before_active_days": _int(0, 3650),
282
+ "after_active_days": _int(0, 3650),
283
+ "verdict": _enum(*VERDICTS),
284
+ "in_effect": _enum(*IN_EFFECT),
285
+ "observed_cost_pct": _PCT,
286
+ "observed_cost_pct_low": _PCT,
287
+ "observed_cost_pct_high": _PCT,
288
+ "observed_compactions_per_kturn": _PER_KTURN,
289
+ "predicted_cost_pct": _PCT,
290
+ "predicted_compactions_per_kturn": _PER_KTURN,
291
+ "replay_after_cost_pct": _PCT,
292
+ "replay_after_compactions_per_kturn": _PER_KTURN,
293
+ }
294
+ _GROUP_FIELDS: dict[str, _Check] = {
295
+ "harness": _enum(*adapter_names()),
296
+ "model": lambda x: _slug_ok(x) and (x == "other" or x in PricingTable.bundled()["models"]),
297
+ "role": _enum(*ROLES),
298
+ "sessions": _rounded(_int(1, 10_000_000), 2),
299
+ "turns": _rounded(_int(1, 1_000_000_000), 2),
300
+ "days": _rounded(_num(0, 3650), 2),
301
+ "active_days": _rounded(_num(0, 3650, nullable=True), 2),
302
+ "observed_compactions": _rounded(_int(0, 100_000_000), 2),
303
+ "window": _int(10_000, 100_000_000),
304
+ "default_threshold": _int(1_000, 100_000_000),
305
+ "current_threshold": _int(1_000, 100_000_000, nullable=True),
306
+ "cache_ttl_s": _int(0, 86_400),
307
+ "cache_ttl_source": _enum("default", "logs", "override"),
308
+ "price_source": _enum("bundled", "refreshed", "user", "other"),
309
+ "turn_source": _enum(*TIME_SOURCES, "other"),
310
+ "compact_source": _enum(*TIME_SOURCES, "other"),
311
+ "penalty_source": _enum(*PENALTY_SOURCES, "other"),
312
+ "no_action_needed": _bool,
313
+ "replay_over_logged": _rounded(_num(0, 1000, nullable=True), 3),
314
+ "current_vs_default": lambda x: x is None or isinstance(x, dict), # fields checked in validate()
315
+ "profiles": _any, # checked in validate()
316
+ "verification": lambda x: x is None or isinstance(x, dict), # /2 only; fields checked in validate()
317
+ }
318
+
319
+
320
+ def validate(rec: Any) -> list[str]:
321
+ """Problems with a record, empty if it is acceptable. Never echoes more than a short, cleaned key name."""
322
+ out: list[str] = []
323
+ if not isinstance(rec, dict):
324
+ return ["record: expected a JSON object"]
325
+ top: dict[str, _Check] = {
326
+ "schema": _enum(*SCHEMAS),
327
+ "compactlab": lambda x: isinstance(x, str) and bool(VERSION.match(x)),
328
+ "estimated": lambda x: x is True,
329
+ "mode": _enum(*MODES),
330
+ "groups": lambda x: isinstance(x, list) and 1 <= len(x) <= MAX_GROUPS,
331
+ }
332
+ _check_fields("record", rec, top, out)
333
+ groups = rec.get("groups")
334
+ if not isinstance(groups, list):
335
+ return out
336
+ seen: set[tuple[Any, Any, Any]] = set()
337
+ for i, g in enumerate(groups[:MAX_GROUPS]):
338
+ p = f"groups[{i}]"
339
+ if isinstance(g, dict):
340
+ ident = (g.get("harness"), g.get("model"), g.get("role"))
341
+ if all(isinstance(x, str) for x in ident): # never hash an unvetted object; wrong types are reported below
342
+ if ident in seen:
343
+ out.append(f"{p}: the same harness, model and role appears twice")
344
+ seen.add(ident)
345
+ _check_fields(p, g, _GROUP_FIELDS, out, optional=("verification",))
346
+ if not isinstance(g, dict):
347
+ continue
348
+ if isinstance(g.get("verification"), dict):
349
+ if rec.get("schema") == SCHEMA_V1:
350
+ out.append(f"{p}.verification: not part of schema 1")
351
+ out += _issues(f"{p}.verification", g["verification"], _VERIFY_FIELDS)
352
+ if isinstance(g.get("current_vs_default"), dict):
353
+ out += _issues(f"{p}.current_vs_default", g["current_vs_default"], _METRIC_FIELDS)
354
+ profs = g.get("profiles")
355
+ if not isinstance(profs, dict) or set(profs) != set(PROFILE_NAMES):
356
+ out.append(f"{p}.profiles: expected exactly {', '.join(PROFILE_NAMES)}")
357
+ continue
358
+ for n, pr in profs.items():
359
+ pp = f"{p}.profiles.{n}"
360
+ spec = {**_PROFILE_FIELDS, "vs_default": _any, "vs_current": _any}
361
+ _check_fields(pp, pr, spec, out)
362
+ if isinstance(pr, dict):
363
+ out += _issues(f"{pp}.vs_default", pr.get("vs_default"), _METRIC_FIELDS)
364
+ if pr.get("vs_current") is not None:
365
+ out += _issues(f"{pp}.vs_current", pr["vs_current"], _METRIC_FIELDS)
366
+ if len(json.dumps(rec)) > MAX_RECORD_BYTES:
367
+ out.append("record: too large")
368
+ return out
369
+
370
+
371
+ # ---------- reading records back ----------
372
+
373
+ _FENCE = re.compile(r"```(?:json)?\s*\n(.*?)\n```", re.S)
374
+
375
+
376
+ def _no_dupes(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
377
+ out: dict[str, Any] = {}
378
+ for k, v in pairs:
379
+ if k in out:
380
+ raise ValueError("duplicate key")
381
+ out[k] = v
382
+ return out
383
+
384
+
385
+ def loads(text: str) -> Any:
386
+ """Strict JSON: bounded size, and a field that appears twice is an error (the first value would hide)."""
387
+ if len(text) > MAX_BODY_CHARS:
388
+ raise ShareError("the record is too large")
389
+ try:
390
+ return json.loads(text, object_pairs_hook=_no_dupes)
391
+ except (ValueError, RecursionError) as e:
392
+ raise ShareError("not valid JSON, or a field appears twice") from e
393
+
394
+
395
+ def parse_issue_body(body: str) -> Any:
396
+ """The JSON record in a GitHub issue-form body (the textarea arrives in a fenced block), or raise ShareError."""
397
+ body = body or ""
398
+ if len(body) > MAX_BODY_CHARS:
399
+ raise ShareError("the record is too large")
400
+ err: ShareError | None = None
401
+ for m in _FENCE.finditer(body):
402
+ try:
403
+ return loads(m.group(1))
404
+ except ShareError as e:
405
+ err = e
406
+ try:
407
+ return loads(body)
408
+ except ShareError:
409
+ msg = "no JSON record found; paste the whole content of the file compactlab share wrote"
410
+ raise err or ShareError(msg) from None
411
+
412
+
413
+ # ---------- aggregation ----------
414
+
415
+
416
+ def _median(xs: list[float]) -> float | None:
417
+ return _sig(statistics.median(xs)) if xs else None
418
+
419
+
420
+ def aggregate(records: Iterable[dict[str, Any]]) -> dict[str, Any]:
421
+ """Medians per (harness, model, role) of the estimated change vs the default, over valid records only."""
422
+ cells: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
423
+ n = 0
424
+ for rec in records:
425
+ if validate(rec):
426
+ continue
427
+ n += 1
428
+ for g in rec["groups"]:
429
+ cells.setdefault((g["harness"], g["model"], g["role"]), []).append(g)
430
+ rows = []
431
+ for (h, m, r), gs in sorted(cells.items()):
432
+ act = gs # a group with nothing to change saves nothing: it stays in the medians as zero
433
+ row: dict[str, Any] = {
434
+ "harness": h,
435
+ "model": m,
436
+ "role": r,
437
+ "groups": len(gs),
438
+ "no_action_needed": sum(g["no_action_needed"] for g in gs),
439
+ "median_days": _median([g["days"] for g in gs]),
440
+ "median_replay_over_logged": _median([g["replay_over_logged"] for g in gs if g["replay_over_logged"]]),
441
+ "profiles": {},
442
+ }
443
+ for p in PROFILE_NAMES:
444
+ # "keep default" means the user changes nothing: that group saves nothing, whatever the profile's pick said
445
+ vs = [
446
+ g["profiles"][p]["vs_default"]
447
+ if g["profiles"][p]["action"] in CHANGING and not g["no_action_needed"]
448
+ else dict.fromkeys(_METRIC_FIELDS, 0.0)
449
+ for g in act
450
+ ]
451
+ row["profiles"][p] = {
452
+ "median_cost_pct": _median([v["cost_pct"] for v in vs]),
453
+ "median_usd_per_day": _median([v["usd_per_day"] for v in vs]),
454
+ "median_minutes_per_day": _median([v["minutes_per_day"] for v in vs]),
455
+ "median_threshold": _median(
456
+ [g["profiles"][p]["threshold"] for g in act if g["profiles"][p]["action"] in CHANGING]
457
+ ),
458
+ "share_changing": _sig(sum(g["profiles"][p]["action"] in CHANGING for g in act) / len(act))
459
+ if act
460
+ else None,
461
+ }
462
+ cur = [g["current_vs_default"] for g in act if g["current_vs_default"]]
463
+ row["current_vs_default"] = {
464
+ "groups": len(cur),
465
+ "median_cost_pct": _median([c["cost_pct"] for c in cur]),
466
+ "median_usd_per_day": _median([c["usd_per_day"] for c in cur]),
467
+ "median_minutes_per_day": _median([c["minutes_per_day"] for c in cur]),
468
+ }
469
+ ver = [
470
+ v
471
+ for g in gs
472
+ if (v := g.get("verification"))
473
+ and v["verdict"] in ("consistent", "less", "more")
474
+ and v["observed_cost_pct"] is not None
475
+ and v["predicted_cost_pct"] is not None
476
+ ]
477
+ row["verification"] = {
478
+ "groups": len(ver),
479
+ "consistent": sum(v["verdict"] == "consistent" for v in ver),
480
+ "not_in_effect": sum(v["in_effect"] == "no" for v in ver),
481
+ "median_observed_cost_pct": _median([v["observed_cost_pct"] for v in ver]),
482
+ "median_predicted_cost_pct": _median([v["predicted_cost_pct"] for v in ver]),
483
+ # observed minus predicted, in percentage points: positive = saved less than the replay said
484
+ "median_error_pts": _median([v["observed_cost_pct"] - v["predicted_cost_pct"] for v in ver]),
485
+ }
486
+ rows.append(row)
487
+ return {"records": n, "cells": rows}
488
+
489
+
490
+ def aggregate_text(agg: dict[str, Any], profile: str = "balanced") -> str:
491
+ lines = [
492
+ f"{agg['records']} valid record(s); medians of the estimated change vs the harness default "
493
+ f"(replay estimate, list prices; negative = saved)",
494
+ f"{'harness':12} {'model':20} {'role':9} {'n':>3} {'thr':>6} {'cost%':>7} {'$/day':>7} {'min/day':>8}"
495
+ f" {'cur cost%':>10} {'replay/logged':>14}",
496
+ ]
497
+
498
+ def f(x: float | None, spec: str) -> str:
499
+ return "-" if x is None else format(x, spec)
500
+
501
+ for r in agg["cells"]:
502
+ p, c = r["profiles"][profile], r["current_vs_default"]
503
+ thr = f(p["median_threshold"] and p["median_threshold"] / 1000, ".0f")
504
+ thr = thr + "k" if thr != "-" else thr
505
+ lines.append(
506
+ f"{r['harness']:12} {r['model']:20} {r['role']:9} {r['groups']:>3} {thr:>6}"
507
+ f" {f(p['median_cost_pct'], '+.1f'):>7} {f(p['median_usd_per_day'], '+.2f'):>7}"
508
+ f" {f(p['median_minutes_per_day'], '+.1f'):>8} {f(c['median_cost_pct'], '+.1f'):>10}"
509
+ f" {f(r['median_replay_over_logged'], '.2f'):>14}"
510
+ )
511
+ checked = [r for r in agg["cells"] if r["verification"]["groups"]]
512
+ if checked:
513
+ lines += [
514
+ "",
515
+ "checked against the logs after the change (cost per 1k turns; error = observed - predicted, points):",
516
+ f"{'harness':12} {'model':20} {'role':9} {'n':>3} {'observed%':>10} {'predicted%':>11} {'error pts':>10}"
517
+ f" {'consistent':>11} {'not applied':>12}",
518
+ ]
519
+ for r in checked:
520
+ v = r["verification"]
521
+ lines.append(
522
+ f"{r['harness']:12} {r['model']:20} {r['role']:9} {v['groups']:>3}"
523
+ f" {f(v['median_observed_cost_pct'], '+.1f'):>10} {f(v['median_predicted_cost_pct'], '+.1f'):>11}"
524
+ f" {f(v['median_error_pts'], '+.1f'):>10} {v['consistent']:>11} {v['not_in_effect']:>12}"
525
+ )
526
+ return "\n".join(lines)
527
+
528
+
529
+ def preview(rec: dict[str, Any]) -> str:
530
+ """A few lines a person can read before posting: what is in the record and what each group estimates."""
531
+ out = [f"{len(rec['groups'])} group(s), compactlab {rec['compactlab']}, {rec['mode']} mode"]
532
+ for g in rec["groups"]:
533
+ b = g["profiles"]["balanced"]
534
+ v = b["vs_default"]
535
+ if g["no_action_needed"]:
536
+ what = "no action needed (the default never compacts here)"
537
+ elif b["action"] == "keep current":
538
+ what = f"keep current (balanced {b['threshold'] // 1000}k would not beat it by more than the tolerance)"
539
+ elif b["action"] not in CHANGING:
540
+ what = f"keep default (balanced {b['threshold'] // 1000}k would not beat it)"
541
+ else:
542
+ what = (
543
+ f"balanced {b['threshold'] // 1000}k: {v['cost_pct']:+.1f}% cost, "
544
+ f"{v['minutes_per_day']:+.1f} min/day wall-clock vs default"
545
+ )
546
+ out.append(f" {g['harness']} · {g['model']} · {g['role']} · {g['sessions']} sessions: {what}")
547
+ if x := g.get("verification"):
548
+ pct = lambda v: "-" if v is None else f"{v:+.1f}%" # noqa: E731
549
+ out.append(
550
+ f" checked after the change ({x['verdict']}, setting in effect: {x['in_effect']}): "
551
+ f"cost {pct(x['observed_cost_pct'])} observed vs {pct(x['predicted_cost_pct'])} predicted"
552
+ )
553
+ return "\n".join(out)
@@ -0,0 +1 @@
1
+ """Replay simulation, penalty calibration and threshold selection."""