@giamme/forge 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/VERSION +1 -1
- package/docs/dataset.md +8 -0
- package/docs/reviews.md +15 -1
- package/package.json +1 -1
- package/references/dataset.md +124 -5
- package/references/decision-models.md +15 -2
- package/references/decompose.md +46 -10
- package/references/planning.md +3 -2
- package/scripts/forge-contract.py +52 -1
- package/scripts/forge-issues.py +4 -3
- package/scripts/forge-ledger.py +3 -1
- package/scripts/forge-lib-adopt.sh +7 -1
- package/scripts/forge-metrics.sh +22 -0
- package/scripts/forge-parallel.sh +3 -1
- package/scripts/forge-plan-check.py +25 -2
- package/scripts/forge-planner.py +20 -6
- package/scripts/forge-shadow.py +28 -9
- package/scripts/forge-sweep.py +25 -10
- package/scripts/forge_dataset/cli.py +83 -0
- package/scripts/forge_dataset/facts.py +278 -0
- package/scripts/forge_dataset/harvest.py +16 -3
- package/scripts/forge_dataset/outcomes.py +206 -58
- package/scripts/forge_dataset/pairs.py +174 -0
- package/scripts/forge_dataset/risk.py +108 -0
- package/scripts/forge_dataset/tiers.py +427 -0
- package/scripts/forge_decide/cli.py +23 -2
- package/scripts/forge_decide/labels.py +30 -6
- package/scripts/forge_decide/replay.py +10 -4
- package/ui/docs/api.md +12 -3
- package/ui/forge_ui/export.py +9 -2
- package/ui/forge_ui/findings.py +4 -2
- package/ui/forge_ui/reader.py +71 -4
- package/ui/forge_ui/server.py +8 -0
- package/ui/forge_ui/static/app.js +6 -1
- package/ui/forge_ui/static/diffview.js +7 -3
- package/ui/forge_ui/static/panel.js +43 -2
- package/ui/forge_ui/static/style.css +1 -0
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""`forge dataset tiers`: what explains results inside a difficulty tier (#123), before anyone adds a tier.
|
|
2
|
+
|
|
3
|
+
Difficulty works as a label, but `high` holds most of the unfinished tasks and may mix groups that behave
|
|
4
|
+
very differently. This report looks inside each tier with only what the dataset already has, and changes
|
|
5
|
+
nothing in a run.
|
|
6
|
+
|
|
7
|
+
Population: the tasks `forge dataset routing` counts, whose first attempt says something about the
|
|
8
|
+
implementer (fractal runs left out). Each task is described by:
|
|
9
|
+
|
|
10
|
+
plan time known before dispatch, so a rule could route on it: declared files, dependencies, wave,
|
|
11
|
+
the size of the task's prompt (KB)
|
|
12
|
+
afterwards known only once the first attempt ran, so it can explain a result but never route one:
|
|
13
|
+
lines in that attempt's diff, files it changed
|
|
14
|
+
|
|
15
|
+
and three outcomes: first attempt passed, attempts taken, unfinished (never passed and not accepted).
|
|
16
|
+
|
|
17
|
+
For each fact inside a tier:
|
|
18
|
+
|
|
19
|
+
bins the tier split into thirds of that fact, each with tasks, runs, first pass (Wilson 95%),
|
|
20
|
+
mean attempts and unfinished. Descriptive: a run's tasks are correlated and routing chose
|
|
21
|
+
who ran what, so read the intervals as optimistic.
|
|
22
|
+
held out whether a split on the fact predicts an outcome on runs it never saw. Runs go to FOLDS
|
|
23
|
+
folds by a hash of their id. On the other folds' runs, each candidate threshold (the
|
|
24
|
+
training values' quartiles) is scored on outcomes adjusted for the implementer: an
|
|
25
|
+
outcome minus its model's mean in that tier, shrunk toward the tier's mean by SHRINK
|
|
26
|
+
tasks, so a harder model mix is not read as harder tasks. The best threshold, and the
|
|
27
|
+
side it says scores higher, is then applied to the held-out runs, adjusted by the
|
|
28
|
+
training runs' model means. `lift` is the held-out difference between the side
|
|
29
|
+
predicted higher and the other, in the outcome's units; above 0 means the training
|
|
30
|
+
direction held. Its interval resamples held-out runs (BOOTSTRAP draws). A tier with
|
|
31
|
+
fewer than MIN_RUNS runs, or no threshold leaving MIN_SIDE tasks on each side, gets
|
|
32
|
+
none.
|
|
33
|
+
|
|
34
|
+
Repos are listed per tier too (first pass and the implementer-adjusted residual, with a run bootstrap),
|
|
35
|
+
but not held out: a repo's runs mostly sit in that repo, so a fold would just learn the repo.
|
|
36
|
+
|
|
37
|
+
Label noise: `--sample N --out DIR` writes N past task prompts (one task per run where it can, tiers
|
|
38
|
+
hidden) to DIR/prompts/<n>.md and DIR/sample.tsv; whoever rates them blind writes DIR/ratings.tsv as
|
|
39
|
+
`<n><TAB>low|medium|high`. `--blind DIR` then reports how often the blind rating matches the recorded
|
|
40
|
+
tier (Wilson 95%), Cohen's kappa and the confusion table. Rating costs model calls or a person's time,
|
|
41
|
+
so this report never starts one.
|
|
42
|
+
|
|
43
|
+
Advisory only: nothing that routes or plans reads it.
|
|
44
|
+
"""
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import hashlib
|
|
48
|
+
import json
|
|
49
|
+
import os
|
|
50
|
+
import random
|
|
51
|
+
import statistics
|
|
52
|
+
from collections import Counter, defaultdict
|
|
53
|
+
from pathlib import Path
|
|
54
|
+
|
|
55
|
+
from . import connect, dataset_dir
|
|
56
|
+
from .export import Runs, Store, _attempts
|
|
57
|
+
from .facts import _kappa
|
|
58
|
+
from .harvest import split_list
|
|
59
|
+
from .routing import tasks as routing_tasks, wilson
|
|
60
|
+
|
|
61
|
+
LEVELS = ('low', 'medium', 'high')
|
|
62
|
+
OUTCOMES = ('first_pass', 'attempts', 'unfinished')
|
|
63
|
+
PLAN_FACTS = ('files', 'deps', 'wave', 'prompt_kb')
|
|
64
|
+
AFTER_FACTS = ('diff_lines', 'changed_files')
|
|
65
|
+
FOLDS = 5
|
|
66
|
+
MIN_RUNS = 10
|
|
67
|
+
MIN_SIDE = 5
|
|
68
|
+
SHRINK = 5
|
|
69
|
+
BOOTSTRAP = 1000
|
|
70
|
+
MIN_REPO = 10
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _fold(run) -> int:
|
|
74
|
+
return int(hashlib.sha1(str(run).encode()).hexdigest(), 16) % FOLDS
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _held(runs: Runs) -> dict:
|
|
78
|
+
"""(run, task) -> (plan revision, row): the latest revision that held the task, as routing reads it."""
|
|
79
|
+
held = {}
|
|
80
|
+
for run, revisions in runs.plans.items():
|
|
81
|
+
for plan in revisions:
|
|
82
|
+
for tid, row in (plan['d'].get('tasks') or {}).items():
|
|
83
|
+
held[(run, tid)] = (plan, row)
|
|
84
|
+
return held
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _diff(first) -> tuple:
|
|
88
|
+
for e in reversed(first['events']):
|
|
89
|
+
numstat = e['d'].get('numstat')
|
|
90
|
+
if isinstance(numstat, dict) and (numstat or e['d'].get('changed_files') is not None):
|
|
91
|
+
lines = sum(x for counts in numstat.values() if isinstance(counts, (list, tuple))
|
|
92
|
+
for x in counts if isinstance(x, int))
|
|
93
|
+
return lines, len(e['d'].get('changed_files') or numstat)
|
|
94
|
+
return None, None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _repo_name(runs: Runs, repo, names) -> str | None:
|
|
98
|
+
if repo is None:
|
|
99
|
+
return None
|
|
100
|
+
if names and names.get(repo):
|
|
101
|
+
return names[repo]
|
|
102
|
+
path = runs.store.repo_paths.get(repo)
|
|
103
|
+
return os.path.basename(path.rstrip('/')) if path else repo
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def records(runs: Runs, repo: str = None, names: dict = None) -> list:
|
|
107
|
+
held = _held(runs)
|
|
108
|
+
out = []
|
|
109
|
+
for r in routing_tasks(runs, repo=repo):
|
|
110
|
+
if r['first_pass'] is None or r['tier'] not in LEVELS or (r['run'], r['task']) not in held:
|
|
111
|
+
continue
|
|
112
|
+
plan, row = held[(r['run'], r['task'])]
|
|
113
|
+
attempts = _attempts(runs, r['run'], r['task'], runs.attempts.get((r['run'], r['task']), []))
|
|
114
|
+
lines, changed = _diff(attempts[0]) if attempts else (None, None)
|
|
115
|
+
prompt = runs.store.text(row.get('prompt')) or ''
|
|
116
|
+
wave = (plan['d'].get('waves') or {}).get(r['task'])
|
|
117
|
+
out.append(dict(
|
|
118
|
+
run=r['run'], task=r['task'], tier=r['tier'], model=r['model'] or r['ran'] or '?',
|
|
119
|
+
repo=_repo_name(runs, plan.get('repo'), names),
|
|
120
|
+
first_pass=int(bool(r['first_pass'])), attempts=r['attempts'], unfinished=int(not r['passed']),
|
|
121
|
+
facts=dict(files=len(split_list(row.get('files'))), deps=len(split_list(row.get('deps'))),
|
|
122
|
+
wave=wave if isinstance(wave, int) else None,
|
|
123
|
+
prompt_kb=round(len(prompt.encode()) / 1024, 1) if prompt.strip() else None,
|
|
124
|
+
diff_lines=lines, changed_files=changed)))
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _summary(rows) -> dict:
|
|
129
|
+
n = len(rows)
|
|
130
|
+
k = sum(r['first_pass'] for r in rows)
|
|
131
|
+
low, high = wilson(k, n)
|
|
132
|
+
return dict(tasks=n, runs=len({r['run'] for r in rows}), first_pass=k / n if n else None,
|
|
133
|
+
ci=[low, high], attempts=statistics.mean(r['attempts'] for r in rows) if n else None,
|
|
134
|
+
unfinished=sum(r['unfinished'] for r in rows))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _bins(rows, fact) -> list:
|
|
138
|
+
rows = sorted((r for r in rows if r['facts'][fact] is not None), key=lambda r: r['facts'][fact])
|
|
139
|
+
values = [r['facts'][fact] for r in rows]
|
|
140
|
+
if not values:
|
|
141
|
+
return []
|
|
142
|
+
cuts = sorted(set(statistics.quantiles(values, n=3, method='inclusive'))) if len(set(values)) > 1 else []
|
|
143
|
+
groups = defaultdict(list)
|
|
144
|
+
for r in rows:
|
|
145
|
+
groups[sum(r['facts'][fact] > c for c in cuts)].append(r)
|
|
146
|
+
out = []
|
|
147
|
+
for _, group in sorted(groups.items()):
|
|
148
|
+
lo, hi = group[0]['facts'][fact], group[-1]['facts'][fact]
|
|
149
|
+
out.append(dict(_summary(group), lo=lo, hi=hi))
|
|
150
|
+
return out
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _residuals(rows, outcome, train) -> list:
|
|
154
|
+
base = statistics.mean(r[outcome] for r in train)
|
|
155
|
+
by = defaultdict(list)
|
|
156
|
+
for r in train:
|
|
157
|
+
by[r['model']].append(r[outcome])
|
|
158
|
+
means = {m: (sum(v) + SHRINK * base) / (len(v) + SHRINK) for m, v in by.items()}
|
|
159
|
+
return [r[outcome] - means.get(r['model'], base) for r in rows]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _candidates(values) -> list:
|
|
163
|
+
return sorted(set(statistics.quantiles(values, n=4, method='inclusive'))) if len(set(values)) > 1 else []
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _lift(per_run, chosen) -> float | None:
|
|
167
|
+
hi_n = hi_s = lo_n = lo_s = 0
|
|
168
|
+
for run in chosen:
|
|
169
|
+
a, b, c, d = per_run[run]
|
|
170
|
+
hi_n, hi_s, lo_n, lo_s = hi_n + a, hi_s + b, lo_n + c, lo_s + d
|
|
171
|
+
return hi_s / hi_n - lo_s / lo_n if hi_n and lo_n else None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def heldout(rows, fact, outcome, seed: int = 7) -> dict:
|
|
175
|
+
rows = [r for r in rows if r['facts'][fact] is not None]
|
|
176
|
+
runs = {r['run'] for r in rows}
|
|
177
|
+
if len(runs) < MIN_RUNS:
|
|
178
|
+
return dict(lift=None, reason='under %d runs' % MIN_RUNS, runs=len(runs))
|
|
179
|
+
per_run = defaultdict(lambda: [0, 0.0, 0, 0.0])
|
|
180
|
+
picks = Counter()
|
|
181
|
+
for k in range(FOLDS):
|
|
182
|
+
train = [r for r in rows if _fold(r['run']) != k]
|
|
183
|
+
test = [r for r in rows if _fold(r['run']) == k]
|
|
184
|
+
if not train or not test:
|
|
185
|
+
continue
|
|
186
|
+
res = _residuals(train, outcome, train)
|
|
187
|
+
best = None
|
|
188
|
+
for t in _candidates([r['facts'][fact] for r in train]):
|
|
189
|
+
above = [e for r, e in zip(train, res) if r['facts'][fact] > t]
|
|
190
|
+
below = [e for r, e in zip(train, res) if r['facts'][fact] <= t]
|
|
191
|
+
if len(above) < MIN_SIDE or len(below) < MIN_SIDE:
|
|
192
|
+
continue
|
|
193
|
+
d = statistics.mean(above) - statistics.mean(below)
|
|
194
|
+
if best is None or abs(d) > abs(best[1]):
|
|
195
|
+
best = (t, d)
|
|
196
|
+
if best is None:
|
|
197
|
+
continue
|
|
198
|
+
t, d = best
|
|
199
|
+
picks[(t, d > 0)] += 1
|
|
200
|
+
for r, e in zip(test, _residuals(test, outcome, train)):
|
|
201
|
+
cell = per_run[r['run']]
|
|
202
|
+
if (r['facts'][fact] > t) == (d > 0):
|
|
203
|
+
cell[0] += 1
|
|
204
|
+
cell[1] += e
|
|
205
|
+
else:
|
|
206
|
+
cell[2] += 1
|
|
207
|
+
cell[3] += e
|
|
208
|
+
scored = sorted(per_run)
|
|
209
|
+
lift = _lift(per_run, scored)
|
|
210
|
+
if lift is None:
|
|
211
|
+
return dict(lift=None, reason='no split leaves %d tasks a side' % MIN_SIDE, runs=len(runs))
|
|
212
|
+
rng = random.Random(seed)
|
|
213
|
+
draws = sorted(x for x in (_lift(per_run, [rng.choice(scored) for _ in scored]) for _ in range(BOOTSTRAP))
|
|
214
|
+
if x is not None)
|
|
215
|
+
(t, above_higher), folds = picks.most_common(1)[0]
|
|
216
|
+
return dict(lift=lift, ci=[draws[int(0.025 * len(draws))], draws[int(0.975 * len(draws)) - 1]] if draws else None,
|
|
217
|
+
tasks=sum(per_run[r][0] + per_run[r][2] for r in scored), runs=len(scored),
|
|
218
|
+
threshold=t, above_higher=above_higher, folds=folds, of=sum(picks.values()))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _repos(rows, seed: int = 7) -> list:
|
|
222
|
+
res = dict(zip((id(r) for r in rows), _residuals(rows, 'first_pass', rows))) if rows else {}
|
|
223
|
+
counts = Counter(r['repo'] for r in rows)
|
|
224
|
+
groups = defaultdict(list)
|
|
225
|
+
for r in rows:
|
|
226
|
+
groups[r['repo'] if counts[r['repo']] >= MIN_REPO else None].append(r)
|
|
227
|
+
out = []
|
|
228
|
+
rng = random.Random(seed)
|
|
229
|
+
for name, group in sorted(groups.items(), key=lambda kv: (kv[0] is None, -len(kv[1]), str(kv[0]))):
|
|
230
|
+
by_run = defaultdict(list)
|
|
231
|
+
for r in group:
|
|
232
|
+
by_run[r['run']].append(res[id(r)])
|
|
233
|
+
keys = sorted(by_run)
|
|
234
|
+
draws = []
|
|
235
|
+
for _ in range(BOOTSTRAP):
|
|
236
|
+
pick = [x for _ in keys for x in by_run[rng.choice(keys)]]
|
|
237
|
+
draws.append(sum(pick) / len(pick))
|
|
238
|
+
draws.sort()
|
|
239
|
+
values = [res[id(r)] for r in group]
|
|
240
|
+
out.append(dict(_summary(group), repo=name, adjusted=sum(values) / len(values),
|
|
241
|
+
adjusted_ci=[draws[int(0.025 * BOOTSTRAP)], draws[int(0.975 * BOOTSTRAP) - 1]]))
|
|
242
|
+
return out
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def tier_report(rows) -> dict:
|
|
246
|
+
facts = []
|
|
247
|
+
for phase, names in (('plan', PLAN_FACTS), ('after', AFTER_FACTS)):
|
|
248
|
+
for fact in names:
|
|
249
|
+
facts.append(dict(fact=fact, phase=phase, known=sum(r['facts'][fact] is not None for r in rows),
|
|
250
|
+
bins=_bins(rows, fact), heldout={o: heldout(rows, fact, o) for o in OUTCOMES}))
|
|
251
|
+
return dict(_summary(rows), facts=facts, repos=_repos(rows))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _recorded(runs: Runs) -> dict:
|
|
255
|
+
return {key: row.get('declared_difficulty') or row.get('difficulty') for key, (_, row) in _held(runs).items()}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def sample(runs: Runs, n: int, out: Path, seed: int = 7) -> int:
|
|
259
|
+
"""Write n past prompts for blind rating, spread one task per run before any run gives a second."""
|
|
260
|
+
out = Path(out)
|
|
261
|
+
if out.exists() and any(out.iterdir()):
|
|
262
|
+
raise SystemExit('forge dataset tiers: %s is not empty; pick a new directory' % out)
|
|
263
|
+
recorded = _recorded(runs)
|
|
264
|
+
held = _held(runs)
|
|
265
|
+
by_run = defaultdict(list)
|
|
266
|
+
for (run, task), tier in sorted(recorded.items()):
|
|
267
|
+
if tier in LEVELS and (runs.store.text(held[(run, task)][1].get('prompt')) or '').strip():
|
|
268
|
+
by_run[run].append(task)
|
|
269
|
+
rng = random.Random(seed)
|
|
270
|
+
queues = [[(run, task) for task in rng.sample(by_run[run], len(by_run[run]))]
|
|
271
|
+
for run in rng.sample(sorted(by_run), len(by_run))]
|
|
272
|
+
chosen = []
|
|
273
|
+
while len(chosen) < n and any(queues):
|
|
274
|
+
for queue in queues:
|
|
275
|
+
if queue and len(chosen) < n:
|
|
276
|
+
chosen.append(queue.pop(0))
|
|
277
|
+
(out / 'prompts').mkdir(parents=True, exist_ok=True)
|
|
278
|
+
lines = ['# n\trun\ttask (rate prompts/<n>.md blind; write ratings.tsv as <n><TAB>low|medium|high)']
|
|
279
|
+
for i, (run, task) in enumerate(chosen, 1):
|
|
280
|
+
(out / 'prompts' / ('%d.md' % i)).write_text(runs.store.text(held[(run, task)][1].get('prompt')))
|
|
281
|
+
lines.append('%d\t%s\t%s' % (i, run, task))
|
|
282
|
+
(out / 'sample.tsv').write_text('\n'.join(lines) + '\n')
|
|
283
|
+
return len(chosen)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def blind(runs: Runs, where: Path) -> dict:
|
|
287
|
+
where = Path(where)
|
|
288
|
+
numbered = {}
|
|
289
|
+
for line in (where / 'sample.tsv').read_text().splitlines():
|
|
290
|
+
cells = line.split('\t')
|
|
291
|
+
if len(cells) >= 3 and cells[0].isdigit():
|
|
292
|
+
numbered[cells[0]] = (cells[1], cells[2])
|
|
293
|
+
recorded = _recorded(runs)
|
|
294
|
+
pairs, unknown, invalid = [], 0, 0
|
|
295
|
+
for line in (where / 'ratings.tsv').read_text().splitlines():
|
|
296
|
+
cells = line.strip().split('\t')
|
|
297
|
+
if len(cells) < 2 or not cells[0].isdigit():
|
|
298
|
+
continue
|
|
299
|
+
rating = cells[1].strip().lower()
|
|
300
|
+
key = numbered.get(cells[0])
|
|
301
|
+
if rating not in LEVELS:
|
|
302
|
+
invalid += 1
|
|
303
|
+
elif key is None or recorded.get(key) not in LEVELS:
|
|
304
|
+
unknown += 1
|
|
305
|
+
else:
|
|
306
|
+
pairs.append((recorded[key], rating))
|
|
307
|
+
agree = sum(a == b for a, b in pairs)
|
|
308
|
+
low, high = wilson(agree, len(pairs))
|
|
309
|
+
kappa = _kappa(pairs)
|
|
310
|
+
confusion = {a: {b: sum(1 for x, y in pairs if (x, y) == (a, b)) for b in LEVELS} for a in LEVELS}
|
|
311
|
+
return dict(rated=len(pairs), agree=agree, rate=agree / len(pairs) if pairs else None, ci=[low, high],
|
|
312
|
+
kappa=None if kappa is None else round(kappa, 3), confusion=confusion, unknown=unknown, invalid=invalid)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def report(runs: Runs, repo: str = None, names: dict = None, tier: str = None) -> dict:
|
|
316
|
+
rows = records(runs, repo=repo, names=names)
|
|
317
|
+
tiers = {}
|
|
318
|
+
for level in LEVELS:
|
|
319
|
+
group = [r for r in rows if r['tier'] == level]
|
|
320
|
+
if group and (tier is None or tier == level):
|
|
321
|
+
tiers[level] = tier_report(group)
|
|
322
|
+
return dict(tasks=len(rows), runs=len({r['run'] for r in rows}), tiers=tiers,
|
|
323
|
+
settings=dict(folds=FOLDS, min_runs=MIN_RUNS, min_side=MIN_SIDE, shrink=SHRINK, bootstrap=BOOTSTRAP))
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _names(db) -> dict:
|
|
327
|
+
out = {}
|
|
328
|
+
for repo, origin, path in db.execute('SELECT repo, origin, path FROM repos'):
|
|
329
|
+
source = (origin or '').rstrip('/') or (path or '').rstrip('/')
|
|
330
|
+
name = source.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
|
|
331
|
+
out[repo] = name[:-4] if name.endswith('.git') else (name or None)
|
|
332
|
+
return out
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _runs():
|
|
336
|
+
if not (dataset_dir() / 'dataset.sqlite').exists():
|
|
337
|
+
return None, {}
|
|
338
|
+
db = connect()
|
|
339
|
+
try:
|
|
340
|
+
return Runs(Store(db)), _names(db)
|
|
341
|
+
finally:
|
|
342
|
+
db.close()
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _pct(x):
|
|
346
|
+
return '-' if x is None else '%.0f%%' % (100 * x)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _signed(x, outcome):
|
|
350
|
+
return ('%+.0f pts' % (100 * x)) if outcome != 'attempts' else '%+.2f' % x
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _range(b):
|
|
354
|
+
return ('%g' % b['lo']) if b['lo'] == b['hi'] else '%g-%g' % (b['lo'], b['hi'])
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _line(s):
|
|
358
|
+
return '%4d tasks %3d runs first pass %4s (%s-%s) %.2f attempts %d unfinished' % (
|
|
359
|
+
s['tasks'], s['runs'], _pct(s['first_pass']), _pct(s['ci'][0]), _pct(s['ci'][1]), s['attempts'], s['unfinished'])
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _held_line(fact, outcome, h):
|
|
363
|
+
if h.get('lift') is None:
|
|
364
|
+
return '%s: none (%s)' % (outcome.replace('_', ' '), h['reason'])
|
|
365
|
+
side = ('> %g' if h['above_higher'] else '<= %g') % h['threshold']
|
|
366
|
+
ci = ' [%s, %s]' % (_signed(h['ci'][0], outcome), _signed(h['ci'][1], outcome)) if h.get('ci') else ''
|
|
367
|
+
return '%s %s%s, higher at %s %s (%d/%d folds), %d runs' % (
|
|
368
|
+
outcome.replace('_', ' '), _signed(h['lift'], outcome), ci, fact, side, h['folds'], h['of'], h['runs'])
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def main(args) -> int:
|
|
372
|
+
runs, names = _runs()
|
|
373
|
+
if getattr(args, 'sample', None):
|
|
374
|
+
if not args.out:
|
|
375
|
+
raise SystemExit('forge dataset tiers: --sample needs --out DIR')
|
|
376
|
+
if runs is None:
|
|
377
|
+
raise SystemExit('forge dataset tiers: no dataset yet')
|
|
378
|
+
n = sample(runs, args.sample, Path(args.out))
|
|
379
|
+
print('wrote %d prompts to %s/prompts; rate them blind into %s/ratings.tsv, then: forge dataset tiers --blind %s'
|
|
380
|
+
% (n, args.out, args.out, args.out))
|
|
381
|
+
return 0
|
|
382
|
+
if getattr(args, 'blind', None):
|
|
383
|
+
if runs is None:
|
|
384
|
+
raise SystemExit('forge dataset tiers: no dataset yet')
|
|
385
|
+
rep = blind(runs, Path(args.blind))
|
|
386
|
+
if args.json:
|
|
387
|
+
print(json.dumps(rep, indent=2, sort_keys=True))
|
|
388
|
+
return 0
|
|
389
|
+
print('blind ratings: %d matched to a recorded tier%s' % (
|
|
390
|
+
rep['rated'], ''.join(', %d %s' % (rep[k], k) for k in ('unknown', 'invalid') if rep[k])))
|
|
391
|
+
if rep['rated']:
|
|
392
|
+
kappa = '' if rep['kappa'] is None else ', kappa %.2f' % rep['kappa']
|
|
393
|
+
print(' agree %d of %d: %s (%s-%s)%s' % (rep['agree'], rep['rated'], _pct(rep['rate']),
|
|
394
|
+
_pct(rep['ci'][0]), _pct(rep['ci'][1]), kappa))
|
|
395
|
+
print(' %-10s %s' % ('recorded', ' '.join('%7s' % b for b in LEVELS)))
|
|
396
|
+
for a in LEVELS:
|
|
397
|
+
print(' %-10s %s' % (a, ' '.join('%7d' % rep['confusion'][a][b] for b in LEVELS)))
|
|
398
|
+
return 0
|
|
399
|
+
rep = report(runs, repo=os.path.realpath(args.repo) if args.repo else None, names=names,
|
|
400
|
+
tier=getattr(args, 'tier', None)) if runs else report_empty()
|
|
401
|
+
if args.json:
|
|
402
|
+
print(json.dumps(rep, indent=2, sort_keys=True))
|
|
403
|
+
return 0
|
|
404
|
+
print('tiers: %d tasks whose first attempt says something, in %d runs; advisory only' % (rep['tasks'], rep['runs']))
|
|
405
|
+
if not rep['tasks']:
|
|
406
|
+
return 0
|
|
407
|
+
for level, t in rep['tiers'].items():
|
|
408
|
+
print()
|
|
409
|
+
print('%s: %s' % (level, _line(t).strip()))
|
|
410
|
+
for f in t['facts']:
|
|
411
|
+
print(' %s (%s, known for %d)' % (f['fact'], 'plan time' if f['phase'] == 'plan' else 'afterwards', f['known']))
|
|
412
|
+
for b in f['bins']:
|
|
413
|
+
print(' %-10s %s' % (_range(b), _line(b)))
|
|
414
|
+
for o in OUTCOMES:
|
|
415
|
+
print(' held out: %s' % _held_line(f['fact'], o, f['heldout'][o]))
|
|
416
|
+
print(' repos (first pass; adjusted = vs the same implementers elsewhere in the tier)')
|
|
417
|
+
for r in t['repos']:
|
|
418
|
+
print(' %-28s %s adjusted %s [%s, %s]' % (
|
|
419
|
+
(r['repo'] or 'other (under %d tasks each)' % MIN_REPO)[:28], _line(r),
|
|
420
|
+
_signed(r['adjusted'], 'first_pass'), _signed(r['adjusted_ci'][0], 'first_pass'),
|
|
421
|
+
_signed(r['adjusted_ci'][1], 'first_pass')))
|
|
422
|
+
return 0
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def report_empty() -> dict:
|
|
426
|
+
return dict(tasks=0, runs=0, tiers={},
|
|
427
|
+
settings=dict(folds=FOLDS, min_runs=MIN_RUNS, min_side=MIN_SIDE, shrink=SHRINK, bootstrap=BOOTSTRAP))
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
doctor [--live] [--json] [--repo DIR]
|
|
12
12
|
migrate [--force] [--json]
|
|
13
13
|
report [--runs N] [--run DIR]... [--site S] [--all] [--json]
|
|
14
|
-
replay --site S --provider P --model M [--runs N] [--send] [--workers 3] [--seed 7]
|
|
14
|
+
replay --site S --provider P --model M [--runs N] [--send | --label V] [--workers 3] [--seed 7]
|
|
15
15
|
[--margin 0.02] [--json]
|
|
16
16
|
|
|
17
17
|
`report` sums each site's jev.jsonl calls, cache hits, skips, tokens and cost over the newest
|
|
@@ -24,6 +24,8 @@ provider, else the legacy typesafe/cloudflare transport) with model M (forge_dec
|
|
|
24
24
|
Without --send it only prints the count, estimated input tokens and cost. With --send it asks
|
|
25
25
|
the unanswered ones, outside any budget, then judges replay, baseline and live answers on the
|
|
26
26
|
newer half of the runs and records the result in replays/<gate>.json, which `gate on` reads.
|
|
27
|
+
--label V judges the answers already stored on another label of the site instead (jev-drift:
|
|
28
|
+
first-attempt, the 2026-10-16 label); it sends nothing and records nothing.
|
|
27
29
|
Its --json is the dry run's estimate, or the evaluation (also `sent`). An unknown provider is
|
|
28
30
|
exit 2, a provider with no key that is not local exit 1.
|
|
29
31
|
|
|
@@ -798,6 +800,7 @@ def cmd_report(args) -> int:
|
|
|
798
800
|
|
|
799
801
|
|
|
800
802
|
def cmd_replay(args) -> int:
|
|
803
|
+
from . import labels as labels_module
|
|
801
804
|
from . import replay as replay_module
|
|
802
805
|
from . import sites as sites_module
|
|
803
806
|
record = sites_module.site(args.site)
|
|
@@ -820,7 +823,23 @@ def cmd_replay(args) -> int:
|
|
|
820
823
|
if not spec['key'] and not spec['local']:
|
|
821
824
|
raise Failed('provider %s has no key (forge decide provider add ... --key-stdin, or its key_env)'
|
|
822
825
|
% args.provider)
|
|
823
|
-
|
|
826
|
+
if args.label is not None:
|
|
827
|
+
if args.label not in labels_module.VARIANTS.get(args.site, {}):
|
|
828
|
+
raise Usage('%s has no label variant %s (variants: %s)' % (
|
|
829
|
+
args.site, args.label, ', '.join(sorted(labels_module.VARIANTS.get(args.site, {}))) or 'none'))
|
|
830
|
+
if args.send:
|
|
831
|
+
raise Usage('a label variant judges the answers already stored and records nothing: drop --send')
|
|
832
|
+
plan = replay_module.plan(args.site, spec['name'], spec['model'], spec, runs=args.runs, variant=args.label)
|
|
833
|
+
if args.label is not None:
|
|
834
|
+
result = replay_module.evaluate(plan, seed=args.seed, margin=args.margin)
|
|
835
|
+
result.update(label=args.label, recorded=None)
|
|
836
|
+
if args.json:
|
|
837
|
+
print(json.dumps(result, indent=2))
|
|
838
|
+
else:
|
|
839
|
+
print(replay_module.render(result))
|
|
840
|
+
print('label %s: judged on the %d answered of %d requests; not recorded (promotion reads the '
|
|
841
|
+
"site's own label)" % (args.label, result['answered'], result['requests']))
|
|
842
|
+
return 0
|
|
824
843
|
if not args.send:
|
|
825
844
|
data = replay_module.estimate(plan)
|
|
826
845
|
print(json.dumps(data, indent=2) if args.json else replay_module.render_estimate(data))
|
|
@@ -928,6 +947,8 @@ def parser() -> argparse.ArgumentParser:
|
|
|
928
947
|
s.add_argument('--model', required=True, metavar='M')
|
|
929
948
|
s.add_argument('--runs', type=int, metavar='N', help='only the newest N dataset runs')
|
|
930
949
|
s.add_argument('--send', action='store_true', help='ask the provider (without it: a dry run)')
|
|
950
|
+
s.add_argument('--label', metavar='V', help='judge the stored answers on another label of the site '
|
|
951
|
+
'(jev-drift: first-attempt); sends and records nothing')
|
|
931
952
|
s.add_argument('--workers', type=int, default=3)
|
|
932
953
|
s.add_argument('--seed', type=int, default=7, help='bootstrap seed of the reported interval')
|
|
933
954
|
s.add_argument('--margin', type=float, default=0.02)
|
|
@@ -161,13 +161,23 @@ def _drift_added(index: _Index, run, task) -> set:
|
|
|
161
161
|
return out
|
|
162
162
|
|
|
163
163
|
|
|
164
|
-
def
|
|
164
|
+
def _first_attempt(rows):
|
|
165
|
+
"""The last execution of the task's first real attempt, passed or not: what attempt 1 edited.
|
|
166
|
+
A refunded or infra-stopped execution spent no attempt (export._attempts)."""
|
|
167
|
+
real = [e for e in rows if e['d'].get('status') and not e['d'].get('refunded') and not e['d'].get('infra')]
|
|
168
|
+
if not real:
|
|
169
|
+
return None
|
|
170
|
+
first = min(e['attempt'] or 0 for e in real)
|
|
171
|
+
return [e for e in real if (e['attempt'] or 0) == first][-1]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _drift(index: _Index, record, event, body, pick=export.final_pass) -> dict:
|
|
165
175
|
state = _state(body)
|
|
166
176
|
task = state.get('task') if isinstance(state.get('task'), dict) else {}
|
|
167
177
|
task_id = task.get('id')
|
|
168
178
|
if not task_id:
|
|
169
179
|
return {}
|
|
170
|
-
final =
|
|
180
|
+
final = pick(index.attempts(event['run'], event['repo'], task_id, event['ts']))
|
|
171
181
|
if final is None:
|
|
172
182
|
return {}
|
|
173
183
|
changed = set(export.words(final['d'].get('changed_files')))
|
|
@@ -293,14 +303,28 @@ LABELLERS = {
|
|
|
293
303
|
}
|
|
294
304
|
|
|
295
305
|
|
|
296
|
-
def
|
|
306
|
+
def _drift_first_attempt(index: _Index, record, event, body) -> dict:
|
|
307
|
+
return _drift(index, record, event, body, pick=_first_attempt)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
# Other labels of a site, to check a past result against (`forge decide replay --label`). A
|
|
311
|
+
# variant's replay is never recorded, so promotion only ever reads the site's own label.
|
|
312
|
+
# drift first-attempt: the 2026-10-16 drift replay's label, "the file is in attempt 1's
|
|
313
|
+
# changed files", where the site's own is the final passing attempt's.
|
|
314
|
+
VARIANTS = {
|
|
315
|
+
'jev-drift': {'first-attempt': _drift_first_attempt},
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def collect(site: str, *, store: export.Store | None = None, runs=None, variant: str | None = None) -> list[dict]:
|
|
297
320
|
"""One row per stored live request of `site` with at least one labelled decision.
|
|
298
321
|
|
|
299
322
|
`store` is an already-open forge_dataset.export.Store; without one the store is opened
|
|
300
|
-
read-only. `runs`, when given, keeps only those dataset run uids.
|
|
301
|
-
(prompt, memory-curate,
|
|
323
|
+
read-only. `runs`, when given, keeps only those dataset run uids. `variant` names one of the
|
|
324
|
+
site's VARIANTS instead of its own label. A site with no label (prompt, memory-curate,
|
|
325
|
+
memory-stale), an unknown one, or an unknown variant returns []."""
|
|
302
326
|
record = sites.site(site)
|
|
303
|
-
labeller = LABELLERS.get(site)
|
|
327
|
+
labeller = LABELLERS.get(site) if variant is None else VARIANTS.get(site, {}).get(variant)
|
|
304
328
|
if record is None or record.label is None or labeller is None:
|
|
305
329
|
return []
|
|
306
330
|
if store is None:
|
|
@@ -96,7 +96,8 @@ def _newest_runs(events, n: int) -> set:
|
|
|
96
96
|
return set(sorted(first, key=lambda run: (first[run], str(run)), reverse=True)[:n])
|
|
97
97
|
|
|
98
98
|
|
|
99
|
-
def plan(site: str, provider: str, model: str, spec: dict, *, runs: int | None = None, store=None
|
|
99
|
+
def plan(site: str, provider: str, model: str, spec: dict, *, runs: int | None = None, store=None,
|
|
100
|
+
variant: str | None = None) -> Plan:
|
|
100
101
|
"""The labelled live requests of `site` (newest `runs` dataset runs only, when given), less
|
|
101
102
|
those whose own repo has the privacy floor, and which of them the replay file answers."""
|
|
102
103
|
store = store if store is not None else labels._open_store()
|
|
@@ -106,7 +107,7 @@ def plan(site: str, provider: str, model: str, spec: dict, *, runs: int | None =
|
|
|
106
107
|
usage = {event['d'].get('key'): event['d'].get('usage') for event, _body in stored}
|
|
107
108
|
keep = _newest_runs([event for event, _body in stored], runs) if runs else None
|
|
108
109
|
floors = {}
|
|
109
|
-
for row in labels.collect(site, store=store, runs=keep):
|
|
110
|
+
for row in labels.collect(site, store=store, runs=keep, variant=variant):
|
|
110
111
|
path = store.repo_paths.get(row['repo'])
|
|
111
112
|
# No recorded path, no floor: privacy_floor(None) would read the working directory's.
|
|
112
113
|
if path not in floors:
|
|
@@ -250,7 +251,7 @@ def evaluate(plan_: Plan, *, seed: int = 7, margin: float = 0.02) -> dict:
|
|
|
250
251
|
threshold = (forge_jev.threshold(record.threshold, site=plan_.site, model=plan_.model)
|
|
251
252
|
if record.threshold else None)
|
|
252
253
|
if threshold is not None and record.invert:
|
|
253
|
-
threshold = 1.0 - threshold
|
|
254
|
+
threshold = round(1.0 - threshold, 9) # 1 - 0.55 is 0.44999999999999996
|
|
254
255
|
answered_pairs = [(r['replay'], r['label']) for r in judged if r['replay'] is not None]
|
|
255
256
|
precision = (metrics.precision_at(answered_pairs, threshold) if threshold is not None
|
|
256
257
|
else dict(precision=None, recall=None, flagged=None))
|
|
@@ -343,7 +344,12 @@ def render(result: dict) -> str:
|
|
|
343
344
|
+ ('-' if ci is None else f'[{ci[0]:.3f}, {ci[1]:.3f}]') + f" (margin {result['margin']})",
|
|
344
345
|
]
|
|
345
346
|
if result['threshold'] is not None:
|
|
346
|
-
|
|
347
|
+
record = sites.site(result['site'])
|
|
348
|
+
cut = result['threshold']
|
|
349
|
+
# An inverted site's config value is on the other scale: show it as configured, and the cut.
|
|
350
|
+
at = (f"{result['threshold_name']} {round(1.0 - cut, 9):g} (inverted: a score at or above {cut:g})"
|
|
351
|
+
if record is not None and record.invert else f"{result['threshold_name']} {cut:g}")
|
|
352
|
+
lines.append(f" at {at}: precision "
|
|
347
353
|
f"{_number(result['precision'])}, recall {_number(result['recall'])}, "
|
|
348
354
|
f"{result['flagged']} flagged (floor {_number(result['floor'], 2)})")
|
|
349
355
|
lines += ['', ('PASSES: ' if result['passes'] else 'does not pass: ') + result['reason']]
|
package/ui/docs/api.md
CHANGED
|
@@ -90,7 +90,7 @@ written), and the reader must never raise because of one.
|
|
|
90
90
|
| `fractal-selection.json` | `{"enabled": true, "run": "run-<20 hex>"}` (or `enabled: false`): the run's Fractal choice, see Fractal below |
|
|
91
91
|
| `tasks/<id>/route.jsonl` | one JSON object per line, one per routing decision: `at` (epoch), `task`, `tier`, `epsilon`, `candidates` (list of specs), `default` (spec), `chosen` (spec), `explored` (bool), `propensity` (probability the chosen spec had), `inputs` (object), `decision` (a short hash identifying the decision). Keep unknown fields |
|
|
92
92
|
| `tasks/<id>/route.explored` | exists when the task's route was an exploratory pick |
|
|
93
|
-
| `shadow/<id>/<attempt>-<k>/shadow.json` | JSON: `task`, `attempt`, `reviewed`, `primary`, `spec`, `pick`, `started`. A second, never-read review of attempt `<attempt>` |
|
|
93
|
+
| `shadow/<id>/<attempt>-<k>/shadow.json` | JSON: `task`, `attempt`, `reviewed`, `primary`, `spec`, `pick` (`other_family`, `same_model`, `same_family` or `control`: identical to the primary), `started`. A second, never-read review of attempt `<attempt>` |
|
|
94
94
|
| `shadow/<id>/<attempt>-<k>/shadow.status` | one word |
|
|
95
95
|
| `shadow/<id>/<attempt>-<k>/qa.last` | the shadow reviewer's final message, verdict as above |
|
|
96
96
|
| `shadow/<id>/<attempt>-<k>/attempts/qa-<uuid>/` | the shadow review's execution |
|
|
@@ -248,6 +248,8 @@ its last 20,000 behind a leading `…`. Their `truncated` lists the field names
|
|
|
248
248
|
| `GET /api/runs/<key>/tasks/<id>/diff[/<which>]` | `200 DiffDetail`; `<which>` is `current` (the default: `changes.diff`), `prev`, `committed` (plan tasks), `existing` (solo) |
|
|
249
249
|
| `GET /api/runs/<key>/executions/<qa-or-dwarf>/diff` | `200 DiffDetail` of the diff that review read (a dwarf: its attempt's primary review) |
|
|
250
250
|
| `GET /api/runs/<key>/final-reviews/<name>/diff` | `200 DiffDetail` |
|
|
251
|
+
| `GET /api/runs/<key>/adoptions/<name>` | `200 AdoptionDetail`; `<name>` is the `adopt-<e>-<p>` an `adoptions.tsv` row names: `{name, adoption, verdict, threshold, gate, started, ended, duration_s, qa_input, qa_last, known_issues, findings, tests, diff}` (`adoption` is its row in `RunDetail.adoptions`; `diff` says the range's diff is there) |
|
|
252
|
+
| `GET /api/runs/<key>/adoptions/<name>/diff` | `200 DiffDetail` of the range (`range.diff`, else the prompt's fence), the review's findings pinned; unavailable with a reason past the 400 KB inline limit |
|
|
251
253
|
| `GET /api/runs/<key>/files` | `200 Files` |
|
|
252
254
|
| `GET /api/runs/<key>/findings` | `200 RunFindings` |
|
|
253
255
|
| `GET /api/runs/<key>/executions/<qa-or-dwarf>/transcript` | `200 ExecutionTranscript` |
|
|
@@ -423,7 +425,8 @@ Every RunSummary field, plus:
|
|
|
423
425
|
"final_review": FinalReviewSummary,
|
|
424
426
|
"final_reviews": [FinalReviewSummary, ...],
|
|
425
427
|
"adoptions": [{"at": 1760621000.0, "base": "...", "tip": "...", "verdict": "PASS", "approved": false,
|
|
426
|
-
"spec": "opus", "review": "adopt-1760621000-7", "reason": "..."
|
|
428
|
+
"spec": "opus", "review": "adopt-1760621000-7", "reason": "...",
|
|
429
|
+
"findings": FindingsSummary, "diff": true}],
|
|
427
430
|
"scheduler": {"live": true, "drained": false, "stopping": null, "max_parallel": 3,
|
|
428
431
|
"pauses": [{"scope": "model:codex/gpt-6", "class": "rate_limit", "harness": "codex", "model": "gpt-6",
|
|
429
432
|
"tasks": ["perf"], "cycle": 1, "until": 1760622130.0, "exhausted": false}]},
|
|
@@ -766,12 +769,18 @@ FindingsSummary is `null` when there is no text or no contract module.
|
|
|
766
769
|
```json
|
|
767
770
|
{"severity": "P1", "status": "CONFIRMED", "location": "src/x.py:12", "line": 7,
|
|
768
771
|
"summary": "- [P1][CONFIRMED] src/x.py:12 — first line, at most 240 characters",
|
|
772
|
+
"facts": {"reach": "realistic", "origin": "new", "evidence": "traced"},
|
|
769
773
|
"text": "the whole finding block"}
|
|
770
774
|
```
|
|
771
775
|
|
|
772
776
|
`status` is `CONFIRMED`, `PLAUSIBLE` or `UNSTATED`; `severity` may be `null`; `location` is the
|
|
773
777
|
first match of the contract's `_LOCATION` in the first line, or `null`; `line` is the
|
|
774
|
-
block's 1-based line in the reply. Lists of Findings keep the first 200.
|
|
778
|
+
block's 1-based line in the reply. Lists of Findings keep the first 200. `facts` is the
|
|
779
|
+
reviewer's `{reach=… origin=… evidence=…}` suffix (#119), cut from `summary`: `null` when the
|
|
780
|
+
finding has none, and a fact whose value is not one of its words is `null`. `reach` is `main`,
|
|
781
|
+
`realistic` or `unusual`, `origin` `new` or `existing`, `evidence` `ran`, `traced` or
|
|
782
|
+
`suspected`. They are recorded in shadow: nothing in forge decides on them. A diff's and a
|
|
783
|
+
RunFindings' Findings carry `facts` too.
|
|
775
784
|
|
|
776
785
|
## FinalReviewSummary
|
|
777
786
|
|