@giamme/forge 0.11.1 → 0.12.1

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 (54) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/SKILL.md +7 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +50 -11
  5. package/docs/commands.md +56 -8
  6. package/docs/decomposed-runs.md +43 -2
  7. package/docs/forge-ui.md +55 -8
  8. package/docs/reviews.md +64 -6
  9. package/package.json +1 -1
  10. package/references/dataset.md +4 -2
  11. package/references/decompose.md +191 -17
  12. package/references/harnesses.md +13 -1
  13. package/references/ui.md +25 -4
  14. package/scripts/forge-contract.py +37 -7
  15. package/scripts/forge-control.py +268 -25
  16. package/scripts/forge-dispatch.sh +90 -3
  17. package/scripts/forge-guard.py +156 -15
  18. package/scripts/forge-issues.py +47 -3
  19. package/scripts/forge-lib-plans.sh +9 -3
  20. package/scripts/forge-lib-review.sh +24 -5
  21. package/scripts/forge-lib-task.sh +53 -5
  22. package/scripts/forge-lib-verify.sh +137 -6
  23. package/scripts/forge-parallel-options.sh +85 -0
  24. package/scripts/forge-parallel.sh +262 -31
  25. package/scripts/forge-ripwire.py +1 -1
  26. package/scripts/forge-route.py +157 -5
  27. package/scripts/forge-runtime.py +49 -1
  28. package/scripts/forge-schedule.py +735 -53
  29. package/scripts/forge-solo.sh +3 -1
  30. package/scripts/forge-sweep.py +542 -0
  31. package/scripts/forge-verify.py +878 -0
  32. package/scripts/forge_dataset/forecast.py +33 -5
  33. package/scripts/forge_dataset/harvest.py +10 -4
  34. package/scripts/forge_verify_reports.py +225 -0
  35. package/ui/README.md +58 -12
  36. package/ui/docs/api.md +277 -28
  37. package/ui/forge_ui/checks.py +331 -0
  38. package/ui/forge_ui/control.py +12 -2
  39. package/ui/forge_ui/export.py +25 -8
  40. package/ui/forge_ui/reader.py +657 -24
  41. package/ui/forge_ui/server.py +29 -0
  42. package/ui/forge_ui/static/app.js +15 -7
  43. package/ui/forge_ui/static/checksview.js +449 -0
  44. package/ui/forge_ui/static/controls.js +217 -33
  45. package/ui/forge_ui/static/convo.js +11 -2
  46. package/ui/forge_ui/static/findingsview.js +6 -4
  47. package/ui/forge_ui/static/gantt.js +14 -9
  48. package/ui/forge_ui/static/index.html +2 -0
  49. package/ui/forge_ui/static/panel.js +44 -1
  50. package/ui/forge_ui/static/runmodel.js +109 -12
  51. package/ui/forge_ui/static/scene3d.js +9 -5
  52. package/ui/forge_ui/static/style.css +113 -0
  53. package/ui/forge_ui/static/verifyview.js +324 -0
  54. package/ui/forge_ui/transcripts.py +225 -54
@@ -11,6 +11,11 @@ Two opt-in behaviours live here, both off by default so a plain `run` is unchang
11
11
  stops dispatching, lets running tasks drain and exits 8: nothing was the task's fault
12
12
  and no attempt was spent, so the next `run` simply resumes.
13
13
 
14
+ A third, ``--sweep Pn``, also per invocation: once every task has merged, the open review
15
+ findings at Pn or worse become fix tasks (``forge-parallel.sh _sweep``, forge-sweep.py) that
16
+ this run then dispatches like any other, once per plan. A fix task that fails leaves its
17
+ findings for ``forge issues`` and does not fail the run.
18
+
14
19
  Both numbers are per invocation, but while the scheduler runs they are mirrored into the
15
20
  plan dir (retry_budget, infra_budget, tasks/<id>/retry_budget) and re-read at every
16
21
  decision, so `forge control` can change them mid-run. See "live control files" below.
@@ -23,6 +28,7 @@ import errno
23
28
  import fcntl
24
29
  import json
25
30
  import os
31
+ import re
26
32
  from pathlib import Path
27
33
  import posixpath
28
34
  import signal
@@ -74,19 +80,121 @@ def infra_info(root: Path) -> dict:
74
80
  return info
75
81
 
76
82
 
77
- def infra_wait(info: dict, cycle: int) -> float:
78
- """Seconds to wait before re-dispatching after an infrastructure failure."""
83
+ # --- backoff shapes ----------------------------------------------------------------------
84
+ # One parser for the --infra-backoff flag (through `forge-schedule.py backoff-check`), for
85
+ # `forge control set infra-backoff` (which loads this file) and for the waits themselves.
86
+ BACKOFF_FORMS = 'exp:<base>[,<cap>], linear:<start>,<step>[,<cap>], list:<a>,<b>,... or <a>,<b>,... (seconds, positive)'
87
+ _NUMBER = re.compile(r'(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)')
88
+ _COUNTS = {'exp': (1, 2), 'linear': (2, 3), 'list': (1, 1000)}
89
+
90
+
91
+ def parse_backoff(text: str) -> tuple:
92
+ """(kind, numbers) for a backoff shape; ValueError naming the forms when malformed."""
93
+ shape = (text or '').strip()
94
+ kind, colon, rest = shape.partition(':')
95
+ if not colon:
96
+ kind, rest = 'list', shape
97
+ if kind not in _COUNTS:
98
+ raise ValueError('unknown backoff shape %r: use %s' % (shape, BACKOFF_FORMS))
99
+ numbers = []
100
+ for part in rest.split(','):
101
+ part = part.strip()
102
+ if not _NUMBER.fullmatch(part) or float(part) <= 0:
103
+ raise ValueError('backoff %r needs positive numbers: use %s' % (shape, BACKOFF_FORMS))
104
+ numbers.append(float(part))
105
+ low, high = _COUNTS[kind]
106
+ if not low <= len(numbers) <= high:
107
+ raise ValueError('backoff %r has the wrong number of values: use %s' % (shape, BACKOFF_FORMS))
108
+ return kind, numbers
109
+
110
+
111
+ def backoff_wait(shape: tuple, cycle: int) -> float:
112
+ """Seconds to wait before resuming for a 0-based wait number."""
113
+ kind, numbers = shape
114
+ if kind == 'exp':
115
+ cap = numbers[1] if len(numbers) > 1 else max(numbers[0], 1800.0)
116
+ return min(numbers[0] * 2 ** min(cycle, 64), cap)
117
+ if kind == 'linear':
118
+ wait = numbers[0] + numbers[1] * cycle
119
+ return min(wait, numbers[2]) if len(numbers) > 2 else wait
120
+ return numbers[min(cycle, len(numbers) - 1)]
121
+
122
+
123
+ def default_backoff() -> tuple:
124
+ """Today's shape: exp with FORGE_INFRA_BACKOFF (60 s) as the base. (shape, its name)"""
79
125
  try:
