@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.
Files changed (38) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/VERSION +1 -1
  3. package/docs/dataset.md +8 -0
  4. package/docs/reviews.md +15 -1
  5. package/package.json +1 -1
  6. package/references/dataset.md +124 -5
  7. package/references/decision-models.md +15 -2
  8. package/references/decompose.md +46 -10
  9. package/references/planning.md +3 -2
  10. package/scripts/forge-contract.py +52 -1
  11. package/scripts/forge-issues.py +4 -3
  12. package/scripts/forge-ledger.py +3 -1
  13. package/scripts/forge-lib-adopt.sh +7 -1
  14. package/scripts/forge-metrics.sh +22 -0
  15. package/scripts/forge-parallel.sh +3 -1
  16. package/scripts/forge-plan-check.py +25 -2
  17. package/scripts/forge-planner.py +20 -6
  18. package/scripts/forge-shadow.py +28 -9
  19. package/scripts/forge-sweep.py +25 -10
  20. package/scripts/forge_dataset/cli.py +83 -0
  21. package/scripts/forge_dataset/facts.py +278 -0
  22. package/scripts/forge_dataset/harvest.py +16 -3
  23. package/scripts/forge_dataset/outcomes.py +206 -58
  24. package/scripts/forge_dataset/pairs.py +174 -0
  25. package/scripts/forge_dataset/risk.py +108 -0
  26. package/scripts/forge_dataset/tiers.py +427 -0
  27. package/scripts/forge_decide/cli.py +23 -2
  28. package/scripts/forge_decide/labels.py +30 -6
  29. package/scripts/forge_decide/replay.py +10 -4
  30. package/ui/docs/api.md +12 -3
  31. package/ui/forge_ui/export.py +9 -2
  32. package/ui/forge_ui/findings.py +4 -2
  33. package/ui/forge_ui/reader.py +71 -4
  34. package/ui/forge_ui/server.py +8 -0
  35. package/ui/forge_ui/static/app.js +6 -1
  36. package/ui/forge_ui/static/diffview.js +7 -3
  37. package/ui/forge_ui/static/panel.js +43 -2
  38. package/ui/forge_ui/static/style.css +1 -0
@@ -14,6 +14,19 @@ default) after the integration, and whether any later commit reverted it.
14
14
  Survival describes the artifact that landed (with every retry it took), not the first
15
15
  model that was routed to the task: the exporter attaches it to the review of that diff.
16
16
 
