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.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
compactlab/sim/engine.py
ADDED
|
@@ -0,0 +1,1130 @@
|
|
|
1
|
+
"""Replay simulator: cost / penalty / recall for each auto-compact threshold."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import bisect
|
|
6
|
+
import dataclasses
|
|
7
|
+
import math
|
|
8
|
+
import statistics
|
|
9
|
+
import time
|
|
10
|
+
from collections import Counter, defaultdict
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ..model import Session, Turn, is_auto, is_threshold
|
|
15
|
+
from ..pricing import Price, PricingTable
|
|
16
|
+
from ..pricing.ids import family as model_family
|
|
17
|
+
from ..pricing.ids import parse as parse_model
|
|
18
|
+
from .baseline import default_note_zh, default_threshold, effective_max
|
|
19
|
+
from .calibrate import PenaltyParams, calibrate, rediscovery_step
|
|
20
|
+
from .select import (
|
|
21
|
+
DEFAULT_PROFILE,
|
|
22
|
+
PROFILE_NAMES,
|
|
23
|
+
PROFILES,
|
|
24
|
+
WAIT_CAP_MIN_PER_DAY,
|
|
25
|
+
InfeasibleCap,
|
|
26
|
+
compare,
|
|
27
|
+
pareto,
|
|
28
|
+
point,
|
|
29
|
+
score,
|
|
30
|
+
select_all,
|
|
31
|
+
)
|
|
32
|
+
from .timing import TimeModel, fit
|
|
33
|
+
|
|
34
|
+
SESSIONS_SHOWN = 30 # per group in the report's session picker (keep in step with report/template.html sessList)
|
|
35
|
+
DEFAULT_ROT = [(0, 1.0), (100_000, 0.98), (200_000, 0.95), (400_000, 0.90), (600_000, 0.84), (1_000_000, 0.75)]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Claude Code idle compaction: a long conversation left idle on the one-hour cache is summarized while that cache is
|
|
39
|
+
# still warm (about 55 min in; 54.5-62 min in the maintainer's logs) and the summary is applied when the user returns.
|
|
40
|
+
IDLE_MIN_TOKENS = 200_000 # documented default of CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS (values under 100k count as 100k)
|
|
41
|
+
IDLE_AFTER_S = 55 * 60
|
|
42
|
+
IDLE_TTL_S = 3600 # only on the one-hour cache
|
|
43
|
+
IDLE_MIN_OBSERVED = 5
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class SimOptions:
|
|
48
|
+
grid_start: int = 100_000
|
|
49
|
+
grid_stop: int | None = None # None -> model max window
|
|
50
|
+
grid_step: int = 25_000
|
|
51
|
+
ttl_seconds: int | None = None # None -> pricing default
|
|
52
|
+
summary_tokens: int | None = None # None -> observed median or 12k
|
|
53
|
+
base_tokens: int | None = None # None -> observed median first-turn ctx or 35k
|
|
54
|
+
recall_floor: float = 0.90
|
|
55
|
+
tolerance: float = 0.02
|
|
56
|
+
range_tolerance: float = 0.05
|
|
57
|
+
retention: float = 0.90 # fraction of facts kept right after a compaction (assumed)
|
|
58
|
+
retention_half_turns: float = 15.0 # recovery time scale (assumed)
|
|
59
|
+
rot_table: list[tuple[int, float]] = field(default_factory=lambda: list(DEFAULT_ROT))
|
|
60
|
+
penalty: PenaltyParams | None = None # None -> calibrate
|
|
61
|
+
profile: str = DEFAULT_PROFILE # "cost" | "balanced" | "time" (see sim.select.PROFILES)
|
|
62
|
+
value_of_time: float | None = None # USD/h; overrides the selected profile's value of time
|
|
63
|
+
wait_cap_min_per_day: float = WAIT_CAP_MIN_PER_DAY # guardrail on added compaction wait vs default
|
|
64
|
+
max_threshold: int | None = None # never recommend above this (user cap)
|
|
65
|
+
# Claude Code idle compaction (`idleCompaction`): None -> on (the harness default) unless config says otherwise
|
|
66
|
+
idle_compaction: bool | None = None
|
|
67
|
+
idle_min_tokens: int = IDLE_MIN_TOKENS # CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS
|
|
68
|
+
# CLAUDE_CODE_MAX_CONTEXT_TOKENS: the window Claude Code uses for model IDs it does not recognize (else 200K)
|
|
69
|
+
claude_max_context: int | None = None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class Trace:
|
|
74
|
+
g: list[int] # tokens added to context this turn
|
|
75
|
+
o: list[int] # output tokens this turn
|
|
76
|
+
gap: list[float] # idle seconds before this turn
|
|
77
|
+
boundaries: set[int]
|
|
78
|
+
manual: dict[int, int] = field(default_factory=dict) # turn after a hand-typed /compact -> context it was typed at
|
|
79
|
+
models: list[str] | None = None # per-turn model when the session switched models (else the group's price)
|
|
80
|
+
# turn -> did an idle compaction come before it, for each turn the log shows was eligible (away long enough with a
|
|
81
|
+
# large enough context). Whether one fires depends on the app running and the machine awake, not on the context
|
|
82
|
+
# size, so a replay keeps the logged outcome; other gaps fire at the group's observed rate.
|
|
83
|
+
idle_obs: dict[int, bool] = field(default_factory=dict)
|
|
84
|
+
tail_gap: float = 0.0 # seconds from the last turn to the end of the data: a session left idle, never resumed
|
|
85
|
+
seed: int = 0 # for the rate draw on gaps the log says nothing about
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# A replay keeps a hand-typed /compact only while the replayed context is still near the size it was typed at: if a
|
|
89
|
+
# lower threshold already shrank the context, the user would not have needed to.
|
|
90
|
+
MANUAL_KEEP = 0.7
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def make_trace(
|
|
94
|
+
s: Session,
|
|
95
|
+
base: int,
|
|
96
|
+
data_end: float | None = None,
|
|
97
|
+
idle_min: int = IDLE_MIN_TOKENS,
|
|
98
|
+
idle_after: float = IDLE_AFTER_S,
|
|
99
|
+
idle_since: float | None = None,
|
|
100
|
+
) -> Trace:
|
|
101
|
+
g, o, gap = [], [], []
|
|
102
|
+
bset = {c.turn_index for c in s.compactions}
|
|
103
|
+
idle_at = {c.turn_index for c in s.compactions if c.idle}
|
|
104
|
+
prev = base
|
|
105
|
+
prev_ts = None
|
|
106
|
+
for i, t in enumerate(s.turns):
|
|
107
|
+
g.append(0 if i in bset else max(t.ctx - prev, 0))
|
|
108
|
+
o.append(t.output)
|
|
109
|
+
gap.append(max(t.ts - prev_ts, 0.0) if (t.ts and prev_ts) else 0.0)
|
|
110
|
+
prev, prev_ts = t.ctx, t.ts or prev_ts
|
|
111
|
+
models = [t.model for t in s.turns]
|
|
112
|
+
manual = {
|
|
113
|
+
c.turn_index: c.pre_tokens for c in s.compactions if c.trigger == "manual" and c.pre_tokens and c.turn_index
|
|
114
|
+
}
|
|
115
|
+
turns = s.turns
|
|
116
|
+
idle_obs = idle_observations(s, idle_min, idle_after, idle_since, gap, idle_at)
|
|
117
|
+
last_ts = turns[-1].ts if turns else None
|
|
118
|
+
tail = max(data_end - last_ts, 0.0) if (data_end and last_ts) else 0.0
|
|
119
|
+
seed = int.from_bytes(s.id.encode()[-8:].rjust(8, b"\0"), "big") % 1_000_003
|
|
120
|
+
return Trace(g, o, gap, bset, models=models if len(set(models)) > 1 else None, manual=manual, idle_obs=idle_obs,
|
|
121
|
+
tail_gap=tail, seed=seed) # fmt: skip
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def idle_observations(
|
|
125
|
+
s: Session,
|
|
126
|
+
idle_min: int,
|
|
127
|
+
idle_after: float,
|
|
128
|
+
since: float | None,
|
|
129
|
+
gap: list[float] | None = None,
|
|
130
|
+
idle_at: set[int] | None = None,
|
|
131
|
+
) -> dict[int, bool]:
|
|
132
|
+
"""Turn -> was it preceded by an idle compaction, for every turn the log shows was eligible for one. Only from
|
|
133
|
+
`since` (the first idle compaction in the logs) on: before it the harness may not have had the feature, so a gap
|
|
134
|
+
without one says nothing. With `since` None there is no observation at all."""
|
|
135
|
+
if since is None:
|
|
136
|
+
return {}
|
|
137
|
+
turns = s.turns
|
|
138
|
+
if gap is None:
|
|
139
|
+
prev = [turns[0], *turns[:-1]] if turns else []
|
|
140
|
+
gap = [max(b.ts - a.ts, 0.0) if (a.ts and b.ts) else 0.0 for a, b in zip(prev, turns, strict=True)]
|
|
141
|
+
if idle_at is None:
|
|
142
|
+
idle_at = {c.turn_index for c in s.compactions if c.idle}
|
|
143
|
+
return {
|
|
144
|
+
i: i in idle_at
|
|
145
|
+
for i in range(1, len(turns))
|
|
146
|
+
if ((gap[i] >= idle_after and turns[i - 1].ctx >= idle_min) or i in idle_at) and (turns[i].ts or 0) >= since
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def idle_rate(obs: list[bool], pooled: list[bool]) -> tuple[float, str, int, int]:
|
|
151
|
+
"""(rate, scope, fired, eligible): the share of eligible idle gaps that ended in an idle compaction, from the
|
|
152
|
+
group when it has enough, else the harness, else 1.0 ("assumed": the documented behaviour, on for conversations
|
|
153
|
+
that meet its conditions)."""
|
|
154
|
+
for xs, scope in ((obs, "group"), (pooled, "harness")):
|
|
155
|
+
if len(xs) >= IDLE_MIN_OBSERVED:
|
|
156
|
+
return sum(xs) / len(xs), scope, sum(xs), len(xs)
|
|
157
|
+
return 1.0, "assumed", 0, 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _draw(seed: int, i: int) -> float:
|
|
161
|
+
"""A fixed pseudo-random number in [0, 1) per (session, turn): the same gap fires the same way at every
|
|
162
|
+
threshold, so the sweep stays smooth."""
|
|
163
|
+
return ((seed * 1_000_003 + i * 2_654_435_761) % 1_000_000_007) / 1_000_000_007
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def rot_fn(table: list[tuple[int, float]]):
|
|
167
|
+
xs = [x for x, _ in table]
|
|
168
|
+
ys = [y for _, y in table]
|
|
169
|
+
|
|
170
|
+
def f(ctx: int) -> float:
|
|
171
|
+
if ctx <= xs[0]:
|
|
172
|
+
return ys[0]
|
|
173
|
+
if ctx >= xs[-1]:
|
|
174
|
+
return ys[-1]
|
|
175
|
+
i = bisect.bisect_right(xs, ctx)
|
|
176
|
+
w = (ctx - xs[i - 1]) / (xs[i] - xs[i - 1])
|
|
177
|
+
return ys[i - 1] + w * (ys[i] - ys[i - 1])
|
|
178
|
+
|
|
179
|
+
return f
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@dataclass
|
|
183
|
+
class Run:
|
|
184
|
+
"""One replay of a set of traces at one threshold."""
|
|
185
|
+
|
|
186
|
+
cost: float = 0.0 # USD, without penalty
|
|
187
|
+
penalty: float = 0.0 # USD added by re-discovery and corrections
|
|
188
|
+
compactions: int = 0
|
|
189
|
+
recall_sum: float = 0.0
|
|
190
|
+
t_turns: float = 0.0 # seconds spent in model turns (depends on context size)
|
|
191
|
+
t_compact: float = 0.0 # seconds spent compacting
|
|
192
|
+
t_redisc: float = 0.0 # seconds spent re-discovering after compactions
|
|
193
|
+
idle_compactions: int = 0 # of `compactions`, the idle ones
|
|
194
|
+
idle_cost: float = 0.0 # USD in `cost` for idle-compaction summaries, applied or not
|
|
195
|
+
idle_tail_cost: float = 0.0 # of that, summaries made for sessions left idle and never resumed (expected value)
|
|
196
|
+
manual_compactions: int = 0 # of `compactions`, the hand-typed /compact the replay kept
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def time_s(self) -> float:
|
|
200
|
+
return self.t_turns + self.t_compact + self.t_redisc
|
|
201
|
+
|
|
202
|
+
def add(self, o: Run) -> None:
|
|
203
|
+
for k in ("cost", "penalty", "compactions", "recall_sum", "t_turns", "t_compact", "t_redisc",
|
|
204
|
+
"idle_compactions", "idle_cost", "idle_tail_cost", "manual_compactions"): # fmt: skip
|
|
205
|
+
setattr(self, k, getattr(self, k) + getattr(o, k))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dataclass
|
|
209
|
+
class Ctx:
|
|
210
|
+
"""Per-group constants for replay."""
|
|
211
|
+
|
|
212
|
+
price: Price
|
|
213
|
+
base: int
|
|
214
|
+
summ: int
|
|
215
|
+
ttl: float
|
|
216
|
+
pen: PenaltyParams
|
|
217
|
+
tm: TimeModel
|
|
218
|
+
step_tokens: int
|
|
219
|
+
rot: Any
|
|
220
|
+
opts: SimOptions
|
|
221
|
+
prices: dict[str, Price] | None = None # model -> price at the group's TTL, for sessions that switched models
|
|
222
|
+
idle_on: bool = False # replay idle compaction (Claude Code, one-hour cache, setting on)
|
|
223
|
+
idle_min: int = IDLE_MIN_TOKENS
|
|
224
|
+
idle_after: float = IDLE_AFTER_S
|
|
225
|
+
idle_rate: float = 1.0 # share of eligible gaps that fire, where the log does not say
|
|
226
|
+
_tabs: Any = None
|
|
227
|
+
_rates: Any = None
|
|
228
|
+
|
|
229
|
+
def rate_tab(self, model: str | None) -> tuple[Any, int, Any]:
|
|
230
|
+
"""(short-context rates, long-context threshold, long-context rates) for a model; the group's by default."""
|
|
231
|
+
if self._rates is None:
|
|
232
|
+
self._rates = {}
|
|
233
|
+
price = (self.prices or {}).get(model) if model else None
|
|
234
|
+
key = model if price else None
|
|
235
|
+
if key not in self._rates:
|
|
236
|
+
p = price or self.price
|
|
237
|
+
la = p.long_above if p.long_above is not None else 10**12
|
|
238
|
+
self._rates[key] = (p.rates(0), la, p.rates(la + 1) if p.long_above is not None else p.rates(0))
|
|
239
|
+
return self._rates[key]
|
|
240
|
+
|
|
241
|
+
def tables(self) -> tuple[list[float], list[float], list[float], int]:
|
|
242
|
+
"""Lookup tables at 1k-token resolution (turn latency, recall rot) and the retention decay by turn."""
|
|
243
|
+
if self._tabs is None:
|
|
244
|
+
n = 2100 # up to 2.1M tokens
|
|
245
|
+
lat = [self.tm.turn(i * 1000) for i in range(n)]
|
|
246
|
+
rot = [self.rot(i * 1000) for i in range(n)]
|
|
247
|
+
o = self.opts
|
|
248
|
+
dec = [1 - (1 - o.retention) * math.exp(-k / o.retention_half_turns) for k in range(400)]
|
|
249
|
+
self._tabs = (lat, rot, dec, n - 1)
|
|
250
|
+
return self._tabs
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def replay(tr: Trace, T: float, c: Ctx, with_penalty: bool = True) -> Run:
|
|
254
|
+
"""Replay one trace at threshold T. Penalty cost/time are tracked separately from base cost."""
|
|
255
|
+
base, summ = c.base, c.summ
|
|
256
|
+
lat, rot, dec, top = c.tables()
|
|
257
|
+
short, long_above, long_ = c.rate_tab(None)
|
|
258
|
+
models = tr.models
|
|
259
|
+
man = tr.manual
|
|
260
|
+
ttl, rho, fixed, corr = c.ttl, c.pen.rho, c.pen.fixed_tokens, c.pen.correction_turns
|
|
261
|
+
step_tokens, med_turn = max(c.step_tokens, 1), c.tm.median_turn_s
|
|
262
|
+
ndec = len(dec)
|
|
263
|
+
ctx = base
|
|
264
|
+
cost = penalty = t_turns = t_compact = t_redisc = recall = idle_cost = 0.0
|
|
265
|
+
comps = idle_comps = manual_comps = 0
|
|
266
|
+
idle_on, idle_min, idle_after, idle_obs = c.idle_on, c.idle_min, c.idle_after, tr.idle_obs
|
|
267
|
+
fresh = False
|
|
268
|
+
since = ndec # "long ago": decay factor 1
|
|
269
|
+
extra = 0
|
|
270
|
+
gs, os_, gaps = tr.g, tr.o, tr.gap
|
|
271
|
+
avg_out = (sum(os_) / len(os_)) if os_ else 0
|
|
272
|
+
for i in range(len(gs)):
|
|
273
|
+
if models is not None: # price each turn at the model that served it
|
|
274
|
+
short, long_above, long_ = c.rate_tab(models[i])
|
|
275
|
+
if idle_on and i and ctx >= idle_min:
|
|
276
|
+
fired = idle_obs.get(i) # the logged outcome where the log shows one (an idle return can be 50+ min)
|
|
277
|
+
if fired is None:
|
|
278
|
+
fired = gaps[i] >= idle_after and _draw(tr.seed, i) < c.idle_rate
|
|
279
|
+
if fired: # summarized while the cache was warm: a cache read and the summary; nobody waits for it
|
|
280
|
+
_, ro_, _, rr_ = long_ if ctx > long_above else short
|
|
281
|
+
ic = ctx * rr_ + summ * ro_
|
|
282
|
+
cost += ic
|
|
283
|
+
idle_cost += ic
|
|
284
|
+
dropped = ctx - base - summ
|
|
285
|
+
ctx = base + summ
|
|
286
|
+
fresh = True # the turn on return writes the small context to the cache
|
|
287
|
+
since = 0
|
|
288
|
+
comps += 1
|
|
289
|
+
idle_comps += 1
|
|
290
|
+
if with_penalty:
|
|
291
|
+
extra = int(rho * max(dropped, 0) + fixed)
|
|
292
|
+
_, ro2, _, rr2 = long_ if ctx > long_above else short
|
|
293
|
+
penalty += corr * (ctx * rr2 + avg_out * ro2)
|
|
294
|
+
t_redisc += (extra / step_tokens + corr) * med_turn
|
|
295
|
+
g = gs[i] + extra
|
|
296
|
+
prev = ctx
|
|
297
|
+
ctx += g
|
|
298
|
+
_, ro, rw, rr = long_ if ctx > long_above else short
|
|
299
|
+
turn = prev * (rw if (fresh or gaps[i] > ttl) else rr) + g * rw + os_[i] * ro
|
|
300
|
+
if extra: # the share caused by re-discovered tokens is penalty, not base cost
|
|
301
|
+
penalty += extra * rw
|
|
302
|
+
turn -= extra * rw
|
|
303
|
+
extra = 0
|
|
304
|
+
cost += turn
|
|
305
|
+
fresh = False
|
|
306
|
+
ki = ctx // 1000
|
|
307
|
+
if ki > top:
|
|
308
|
+
ki = top
|
|
309
|
+
t_turns += lat[ki]
|
|
310
|
+
recall += rot[ki] * (dec[since] if since < ndec else 1.0)
|
|
311
|
+
since += 1
|
|
312
|
+
if ctx > T or (man and ctx >= MANUAL_KEEP * man.get(i + 1, 1 << 60)):
|
|
313
|
+
if ctx <= T:
|
|
314
|
+
manual_comps += 1
|
|
315
|
+
cost += ctx * rr + summ * ro # summarizer call reads the whole context
|
|
316
|
+
t_compact += c.tm.compact(ctx)
|
|
317
|
+
dropped = ctx - base - summ
|
|
318
|
+
ctx = base + summ
|
|
319
|
+
fresh = True
|
|
320
|
+
since = 0
|
|
321
|
+
comps += 1
|
|
322
|
+
if with_penalty:
|
|
323
|
+
extra = int(rho * max(dropped, 0) + fixed)
|
|
324
|
+
_, ro2, _, rr2 = long_ if ctx > long_above else short
|
|
325
|
+
penalty += corr * (ctx * rr2 + avg_out * ro2)
|
|
326
|
+
t_redisc += (extra / step_tokens + corr) * med_turn
|
|
327
|
+
tail = 0.0
|
|
328
|
+
if idle_on and tr.tail_gap >= idle_after and ctx >= idle_min: # left idle, never resumed: a summary nobody used
|
|
329
|
+
_, ro_, _, rr_ = long_ if ctx > long_above else short
|
|
330
|
+
tail = c.idle_rate * (ctx * rr_ + summ * ro_)
|
|
331
|
+
return Run(cost + tail, penalty, comps, recall, t_turns, t_compact, t_redisc, idle_comps, idle_cost + tail, tail,
|
|
332
|
+
manual_comps) # fmt: skip
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def run_all(traces: list[Trace], T: float, c: Ctx) -> Run:
|
|
336
|
+
tot = Run()
|
|
337
|
+
for tr in traces:
|
|
338
|
+
tot.add(replay(tr, T, c))
|
|
339
|
+
return tot
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _median(xs, default):
|
|
343
|
+
return int(statistics.median(xs)) if xs else default
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def grid_for(opts: SimOptions, max_threshold: int) -> list[int]:
|
|
347
|
+
stop = min(opts.grid_stop or max_threshold, max_threshold)
|
|
348
|
+
return list(range(opts.grid_start, stop + 1, opts.grid_step))
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
ROW_KEYS = ("cost", "penalty", "combined_cost", "recall", "compactions", "time_s", "time_turns_s", "time_compact_s",
|
|
352
|
+
"time_redisc_s", "idle_compactions", "idle_cost", "idle_tail_cost", "manual_compactions") # fmt: skip
|
|
353
|
+
BRIEF_KEYS = ("cost", "penalty", "combined_cost", "time_s", "time_compact_s", "time_redisc_s", "compactions",
|
|
354
|
+
"idle_compactions", "idle_cost", "idle_tail_cost", "recall") # fmt: skip
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _point(run: Run, T: float | None, n_turns: int) -> dict[str, Any]:
|
|
358
|
+
combined_cost = run.cost + run.penalty
|
|
359
|
+
return {
|
|
360
|
+
"threshold": None if T is None or math.isinf(T) else int(T),
|
|
361
|
+
"cost": run.cost,
|
|
362
|
+
"penalty": run.penalty,
|
|
363
|
+
"combined_cost": combined_cost,
|
|
364
|
+
"time_s": run.time_s,
|
|
365
|
+
"time_turns_s": run.t_turns,
|
|
366
|
+
"time_compact_s": run.t_compact,
|
|
367
|
+
"time_redisc_s": run.t_redisc,
|
|
368
|
+
"compactions": run.compactions,
|
|
369
|
+
"idle_compactions": run.idle_compactions,
|
|
370
|
+
"idle_cost": run.idle_cost,
|
|
371
|
+
"idle_tail_cost": run.idle_tail_cost,
|
|
372
|
+
"manual_compactions": run.manual_compactions,
|
|
373
|
+
"recall": run.recall_sum / max(n_turns, 1),
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def select_group(g: dict[str, Any], opts: dict[str, Any]) -> None:
|
|
378
|
+
"""(Re)compute a group's profiles, comparison and Pareto set in place from its grid arrays.
|
|
379
|
+
`opts` is a result's "options" dict, so a stored result can be re-selected without replaying."""
|
|
380
|
+
sel = opts.get("profile") or DEFAULT_PROFILE
|
|
381
|
+
profs = select_all(
|
|
382
|
+
g,
|
|
383
|
+
selected=sel,
|
|
384
|
+
vot=opts.get("value_of_time"),
|
|
385
|
+
floor=opts.get("recall_floor", 0.90),
|
|
386
|
+
tol=opts.get("tolerance", 0.02),
|
|
387
|
+
range_tol=opts.get("range_tolerance", 0.05),
|
|
388
|
+
wait_cap=opts.get("wait_cap_min_per_day", WAIT_CAP_MIN_PER_DAY),
|
|
389
|
+
cap=opts.get("max_threshold"),
|
|
390
|
+
)
|
|
391
|
+
d, cur = g["default"], g.get("current")
|
|
392
|
+
main = profs[sel]
|
|
393
|
+
g["profile"] = sel
|
|
394
|
+
g["profiles"] = profs
|
|
395
|
+
g["comparison"] = {name: _comparison(g, p) for name, p in profs.items()}
|
|
396
|
+
g["recommendation"] = main["recommendation"]
|
|
397
|
+
g["value_of_time"] = main["value_of_time"]
|
|
398
|
+
g["combined"] = score(g, main["value_of_time"])
|
|
399
|
+
g["pareto"] = [g["grid"][i] for i in pareto(g["combined"], g["recall"])]
|
|
400
|
+
g["default"]["combined"] = d["combined_cost"] + d["time_s"] / 3600 * main["value_of_time"]
|
|
401
|
+
if cur:
|
|
402
|
+
cur["combined"] = cur["combined_cost"] + cur["time_s"] / 3600 * main["value_of_time"]
|
|
403
|
+
apply_measured(g) # selection works from the lite proxy; deep-mode measurements still bind
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _comparison(g: dict[str, Any], p: dict[str, Any]) -> dict[str, Any]:
|
|
407
|
+
d, cur, thr = g["default"], g.get("current"), p["threshold"]
|
|
408
|
+
d_score = d["combined_cost"] + d["time_s"] / 3600 * p["value_of_time"]
|
|
409
|
+
tol = p.get("recommendation", {}).get("tolerance", 0.02)
|
|
410
|
+
if g["no_action_needed"]:
|
|
411
|
+
action = "no action needed"
|
|
412
|
+
# your current setting is within the tolerance of the pick: changing it would not pay for the churn (and the pick
|
|
413
|
+
# may even score a little worse, since it is the largest threshold within the tolerance of the best)
|
|
414
|
+
elif cur is not None and cur["combined_cost"] + cur["time_s"] / 3600 * p["value_of_time"] <= p["combined"] * (
|
|
415
|
+
1 + tol
|
|
416
|
+
):
|
|
417
|
+
action = "keep current"
|
|
418
|
+
# not better than leaving the default alone, or better by no more than the tolerance the pick itself allows (the
|
|
419
|
+
# pick is the largest threshold within it of the best score, so a default that close is as good a choice)
|
|
420
|
+
elif thr >= d["threshold"] or d_score <= p["combined"] * (1 + tol):
|
|
421
|
+
action = "keep default"
|
|
422
|
+
else:
|
|
423
|
+
action = "set"
|
|
424
|
+
return {
|
|
425
|
+
"threshold": thr,
|
|
426
|
+
"action": action,
|
|
427
|
+
"vs_default": compare(p, d, g["days"], g.get("active_days")),
|
|
428
|
+
"vs_current": compare(p, cur, g["days"], g.get("active_days")) if cur else None,
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def override_profile(g: dict[str, Any], name: str, threshold: int, flag: str) -> None:
|
|
433
|
+
"""Move one profile to another grid threshold (e.g. after deep mode measured its recall) and refresh it."""
|
|
434
|
+
old = g["profiles"][name]
|
|
435
|
+
p = point(g, g["grid"].index(threshold), old["value_of_time"])
|
|
436
|
+
keep = ("profile", "value_of_time", "min_threshold", "unconstrained_threshold", "recommendation",
|
|
437
|
+
"wait_cap_min_per_day") # fmt: skip
|
|
438
|
+
p.update({k: old[k] for k in keep})
|
|
439
|
+
p["lite_threshold"] = old["threshold"]
|
|
440
|
+
p["fraction_of_max"] = threshold / g["effective_max"] if g.get("effective_max") else 0.0
|
|
441
|
+
p["flags"] = [*old["flags"], flag]
|
|
442
|
+
g["profiles"][name] = p
|
|
443
|
+
g["comparison"][name] = _comparison(g, p)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def apply_measured(g: dict[str, Any]) -> dict[str, int]:
|
|
447
|
+
"""Lower every profile whose pick has a measured recall (`g["measured"]`, from deep mode) below the floor to the
|
|
448
|
+
highest measured threshold under it that clears the floor (else the lowest measured one). Returns the
|
|
449
|
+
{profile: new threshold} moves. Called by select_group, so a reselected result keeps its measured guardrails."""
|
|
450
|
+
pts = g.get("measured")
|
|
451
|
+
if not pts:
|
|
452
|
+
return {}
|
|
453
|
+
floor = g["recommendation"]["recall_floor"]
|
|
454
|
+
adjusted: dict[str, int] = {}
|
|
455
|
+
for name, prof in g["profiles"].items():
|
|
456
|
+
thr = prof["threshold"]
|
|
457
|
+
hp = next((p for p in pts if p["threshold"] == thr), None)
|
|
458
|
+
if hp and hp["measured_recall"] < floor:
|
|
459
|
+
ok_pts = [p["threshold"] for p in pts if p["threshold"] < thr and p["measured_recall"] >= floor]
|
|
460
|
+
adjusted[name] = max(ok_pts) if ok_pts else min(p["threshold"] for p in pts)
|
|
461
|
+
for name, thr in adjusted.items():
|
|
462
|
+
override_profile(g, name, thr, "deep_recall_below_floor")
|
|
463
|
+
if g["profile"] in adjusted:
|
|
464
|
+
g["recommendation"] = dict(g["recommendation"], threshold=adjusted[g["profile"]])
|
|
465
|
+
return adjusted
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
GLOBAL_KEY_HARNESSES = ("codex",) # one threshold for every model (model_auto_compact_token_limit)
|
|
469
|
+
SUPERSEDE_GRACE_S = 3 * 86400
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def superseded(groups: list[dict[str, Any]]) -> dict[tuple[str, str], str]:
|
|
473
|
+
"""(harness, model) -> the newer version of it that took over: same family, a higher version, used after the old
|
|
474
|
+
one's last use, and the old one not used for more than SUPERSEDE_GRACE_S after the new one first appeared
|
|
475
|
+
(gpt-6.1-sol -> gpt-6.2-sol). A model used alongside its successor is not superseded."""
|
|
476
|
+
spans: dict[tuple[str, str], list[float]] = {}
|
|
477
|
+
for g in groups:
|
|
478
|
+
if g.get("span") and g.get("model"):
|
|
479
|
+
s = spans.setdefault((g.get("harness", ""), g["model"]), [g["span"][0], g["span"][1]])
|
|
480
|
+
s[0], s[1] = min(s[0], g["span"][0]), max(s[1], g["span"][1])
|
|
481
|
+
fams = {k: model_family(parse_model(k[1]).id) for k in spans}
|
|
482
|
+
out: dict[tuple[str, str], str] = {}
|
|
483
|
+
for (h, a), (_, last_a) in spans.items():
|
|
484
|
+
fam, va = fams[(h, a)]
|
|
485
|
+
newer = [
|
|
486
|
+
(fams[(h2, b)][1], b)
|
|
487
|
+
for (h2, b), (first_b, last_b) in spans.items()
|
|
488
|
+
if h2 == h and b != a and fam and va and fams[(h2, b)][0] == fam and fams[(h2, b)][1] > va
|
|
489
|
+
and last_b > last_a and last_a <= first_b + SUPERSEDE_GRACE_S
|
|
490
|
+
] # fmt: skip
|
|
491
|
+
if newer:
|
|
492
|
+
out[(h, a)] = max(newer)[1]
|
|
493
|
+
return out
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _global_pick(used: list[dict[str, Any]], name: str, opts: dict[str, Any]) -> dict[str, Any]:
|
|
497
|
+
"""One threshold for every model of a harness: each model is scored at min(T, its own clamp) and the per-day
|
|
498
|
+
scores are summed; then the same rules as one group: the guardrails (your --max-threshold, each model's minimum
|
|
499
|
+
window and recall floor, measured recall from deep mode, and the profile's cap on added compaction wait, summed
|
|
500
|
+
over the models since it is one person's day), the largest T within the tolerance of the best, and keep current /
|
|
501
|
+
keep default within the tolerance."""
|
|
502
|
+
tol = opts.get("tolerance", 0.02)
|
|
503
|
+
cap = opts.get("max_threshold")
|
|
504
|
+
wait_cap = opts.get("wait_cap_min_per_day", WAIT_CAP_MIN_PER_DAY) if PROFILES[name]["enforce_wait_cap"] else None
|
|
505
|
+
vot = float(used[0]["profiles"][name]["value_of_time"])
|
|
506
|
+
|
|
507
|
+
def wait(g: dict[str, Any], p: dict[str, Any]) -> float:
|
|
508
|
+
d = g["default"]
|
|
509
|
+
added = (p["time_compact_s"] + p["time_redisc_s"]) - (d["time_compact_s"] + d["time_redisc_s"])
|
|
510
|
+
return added / 60 / max(float(g.get("days") or 1.0), 1.0)
|
|
511
|
+
|
|
512
|
+
def measured_ok(g: dict[str, Any], p: dict[str, Any], floor: float) -> bool:
|
|
513
|
+
mp = next((m for m in g.get("measured") or [] if m["threshold"] == p["threshold"]), None)
|
|
514
|
+
return mp is None or mp["measured_recall"] >= floor
|
|
515
|
+
|
|
516
|
+
def at(g: dict[str, Any], T: int) -> dict[str, Any] | None:
|
|
517
|
+
eff = min(T, g["effective_max"])
|
|
518
|
+
if eff >= g["default"]["threshold"]:
|
|
519
|
+
return g["default"]
|
|
520
|
+
return point(g, g["grid"].index(eff), vot) if eff in g["grid"] else None
|
|
521
|
+
|
|
522
|
+
def total(pts: list[tuple[dict[str, Any], dict[str, Any]]]) -> float:
|
|
523
|
+
return sum((p["combined_cost"] + p["time_s"] / 3600 * vot) / g["days"] for g, p in pts)
|
|
524
|
+
|
|
525
|
+
Pts = list[tuple[dict[str, Any], dict[str, Any]]]
|
|
526
|
+
scored: list[tuple[int, float, Pts]] = []
|
|
527
|
+
for T in sorted({x for g in used for x in g["grid"]}):
|
|
528
|
+
if cap is not None and cap < T:
|
|
529
|
+
continue
|
|
530
|
+
pts: Pts = []
|
|
531
|
+
for g in used:
|
|
532
|
+
p = at(g, T)
|
|
533
|
+
if p is None: # not on this model's grid
|
|
534
|
+
break
|
|
535
|
+
prof = g["profiles"][name]
|
|
536
|
+
floor = prof["recommendation"]["recall_floor"]
|
|
537
|
+
if p is not g["default"] and (
|
|
538
|
+
prof.get("min_threshold", 0) > T or p["recall"] < floor or not measured_ok(g, p, floor)
|
|
539
|
+
):
|
|
540
|
+
break # a guardrail of this model's profile
|
|
541
|
+
pts.append((g, p))
|
|
542
|
+
else:
|
|
543
|
+
if wait_cap is None or sum(wait(g, p) for g, p in pts if p is not g["default"]) <= wait_cap:
|
|
544
|
+
scored.append((T, total(pts), pts))
|
|
545
|
+
d_pts = [(g, g["default"]) for g in used]
|
|
546
|
+
out: dict[str, Any] = {"threshold": None, "default_score": total(d_pts), "per_model": {}}
|
|
547
|
+
cur = next((g["current"]["configured"] for g in used if g.get("current")), None)
|
|
548
|
+
if all(g["no_action_needed"] for g in used):
|
|
549
|
+
return {**out, "action": "no action needed"}
|
|
550
|
+
if not scored:
|
|
551
|
+
return {**out, "action": "keep default"}
|
|
552
|
+
best = min(s for _, s, _ in scored)
|
|
553
|
+
T, S, pts = max((x for x in scored if x[1] <= best * (1 + tol)), key=lambda x: x[0])
|
|
554
|
+
out.update(threshold=T, score=S,
|
|
555
|
+
d_usd_per_day=sum((p["combined_cost"] - g["default"]["combined_cost"]) / g["days"] for g, p in pts),
|
|
556
|
+
d_min_per_day=sum((p["time_s"] - g["default"]["time_s"]) / 60 / g["days"] for g, p in pts),
|
|
557
|
+
per_model={f"{g['model']} · {g['role']}": (None if p is g["default"] else p["threshold"])
|
|
558
|
+
for g, p in pts}) # fmt: skip
|
|
559
|
+
binding = any(p is not g["default"] for g, p in pts)
|
|
560
|
+
if cur is not None and total([(g, g.get("current") or g["default"]) for g in used]) <= S * (1 + tol):
|
|
561
|
+
return {**out, "action": "keep current", "current": cur}
|
|
562
|
+
if not binding or out["default_score"] <= S * (1 + tol):
|
|
563
|
+
return {**out, "action": "keep default"}
|
|
564
|
+
return {**out, "action": "set"}
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _apply_global(g: dict[str, Any], name: str, gp: dict[str, Any], harness: str, models: list[str]) -> None:
|
|
568
|
+
"""Make one group's comparison say what the harness-wide value does to it."""
|
|
569
|
+
T = gp["threshold"] if gp["action"] == "set" else None
|
|
570
|
+
eff = min(T, g["effective_max"]) if T else None
|
|
571
|
+
if eff is not None and eff < g["default"]["threshold"] and eff in g["grid"]:
|
|
572
|
+
override_profile(g, name, eff, "global_key")
|
|
573
|
+
g["comparison"][name]["action"] = "set"
|
|
574
|
+
elif g["no_action_needed"]:
|
|
575
|
+
g["comparison"][name]["action"] = "no action needed"
|
|
576
|
+
elif gp["action"] == "keep current" and g.get("current"):
|
|
577
|
+
g["comparison"][name]["action"] = "keep current"
|
|
578
|
+
else:
|
|
579
|
+
g["comparison"][name]["action"] = "keep default"
|
|
580
|
+
g["comparison"][name]["global"] = {"harness": harness, "action": gp["action"], "threshold": gp["threshold"],
|
|
581
|
+
"models": models, "superseded_by": g.get("superseded_by")} # fmt: skip
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def global_keys(groups: list[dict[str, Any]], opts: dict[str, Any]) -> dict[str, Any]:
|
|
585
|
+
"""Harnesses with one threshold for every model (Codex): choose it across the models in use (a model a newer
|
|
586
|
+
version took over is left out) and rewrite each of its groups' comparison to match. Marks `superseded_by` on
|
|
587
|
+
every group, of any harness."""
|
|
588
|
+
sup = superseded(groups)
|
|
589
|
+
for g in groups:
|
|
590
|
+
g["superseded_by"] = sup.get((g.get("harness", ""), g.get("model", "")))
|
|
591
|
+
out: dict[str, Any] = {}
|
|
592
|
+
for h in GLOBAL_KEY_HARNESSES:
|
|
593
|
+
hs = [g for g in groups if g.get("harness") == h]
|
|
594
|
+
if not hs:
|
|
595
|
+
continue
|
|
596
|
+
used = [g for g in hs if not g["superseded_by"]] or hs
|
|
597
|
+
models = [f"{g['model']} · {g['role']}" for g in used]
|
|
598
|
+
res: dict[str, Any] = {
|
|
599
|
+
"models": models,
|
|
600
|
+
"superseded": {g["model"]: g["superseded_by"] for g in hs if g["superseded_by"]},
|
|
601
|
+
"profiles": {n: _global_pick(used, n, opts) for n in PROFILE_NAMES},
|
|
602
|
+
}
|
|
603
|
+
for g in hs:
|
|
604
|
+
for n in PROFILE_NAMES:
|
|
605
|
+
_apply_global(g, n, res["profiles"][n], h, models)
|
|
606
|
+
out[h] = res
|
|
607
|
+
return out
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def harness_options(result: dict[str, Any], harness: str) -> dict[str, Any]:
|
|
611
|
+
"""The options a harness's groups were selected with: a result that keeps every harness's latest run
|
|
612
|
+
(publish.py) records them per harness; otherwise the result's own."""
|
|
613
|
+
info = (result.get("harnesses") or {}).get(harness)
|
|
614
|
+
opts = info.get("options") if isinstance(info, dict) else None
|
|
615
|
+
if isinstance(opts, dict):
|
|
616
|
+
return opts
|
|
617
|
+
return result["options"] if isinstance(result.get("options"), dict) else {}
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def reselect(result: dict[str, Any], profile: str | None = None, value_of_time: float | None = None) -> dict:
|
|
621
|
+
"""Re-run profile selection on a stored result (no replay), each harness under its own options, with `profile`
|
|
622
|
+
and `value_of_time` applied to all. Mutates and returns `result`."""
|
|
623
|
+
over = {k: v for k, v in (("profile", profile), ("value_of_time", value_of_time)) if v is not None}
|
|
624
|
+
groups = result["groups"]
|
|
625
|
+
harnesses = sorted({g.get("harness", "") for g in groups})
|
|
626
|
+
for o in (result.setdefault("options", {}), *(harness_options(result, h) for h in harnesses)):
|
|
627
|
+
o.update(over)
|
|
628
|
+
for g in groups:
|
|
629
|
+
select_group(g, harness_options(result, g.get("harness", "")))
|
|
630
|
+
keys: dict[str, Any] = {}
|
|
631
|
+
for h in harnesses: # per harness, like the single-key decision and the superseded models themselves
|
|
632
|
+
keys.update(global_keys([g for g in groups if g.get("harness", "") == h], harness_options(result, h)))
|
|
633
|
+
result["global_keys"] = keys
|
|
634
|
+
for g in groups:
|
|
635
|
+
if (g.get("idle") or {}).get("alt", {}).get("rows"):
|
|
636
|
+
idle_select(g)
|
|
637
|
+
if "idle_compaction" in result: # Claude Code's setting: only its groups have the idle alternative
|
|
638
|
+
result["idle_compaction"] = idle_advice(groups, harness_options(result, "claude-code"))
|
|
639
|
+
return result
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def no_action(default: dict[str, Any]) -> bool:
|
|
643
|
+
"""The default threshold is never reached: no compaction but idle ones and the hand-typed /compact kept."""
|
|
644
|
+
return default["compactions"] - default.get("idle_compactions", 0) - default.get("manual_compactions", 0) == 0
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def idle_select(g: dict[str, Any]) -> None:
|
|
648
|
+
"""Record what would be in force with idle compaction as configured and flipped, both at the thresholds the group
|
|
649
|
+
emits (its profile picks, or the current setting). The flipped sweep is not re-selected: the recommendation only
|
|
650
|
+
adds the idle toggle to these picks, so the verdict must compare the two states at them."""
|
|
651
|
+
alt = g["idle"]["alt"]
|
|
652
|
+
ga = {**g, **alt["rows"], "default": alt["default_point"], "current": alt["current_point"]}
|
|
653
|
+
alt["profiles"] = {n: in_force(ga, n) for n in PROFILE_NAMES}
|
|
654
|
+
alt["current"] = in_force(ga, None)
|
|
655
|
+
g["idle"]["profiles"] = {n: in_force(g, n) for n in PROFILE_NAMES}
|
|
656
|
+
g["idle"]["current"] = in_force(g, None)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _one_hour(s: Session) -> bool:
|
|
660
|
+
"""Most of the session's cache writes were billed at the one-hour tier (idle compaction needs it)."""
|
|
661
|
+
w = sum(t.cache_write for t in s.turns)
|
|
662
|
+
return w > 0 and 2 * sum(t.cache_write_1h for t in s.turns) >= w
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def in_force(g: dict[str, Any], profile: str | None) -> dict[str, Any]:
|
|
666
|
+
"""The replayed point that would be in force: a profile's pick when its action is "set", your setting when it is
|
|
667
|
+
"keep current", else the default; with `profile` None, the current setting (or the default when none is set)."""
|
|
668
|
+
action = g["comparison"][profile]["action"] if profile is not None else None
|
|
669
|
+
if profile is None or (action == "keep current" and g.get("current")):
|
|
670
|
+
src = g.get("current") or g["default"]
|
|
671
|
+
elif action == "set":
|
|
672
|
+
i = g["grid"].index(g["comparison"][profile]["threshold"])
|
|
673
|
+
src = {k: g[k][i] for k in BRIEF_KEYS if k in g}
|
|
674
|
+
src["threshold"] = g["grid"][i]
|
|
675
|
+
else:
|
|
676
|
+
src = g["default"]
|
|
677
|
+
return {"threshold": src.get("threshold"), **{k: src.get(k, 0.0) for k in BRIEF_KEYS}}
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def idle_advice(groups: list[dict[str, Any]], opts: dict[str, Any]) -> dict[str, Any] | None:
|
|
681
|
+
"""Keep Claude Code's idle compaction on or off? It is one global setting, so the answer adds up every group it
|
|
682
|
+
applies to, each at what would be in force (a profile's picks, or the current settings), with the setting as it is
|
|
683
|
+
and flipped. Switch only when the flip beats the current state by more than the selection tolerance."""
|
|
684
|
+
gs = [g for g in groups if g.get("idle", {}).get("alt")]
|
|
685
|
+
if not gs:
|
|
686
|
+
return None
|
|
687
|
+
tol = opts.get("tolerance", 0.02)
|
|
688
|
+
enabled = gs[0]["idle"]["enabled"]
|
|
689
|
+
|
|
690
|
+
def per_day(side: str, name: str | None) -> dict[str, float]:
|
|
691
|
+
tot = {k: 0.0 for k in BRIEF_KEYS if k != "recall"}
|
|
692
|
+
rec = turns = 0.0
|
|
693
|
+
for g in gs:
|
|
694
|
+
src = g["idle"] if side == "configured" else g["idle"]["alt"]
|
|
695
|
+
pt = src["current"] if name is None else src["profiles"][name]
|
|
696
|
+
for k in tot:
|
|
697
|
+
tot[k] += pt[k] / g["days"]
|
|
698
|
+
rec += pt["recall"] * g["n_turns"]
|
|
699
|
+
turns += g["n_turns"]
|
|
700
|
+
tot["recall"] = rec / turns if turns else 0.0
|
|
701
|
+
return tot
|
|
702
|
+
|
|
703
|
+
def verdict(name: str | None, vot: float) -> dict[str, Any]:
|
|
704
|
+
a, b = per_day("configured", name), per_day("flipped", name)
|
|
705
|
+
sa = a["combined_cost"] + a["time_s"] / 3600 * vot
|
|
706
|
+
sb = b["combined_cost"] + b["time_s"] / 3600 * vot
|
|
707
|
+
return {
|
|
708
|
+
"configured": a,
|
|
709
|
+
"flipped": b,
|
|
710
|
+
"d_usd_per_day": b["combined_cost"] - a["combined_cost"],
|
|
711
|
+
"d_min_per_day": (b["time_s"] - a["time_s"]) / 60,
|
|
712
|
+
"d_compactions_per_day": b["compactions"] - a["compactions"],
|
|
713
|
+
"d_recall": b["recall"] - a["recall"],
|
|
714
|
+
"d_score_pct": (sb - sa) / sa if sa else 0.0,
|
|
715
|
+
"switch": sb < sa * (1 - tol),
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
sel = opts.get("profile") or DEFAULT_PROFILE
|
|
719
|
+
vots = {n: gs[0]["profiles"][n]["value_of_time"] for n in PROFILE_NAMES}
|
|
720
|
+
return {
|
|
721
|
+
"enabled": enabled,
|
|
722
|
+
"configured": gs[0]["idle"]["configured"],
|
|
723
|
+
"min_tokens": gs[0]["idle"]["min_tokens"],
|
|
724
|
+
"groups": [f"{g['model']} · {g['role']}" for g in gs],
|
|
725
|
+
"profile": sel,
|
|
726
|
+
"profiles": {n: verdict(n, vots[n]) for n in PROFILE_NAMES},
|
|
727
|
+
"current": verdict(None, vots[sel]),
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
CLAUDE_UNKNOWN_WINDOW = 200_000 # Claude Code's window for a model ID it does not recognize
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def claude_recognizes(model: str) -> bool:
|
|
735
|
+
"""Claude Code sizes the window from the model ID: Claude IDs (on any platform) it knows; anything else, such as a
|
|
736
|
+
third-party model behind ANTHROPIC_BASE_URL or a gateway alias, gets 200K unless CLAUDE_CODE_MAX_CONTEXT_TOKENS
|
|
737
|
+
says otherwise."""
|
|
738
|
+
return model in ("unknown", "<synthetic>") or parse_model(model).id.startswith("claude-")
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
PRICE_FIELDS = ("input", "output", "cache_write", "cache_read", "max_window")
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def price_snapshot(p: Price) -> dict[str, Any]:
|
|
745
|
+
"""The list price a group was replayed with, kept in the result so a later price change can be noticed."""
|
|
746
|
+
return {**{f: getattr(p, f) for f in PRICE_FIELDS}, "key": p.key, "source": p.source}
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def price_drift(result: dict[str, Any], pricing: PricingTable) -> list[dict[str, Any]]:
|
|
750
|
+
"""Prices and windows that differ between a saved result and the table now (one entry per model and field)."""
|
|
751
|
+
out: dict[tuple[str, str], dict[str, Any]] = {}
|
|
752
|
+
for g in result.get("groups", []):
|
|
753
|
+
was = g.get("price")
|
|
754
|
+
if not was:
|
|
755
|
+
continue
|
|
756
|
+
now = price_snapshot(pricing.lookup(g["model"], g.get("platform")))
|
|
757
|
+
for f in PRICE_FIELDS:
|
|
758
|
+
if was.get(f) is not None and float(was[f]) != float(now[f]):
|
|
759
|
+
out.setdefault((g["model"], f), {"model": g["model"], "field": f, "old": was[f], "new": now[f],
|
|
760
|
+
"source": now["source"]}) # fmt: skip
|
|
761
|
+
return list(out.values())
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
WINDOW_RECENT = 10
|
|
765
|
+
SWITCH_SHARE = 0.8 # a window change is reported when each side agrees this much (not when sessions alternate)
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def _mode(xs: list[int]) -> int:
|
|
769
|
+
"""The most common value (the larger on a tie)."""
|
|
770
|
+
c = Counter(xs)
|
|
771
|
+
return max(c, key=lambda x: (c[x], x))
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def group_window(
|
|
775
|
+
harness: str, model: str, ss: list[Session], table_window: int, opts: SimOptions
|
|
776
|
+
) -> tuple[int, str, dict[str, Any] | None]:
|
|
777
|
+
"""(window, where it came from, a note when it moved or contradicts the logs). Harnesses change a model's window
|
|
778
|
+
over time, so the latest session's logged window wins over older ones (Codex logs it per session); without one,
|
|
779
|
+
the price data's. Claude Code gives a model ID it does not recognize 200K (or CLAUDE_CODE_MAX_CONTEXT_TOKENS).
|
|
780
|
+
Contexts in the logs larger than that window mean it is out of date: a Claude model then has the 1M window, any
|
|
781
|
+
other the largest context seen."""
|
|
782
|
+
dated = sorted((s.turns[-1].ts or 0.0, int(s.context_window)) for s in ss if s.context_window and s.turns)
|
|
783
|
+
note: dict[str, Any] | None = None
|
|
784
|
+
if dated:
|
|
785
|
+
# the most common window of the latest sessions (sessions of one model can differ, e.g. by client version);
|
|
786
|
+
# a change is reported only when the earlier sessions agreed on another one
|
|
787
|
+
recent, older = dated[-WINDOW_RECENT:], dated[:-WINDOW_RECENT]
|
|
788
|
+
window = _mode([w for _, w in recent])
|
|
789
|
+
source = "observed in logs (latest sessions)"
|
|
790
|
+
was = _mode([w for _, w in older]) if older else window
|
|
791
|
+
|
|
792
|
+
def share(block: list[tuple[float, int]], x: int) -> float:
|
|
793
|
+
return sum(w == x for _, w in block) / len(block)
|
|
794
|
+
|
|
795
|
+
if was != window and share(recent, window) >= SWITCH_SHARE and share(older, was) >= SWITCH_SHARE:
|
|
796
|
+
since = next(t for t, w in recent if w == window)
|
|
797
|
+
note = {"kind": "window_changed", "from": was, "to": window, "since": since}
|
|
798
|
+
else:
|
|
799
|
+
window, source = table_window, "pricing data"
|
|
800
|
+
if harness == "claude-code" and not claude_recognizes(model):
|
|
801
|
+
window = opts.claude_max_context or CLAUDE_UNKNOWN_WINDOW
|
|
802
|
+
source = (
|
|
803
|
+
"CLAUDE_CODE_MAX_CONTEXT_TOKENS"
|
|
804
|
+
if opts.claude_max_context
|
|
805
|
+
else "Claude Code assumes 200K for a model ID it does not recognize"
|
|
806
|
+
)
|
|
807
|
+
peak = max((s.peak for s in ss), default=0)
|
|
808
|
+
if not dated and peak > window: # a logged window is the harness's own word; an assumed one can be stale
|
|
809
|
+
was = window
|
|
810
|
+
window = 1_000_000 if harness == "claude-code" and claude_recognizes(model) and peak <= 1_000_000 else peak
|
|
811
|
+
source = f"contexts in the logs reached {peak:,}, beyond the {was:,} assumed"
|
|
812
|
+
note = {"kind": "peak_over_window", "assumed": was, "peak": peak, "window": window}
|
|
813
|
+
return window, source, note
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
DRIFT_RECENT = 10 # threshold compactions to look at, newest first
|
|
817
|
+
DRIFT_MIN = 5
|
|
818
|
+
DRIFT_FRAC = 0.10
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def default_drift(ss: list[Session], assumed: int) -> dict[str, Any] | None:
|
|
822
|
+
"""With no setting of yours in force, the threshold compactions should land near the harness default. When the
|
|
823
|
+
latest ones (at least DRIFT_MIN of the last DRIFT_RECENT) land more than 10% away, either the harness changed its
|
|
824
|
+
default (an update) or a setting compactlab cannot see is in force (an env var, a project file, a CLI flag)."""
|
|
825
|
+
recent = sorted((c for s in ss for c in s.compactions if c.pre_tokens and is_threshold(c)), key=lambda c: c.ts or 0)
|
|
826
|
+
recent = recent[-DRIFT_RECENT:]
|
|
827
|
+
if len(recent) < DRIFT_MIN:
|
|
828
|
+
return None
|
|
829
|
+
observed = int(_median([c.pre_tokens or 0 for c in recent], 0))
|
|
830
|
+
if abs(observed - assumed) <= DRIFT_FRAC * assumed:
|
|
831
|
+
return None
|
|
832
|
+
return {"assumed": assumed, "observed": observed, "n": len(recent), "since": recent[0].ts}
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def model_notes(groups: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
|
|
836
|
+
"""Models priced from something other than their own row (another platform's price, a borrowed family row or the
|
|
837
|
+
fallback); Claude Code models with no window of their own while other models have one (a new model the settings
|
|
838
|
+
file has not caught up with), counted only when its sessions reach where the setting would act; windows that
|
|
839
|
+
changed or that the logs contradict; and defaults the latest compactions do not match."""
|
|
840
|
+
prices: dict[tuple[str, str], dict[str, Any]] = {}
|
|
841
|
+
for g in groups:
|
|
842
|
+
if g.get("price_kind", "exact") != "exact":
|
|
843
|
+
prices.setdefault((g["harness"], g["model"]), {
|
|
844
|
+
"harness": g["harness"], "model": g["model"], "kind": g["price_kind"], "row": g["price_key"],
|
|
845
|
+
"platform": g.get("platform"), "source": g["price_source"]}) # fmt: skip
|
|
846
|
+
unset = []
|
|
847
|
+
for g in groups:
|
|
848
|
+
if g["harness"] != "claude-code" or g["role"] != "main" or g.get("current") is not None:
|
|
849
|
+
continue
|
|
850
|
+
peers = [x for x in groups if x["harness"] == g["harness"] and x["model"] != g["model"] and x.get("current")]
|
|
851
|
+
if not peers:
|
|
852
|
+
continue
|
|
853
|
+
fam = model_family(parse_model(g["model"]).id)[0]
|
|
854
|
+
same = [x for x in peers if model_family(parse_model(x["model"]).id)[0] == fam]
|
|
855
|
+
peer = max(same or peers, key=lambda x: x["n_turns"])
|
|
856
|
+
if peer["current"]["configured"] >= g["default"]["threshold"]:
|
|
857
|
+
continue # the peer's value would not lower this model's compaction point (e.g. a 200K window)
|
|
858
|
+
if g.get("peak_max", 0) < peer["current"]["configured"]:
|
|
859
|
+
continue # its sessions never get where a setting would act: nothing to catch up on yet
|
|
860
|
+
unset.append({
|
|
861
|
+
"harness": g["harness"], "model": g["model"], "default": g["default"]["threshold"],
|
|
862
|
+
"active_days": g["active_days"], "peer": peer["model"], "peer_value": peer["current"]["configured"],
|
|
863
|
+
"same_family": bool(same)}) # fmt: skip
|
|
864
|
+
windows = [{"harness": g["harness"], "model": g["model"], "role": g["role"], **g["window_note"]}
|
|
865
|
+
for g in groups if g.get("window_note")] # fmt: skip
|
|
866
|
+
defaults = [{"harness": g["harness"], "model": g["model"], "role": g["role"], **g["default_drift"]}
|
|
867
|
+
for g in groups if g.get("default_drift")] # fmt: skip
|
|
868
|
+
last: dict[tuple[str, str, str], float] = {}
|
|
869
|
+
for g in groups:
|
|
870
|
+
if g.get("superseded_by"):
|
|
871
|
+
key = (g["harness"], g["model"], g["superseded_by"])
|
|
872
|
+
last[key] = max(last.get(key, 0.0), g["span"][1] if g.get("span") else 0.0)
|
|
873
|
+
replaced = [{"harness": h, "model": m, "by": b, "last_used": t, "global_key": h in GLOBAL_KEY_HARNESSES}
|
|
874
|
+
for (h, m, b), t in sorted(last.items())] # fmt: skip
|
|
875
|
+
return {"prices": list(prices.values()), "unset": unset, "windows": windows, "defaults": defaults,
|
|
876
|
+
"superseded": replaced} # fmt: skip
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def analyze(
|
|
880
|
+
sessions: list[Session],
|
|
881
|
+
pricing: PricingTable,
|
|
882
|
+
opts: SimOptions | None = None,
|
|
883
|
+
current: dict[tuple[str, str], tuple[int | None, str]] | None = None,
|
|
884
|
+
progress: Any = None,
|
|
885
|
+
) -> dict:
|
|
886
|
+
"""`current` maps (harness, model) -> (configured threshold or None, description), read from config."""
|
|
887
|
+
opts = opts or SimOptions()
|
|
888
|
+
if opts.max_threshold is not None and opts.max_threshold < opts.grid_start:
|
|
889
|
+
raise InfeasibleCap(
|
|
890
|
+
f"--max-threshold {opts.max_threshold:,} is below the grid start {opts.grid_start:,}: "
|
|
891
|
+
"lower the grid start (--grid) or raise the cap"
|
|
892
|
+
)
|
|
893
|
+
default_ttl = pricing.default_ttl
|
|
894
|
+
rot = rot_fn(opts.rot_table)
|
|
895
|
+
opt_d = {k: (v if k != "penalty" else (v.to_dict() if v else None)) for k, v in opts.__dict__.items()}
|
|
896
|
+
groups: dict[tuple[str, str, str], list[Session]] = defaultdict(list)
|
|
897
|
+
by_harness: dict[str, list[Session]] = defaultdict(list)
|
|
898
|
+
for s in sessions:
|
|
899
|
+
groups[(s.harness, s.model, s.role)].append(s) # the same model name under two harnesses is two groups
|
|
900
|
+
by_harness[s.harness].append(s)
|
|
901
|
+
pooled = {h: fit(ss) for h, ss in by_harness.items()}
|
|
902
|
+
data_end = max((t.ts for s in sessions for t in s.turns if t.ts), default=None)
|
|
903
|
+
idle_enabled = True if opts.idle_compaction is None else bool(opts.idle_compaction)
|
|
904
|
+
idle_min = max(int(opts.idle_min_tokens), 100_000) # the harness raises smaller values to 100k
|
|
905
|
+
# The logs only say how often idle compaction fires while it is on, and from when the harness had it: the first
|
|
906
|
+
# idle compaction seen (per harness). Before that, or with the setting off, no gap is an observation.
|
|
907
|
+
idle_since = {
|
|
908
|
+
h: min((c.ts for s in ss for c in s.compactions if c.idle and c.ts), default=None) if idle_enabled else None
|
|
909
|
+
for h, ss in by_harness.items()
|
|
910
|
+
}
|
|
911
|
+
pooled_idle = { # main sessions on the one-hour cache: the ones idle compaction is for
|
|
912
|
+
h: [
|
|
913
|
+
v
|
|
914
|
+
for s in ss
|
|
915
|
+
if s.role == "main" and _one_hour(s)
|
|
916
|
+
for v in idle_observations(s, idle_min, IDLE_AFTER_S, idle_since[h]).values()
|
|
917
|
+
]
|
|
918
|
+
for h, ss in by_harness.items()
|
|
919
|
+
}
|
|
920
|
+
out_groups = []
|
|
921
|
+
base_of: dict[int, int] = {} # id(session) -> its group's base tokens
|
|
922
|
+
shown: set[int] = set() # sessions the report can list (the group's SESSIONS_SHOWN largest): full-resolution growth
|
|
923
|
+
for gi, ((harness, model, role), ss) in enumerate(sorted(groups.items()), 1):
|
|
924
|
+
if progress:
|
|
925
|
+
progress(gi, len(groups), f"{model} · {role} ({len(ss)} sessions)")
|
|
926
|
+
platform = next(iter(Counter(s.platform for s in ss if s.platform).most_common(1)), (None, 0))[0]
|
|
927
|
+
list_price = pricing.lookup(model, platform)
|
|
928
|
+
platform = platform or list_price.platform # a Bedrock or Vertex ID names its platform itself
|
|
929
|
+
ttl, ttl_source = group_ttl(ss, opts.ttl_seconds, default_ttl)
|
|
930
|
+
price = list_price.for_ttl(ttl)
|
|
931
|
+
window, window_source, window_note = group_window(harness, model, ss, price.max_window, opts)
|
|
932
|
+
cap = effective_max(harness, window)
|
|
933
|
+
base = opts.base_tokens or min(max(_median([s.turns[0].ctx for s in ss], 35_000), 10_000), 80_000)
|
|
934
|
+
obs_summ = [c.summary_len // 4 for s in ss for c in s.compactions if c.summary_len]
|
|
935
|
+
summ = opts.summary_tokens or _median(obs_summ, 12_000)
|
|
936
|
+
pen = opts.penalty or calibrate(ss, base, summ)
|
|
937
|
+
tm = fit(ss, pooled.get(harness))
|
|
938
|
+
step_tokens = rediscovery_step(ss, pen)
|
|
939
|
+
turn_models = {t.model for s in ss for t in s.turns}
|
|
940
|
+
prices = {m: pricing.lookup(m, platform).for_ttl(ttl) for m in turn_models} if len(turn_models) > 1 else None
|
|
941
|
+
traces = [make_trace(s, base, data_end, idle_min, idle_since=idle_since[harness]) for s in ss]
|
|
942
|
+
# a conversation you step away from: the main session, on the one-hour cache
|
|
943
|
+
idle_applies = harness == "claude-code" and role == "main" and ttl >= IDLE_TTL_S
|
|
944
|
+
obs = [v for tr in traces for v in tr.idle_obs.values()]
|
|
945
|
+
rate, rate_scope, rate_fired, rate_eligible = idle_rate(obs, pooled_idle.get(harness, []))
|
|
946
|
+
c = Ctx(price, base, summ, ttl, pen, tm, step_tokens, rot, opts, prices, idle_on=idle_applies and idle_enabled,
|
|
947
|
+
idle_min=idle_min, idle_rate=rate) # fmt: skip
|
|
948
|
+
base_of.update({id(s): base for s in ss})
|
|
949
|
+
shown.update(id(s) for s in sorted(sorted(ss, key=lambda s: s.id), key=lambda s: -s.peak)[:SESSIONS_SHOWN])
|
|
950
|
+
grid = grid_for(opts, cap)
|
|
951
|
+
n_turns = sum(len(t.g) for t in traces)
|
|
952
|
+
pts = [_point(run_all(traces, T, c), T, n_turns) for T in grid]
|
|
953
|
+
rows: dict[str, list[Any]] = {k: [p[k] for p in pts] for k in ROW_KEYS}
|
|
954
|
+
tss = [t.ts for s in ss for t in s.turns if t.ts]
|
|
955
|
+
days = max((max(tss) - min(tss)) / 86400, 1.0) if tss else 1.0
|
|
956
|
+
# local dates with at least one turn, never more than the span (a 10.2-day span can touch 11 dates)
|
|
957
|
+
active_days = min(len({time.strftime("%Y-%m-%d", time.localtime(t)) for t in tss}) or 1, days)
|
|
958
|
+
|
|
959
|
+
d_thr, d_note = default_threshold(harness, model, window)
|
|
960
|
+
default = _point(run_all(traces, d_thr, c), d_thr, n_turns)
|
|
961
|
+
default["note"] = d_note
|
|
962
|
+
default["note_zh"] = default_note_zh(harness, model, window)
|
|
963
|
+
cur_val, cur_desc = (current or {}).get((harness, model), (None, ""))
|
|
964
|
+
cur = None
|
|
965
|
+
if cur_val is not None:
|
|
966
|
+
eff = min(cur_val, cap)
|
|
967
|
+
cur = _point(run_all(traces, eff, c), eff, n_turns)
|
|
968
|
+
cur["configured"] = cur_val
|
|
969
|
+
cur["source"] = cur_desc
|
|
970
|
+
|
|
971
|
+
pre = [x.pre_tokens for s in ss for x in s.compactions if x.pre_tokens and is_threshold(x)]
|
|
972
|
+
t_hist = _median(pre, 0) or None
|
|
973
|
+
drift = default_drift(ss, d_thr) if cur_val is None else None
|
|
974
|
+
hist_run = run_all(traces, float(t_hist) if t_hist else math.inf, c)
|
|
975
|
+
g: dict[str, Any] = {
|
|
976
|
+
"harness": harness,
|
|
977
|
+
"model": model,
|
|
978
|
+
"role": role,
|
|
979
|
+
"price_key": price.key,
|
|
980
|
+
"price_source": price.source,
|
|
981
|
+
"price_kind": price.kind,
|
|
982
|
+
"price": price_snapshot(list_price),
|
|
983
|
+
"platform": platform,
|
|
984
|
+
"cache_ttl": ttl,
|
|
985
|
+
"cache_ttl_source": ttl_source,
|
|
986
|
+
"n_sessions": len(ss),
|
|
987
|
+
"n_turns": n_turns,
|
|
988
|
+
"days": days,
|
|
989
|
+
"active_days": active_days,
|
|
990
|
+
"span": [min(tss), max(tss)] if tss else None,
|
|
991
|
+
"max_window": window,
|
|
992
|
+
"window_source": window_source,
|
|
993
|
+
"window_note": window_note,
|
|
994
|
+
"default_drift": drift,
|
|
995
|
+
"effective_max": cap,
|
|
996
|
+
"base_tokens": base,
|
|
997
|
+
"summary_tokens": summ,
|
|
998
|
+
"penalty_params": pen.to_dict(),
|
|
999
|
+
"time_model": tm.summary(),
|
|
1000
|
+
"observed_compactions": sum(is_threshold(c) for s in ss for c in s.compactions),
|
|
1001
|
+
"observed_idle_compactions": sum(c.idle for s in ss for c in s.compactions),
|
|
1002
|
+
"observed_manual_compactions": sum(not is_auto(c) for s in ss for c in s.compactions),
|
|
1003
|
+
"peak_p50": _median([s.peak for s in ss], 0),
|
|
1004
|
+
"peak_max": max(s.peak for s in ss),
|
|
1005
|
+
"grid": grid,
|
|
1006
|
+
**rows,
|
|
1007
|
+
"baseline_cost": run_all(traces, math.inf, c).cost,
|
|
1008
|
+
"actual_cost": sum(_session_actual_cost(s, pricing) for s in ss),
|
|
1009
|
+
"default": default,
|
|
1010
|
+
"current": cur,
|
|
1011
|
+
"current_note": cur_desc,
|
|
1012
|
+
"no_action_needed": no_action(default),
|
|
1013
|
+
"history": {
|
|
1014
|
+
"threshold": t_hist,
|
|
1015
|
+
"combined_cost": hist_run.cost + hist_run.penalty,
|
|
1016
|
+
"time_s": hist_run.time_s,
|
|
1017
|
+
"cost": hist_run.cost,
|
|
1018
|
+
"recall": hist_run.recall_sum / max(n_turns, 1),
|
|
1019
|
+
},
|
|
1020
|
+
"hist": _hist([t.ctx for s in ss for t in s.turns], window),
|
|
1021
|
+
}
|
|
1022
|
+
select_group(g, opt_d)
|
|
1023
|
+
g["idle"] = {
|
|
1024
|
+
"applies": idle_applies,
|
|
1025
|
+
"enabled": idle_enabled,
|
|
1026
|
+
"min_tokens": idle_min,
|
|
1027
|
+
"after_s": IDLE_AFTER_S,
|
|
1028
|
+
"configured": opts.idle_compaction is not None,
|
|
1029
|
+
"rate": rate,
|
|
1030
|
+
"rate_scope": rate_scope, # "group" | "harness" | "assumed"
|
|
1031
|
+
"rate_fired": rate_fired,
|
|
1032
|
+
"rate_eligible": rate_eligible,
|
|
1033
|
+
}
|
|
1034
|
+
if idle_applies: # the same sweep with the setting flipped, kept so a saved result can be re-selected
|
|
1035
|
+
ca = dataclasses.replace(c, idle_on=not c.idle_on)
|
|
1036
|
+
apts = [_point(run_all(traces, T, ca), T, n_turns) for T in grid]
|
|
1037
|
+
acur = None
|
|
1038
|
+
if cur is not None:
|
|
1039
|
+
acur = {**cur, **_point(run_all(traces, cur["threshold"], ca), cur["threshold"], n_turns)}
|
|
1040
|
+
g["idle"]["alt"] = {
|
|
1041
|
+
"enabled": not idle_enabled,
|
|
1042
|
+
"rows": {k: [p[k] for p in apts] for k in ROW_KEYS},
|
|
1043
|
+
"default_point": {**_point(run_all(traces, d_thr, ca), d_thr, n_turns), "note": d_note},
|
|
1044
|
+
"current_point": acur,
|
|
1045
|
+
}
|
|
1046
|
+
idle_select(g)
|
|
1047
|
+
out_groups.append(g)
|
|
1048
|
+
keys = global_keys(out_groups, opt_d) # before the notes: it marks superseded models
|
|
1049
|
+
return {
|
|
1050
|
+
"schema": 4,
|
|
1051
|
+
"mode": "lite",
|
|
1052
|
+
"data_through": max((t.ts for s in sessions for t in s.turns if t.ts), default=None),
|
|
1053
|
+
"options": opt_d,
|
|
1054
|
+
"pricing_note": pricing.data.get("note", ""),
|
|
1055
|
+
"groups": out_groups,
|
|
1056
|
+
"idle_compaction": idle_advice(out_groups, opt_d),
|
|
1057
|
+
"global_keys": keys,
|
|
1058
|
+
"model_notes": {**model_notes(out_groups), "fallback": dict(pricing.data["fallback"])},
|
|
1059
|
+
"sessions": [
|
|
1060
|
+
{
|
|
1061
|
+
"id": s.id,
|
|
1062
|
+
"harness": s.harness,
|
|
1063
|
+
"role": s.role,
|
|
1064
|
+
"model": s.model,
|
|
1065
|
+
"turns": len(s.turns),
|
|
1066
|
+
"peak": s.peak,
|
|
1067
|
+
"compactions": len(s.compactions),
|
|
1068
|
+
"curve": _downsample([t.ctx for t in s.turns], 160),
|
|
1069
|
+
# the in-browser replay needs every turn: binned growth would count bins as turns
|
|
1070
|
+
"growth": make_trace(s, base_of[id(s)]).g if id(s) in shown else [],
|
|
1071
|
+
"manual": make_trace(s, base_of[id(s)]).manual if id(s) in shown else {},
|
|
1072
|
+
"unknown_events": s.unknown_events,
|
|
1073
|
+
"skipped_inherited": s.skipped_inherited,
|
|
1074
|
+
}
|
|
1075
|
+
for s in sorted(sessions, key=lambda s: (s.harness, s.role, s.id))
|
|
1076
|
+
],
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
|
|
1080
|
+
def _downsample(xs: list[int], n: int) -> list[int]:
|
|
1081
|
+
if len(xs) <= n:
|
|
1082
|
+
return xs
|
|
1083
|
+
step = len(xs) / n
|
|
1084
|
+
return [xs[int(i * step)] for i in range(n)]
|
|
1085
|
+
|
|
1086
|
+
|
|
1087
|
+
def group_ttl(ss: list[Session], override: int | None, default: int) -> tuple[int, str]:
|
|
1088
|
+
"""Cache TTL to replay a group with: the override, else the tier most cache-write tokens were billed at."""
|
|
1089
|
+
if override:
|
|
1090
|
+
return override, "--cache-ttl"
|
|
1091
|
+
written = sum(t.cache_write for s in ss for t in s.turns)
|
|
1092
|
+
hour = sum(t.cache_write_1h for s in ss for t in s.turns)
|
|
1093
|
+
if not hour:
|
|
1094
|
+
return default, "pricing default"
|
|
1095
|
+
return (3600 if hour * 2 >= written else default), f"logs: {hour / written:.0%} of cache writes at the 1-hour tier"
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def _session_actual_cost(s: Session, pricing: PricingTable) -> float:
|
|
1099
|
+
"""`_actual_cost` with every turn at its own model's price (a session may switch models)."""
|
|
1100
|
+
by_model: dict[str, list[Turn]] = defaultdict(list)
|
|
1101
|
+
for t in s.turns:
|
|
1102
|
+
by_model[t.model].append(t)
|
|
1103
|
+
return sum(
|
|
1104
|
+
_actual_cost(Session(s.id, s.harness, s.role, s.path, turns=ts), pricing.lookup(m, s.platform))
|
|
1105
|
+
for m, ts in by_model.items()
|
|
1106
|
+
)
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def _actual_cost(s: Session, price: Price) -> float:
|
|
1110
|
+
"""What the logged requests cost at list price, each cache write at the tier it was billed at."""
|
|
1111
|
+
hour = price.for_ttl(3600)
|
|
1112
|
+
c = 0.0
|
|
1113
|
+
for t in s.turns:
|
|
1114
|
+
ri, ro, rw, rr = price.rates(t.ctx)
|
|
1115
|
+
rw1 = hour.rates(t.ctx)[2]
|
|
1116
|
+
w5 = t.cache_write - t.cache_write_1h
|
|
1117
|
+
c += max(t.ctx - t.cache_read - t.cache_write, 0) * ri + t.cache_read * rr + w5 * rw + t.cache_write_1h * rw1
|
|
1118
|
+
c += t.output * ro
|
|
1119
|
+
return c
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def _hist(ctxs: list[int], max_window: int, size: int = 50_000) -> dict:
|
|
1123
|
+
n = max(max_window // size, 1)
|
|
1124
|
+
turns, tok = [0] * n, [0] * n
|
|
1125
|
+
for x in ctxs:
|
|
1126
|
+
i = min(x // size, n - 1)
|
|
1127
|
+
turns[i] += 1
|
|
1128
|
+
tok[i] += x
|
|
1129
|
+
tt, ts = max(sum(turns), 1), max(sum(tok), 1)
|
|
1130
|
+
return {"bin": size, "turns": [v / tt for v in turns], "share": [v / ts for v in tok]}
|