80
126
  base = float(os.environ.get('FORGE_INFRA_BACKOFF', '60'))
81
127
  except ValueError:
82
128
  base = 60.0
129
+ return ('exp', [base]), 'exp:%g' % base
130
+
131
+
132
+ def infra_wait(info: dict, cycle: int, backoff: tuple | None = None) -> tuple:
133
+ """(seconds, what decided it) before re-dispatching after an infrastructure failure. A
134
+ provider's retry-after wins; otherwise the backoff shape (shape, name) for this wait."""
83
135
  try:
84
136
  hinted = float(info.get('retry_after', ''))
85
137
  except ValueError:
86
138
  hinted = None
87
139
  if hinted is not None and hinted >= 0:
88
- return min(hinted, INFRA_WAIT_CAP)
89
- return min(base * (2 ** cycle), max(base, 1800.0))
140
+ return min(hinted, INFRA_WAIT_CAP), 'provider retry-after'
141
+ shape, name = backoff or default_backoff()
142
+ return backoff_wait(shape, cycle), 'backoff ' + name
143
+
144
+
145
+ # --- pause scopes ----------------------------------------------------------------------
146
+ # A capacity error on one model says nothing about another, and a quota or auth stop is one
147
+ # harness's account; only the remaining classes (network, empty output, ...) stop everything.
148
+ def infra_scope(info: dict) -> tuple:
149
+ """(scope, harness, model) for a stop's infra.txt."""
150
+ cls, harness, model = info.get('class', ''), info.get('harness', ''), info.get('model', '')
151
+ if cls == 'rate_limit' and harness and model:
152
+ return 'model:%s/%s' % (harness, model), harness, model
153
+ if cls in ('quota', 'auth') and harness:
154
+ return 'harness:' + harness, harness, ''
155
+ return 'all', harness, model
156
+
157
+
158
+ def load_registry() -> list:
159
+ path = os.environ.get('FORGE_REGISTRY') or str(Path(__file__).resolve().parent.parent / 'registry.tsv')
160
+ rows = []
161
+ try:
162
+ with open(path, errors='replace') as handle:
163
+ for line in handle:
164
+ columns = line.rstrip('\n').split('\t')
165
+ if not line.startswith('#') and len(columns) >= 3:
166
+ rows.append(columns)
167
+ except OSError:
168
+ pass
169
+ return rows
170
+
171
+
172
+ def spec_pair(registry: list, spec: str) -> tuple | None:
173
+ """(harness, model) for a spec, resolved the way forge-dispatch.sh's lookup does: an
174
+ alias's first row is its default harness, alias:effort:harness picks that row, and an
175
+ unknown alias with a harness is a literal model id. None when it cannot be resolved."""
176
+ if not spec or spec in ('-', 'UNASSIGNED') or ',' in spec:
177
+ return None
178
+ parts = spec.split(':')
179
+ alias, harness = parts[0], ':'.join(parts[2:])
180
+ if not alias:
181
+ return None
182
+ for row in registry:
183
+ if row[0] == alias and (not harness or row[1] == harness):
184
+ return row[1], row[2]
185
+ return (harness, alias) if harness else None
186
+
187
+
188
+ def holds(pause: dict, pairs: list) -> bool:
189
+ """True when a task whose next dispatch uses these pairs falls under this pause."""
190
+ for pair in pairs:
191
+ if pair is None:
192
+ continue
193
+ if pause['model'] is not None and pair == (pause['harness'], pause['model']):
194
+ return True
195
+ if pause['model'] is None and pair[0] == pause['harness']:
196
+ return True
197
+ return False
90
198
 
91
199
 
92
200
  # --- live control files ------------------------------------------------------------------
@@ -208,6 +316,50 @@ def _task_dirs(plan: object, names: object) -> list[str]:
208
316
  return sorted(found)
209
317
 
210
318
 