17
+ Integrations are followed where they went (#120). One whose branch was deleted, or whose
18
+ candidate is no longer on that branch's first-parent chain, is looked for in every other
19
+ branch (local, then remote; never forge's own): the commit where it entered a branch's
20
+ first-parent chain, a merge or itself, is where the horizon is walked from. A run nobody
21
+ ran `integrate` for, its integration branch merged by hand, is followed the same way from
22
+ its last integration commit, with the horizon counted from when it landed. A squash or a
23
+ rebase leaves no ancestry to follow: an `integrate` that went that way is `lost`, and a
24
+ hand-merged run that did is `not_landed`, retried at every harvest and never written.
25
+
26
+ `--deadline S` stops starting new work after S seconds and records what it has; the run's
27
+ automatic harvest (end of `run` and `integrate`, FORGE_OUTCOMES=off to skip) uses it. Every
28
+ harvest that writes leaves `outcomes.last` in the dataset dir for `forge dataset status`.
29
+
17
30
  Read-only by construction: the store is opened read-only (connect() would migrate it),
18
31
  and git runs only object-store queries (rev-parse, rev-list, log, diff between commits,
19
32
  blame at a commit, cat-file) with GIT_OPTIONAL_LOCKS=0, so nothing touches a working
@@ -37,6 +50,7 @@ from . import dataset_dir, record, sha256
37
50
 
38
51
  HORIZON_DAYS = 14
39
52
  GIT_TIMEOUT_S = 120
53
+ _FORGE_REF = re.compile(r'^refs/(?:heads|remotes/[^/]+)/forge/')
40
54
  _REVERTS = re.compile(r'This reverts commit ([0-9a-f]{7,40})')
41
55
  _HUNK = re.compile(rb'^([0-9a-f]{40}) \d+ \d+ (\d+)$')
42
56
 
@@ -104,7 +118,7 @@ def read_store():
104
118
  have = {rid for (rid,) in db.execute("SELECT rid FROM events WHERE kind = 'outcome'")}
105
119
  finally:
106
120
  db.close()
107
- integrations, merges, bases = [], {}, {}
121
+ integrations, merges, bases, landed_by_hand = [], {}, {}, defaultdict(list)
108
122
  for kind, run, task, repo, ts, data in rows:
109
123
  d = json.loads(data)
110
124
  if kind == 'attempt':
@@ -118,41 +132,89 @@ def read_store():
118
132
  if commit:
119
133
  # The last MERGED event for a commit wins; split/combine copies keep their run.
120
134
  merges[(repo, commit)] = dict(run=run, task=task, commit=commit, integration=d.get('integration'))
135
+ if d.get('integration'):
136
+ landed_by_hand[(repo, run)].append((ts, d['integration']))
137
+ integrated = {(i['repo'], i['run']) for i in integrations}
138
+ runs = [dict(repo=repo, run=run, commits=[c for _, c in sorted(found)]) for (repo, run), found in landed_by_hand.items()
139
+ if (repo, run) not in integrated]
121
140
  return dict(integrations=sorted(integrations, key=lambda i: i['ts']), merges=merges, bases=bases,
122
- repos=repos, have=have)
141
+ repos=repos, have=have, runs=sorted(runs, key=lambda r: (r['repo'] or '', r['run'] or '')))
123
142
 
124
143
 
125
144
  def outcome_rid(candidate: str, reviewed: str, horizon_days: int) -> str:
126
145
  return 'outcome:survival:' + sha256(('%s:%s:%d' % (candidate, reviewed, horizon_days)).encode())[:24]
127
146
 
128
147
 
148
+ def landing(git: Git, tip: str, candidate: str):
149
+ """The commit where `candidate` entered `tip`'s first-parent chain: `candidate` itself when it is on
150
+ that chain, else the oldest chain commit that contains it (the merge that brought it in); None when
151
+ `tip` does not contain it."""
152
+ if tip == candidate:
153
+ return candidate
154
+ if git.out('merge-base', '--is-ancestor', candidate, tip, ok=(0, 1))[0]:
155
+ return None
156
+ chain = [line.split() for line in git.text('log', '--first-parent', '--format=%H %P', '%s..%s' % (candidate, tip)
157
+ ).splitlines()] # newest first
158
+ if chain and chain[-1][1:2] == [candidate]:
159
+ return candidate
160
+ descendants = set(git.text('rev-list', '--ancestry-path', '%s..%s' % (candidate, tip)).split())
161
+ return next((row[0] for row in reversed(chain) if row[0] in descendants), None)
162
+
163
+
164
+ def walk(git: Git, tip: str, start: str, cutoff: float, now: float):
165
+ """('ok', rev, ts) | ('pending', None, None): the last commit of `tip`'s first-parent chain from `start`
166
+ on that was there at `cutoff`. By position along the chain, so out-of-order commit dates cannot jump
167
+ past a commit that came later; `start` itself when it came after the cutoff."""
168
+ chain = []
169
+ for line in git.text('log', '--first-parent', '--format=%H %ct', '%s..%s' % (start, tip)).splitlines():
170
+ sha, ct = line.split()[:2]
171
+ chain.append((sha, int(ct)))
172
+ rev, rev_ts = start, int(git.text('log', '-1', '--format=%ct', start).strip())
173
+ for sha, ct in reversed(chain):
174
+ if ct > cutoff:
175
+ return 'ok', rev, rev_ts
176
+ rev, rev_ts = sha, ct
177
+ if now < cutoff:
178
+ return 'pending', None, None # more commits may still land before the horizon
179
+ return 'ok', rev, rev_ts
180
+
181
+
129
182
  def horizon_rev(git: Git, branch: str, candidate: str, cutoff: float, now: float):
130
- """('ok', rev, ts) | ('lost', None, None) | ('pending', None, None).
183
+ """('ok', rev, ts) | ('lost', None, None) | ('pending', None, None) on the branch `integrate` advanced.
131
184
 
132
185
  The branch is resolved once to an immutable tip. The candidate must sit on its
133
- first-parent chain (a rebase, squash or reset loses it: unobservable, not failure).
134
- The horizon is found by position along that chain, so out-of-order commit dates
135
- cannot jump past a commit that came later.
186
+ first-parent chain; when it does not (the branch was deleted, rebased, squashed or reset),
187
+ harvest() looks for it elsewhere with follow().
136
188
  """
137
189
  if not branch or git.out('rev-parse', '--verify', '-q', branch + '^{commit}', ok=(0, 1))[0]:
138
190
  return 'lost', None, None
139
191
  tip = git.text('rev-parse', branch + '^{commit}').strip()
140
- chain = [] # first-parent commits after the candidate, newest first
141
- for line in git.text('log', '--first-parent', '--format=%H %ct %P', '%s..%s' % (candidate, tip)).splitlines():
142
- sha, ct, *parents = line.split()
143
- chain.append((sha, int(ct), parents))
144
- if tip != candidate and (not chain or chain[-1][2][:1] != [candidate]):
192
+ if landing(git, tip, candidate) != candidate:
145
193
  return 'lost', None, None # the walk never passed through the candidate
146
- chain = [(sha, ct) for sha, ct, _ in reversed(chain)]
147
- candidate_ct = int(git.text('log', '-1', '--format=%ct', candidate).strip())
148
- rev, rev_ts = candidate, candidate_ct
149
- for sha, ct in chain:
150
- if ct > cutoff:
151
- return 'ok', rev, rev_ts
152
- rev, rev_ts = sha, ct
153
- if now < cutoff:
154
- return 'pending', None, None # more commits may still land before the horizon
155
- return 'ok', rev, rev_ts
194
+ return walk(git, tip, candidate, cutoff, now)
195
+
196
+
197
+ def follow(git: Git, candidate: str):
198
+ """(branch, tip, landing, landing time) of the branch where `candidate` landed first, or None. Every
199
+ branch that contains it (local and remote, never forge's own) is a candidate; the earliest landing
200
+ wins, a local branch before a remote one at the same time, then by name."""
201
+ best = None
202
+ refs = git.text('for-each-ref', '--contains', candidate, '--format=%(refname)', 'refs/heads', 'refs/remotes').split()
203
+ for ref in refs:
204
+ if _FORGE_REF.match(ref) or ref.endswith('/HEAD'):
205
+ continue
206
+ tip = git.text('rev-parse', ref + '^{commit}').strip()
207
+ landed = landing(git, tip, candidate)
208
+ if landed is None:
209
+ continue
210
+ at = int(git.text('log', '-1', '--format=%ct', landed).strip())
211
+ key = (at, ref.startswith('refs/remotes/'), ref)
212
+ if best is None or key < best[0]:
213
+ best = (key, ref, tip, landed, at)
214
+ if best is None:
215
+ return None
216
+ _, ref, tip, landed, at = best
217
+ return ref.split('/', 2)[2], tip, landed, at
156
218
 
157
219
 
158
220
  def survival(git: Git, base: str, reviewed: str, rev: str) -> dict:
@@ -185,77 +247,151 @@ def reverts(git: Git, candidate: str, rev: str, shas: set) -> list:
185
247
 
186
248
 
187
249
  def harvest(*, horizon_days: int = HORIZON_DAYS, repo: str | None = None, include_temp: bool = False,
188
- now: float | None = None) -> tuple[list, Counter]:
250
+ now: float | None = None, deadline: float | None = None) -> tuple[list, Counter]:
251
+ """(events to record, counts). `deadline` (seconds) stops starting new integrations once passed; what
252
+ was left is counted as `deferred` and found again by the next harvest."""
189
253
  from .importer import is_temp
190
254
  state = read_store()
191
255
  counts = Counter()
192
256
  if state is None:
193
257
  return [], counts
194
258
  now = time.time() if now is None else now
259
+ stop = time.monotonic() + deadline if deadline is not None else None
195
260
  wanted = str(Path(repo).resolve()) if repo else None
196
261
  by_repo = defaultdict(list)
197
- for integration in state['integrations']:
198
- path = state['repos'].get(integration['repo'])
199
- if not path or (wanted and str(Path(path).resolve()) != wanted):
200
- continue
201
- if is_temp(path) and not include_temp:
202
- counts['skipped_temp'] += 1
203
- continue
204
- if not Path(path).is_dir():
205
- counts['repo_missing'] += 1
206
- continue
207
- by_repo[path].append(integration)
262
+ for kind, items in (('integrate', state['integrations']), ('merged', state['runs'])):
263
+ for item in items:
264
+ path = state['repos'].get(item['repo'])
265
+ if not path or (wanted and str(Path(path).resolve()) != wanted):
266
+ continue
267
+ if is_temp(path) and not include_temp:
268
+ counts['skipped_temp'] += 1
269
+ continue
270
+ if not Path(path).is_dir():
271
+ counts['repo_missing'] += 1
272
+ continue
273
+ by_repo[path].append((kind, item))
208
274
  out = []
209
- for path, integrations in by_repo.items():
275
+ for path, items in by_repo.items():
210
276
  git = Git(path)
211
- for integration in integrations:
212
- candidate, parent = integration['candidate'], integration['parent']
277
+ for kind, item in items:
278
+ if stop is not None and time.monotonic() > stop:
279
+ counts['deferred'] += 1
280
+ continue
213
281
  try:
214
- if not git.exists(candidate + '^{commit}'):
215
- counts['candidate_missing'] += 1
216
- continue
217
- landed = set(git.text('rev-list', candidate, '^' + parent).split())
218
- tasks = [m for (r, c), m in state['merges'].items() if r == integration['repo'] and c in landed]
219
- todo = [m for m in tasks if outcome_rid(candidate, m['commit'], horizon_days) not in state['have']]
220
- counts['already'] += len(tasks) - len(todo)
221
- if not todo:
222
- continue
223
- cutoff = integration['ts'] + horizon_days * 86400
224
- status, rev, rev_ts = horizon_rev(git, integration['branch'], candidate, cutoff, now)
282
+ found = _locate(git, kind, item, state, horizon_days, now, counts)
225
283
  except GitError:
226
284
  counts['git_error'] += 1
227
285
  continue
228
- if status == 'pending':
229
- counts['pending'] += len(todo)
286
+ if found is None:
230
287
  continue
288
+ candidate, todo, status, rev, rev_ts, where = found
231
289
  for merge in todo:
232
290
  base = state['bases'].get(merge['commit'])
233
291
  if not base:
234
292
  counts['no_base'] += 1
235
293
  continue
236
294
  data = dict(name='survival', candidate=candidate, reviewed=merge['commit'], base_ref=base,
237
- branch=integration['branch'], horizon_days=horizon_days, integrated_ts=integration['ts'],
238
- horizon_rev=rev, horizon_ts=rev_ts, integrate_run=integration['run'])
295
+ horizon_days=horizon_days, horizon_rev=rev, horizon_ts=rev_ts, **where)
239
296
  try:
240
297
  if status == 'ok':
241
- found = survival(git, base, merge['commit'], rev)
242
- task_shas = set(found.pop('commits')) | {s for s in (merge.get('integration'), candidate) if s}
243
- data.update(found, reverted_by=reverts(git, candidate, rev, task_shas),
244
- status='ok' if found['added'] else 'no_additions')
298
+ measured = survival(git, base, merge['commit'], rev)
299
+ task_shas = set(measured.pop('commits')) | {s for s in (merge.get('integration'), candidate) if s}
300
+ data.update(measured, reverted_by=reverts(git, where.get('landed') or candidate, rev, task_shas),
301
+ status='ok' if measured['added'] else 'no_additions')
245
302
  else:
246
303
  data.update(status='lost')
247
304
  except GitError:
248
305
  counts['git_error'] += 1
249
306
  continue
250
307
  counts[data['status']] += 1
308
+ if where.get('followed'):
309
+ counts['followed'] += 1
251
310
  out.append((path, dict(rid=outcome_rid(candidate, merge['commit'], horizon_days), kind='outcome',
252
311
  src='harvest', ts=now, run=merge['run'], task=merge['task'],
253
312
  mode='parallel', data=data)))
254
313
  return out, counts
255
314
 
256
315
 
316
+ def _locate(git, kind, item, state, horizon_days, now, counts):
317
+ """(candidate, merges to record, status, horizon rev, its time, how it was found) for one integration,
318
+ or None when there is nothing to record now (counted)."""
319
+ if kind == 'integrate':
320
+ candidate, parent, run = item['candidate'], item['parent'], item['run']
321
+ else:
322
+ commits = [c for c in item['commits'] if git.exists(c + '^{commit}')]
323
+ if not commits:
324
+ counts['integration_gone'] += 1
325
+ return None
326
+ candidate, run = commits[-1], item['run']
327
+ parent = git.text('rev-parse', commits[0] + '^1').strip() if git.exists(commits[0] + '^1') else None
328
+ if not git.exists(candidate + '^{commit}'):
329
+ counts['candidate_missing'] += 1
330
+ return None
331
+ landed = set(git.text('rev-list', candidate, *(['^' + parent] if parent else [])).split())
332
+ tasks = [m for (r, c), m in state['merges'].items() if r == item['repo'] and c in landed
333
+ and (kind == 'integrate' or m['run'] == run)]
334
+ todo = [m for m in tasks if outcome_rid(candidate, m['commit'], horizon_days) not in state['have']]
335
+ counts['already'] += len(tasks) - len(todo)
336
+ if not todo:
337
+ return None
338
+ if kind == 'integrate':
339
+ cutoff = item['ts'] + horizon_days * 86400
340
+ where = dict(branch=item['branch'], integrated_ts=item['ts'], integrate_run=run)
341
+ status, rev, rev_ts = horizon_rev(git, item['branch'], candidate, cutoff, now)
342
+ if status == 'lost':
343
+ seen = follow(git, candidate)
344
+ if seen is not None:
345
+ branch, tip, landing_commit, _at = seen
346
+ status, rev, rev_ts = walk(git, tip, landing_commit, cutoff, now)
347
+ where.update(followed=branch, landed=landing_commit)
348
+ else:
349
+ gone = not item['branch'] or git.out('rev-parse', '--verify', '-q', item['branch'] + '^{commit}',
350
+ ok=(0, 1))[0] != 0
351
+ where.update(lost_cause='branch_gone' if gone else 'off_branch')
352
+ else:
353
+ seen = follow(git, candidate)
354
+ if seen is None:
355
+ counts['not_landed'] += len(todo) # not merged yet, or squashed: nothing to follow
356
+ return None
357
+ branch, tip, landing_commit, at = seen
358
+ cutoff = at + horizon_days * 86400
359
+ status, rev, rev_ts = walk(git, tip, landing_commit, cutoff, now)
360
+ where = dict(branch=None, integrated_ts=at, integrate_run=None, followed=branch, landed=landing_commit,
361
+ merged_by_hand=True)
362
+ if status == 'pending':
363
+ counts['pending'] += len(todo)
364
+ return None
365
+ return candidate, todo, status, rev, rev_ts, where
366
+
367
+
368
+ LAST = 'outcomes.last'
369
+
370
+
371
+ def last_harvest():
372
+ """What the last harvest that wrote did ({at, repo, recorded, counts}), or None."""
373
+ try:
374
+ data = json.loads((dataset_dir() / LAST).read_text())
375
+ except (OSError, ValueError):
376
+ return None
377
+ return data if isinstance(data, dict) else None
378
+
379
+
257
380
  def main(args) -> int:
258
- events, counts = harvest(horizon_days=args.horizon_days, repo=args.repo, include_temp=args.include_temp)
381
+ if getattr(args, 'quiet', False):
382
+ # the automatic harvest at the end of a run: whatever goes wrong is logged, never raised
383
+ try:
384
+ return _main(args)
385
+ except Exception as error: # noqa: BLE001 - a harvest must never fail the run that called it
386
+ from . import log_error
387
+ log_error('outcomes', error)
388
+ return 0
389
+ return _main(args)
390
+
391
+
392
+ def _main(args) -> int:
393
+ events, counts = harvest(horizon_days=args.horizon_days, repo=args.repo, include_temp=args.include_temp,
394
+ deadline=getattr(args, 'deadline', None))
259
395
  written = 0
260
396
  if not args.dry_run:
261
397
  by_repo = defaultdict(list)
@@ -263,11 +399,23 @@ def main(args) -> int:
263
399
  by_repo[path].append(event)
264
400
  for path, batch in by_repo.items():
265
401
  written += record(batch, repo=path, where='outcomes')
402
+ stamp = dict(at=time.time(), repo=str(Path(args.repo).resolve()) if args.repo else None, recorded=written,
403
+ counts=dict(counts))
404
+ try:
405
+ target = dataset_dir() / LAST
406
+ target.parent.mkdir(parents=True, exist_ok=True)
407
+ tmp = target.with_suffix('.tmp')
408
+ tmp.write_text(json.dumps(stamp, sort_keys=True) + '\n')
409
+ os.replace(tmp, target)
410
+ except OSError:
411
+ pass
412
+ if getattr(args, 'quiet', False):
413
+ return 0
266
414
  label = 'would record' if args.dry_run else 'recorded'
267
415
  print('%s %d survival outcome(s) at %d days' % (label, len(events) if args.dry_run else written,
268
416
  args.horizon_days))
269
- for key in ('ok', 'no_additions', 'lost', 'pending', 'already', 'no_base', 'candidate_missing',
270
- 'repo_missing', 'skipped_temp', 'git_error'):
417
+ for key in ('ok', 'no_additions', 'lost', 'followed', 'pending', 'not_landed', 'already', 'no_base',
418
+ 'candidate_missing', 'integration_gone', 'repo_missing', 'skipped_temp', 'deferred', 'git_error'):
271
419
  if counts.get(key):
272
420
  print(' %-17s %d' % (key, counts[key]))
273
421
  if not args.dry_run and written < len(events):
@@ -0,0 +1,174 @@
1
+ """`forge dataset pairs`: what a second reviewer of the same attempt saw, per pair of reviewer settings (#121).
2
+
3
+ `--shadow-qa` reviews a sampled attempt twice: the primary that decides, and a shadow that nothing reads.
4
+ `forge dataset status` says how often the two agree per model pair. This report splits the pairs by
5
+ what differs between the two reviewers, so an effort comparison is never mixed with a model one:
6
+
7
+ effort the same harness and model at another effort or harness (`sol:medium` beside `sol:high`)
8
+ model another model of the same family
9
+ family another model family
10
+ control identical harness, model and effort: two runs of one reviewer, so their disagreement is
11
+ noise. A control is never an effort comparison; it is the baseline the others are read
12
+ against.
13
+
14
+ For every pair of settings, the two sides are ordered (lower effort, then model, first) and it gives:
15
+ - pairs, verdict agreement and its Wilson 95% interval; `enough` from MIN_PAIRS pairs, the bar
16
+ `forge dataset routing` uses for its randomized arms
17
+ - blocking findings (CONFIRMED, at the attempt's threshold or worse, or unlabelled) found by only
18
+ one side: the other side named nothing within LINE_WINDOW lines of it in the same file. A finding
19
+ both name at different severities is a severity disagreement, not a unique find
20
+ - the medians, over pairs, of b's tokens and time as a multiple of a's
21
+
22
+ "Found more" is not "better": whether a unique find was real is judged afterwards (outcomes, hidden
23
+ tests). Advisory only: nothing that routes or gates reads this report.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import importlib.util
28
+ import json
29
+ import os
30
+ import statistics
31
+ from collections import defaultdict
32
+ from pathlib import Path
33
+
34
+ from . import connect, dataset_dir
35
+ from .export import Runs, Store, shadow_pairs
36
+ from .facts import LINE_WINDOW, _matched, _threshold
37
+ from .routing import wilson
38
+
39
+ MIN_PAIRS = 30
40
+ KINDS = ('effort', 'model', 'family', 'control')
41
+ EFFORT_RANK = dict(minimal=0, low=1, medium=2, high=3, xhigh=4, max=5)
42
+ _SHADOW = None
43
+
44
+
45
+ def family(model: str) -> str:
46
+ """forge-shadow.py's model family, the one its pick prefers to differ from."""
47
+ global _SHADOW
48
+ if _SHADOW is None:
49
+ spec = importlib.util.spec_from_file_location('forge_shadow', Path(__file__).resolve().parents[1] / 'forge-shadow.py')
50
+ _SHADOW = importlib.util.module_from_spec(spec)
51
+ spec.loader.exec_module(_SHADOW)
52
+ return _SHADOW.family(model)
53
+
54
+
55
+ def settings(d) -> tuple:
56
+ return d.get('harness'), d.get('model'), d.get('effort')
57
+
58
+
59
+ def kind(a: tuple, b: tuple) -> str:
60
+ if a == b:
61
+ return 'control'
62
+ if a[1] == b[1]:
63
+ return 'effort'
64
+ return 'model' if family(a[1] or '') == family(b[1] or '') else 'family'
65
+
66
+
67
+ def label(s: tuple) -> str:
68
+ harness, model, effort = s
69
+ return '%s%s%s' % (model or '?', ':' + effort if effort else '', ' (%s)' % harness if harness else '')
70
+
71
+
72
+ def _order(s: tuple):
73
+ return (EFFORT_RANK.get(s[2] or '', -1), s[1] or '', s[0] or '', s[2] or '')
74
+
75
+
76
+ def _blocking(f, rank) -> bool:
77
+ return f.get('status') == 'CONFIRMED' and (f.get('severity') is None or f['severity'] <= rank)
78
+
79
+
80
+ def _unique(mine, theirs, rank) -> int:
81
+ """Blocking findings of `mine` with nothing of `theirs` near them (unlocated ones always count)."""
82
+ matched = {id(a) for a, _ in _matched(mine, theirs)}
83
+ return sum(1 for f in mine if _blocking(f, rank) and id(f) not in matched)
84
+
85
+
86
+ def _tokens(d):
87
+ t = d.get('tokens') or {}
88
+ values = [t.get('input'), t.get('output')]
89
+ return sum(v for v in values if isinstance(v, (int, float))) if any(isinstance(v, (int, float)) for v in values) else None
90
+
91
+
92
+ def _time(d):
93
+ for key in ('elapsed_s', 'duration_s'):
94
+ value = d.get(key)
95
+ if isinstance(value, (int, float)) and value > 0:
96
+ return float(value)
97
+ return None
98
+
99
+
100
+ def _ratio(xs):
101
+ return round(statistics.median(xs), 2) if xs else None
102
+
103
+
104
+ def report(runs: Runs, repo: str = None) -> dict:
105
+ paths = runs.store.repo_paths
106
+ rows = defaultdict(lambda: dict(pairs=0, agree=0, only_a=0, only_b=0, tokens=[], time=[]))
107
+ for (run, task, n), (primary, shadow) in shadow_pairs(runs).items():
108
+ if repo and paths.get(primary['repo']) != repo:
109
+ continue
110
+ sides = [primary['d'], shadow['d']]
111
+ sides.sort(key=lambda d: _order(settings(d)))
112
+ a, b = sides
113
+ row = rows[(kind(settings(a), settings(b)), settings(a), settings(b))]
114
+ rank = _threshold(runs, run, task, n)
115
+ found_a = [f for f in a.get('findings') or [] if isinstance(f, dict)]
116
+ found_b = [f for f in b.get('findings') or [] if isinstance(f, dict)]
117
+ row['pairs'] += 1
118
+ row['agree'] += a.get('verdict') == b.get('verdict')
119
+ row['only_a'] += _unique(found_a, found_b, rank)
120
+ row['only_b'] += _unique(found_b, found_a, rank)
121
+ for key, measure in (('tokens', _tokens), ('time', _time)):
122
+ x, y = measure(a), measure(b)
123
+ if x and y:
124
+ row[key].append(y / x)
125
+ out = []
126
+ for (k, a, b), row in rows.items():
127
+ lo, hi = wilson(row['agree'], row['pairs'])
128
+ out.append(dict(kind=k, a=label(a), b=label(b), pairs=row['pairs'], agree=row['agree'],
129
+ agreement=round(row['agree'] / row['pairs'], 3), ci=[round(lo, 3), round(hi, 3)],
130
+ enough=row['pairs'] >= MIN_PAIRS, only_a=row['only_a'], only_b=row['only_b'],
131
+ tokens_ratio=_ratio(row['tokens']), time_ratio=_ratio(row['time'])))
132
+ out.sort(key=lambda r: (KINDS.index(r['kind']), -r['pairs'], r['a'], r['b']))
133
+ return dict(min_pairs=MIN_PAIRS, line_window=LINE_WINDOW, pairs=sum(r['pairs'] for r in out),
134
+ by_kind={k: sum(r['pairs'] for r in out if r['kind'] == k) for k in KINDS}, comparisons=out)
135
+
136
+
137
+ def load(repo: str = None) -> dict:
138
+ # Reading must not create a store: a fresh machine gets an empty report.
139
+ if not (dataset_dir() / 'dataset.sqlite').exists():
140
+ return dict(min_pairs=MIN_PAIRS, line_window=LINE_WINDOW, pairs=0, by_kind={k: 0 for k in KINDS}, comparisons=[])
141
+ db = connect()
142
+ try:
143
+ runs = Runs(Store(db))
144
+ finally:
145
+ db.close()
146
+ return report(runs, repo=repo)
147
+
148
+
149
+ HEADINGS = dict(effort='effort, within one model', model='another model, one family',
150
+ family='across families', control='controls: identical settings, so disagreement is noise')
151
+
152
+
153
+ def main(args) -> int:
154
+ rep = load(os.path.realpath(args.repo) if args.repo else None)
155
+ if args.json:
156
+ print(json.dumps(rep, indent=2, sort_keys=True))
157
+ return 0
158
+ print('pairs: %d usable shadow pairs (%s); advisory only' % (
159
+ rep['pairs'], ', '.join('%d %s' % (rep['by_kind'][k], k) for k in KINDS)))
160
+ if not rep['comparisons']:
161
+ print(' none yet: `plan --shadow-qa <spec>` reviews a sampled share of attempts twice')
162
+ for k in KINDS:
163
+ rows = [r for r in rep['comparisons'] if r['kind'] == k]
164
+ if not rows:
165
+ continue
166
+ print('%s:' % HEADINGS[k])
167
+ for r in rows:
168
+ sample = '' if r['enough'] else ' (under %d pairs)' % rep['min_pairs']
169
+ cost = ', b costs %sx tokens and %sx time' % (r['tokens_ratio'] if r['tokens_ratio'] is not None else '?',
170
+ r['time_ratio'] if r['time_ratio'] is not None else '?')
171
+ print(' a %s vs b %s: %d pairs, %d agree (%.0f%% [%.0f-%.0f%%]), blocking found only by a %d, only by b %d%s%s'
172
+ % (r['a'], r['b'], r['pairs'], r['agree'], 100 * r['agreement'], 100 * r['ci'][0], 100 * r['ci'][1],
173
+ r['only_a'], r['only_b'], cost, sample))
174
+ return 0
@@ -0,0 +1,108 @@
1
+ """`forge dataset risk`: a task's risk beside its difficulty (#122), measured in shadow.
2
+
3
+ Difficulty is what a task demands of the model; risk is what a mistake that gets through would cost
4
+ (what breaks, for whom, how hard it is to undo). The planner, or whoever writes the plan, records risk
5
+ in `tasks/<id>/risk`; nothing routes on it. This report says whether it should:
6
+
7
+ rated tasks with a risk, and how often it differs from their difficulty (the share that match
8
+ and Cohen's kappa: a rating that only echoes difficulty adds nothing, and the issue says
9
+ to stop there)
10
+ cells every (difficulty, risk) pair: tasks, first attempts that passed, tasks a primary review
11
+ found a CONFIRMED P0 or P1 in, and landed work that did not hold at the longest horizon
12
+ `forge dataset outcomes` followed (reverted, or under SURVIVES_AT of its lines kept).
13
+ Low difficulty with high risk is the case the question is about.
14
+
15
+ A cell under MIN_CELL tasks is flagged: outcomes take 14 days to come due and the interesting cell is
16
+ rare, so a handful of tasks is reported as such rather than read as an answer. Each task counts once,
17
+ as its run's latest plan revision rated it. Advisory only: nothing that routes or gates reads it.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+
24
+ from . import connect, dataset_dir
25
+ from .export import SURVIVES_AT, Runs, Store
26
+ from .facts import _kappa
27
+
28
+ LEVELS = ('low', 'medium', 'high')
29
+ MIN_CELL = 10
30
+
31
+
32
+ def _empty():
33
+ return dict(tasks=0, rated=0, same=0, kappa=None, min_cell=MIN_CELL, survives_at=SURVIVES_AT, cells=[])
34
+
35
+
36
+ def report(runs: Runs, repo: str = None) -> dict:
37
+ out = _empty()
38
+ paths = runs.store.repo_paths
39
+ cells = {}
40
+ pairs = []
41
+ for run, revisions in runs.plans.items():
42
+ plan = revisions[-1]
43
+ if repo and paths.get(plan['repo']) != repo:
44
+ continue
45
+ for task, row in (plan['d'].get('tasks') or {}).items():
46
+ out['tasks'] += 1
47
+ difficulty, risk = row.get('difficulty'), row.get('risk')
48
+ if difficulty not in LEVELS or risk not in LEVELS:
49
+ continue
50
+ out['rated'] += 1
51
+ out['same'] += difficulty == risk
52
+ pairs.append((difficulty, risk))
53
+ cell = cells.setdefault((difficulty, risk), dict(difficulty=difficulty, risk=risk, tasks=0, attempted=0,
54
+ first_pass=0, serious=0, landed=0, did_not_hold=0))
55
+ cell['tasks'] += 1
56
+ attempts = runs.attempts.get((run, task)) or []
57
+ if attempts:
58
+ cell['attempted'] += 1
59
+ cell['first_pass'] += attempts[0]['d'].get('status') == 'PASS'
60
+ reviews = runs.dispatches.get((run, task, 'qa')) or []
61
+ cell['serious'] += any(f.get('status') == 'CONFIRMED' and f.get('severity') in (0, 1)
62
+ for e in reviews for f in e['d'].get('findings') or [] if isinstance(f, dict))
63
+ landed = next((runs.survival[c] for c in (runs.reviewed.get((run, task, a['attempt'])) for a in attempts)
64
+ if c in runs.survival), None)
65
+ if landed:
66
+ cell['landed'] += 1
67
+ cell['did_not_hold'] += (landed['surviving'] / landed['added'] < SURVIVES_AT
68
+ or bool(landed.get('reverted_by')))
69
+ kappa = _kappa(pairs)
70
+ out['kappa'] = None if kappa is None else round(kappa, 3)
71
+ out['cells'] = [dict(cell, enough=cell['tasks'] >= MIN_CELL)
72
+ for _, cell in sorted(cells.items(), key=lambda kv: (LEVELS.index(kv[0][0]), LEVELS.index(kv[0][1])))]
73
+ return out
74
+
75
+
76
+ def load(repo: str = None) -> dict:
77
+ # Reading must not create a store: a fresh machine gets an empty report.
78
+ if not (dataset_dir() / 'dataset.sqlite').exists():
79
+ return _empty()
80
+ db = connect()
81
+ try:
82
+ runs = Runs(Store(db))
83
+ finally:
84
+ db.close()
85
+ return report(runs, repo=repo)
86
+
87
+
88
+ def _rate(k, n):
89
+ return '%d/%d' % (k, n) if n else '-'
90
+
91
+
92
+ def main(args) -> int:
93
+ rep = load(os.path.realpath(args.repo) if args.repo else None)
94
+ if args.json:
95
+ print(json.dumps(rep, indent=2, sort_keys=True))
96
+ return 0
97
+ print('risk: %d of %d tasks rated; advisory only, nothing routes on it' % (rep['rated'], rep['tasks']))
98
+ if not rep['rated']:
99
+ print(' none yet: the planner rates it, or write low, medium or high to tasks/<id>/risk before `plan`')
100
+ return 0
101
+ kappa = '' if rep['kappa'] is None else ', kappa %.2f' % rep['kappa']
102
+ print(' risk equals difficulty for %d of %d (%.0f%%%s)' % (rep['same'], rep['rated'], 100 * rep['same'] / rep['rated'], kappa))
103
+ print(' %-10s %-6s %5s %10s %8s %14s' % ('difficulty', 'risk', 'tasks', 'first pass', 'P0/P1', 'did not hold'))
104
+ for c in rep['cells']:
105
+ print(' %-10s %-6s %5d %10s %8s %14s%s' % (
106
+ c['difficulty'], c['risk'], c['tasks'], _rate(c['first_pass'], c['attempted']), _rate(c['serious'], c['tasks']),
107
+ _rate(c['did_not_hold'], c['landed']), '' if c['enough'] else ' (under %d tasks)' % rep['min_cell']))
108
+ return 0