319
+ def _read_small(plan: object, name: str) -> str | None:
320
+ """A short plan-level control file's stripped text; None when missing or unsafe."""
321
+ try:
322
+ fd = os.open(_resolve(plan, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
323
+ try:
324
+ return os.read(fd, 65).decode('ascii').strip()
325
+ finally:
326
+ os.close(fd)
327
+ except (OSError, UnicodeDecodeError):
328
+ return None
329
+
330
+
331
+ def stop_mode(plan: object) -> str | None:
332
+ """`forge control stop` wrote `graceful` or `now`; anything else is no stop."""
333
+ text = _read_small(plan, 'stop')
334
+ return text if text in ('graceful', 'now') else None
335
+
336
+
337
+ def drained(plan: object) -> bool:
338
+ return _read_small(plan, 'drain') is not None
339
+
340
+
341
+ def _fractal_plan(plan: object) -> bool:
342
+ """fractal-selection.json enabled (unreadable counts: fail closed, as forge-control does)."""
343
+ try:
344
+ text = Path(_resolve(plan, 'fractal-selection.json')).read_text()
345
+ except FileNotFoundError:
346
+ return False
347
+ except OSError:
348
+ return True
349
+ if not text.strip():
350
+ return False
351
+ try:
352
+ return bool(json.loads(text).get('enabled'))
353
+ except (ValueError, AttributeError):
354
+ return True
355
+
356
+
357
+ def live_capacity(plan: object, default: int) -> int:
358
+ """`forge control set max-parallel` (1-64), else the argument the run started with."""
359
+ text = _read_small(plan, 'max_parallel')
360
+ return int(text) if text and text.isdigit() and 1 <= int(text) <= 64 else default
361
+
362
+
211
363
  def _pinned(plan: object, name: str) -> bool:
212
364
  try:
213
365
  return os.path.lexists(_resolve(plan, 'tasks', name, 'escalation.pin'))
@@ -215,6 +367,135 @@ def _pinned(plan: object, name: str) -> bool:
215
367
  return False
216
368
 
217
369
 
370
+ # --- interrupted tasks ---------------------------------------------------------------------
371
+ # A task's harness leads its own session (forge-guard.py session), so the SIGTERM sent to the
372
+ # task's group reaches dispatch but not the harness: dispatch's EXIT trap stops it. The grace
373
+ # lets that trap finish; the guard's `stop` then acts on whatever <role>.harness record a
374
+ # dispatch that died too early left behind.
375
+ GUARD = str(Path(__file__).resolve().parent / 'forge-guard.py')
376
+ HARNESS_ROLES = ('dwarf', 'qa')
377
+ GUARD_STOP_WAIT = 15.0 # seconds; the guard's own bound is about 3 s plus two ps calls
378
+
379
+
380
+ def interrupt_grace() -> float:
381
+ """Seconds an interrupted task group gets to empty before SIGKILL."""
382
+ try:
383
+ value = float(os.environ.get('FORGE_INTERRUPT_GRACE', '10'))
384
+ except ValueError:
385
+ return 10.0
386
+ return value if 0 <= value < float('inf') else 10.0
387
+
388
+
389
+ def _group_alive(pgid: int) -> bool:
390
+ try:
391
+ os.killpg(pgid, 0)
392
+ except ProcessLookupError:
393
+ return False
394
+ except PermissionError:
395
+ return True
396
+ except OSError:
397
+ return False
398
+ return True
399
+
400
+
401
+ def stop_harnesses(plan: object, names: object) -> None:
402
+ """Run the guard's identity-checked `stop` on every harness record of these tasks, all
403
+ at once, so the bound does not grow with the number of tasks. Never raises."""
404
+ stopping = []
405
+ for name in names:
406
+ for role in HARNESS_ROLES:
407
+ try:
408
+ record = _resolve(plan, 'tasks', name, role + '.harness')
409
+ if not os.path.lexists(record):
410
+ continue
411
+ stopping.append((name, role, subprocess.Popen(
412
+ [sys.executable, GUARD, 'stop', record], stdin=subprocess.DEVNULL,
413
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)))
414
+ except (OSError, ValueError) as error:
415
+ _warn('could not stop the ' + role + ' harness of ' + name + ': ' + str(error))
416
+ deadline = time.monotonic() + GUARD_STOP_WAIT
417
+ for name, role, process in stopping:
418
+ try:
419
+ out, _ = process.communicate(timeout=max(deadline - time.monotonic(), 0.1))
420
+ except subprocess.TimeoutExpired:
421
+ process.kill()
422
+ process.communicate()
423
+ _warn('stopping the ' + role + ' harness of ' + name + ' took too long; gave up')
424
+ continue
425
+ count = (out or '').strip()
426
+ if count.isdigit() and count != '0':
427
+ _warn(name + ': stopped ' + count + ' process(es) its ' + role + ' harness left running')
428
+
429
+
430
+ # --- control requests ----------------------------------------------------------------------
431
+ # `forge control retry|add` queue one JSON file each in control.requests/, under control.lock and
432
+ # only while scheduler.live says a scheduler reads them. The scheduler applies or refuses each,
433
+ # logs one outcome line with the same `request` id, and removes it. live_stop settles whatever
434
+ # is left after it withdraws liveness, under the same lock, so no request outlives its run.
435
+ REQUESTS = 'control.requests'
436
+ REQUEST_MAX = 64 * 1024
437
+ RETRYABLE = ('FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED')
438
+
439
+
440
+ def list_requests(plan: object) -> list:
441
+ """Request file names in order; temp (dot) files and anything not a regular file are skipped."""
442
+ directory = os.path.join(os.path.realpath(plan), REQUESTS)
443
+ try:
444
+ if not stat.S_ISDIR(os.lstat(directory).st_mode):
445
+ return []
446
+ with os.scandir(directory) as entries:
447
+ return sorted(e.name for e in entries
448
+ if not e.name.startswith('.') and e.is_file(follow_symlinks=False) and _task_id_ok(e.name))
449
+ except OSError:
450
+ return []
451
+
452
+
453
+ def read_request(plan: object, name: str) -> dict | None:
454
+ try:
455
+ fd = os.open(_resolve(plan, REQUESTS, name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
456
+ try:
457
+ data = os.read(fd, REQUEST_MAX + 1)
458
+ finally:
459
+ os.close(fd)
460
+ request = json.loads(data.decode('utf-8'))
461
+ except (OSError, ValueError, UnicodeDecodeError):
462
+ return None
463
+ if len(data) > REQUEST_MAX or not isinstance(request, dict) or request.get('verb') not in ('retry', 'add'):
464
+ return None
465
+ task, dwarf = request.get('task'), request.get('dwarf')
466
+ if not isinstance(task, str) or not _task_id_ok(task):
467
+ return None
468
+ if dwarf is not None and (not isinstance(dwarf, str) or not dwarf or dwarf.startswith('-')
469
+ or any(c.isspace() or c == ',' for c in dwarf)):
470
+ return None
471
+ return request
472
+
473
+
474
+ def settle_request(plan: object, name: str, request: dict | None, outcome: str, reason: str | None) -> None:
475
+ """The outcome line in control.log, then the request goes. Called under control.lock."""
476
+ verb = request.get('verb') if request else None
477
+ task = request.get('task') if request else None
478
+ entry = {'at': time.time(), 'actor': 'scheduler', 'action': verb, 'task': task, 'key': None,
479
+ 'value': request.get('dwarf') if request else None, 'previous': None, 'request': name,
480
+ 'outcome': outcome, 'reason': reason}
481
+ try:
482
+ fd = os.open(_resolve(plan, 'control.log'), os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o644)
483
+ try:
484
+ os.write(fd, (json.dumps(entry) + '\n').encode('utf-8'))
485
+ finally:
486
+ os.close(fd)
487
+ except OSError as error:
488
+ _warn('could not log the outcome of request ' + name + ': ' + str(error))
489
+ _remove(plan, REQUESTS, name)
490
+ print('forge: control: ' + (verb or 'request') + ' ' + (task or name) + ' '
491
+ + (outcome if outcome == 'applied' else 'refused: ' + (reason or '')), file=sys.stderr, flush=True)
492
+
493
+
494
+ def refuse_requests(plan: object, reason: str) -> None:
495
+ for name in list_requests(plan):
496
+ settle_request(plan, name, read_request(plan, name), 'refused', reason)
497
+
498
+
218
499
  def live_start(plan: object, names: object, retry_failed: int, infra_retries: int) -> None:
219
500
  """Publish the flags and that this scheduler is live. Stale per-task overrides and
220
501
  usage counters from an earlier invocation go first."""
@@ -222,18 +503,28 @@ def live_start(plan: object, names: object, retry_failed: int, infra_retries: in
222
503
  for name in _task_dirs(plan, names):
223
504
  _remove(plan, 'tasks', name, 'retry_budget')
224
505
  _remove(plan, 'tasks', name, 'retries.used')
506
+ _remove(plan, 'infra.paused')
507
+ _remove(plan, 'drain')
508
+ _remove(plan, 'stop')
509
+ # Queued for a scheduler that died: never applied to this run.
510
+ refuse_requests(plan, 'left by an earlier run')
225
511
  _write_atomic(plan, str(retry_failed), 'retry_budget')
226
512
  _write_atomic(plan, str(infra_retries), 'infra_budget')
227
513
  _write_atomic(plan, json.dumps({'pid': os.getpid(), 'started': time.time()}), 'scheduler.live')
228
514
 
229
515
 
230
516
  def live_stop(plan: object, names: object) -> None:
231
- """Withdraw liveness first, then every budget. retries.used stays for the UI."""
517
+ """Withdraw liveness first, then every budget. retries.used stays for the UI. A request
518
+ queued before liveness went is settled here: none can arrive once the lock is released."""
232
519
  try:
233
520
  with _control_lock(plan):
234
521
  _remove(plan, 'scheduler.live')
522
+ refuse_requests(plan, 'run ended')
235
523
  _remove(plan, 'retry_budget')
236
524
  _remove(plan, 'infra_budget')
525
+ _remove(plan, 'infra.paused')
526
+ _remove(plan, 'drain')
527
+ _remove(plan, 'stop')
237
528
  for name in _task_dirs(plan, names):
238
529
  _remove(plan, 'tasks', name, 'retry_budget')
239
530
  except Exception as error:
@@ -241,7 +532,8 @@ def live_stop(plan: object, names: object) -> None:
241
532
 
242
533
 
243
534
  def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
244
- infra_retries: int = 0) -> int:
535
+ infra_retries: int = 0, sweep: str | None = None, sweep_max: int = 5,
536
+ sweep_plausible: bool = False) -> int:
245
537
  if capacity <= 0:
246
538
  raise ValueError('capacity must be positive')
247
539
  if retry_failed < 0 or infra_retries < 0:
@@ -270,8 +562,20 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
270
562
  infra_seen = [] # tasks stopped by an infrastructure failure, awaiting resume
271
563
  held = set() # INFRA tasks not resumed: their pin could not be applied
272
564
  infra_cycles = 0 # how many times this run already waited out an infrastructure pause
273
- paused = False # an infrastructure failure was seen: dispatch nothing new
565
+ paused = False # an `all`-scope infrastructure failure was seen: dispatch nothing new
274
566
  resume_at = 0.0
567
+ all_class = '' # the class of the first `all`-scope stop, for infra.paused
568
+ pauses = {} # scope -> its pause, for model: and harness: scopes; `all` is the above
569
+ scope_waits = {} # scope -> waits it already completed this run
570
+ pairs_cache = {} # task -> (harness, model) pairs its next dispatch uses
571
+ registry = load_registry()
572
+ paused_text = None # what infra.paused holds now
573
+ backoff_warned = [] # an invalid infra_backoff file is reported once
574
+ graceful = False # `forge control stop`: start nothing more, end once running tasks are done
575
+ human = set() # tasks whose next dispatch is a `forge control retry` (dataset trigger human)
576
+ fractal = _fractal_plan(plan)
577
+ drain_told = False # the drained message was printed for this drain
578
+ sweep_asked = False # this invocation already asked for the finding sweep
275
579
 
276
580
  def status(name: str) -> str:
277
581
  root = plan / 'tasks' / name
@@ -323,6 +627,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
323
627
  refused[name] = budget(name)
324
628
  return False
325
629
  refused.pop(name, None)
630
+ pairs_cache.pop(name, None) # the preparation may have escalated the implementer
326
631
  retries[name] = retries.get(name, 0) + 1
327
632
  _write_atomic(plan, str(retries[name]), 'tasks', name, 'retries.used')
328
633
  retried.add(name)
@@ -357,6 +662,314 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
357
662
  offsets[name] = len(data)
358
663
  print(data[start:].decode('utf-8', 'replace'), end='', flush=True)
359
664
 
665
+ def row_now(name: str) -> list:
666
+ """The task's tasks.tsv row as it is now: an escalation rewrites its dwarf column."""
667
+ try:
668
+ for line in (plan / 'tasks.tsv').read_text().splitlines():
669
+ columns = line.split('\t')
670
+ if len(columns) == 7 and columns[0] == name:
671
+ return columns
672
+ except OSError:
673
+ pass
674
+ return tasks[name]
675
+
676
+ def next_pairs(name: str) -> list:
677
+ """The pairs the task's next dispatch uses: QA only when its next entry is a QA-only
678
+ resume (decided by forge-parallel.sh's own check), the implementer and QA otherwise."""
679
+ if name not in pairs_cache:
680
+ row = row_now(name)
681
+ qa_only = (plan / 'tasks' / name / 'resume').exists() and subprocess.run(
682
+ ['/bin/bash', script, '_qa_only', str(plan), name],
683
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
684
+ pairs_cache[name] = [spec_pair(registry, spec) for spec in ([row[5]] if qa_only else [row[4], row[5]])]
685
+ return pairs_cache[name]
686
+
687
+ def scope_held(name: str) -> bool:
688
+ return any(holds(pause, next_pairs(name)) for pause in pauses.values())
689
+
690
+ def live_pause(pause: dict) -> bool:
691
+ """A pause still holding something: its own stopped tasks, or a pending task on its pair.
692
+ One whose tasks all fell back to another model holds nothing."""
693
+ return bool(pause['tasks']) or any(holds(pause, next_pairs(name)) for name in pending)
694
+
695
+ def waiting_scopes() -> bool:
696
+ return any(not pause['exhausted'] and live_pause(pause) for pause in pauses.values())
697
+
698
+ def fall_back(name: str, info: dict, scope: str) -> None:
699
+ """--infra-fallback: a dwarf-stage capacity stop moves to the next healthy model of its
700
+ tier pool. The stop was already recorded as its scope's pause, so every paused or
701
+ exhausted pair is excluded and a pool all at capacity cannot bounce the task forever."""
702
+ if interrupted or graceful or fractal or _read_small(plan, 'infra_fallback') != 'on' or _pinned(plan, name):
703
+ return
704
+ if info.get('stage') != 'dwarf' or info.get('class') != 'rate_limit' or not scope.startswith('model:'):
705
+ return
706
+ excluded = {(info['harness'], info['model'])}
707
+ excluded.update((p['harness'], p['model'] or '*') for p in pauses.values())
708
+ command = ['/bin/bash', script, '_prepare_retry', str(plan), name, '--fallback',
709
+ ','.join(sorted(h + '/' + m for h, m in excluded))]
710
+ if subprocess.run(command).returncode:
711
+ return
712
+ pauses[scope]['tasks'].remove(name)
713
+ pairs_cache.pop(name, None)
714
+ pending.insert(0, name)
715
+
716
+ def write_paused(until_all: float | None = None) -> None:
717
+ """infra.paused for forge-ui and `forge control show`; gone when nothing is paused."""
718
+ nonlocal paused_text
719
+ scopes = []
720
+ if paused:
721
+ scopes.append({'scope': 'all', 'class': all_class or None, 'harness': None, 'model': None,
722
+ 'tasks': list(infra_seen), 'cycle': infra_cycles + (1 if until_all else 0),
723
+ 'until': until_all, 'exhausted': not until_all and infra_cycles >= infra_budget()})
724
+ for pause in pauses.values():
725
+ scopes.append({key: pause[key] for key in
726
+ ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')})
727
+ text = json.dumps({'scopes': scopes}) if scopes else None
728
+ if text == paused_text:
729
+ return
730
+ if text is None:
731
+ _remove(plan, 'infra.paused')
732
+ else:
733
+ _write_atomic(plan, text, 'infra.paused')
734
+ paused_text = text
735
+
736
+ def backoff() -> tuple:
737
+ """The plan's infra_backoff, read at every wait so a change applies to the next one."""
738
+ try:
739
+ fd = os.open(_resolve(plan, 'infra_backoff'), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
740
+ try:
741
+ text = os.read(fd, 4097).decode('ascii').strip()
742
+ finally:
743
+ os.close(fd)
744
+ except FileNotFoundError:
745
+ return default_backoff()
746
+ except (OSError, UnicodeDecodeError) as error:
747
+ text, problem = None, str(error)
748
+ else:
749
+ problem = None
750
+ if text is not None:
751
+ try:
752
+ return parse_backoff(text), text
753
+ except ValueError as error:
754
+ problem = str(error)
755
+ if not backoff_warned:
756
+ backoff_warned.append(problem)
757
+ _warn('infra_backoff ignored, using the default: ' + problem)
758
+ return default_backoff()
759
+
760
+ def start_wait(pause: dict, info: dict, name: str) -> None:
761
+ """Begin the scope's next wait, or mark it exhausted when its budget is spent."""
762
+ done, budget = scope_waits.get(pause['scope'], 0), infra_budget()
763
+ where = pause['harness'] + ('/' + pause['model'] if pause['model'] else '')
764
+ head = 'forge: infrastructure failure (' + pause['class'] + ') on ' + where + ' for ' + name
765
+ if done >= budget:
766
+ pause.update(cycle=done, until=None, exhausted=True)
767
+ print(head + '; its waits are used up (' + str(done) + ' of ' + str(budget)
768
+ + '), so it stays paused; other tasks continue (no attempt spent)', file=sys.stderr, flush=True)
769
+ return
770
+ wait, source = infra_wait(info, done, backoff())
771
+ pause.update(cycle=done + 1, until=time.time() + wait, exhausted=False)
772
+ print(head + '; pausing it, waiting ' + ('%g' % wait) + 's before resuming (' + source + ', wait '
773
+ + str(done + 1) + ' of ' + str(budget) + '); other tasks continue (no attempt spent)',
774
+ file=sys.stderr, flush=True)
775
+
776
+ def infra_stopped(name: str) -> None:
777
+ nonlocal paused, all_class
778
+ pairs_cache.pop(name, None)
779
+ info = infra_info(plan / 'tasks' / name)
780
+ scope, harness, model = infra_scope(info)
781
+ if scope == 'all':
782
+ paused = True
783
+ all_class = all_class or info.get('class', '')
784
+ if name not in infra_seen:
785
+ infra_seen.append(name)
786
+ elif scope in pauses:
787
+ # A stop in a scope already paused joins its wait and is not counted again.
788
+ if name not in pauses[scope]['tasks']:
789
+ pauses[scope]['tasks'].append(name)
790
+ else:
791
+ pauses[scope] = {'scope': scope, 'class': info.get('class', ''), 'harness': harness,
792
+ 'model': model if scope.startswith('model:') else None, 'tasks': [name],
793
+ 'cycle': 0, 'until': None, 'exhausted': False, 'info': info}
794
+ start_wait(pauses[scope], info, name)
795
+ if scope != 'all':
796
+ fall_back(name, info, scope)
797
+ write_paused()
798
+
799
+ def end_scoped_waits() -> None:
800
+ """Resume the tasks of every scope whose wait is over; an exhausted scope whose
801
+ budget was raised meanwhile starts its next wait."""
802
+ for scope, pause in list(pauses.items()):
803
+ if interrupted:
804
+ return
805
+ if pause['exhausted']:
806
+ if scope_waits.get(scope, 0) < infra_budget():
807
+ start_wait(pause, pause['info'], ', '.join(pause['tasks']))
808
+ continue
809
+ if time.time() < pause['until']:
810
+ continue
811
+ scope_waits[scope] = scope_waits.get(scope, 0) + 1
812
+ del pauses[scope]
813
+ for name in reversed(pause['tasks']):
814
+ pairs_cache.pop(name, None)
815
+ if name not in pending and status(name) == 'INFRA' and resume(name):
816
+ pending.insert(0, name)
817
+ print('forge: the pause on ' + scope.partition(':')[2] + ' is over'
818
+ + ('; resuming ' + ', '.join(pause['tasks']) + ' (no attempt spent)' if pause['tasks'] else ''),
819
+ file=sys.stderr, flush=True)
820
+ write_paused()
821
+
822
+ def apply_retry(request: dict) -> tuple:
823
+ name, dwarf = request['task'], request.get('dwarf')
824
+ if name not in tasks:
825
+ return 'refused', 'this run does not know task ' + name
826
+ if name in active:
827
+ return 'refused', 'the task is running'
828
+ if name in pending:
829
+ return 'refused', 'the task is already waiting to run'
830
+ state = status(name)
831
+ if state == 'MERGED':
832
+ return 'refused', 'the task is merged'
833
+ if state == 'INFRA':
834
+ return 'refused', 'an infrastructure stop is resumed by the scheduler itself'
835
+ if state not in RETRYABLE:
836
+ return 'refused', 'a ' + state + ' task is not retried'
837
+ command = ['/bin/bash', script, '_prepare_retry', str(plan), name] + (['--dwarf', dwarf] if dwarf else [])
838
+ rc = subprocess.run(command).returncode
839
+ if rc == 3:
840
+ try:
841
+ why = (plan / 'tasks' / name / 'split.suggested').read_text().strip()
842
+ except OSError:
843
+ why = ''
844
+ return 'refused', why or 'the retry policy stopped this task: split it or name a --dwarf'
845
+ if rc:
846
+ return 'refused', 'the retry could not be prepared (exit ' + str(rc) + '; see the run output)'
847
+ # A human's retry: no automatic budget is spent, and a stop marker the
848
+ # preparation cleared (an explicit --dwarf) no longer holds the task.
849
+ pairs_cache.pop(name, None)
850
+ refused.pop(name, None)
851
+ retried.add(name)
852
+ human.add(name)
853
+ pending.insert(0, name)
854
+ return 'applied', None
855
+
856
+ def apply_add(request: dict) -> tuple:
857
+ name = request['task']
858
+ if name in tasks:
859
+ return 'refused', 'the task is already in this run'
860
+ try:
861
+ rows = [line.split('\t') for line in (plan / 'tasks.tsv').read_text().splitlines()
862
+ if line and not line.startswith('#')]
863
+ except OSError as error:
864
+ return 'refused', 'tasks.tsv could not be read: ' + str(error)
865
+ if any(len(row) != 7 for row in rows):
866
+ return 'refused', 'tasks.tsv requires seven columns'
867
+ if len({row[0] for row in rows}) != len(rows):
868
+ return 'refused', 'tasks.tsv has duplicate task IDs'
869
+ found = [row for row in rows if row[0] == name]
870
+ if not found:
871
+ return 'refused', 'the row is not in tasks.tsv'
872
+ deps = [d for d in found[0][1].split(',') if d and d != '-']
873
+ unknown = [d for d in deps if d not in tasks]
874
+ if unknown:
875
+ # Every known task was read at start, so a dep among them cannot close a cycle.
876
+ return 'refused', 'it depends on task(s) this run does not know: ' + ', '.join(unknown)
877
+ root = plan / 'tasks' / name
878
+ try:
879
+ root.mkdir(parents=True, exist_ok=True)
880
+ if not stat.S_ISDIR(os.lstat(root).st_mode):
881
+ return 'refused', 'tasks/' + name + ' is not a real directory'
882
+ except OSError as error:
883
+ return 'refused', 'tasks/' + name + ' could not be created: ' + str(error)
884
+ tasks[name] = found[0]
885
+ pending.append(name)
886
+ if subprocess.run(['/bin/bash', script, '_waves', str(plan)]).returncode:
887
+ _warn('waves.tsv was not refreshed for ' + name + '; the task still runs')
888
+ return 'applied', None
889
+
890
+ def is_fix(name: str) -> bool:
891
+ """A finding sweep's fix task."""
892
+ return (plan / 'tasks' / name / 'sweep.json').is_file()
893
+
894
+ def sweep_due() -> bool:
895
+ """--sweep was given, every task merged, nothing stops or holds the run, and this plan was
896
+ never swept (sweep/plan.json is the planner's record, and its marker)."""
897
+ return (bool(sweep) and not sweep_asked and not interrupted and not graceful and not paused
898
+ and not drained(plan) and not (plan / 'sweep' / 'plan.json').exists()
899
+ and all(status(name) == 'MERGED' for name in tasks))
900
+
901
+ def start_sweep() -> int:
902
+ """Plan the finding sweep and queue its fix tasks; how many were queued. Whatever goes
903
+ wrong here ends the run without a sweep, never with a failure."""
904
+ nonlocal sweep_asked
905
+ sweep_asked = True
906
+ command = ['/bin/bash', script, '_sweep', str(plan), '--severity', sweep, '--max', str(sweep_max)]
907
+ result = subprocess.run(command + (['--plausible'] if sweep_plausible else []),
908
+ stdout=subprocess.PIPE, text=True)
909
+ if result.returncode:
910
+ _warn('the finding sweep could not be planned (exit ' + str(result.returncode)
911
+ + '); its findings stay for forge issues')
912
+ return 0
913
+ queued = 0
914
+ for name in result.stdout.split():
915
+ outcome, reason = apply_add({'task': name})
916
+ if outcome == 'applied':
917
+ queued += 1
918
+ else:
919
+ _warn('sweep task ' + name + ' was not queued: ' + str(reason))
920
+ return queued
921
+
922
+ def handle_requests() -> None:
923
+ """Apply or refuse each queued request; the outcome is logged under the control lock."""
924
+ for name in list_requests(plan):
925
+ request = read_request(plan, name)
926
+ if request is None:
927
+ outcome, reason = 'refused', 'not a valid request'
928
+ elif interrupted or graceful:
929
+ outcome, reason = 'refused', 'run is stopping'
930
+ elif request['verb'] == 'retry':
931
+ outcome, reason = apply_retry(request)
932
+ else:
933
+ outcome, reason = apply_add(request)
934
+ with _control_lock(plan):
935
+ settle_request(plan, name, request, outcome, reason)
936
+
937
+ def reap_exited(into: set[str] | None = None, *, allow_requeue: bool = True) -> None:
938
+ """Reap every active task whose process has already exited.
939
+
940
+ Merging is serial and can take long enough for another task to finish, so
941
+ repeat until a pass finds nothing. PASS is merged and a process that died
942
+ still RUNNING becomes ERROR. Once `interrupted` is set, every other status
943
+ is kept and nothing is requeued: the next `run --retry-failed` decides.
944
+ `finally` passes allow_requeue=False for the same reason. It also runs when
945
+ the loop raises, and a retry prepared on the way out would clear a recorded
946
+ failure that nothing is left to dispatch.
947
+ """
948
+ while True:
949
+ reaped = False
950
+ for name, (process, log) in list(active.items()):
951
+ if process.poll() is None:
952
+ continue
953
+ reaped = True
954
+ if into is not None:
955
+ into.add(name)
956
+ log.close()
957
+ del active[name]
958
+ if os.environ.get('FORGE_OUTPUT') == 'full':
959
+ echo_output(name)
960
+ state = status(name)
961
+ if state == 'PASS':
962
+ merge(name)
963
+ elif state == 'RUNNING':
964
+ mark(name, 'ERROR')
965
+ elif state == 'INFRA':
966
+ infra_stopped(name)
967
+ elif allow_requeue and not interrupted and not graceful \
968
+ and state in ('FAIL', 'UNKNOWN') and retryable(name):
969
+ requeue(name)
970
+ if not reaped:
971
+ return
972
+
360
973
  def stop(signum: int, frame: object) -> None:
361
974
  nonlocal interrupted
362
975
  interrupted = True
@@ -369,42 +982,38 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
369
982
  # Saved PASS results use the same fingerprint checks without paying for
370
983
  # implementation or QA again; an INFRA stop is not a failure of the work, so it
371
984
  # is simply dispatched again.
985
+ # RUNNING at start means a scheduler was killed without its cleanup: its tasks'
986
+ # harnesses may still be running and editing their worktrees.
987
+ stop_harnesses(plan, [name for name in pending if status(name) == 'RUNNING'])
372
988
  for name in pending[:]:
373
989
  state = status(name)
374
990
  if state == 'PASS':
375
991
  merge(name)
376
992
  if state == 'RUNNING':
377
993
  mark(name, 'INTERRUPTED')
378
- if state in ('FAIL', 'UNKNOWN') and retryable(name):
994
+ if state in ('FAIL', 'UNKNOWN') and not interrupted and retryable(name):
379
995
  requeue(name)
380
- if state == 'INFRA' and not resume(name):
996
+ if state == 'INFRA' and not interrupted and not resume(name):
381
997
  pending.remove(name)
382
998
  continue
383
999
  if status(name) not in ('PENDING', 'BLOCKED', 'INFRA'):
384
1000
  pending.remove(name)
385
1001
  swept = time.monotonic()
386
- while pending or active:
1002
+ while pending or active or waiting_scopes() or sweep_due():
1003
+ # Reap before honouring the stop. A signal during the sleep, and a task
1004
+ # that exits while another merge is still running, have already written
1005
+ # a result; breaking first used to skip them and mark them INTERRUPTED.
1006
+ ended = set()
1007
+ # `stop --now` is SIGTERM by another route; a graceful stop lets the running finish.
1008
+ mode = stop_mode(plan)
1009
+ if mode == 'now':
1010
+ interrupted = True
1011
+ graceful = graceful or mode == 'graceful'
1012
+ reap_exited(ended)
387
1013
  if interrupted:
388
1014
  break
389
- ended = set()
390
- for name, (process, log) in list(active.items()):
391
- if process.poll() is not None:
392
- ended.add(name)
393
- log.close()
394
- del active[name]
395
- if os.environ.get('FORGE_OUTPUT') == 'full':
396
- echo_output(name)
397
- state = status(name)
398
- if state == 'PASS':
399
- merge(name)
400
- elif state == 'RUNNING':
401
- mark(name, 'ERROR')
402
- elif state == 'INFRA':
403
- paused = True
404
- if name not in infra_seen:
405
- infra_seen.append(name)
406
- elif state in ('FAIL', 'UNKNOWN') and retryable(name):
407
- requeue(name)
1015
+ draining = drained(plan)
1016
+ drain_told = drain_told and draining
408
1017
  if time.monotonic() - swept >= SWEEP_EVERY:
409
1018
  # A human can raise a budget after a task already ended FAIL while others
410
1019
  # still run. The initial pass's predicate, for tasks nothing else will look
@@ -413,37 +1022,59 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
413
1022
  for name in tasks:
414
1023
  if name in pending or name in active or name in ended:
415
1024
  continue
416
- if status(name) in ('FAIL', 'UNKNOWN') and retryable(name) \
417
- and refused.get(name) != budget(name):
1025
+ if not interrupted and not graceful and status(name) in ('FAIL', 'UNKNOWN') \
1026
+ and retryable(name) and refused.get(name) != budget(name):
418
1027
  requeue(name)
419
- if paused and not active and infra_seen and infra_cycles < infra_budget():
1028
+ if paused and not active and infra_seen and not graceful and infra_cycles < infra_budget():
420
1029
  # Everything running has drained. Wait out the outage once for all the
421
1030
  # tasks it stopped, then dispatch them again.
422
- wait = max(infra_wait(infra_info(plan / 'tasks' / n), infra_cycles) for n in infra_seen)
1031
+ shape = backoff()
1032
+ wait, source = max(infra_wait(infra_info(plan / 'tasks' / n), infra_cycles, shape) for n in infra_seen)
423
1033
  infra_cycles += 1
424
1034
  print('forge: infrastructure failure on ' + ', '.join(infra_seen)
425
- + '; waiting ' + ('%g' % wait) + 's before resuming (no attempt spent)',
1035
+ + '; waiting ' + ('%g' % wait) + 's before resuming (' + source + ', wait '
1036
+ + str(infra_cycles) + ' of ' + str(infra_budget()) + ') (no attempt spent)',
426
1037
  file=sys.stderr, flush=True)
427
1038
  resume_at = time.time() + wait
1039
+ write_paused(resume_at)
428
1040
  while time.time() < resume_at and not interrupted:
1041
+ # A stop of either kind ends the wait: nothing is active, so it ends the run.
1042
+ mode = stop_mode(plan)
1043
+ if mode:
1044
+ interrupted = interrupted or mode == 'now'
1045
+ graceful = graceful or mode == 'graceful'
1046
+ break
429
1047
  time.sleep(min(0.05, max(resume_at - time.time(), 0)))
430
- if interrupted:
1048
+ if interrupted or graceful:
1049
+ if graceful:
1050
+ print('forge: stopped by forge control stop; ' + str(len(pending) + len(infra_seen))
1051
+ + ' task(s) not started', file=sys.stderr, flush=True)
431
1052
  break
432
1053
  # A pin set before or during the wait applies to the entries that run the
433
1054
  # implementer again; a QA-stage stop keeps it for the next full retry.
434
1055
  for name in reversed(infra_seen):
1056
+ if interrupted:
1057
+ break
435
1058
  if name not in pending and resume(name):
436
1059
  pending.insert(0, name)
437
1060
  infra_seen.clear()
438
1061
  paused = False
1062
+ all_class = ''
1063
+ write_paused()
1064
+ end_scoped_waits()
1065
+ handle_requests()
1066
+ cap = live_capacity(plan, capacity)
1067
+ draining = drained(plan) # again: the infrastructure wait above can last minutes
439
1068
  for name in pending[:]:
440
- if paused or len(active) >= capacity or interrupted:
1069
+ if paused or len(active) >= cap or interrupted or graceful or draining:
441
1070
  break
442
1071
  deps = [d for d in tasks[name][1].split(',') if d and d != '-']
443
1072
  if any(status(dep) != 'MERGED' for dep in deps):
444
1073
  continue
445
1074
  if any(overlap(tasks[name][3], tasks[other][3]) for other in active):
446
1075
  continue
1076
+ if pauses and scope_held(name):
1077
+ continue
447
1078
  root = plan / 'tasks' / name
448
1079
  if not (root / 'base_ref').exists():
449
1080
  worktree = Path((plan / 'wt_root').read_text().strip()) / '_integration'
@@ -452,8 +1083,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
452
1083
  log = open(root / 'task.out', 'ab')
453
1084
  # A retried task runs with the same environment `retry` gives it, so the
454
1085
  # no-progress guard (byte-identical diff) applies under Fractal too.
455
- env = (dict(os.environ, FORGE_FRACTAL_RETRY='1', FORGE_DATASET_TRIGGER='auto')
1086
+ env = (dict(os.environ, FORGE_FRACTAL_RETRY='1',
1087
+ FORGE_DATASET_TRIGGER='human' if name in human else 'auto')
456
1088
  if name in retried else None)
1089
+ human.discard(name)
457
1090
  process = subprocess.Popen(
458
1091
  ['/bin/bash', script, '_task', str(plan), name],
459
1092
  stdout=log, stderr=subprocess.STDOUT, start_new_session=True, env=env,
@@ -461,12 +1094,24 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
461
1094
  active[name] = process, log
462
1095
  pending.remove(name)
463
1096
  print('forge: dispatched ' + name + ' -> ' + str(root), file=sys.stderr, flush=True)
464
- if not active:
465
- if paused or held:
1097
+ if not active and graceful:
1098
+ # Not BLOCKED: a stop is not a dependency failure, so the next run starts them.
1099
+ print('forge: stopped by forge control stop; ' + str(len(pending)) + ' task(s) not started',
1100
+ file=sys.stderr, flush=True)
1101
+ break
1102
+ if not active and draining and (pending or waiting_scopes()):
1103
+ if not drain_told:
1104
+ drain_told = True
1105
+ print('forge: drained — ' + str(len(pending)) + ' task(s) waiting; forge control resume '
1106
+ + str(plan) + ' continues', file=sys.stderr, flush=True)
1107
+ elif not active and not waiting_scopes():
1108
+ if paused or held or any(live_pause(pause) for pause in pauses.values()):
466
1109
  # Infrastructure stop: leave everything not yet run PENDING. Marking it
467
1110
  # BLOCKED would turn "the provider was down" into a recorded failure.
468
1111
  # A task held back by its pin is still an infrastructure stop.
469
1112
  break
1113
+ if not pending and sweep_due() and start_sweep():
1114
+ continue
470
1115
  for name in pending:
471
1116
  mark(name, 'BLOCKED')
472
1117
  break
@@ -474,33 +1119,67 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
474
1119
  finally:
475
1120
  # Not live from here on: a late `forge control` must not edit budgets nobody reads.
476
1121
  live_stop(plan, tasks)
477
- for process, log in active.values():
1122
+ # Poll before any signal. A process that has already exited keeps the result
1123
+ # it wrote (PASS is merged); only a process that is still alive is stopped.
1124
+ # Never requeue here: this block also runs when the loop raises, and a retry
1125
+ # prepared then would erase the recorded failure and spend its budget.
1126
+ reap_exited(allow_requeue=False)
1127
+ stopping = list(active.items())
1128
+ for name, (process, log) in stopping:
478
1129
  try:
479
1130
  os.killpg(process.pid, signal.SIGTERM)
480
- except ProcessLookupError:
1131
+ except OSError:
481
1132
  pass
482
- for name, (process, log) in active.items():
1133
+ # The group outlives its leader while dispatch's EXIT trap stops the harness, so wait
1134
+ # for the group to empty, not for the leader. Reaping the leader matters too: its
1135
+ # zombie would keep the group alive.
1136
+ deadline = time.monotonic() + interrupt_grace()
1137
+ waiting = {name for name, _ in stopping}
1138
+ while waiting:
1139
+ for name, (process, log) in stopping:
1140
+ if name in waiting:
1141
+ process.poll()
1142
+ if not _group_alive(process.pid):
1143
+ waiting.discard(name)
1144
+ if not waiting or time.monotonic() >= deadline:
1145
+ break
1146
+ time.sleep(0.05)
1147
+ for name, (process, log) in stopping:
1148
+ if name in waiting:
1149
+ try:
1150
+ os.killpg(process.pid, signal.SIGKILL)
1151
+ except OSError:
1152
+ pass
483
1153
  try:
484
1154
  process.wait(timeout=5)
485
1155
  except subprocess.TimeoutExpired:
486
1156
  pass
487
- # Remove descendants even if the shell exited before its backend.
488
- try:
489
- os.killpg(process.pid, signal.SIGKILL)
490
- except ProcessLookupError:
491
- pass
492
- process.wait()
493
1157
  log.close()
494
- mark(name, 'INTERRUPTED')
495
- if interrupted:
1158
+ stop_harnesses(plan, [name for name, _ in stopping])
1159
+ for name, _ in stopping:
1160
+ try:
1161
+ mark(name, 'INTERRUPTED')
1162
+ except OSError as error:
1163
+ _warn('could not mark ' + name + ' INTERRUPTED: ' + str(error))
1164
+ if interrupted or (graceful and not all(status(name) == 'MERGED' for name in tasks)):
496
1165
  return 130
497
- if paused or any(status(name) == 'INFRA' for name in tasks):
1166
+ if paused or any(live_pause(pause) for pause in pauses.values()) \
1167
+ or any(status(name) == 'INFRA' for name in tasks):
498
1168
  return INFRA_EXIT
499
- return 0 if all(status(name) == 'MERGED' for name in tasks) else 5
1169
+ # A fix task that did not merge leaves its findings for `forge issues`; the run's own work is done.
1170
+ return 0 if all(status(name) == 'MERGED' for name in tasks if not is_fix(name)) else 5
500
1171
 
501
1172
 
502
1173
  def main() -> None:
503
1174
  try:
1175
+ if sys.argv[1] == 'backoff-check':
1176
+ # The --infra-backoff flag's validation: one parser for every reader of the shape.
1177
+ try:
1178
+ parse_backoff(sys.argv[2] if len(sys.argv) > 2 else '')
1179
+ except ValueError as error:
1180
+ print('forge: --infra-backoff: ' + str(error), file=sys.stderr)
1181
+ sys.exit(2)
1182
+ sys.exit(0)
504
1183
  if sys.argv[1] == 'lock':
505
1184
  _, script, command, plan, *args = sys.argv[1:]
506
1185
  # The shell inherits the lock for its entire operation, including
@@ -516,9 +1195,12 @@ def main() -> None:
516
1195
  parser.add_argument('capacity', type=int)
517
1196
  parser.add_argument('--retry-failed', type=int, default=0, metavar='N')
518
1197
  parser.add_argument('--infra-retries', type=int, default=0, metavar='M')
1198
+ parser.add_argument('--sweep', choices=('P0', 'P1', 'P2', 'P3'))
1199
+ parser.add_argument('--sweep-max', type=int, default=5, metavar='N')
1200
+ parser.add_argument('--sweep-plausible', action='store_true')
519
1201
  args = parser.parse_args(sys.argv[1:])
520
1202
  sys.exit(schedule(args.script, args.plan, args.capacity, args.retry_failed,
521
- args.infra_retries))
1203
+ args.infra_retries, args.sweep, args.sweep_max, args.sweep_plausible))
522
1204
  except (OSError, ValueError, KeyError) as error:
523
1205
  print('forge scheduler: ' + str(error), file=sys.stderr)
524
1206
  sys.exit(3)