@giamme/forge 0.20.0 → 0.21.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 (52) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +7 -0
  3. package/VERSION +1 -1
  4. package/docs/README.md +1 -0
  5. package/docs/development.md +1 -1
  6. package/package.json +1 -1
  7. package/scripts/forge-config.py +10 -9
  8. package/scripts/forge-control.py +51 -35
  9. package/scripts/forge-group.py +2 -1
  10. package/scripts/forge-guard.py +71 -33
  11. package/scripts/forge-handoff.py +14 -17
  12. package/scripts/forge-issues.py +5 -2
  13. package/scripts/forge-parallel.sh +18 -10
  14. package/scripts/forge-planner.py +28 -2
  15. package/scripts/forge-pre-review.py +11 -4
  16. package/scripts/forge-ripwire.py +68 -22
  17. package/scripts/forge-route.py +10 -3
  18. package/scripts/forge-runs-compact.py +3 -2
  19. package/scripts/forge-runs-rm.py +14 -14
  20. package/scripts/forge-runtime.py +36 -19
  21. package/scripts/forge-schedule.py +72 -55
  22. package/scripts/forge-shadow.py +16 -9
  23. package/scripts/forge-summarize.py +7 -3
  24. package/scripts/forge-sweep.py +7 -2
  25. package/scripts/forge-ui.py +8 -13
  26. package/scripts/forge-verify.py +29 -23
  27. package/scripts/forge_brief/__init__.py +1 -1
  28. package/scripts/forge_brief/proposals.py +7 -2
  29. package/scripts/forge_decide/budget.py +6 -1
  30. package/scripts/forge_decide/replay.py +6 -1
  31. package/scripts/forge_findings/apply.py +2 -1
  32. package/scripts/forge_findings/store.py +16 -4
  33. package/scripts/forge_findings/triage.py +6 -15
  34. package/scripts/forge_flock.py +87 -0
  35. package/scripts/forge_fractal/__init__.py +7 -3
  36. package/scripts/forge_fractal/cli.py +7 -2
  37. package/scripts/forge_fractal/execution.py +14 -14
  38. package/scripts/forge_fractal/invocation.py +3 -2
  39. package/scripts/forge_fractal/pipeline.py +2 -1
  40. package/scripts/forge_fractal/selection.py +2 -1
  41. package/scripts/forge_identity.py +2 -1
  42. package/scripts/forge_locations.py +14 -4
  43. package/scripts/forge_posix.py +108 -0
  44. package/scripts/forge_proc.py +399 -0
  45. package/scripts/forge_registry.py +15 -6
  46. package/scripts/forge_retro/__init__.py +8 -2
  47. package/scripts/forge_retro/issues.py +2 -1
  48. package/scripts/forge_side/__init__.py +19 -10
  49. package/scripts/forge_storage.py +11 -1
  50. package/ui/forge_ui/control.py +35 -12
  51. package/ui/forge_ui/reader.py +18 -17
  52. package/ui/forge_ui/server.py +10 -1
@@ -53,9 +53,15 @@ import shutil
53
53
  import stat
54
54
  import subprocess
55
55
  import sys
56
+ from pathlib import Path
57
+
58
+ _SCRIPTS = str(Path(__file__).resolve().parent)
59
+ if _SCRIPTS not in sys.path:
60
+ sys.path.insert(0, _SCRIPTS)
61
+ import forge_posix # noqa: E402
62
+ import forge_proc # noqa: E402
56
63
  import tempfile
57
64
  import time
58
- from pathlib import Path
59
65
 
60
66
  SCRIPTS = Path(__file__).resolve().parent
61
67
  sys.path.insert(0, str(SCRIPTS))
@@ -134,7 +140,7 @@ class Plan:
134
140
  """The text of a regular file under the run dir, or None (missing: silent; anything else warns)."""
135
141
  try:
136
142
  # O_NONBLOCK: a FIFO with no writer would block an open; it is not a regular file anyway.
137
- fd = os.open(self.path / rel, os.O_RDONLY | os.O_NONBLOCK)
143
+ fd = os.open(self.path / rel, os.O_RDONLY | forge_posix.O_NONBLOCK)
138
144
  except FileNotFoundError:
139
145
  return None
140
146
  except (OSError, ValueError) as error:
@@ -240,17 +246,7 @@ def flags_section(plan):
240
246
 
241
247
 
242
248
  def pid_alive(pid):
243
- if type(pid) is not int or pid <= 0:
244
- return False
245
- try:
246
- os.kill(pid, 0)
247
- except ProcessLookupError:
248
- return False
249
- except PermissionError:
250
- return True
251
- except (OSError, OverflowError):
252
- return False
253
- return True
249
+ return forge_proc.pid_alive(pid)
254
250
 
255
251
 
256
252
  def scheduler_section(plan):
@@ -790,7 +786,7 @@ def run_command(plan, flags):
790
786
  value = flags.get(key)
791
787
  return value if type(value) is int and value >= least else None
792
788
 
793
- command = ['/bin/bash', parallel_script(), 'run', str(plan)]
789
+ command = forge_proc.bash_cmd(parallel_script(), 'run', str(plan))
794
790
  for key, option, least in (('retry_failed', '--retry-failed', 0), ('infra_retries', '--infra-retries', 0)):
795
791
  if whole(key, least) is not None:
796
792
  command += [option, str(flags[key])]
@@ -977,7 +973,7 @@ def recover_task(ctrl, plan, wt_root, run_id, task, warn):
977
973
 
978
974
  def prepare_task(plan, task):
979
975
  """forge-parallel.sh retry PLAN TASK --no-dispatch. {task, ok, message}."""
980
- command = ['/bin/bash', parallel_script(), 'retry', str(plan), task, '--no-dispatch']
976
+ command = forge_proc.bash_cmd(parallel_script(), 'retry', str(plan), task, '--no-dispatch')
981
977
  try:
982
978
  result = subprocess.run(command, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=600)
983
979
  except (OSError, subprocess.SubprocessError) as error:
@@ -992,8 +988,9 @@ def start_run(plan, command):
992
988
  log, done = os.path.join(plan, f'resume-{stamp}.log'), os.path.join(plan, f'resume-{stamp}.done')
993
989
  wrapper = '"${@:2}"; rc=$?; printf "%s\\n" "$rc" > "$1.tmp" && mv -f "$1.tmp" "$1"; exit "$rc"'
994
990
  with open(log, 'ab') as out:
995
- process = subprocess.Popen(['/bin/bash', '-c', wrapper, 'forge-resume', done, *command], stdin=subprocess.DEVNULL,
996
- stdout=out, stderr=subprocess.STDOUT, start_new_session=True, cwd=plan)
991
+ process = subprocess.Popen(forge_proc.bash_cmd('-c', wrapper, 'forge-resume', done, *command),
992
+ stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
993
+ cwd=plan, **forge_proc.popen_group_kwargs(detached=True))
997
994
  return {'pid': process.pid, 'log': log, 'done': done}
998
995
 
999
996
 
@@ -76,7 +76,6 @@ from __future__ import annotations
76
76
  import argparse
77
77
  import contextlib
78
78
  import errno
79
- import fcntl
80
79
  import hashlib
81
80
  import importlib.util
82
81
  import json
@@ -91,6 +90,7 @@ import time
91
90
  from pathlib import Path
92
91
 
93
92
  sys.path.insert(0, str(Path(__file__).resolve().parent))
93
+ import forge_posix # noqa: E402
94
94
  from forge_registry import repo_key # noqa: E402
95
95
  import forge_identity # noqa: E402
96
96
  from forge_findings import status as record_status # noqa: E402
@@ -992,7 +992,10 @@ def _read_store(name, noun, shape, valid):
992
992
  if not stat.S_ISREG(os.lstat(path).st_mode):
993
993
  raise Fail(not_regular)
994
994
  # NOFOLLOW again for a swap after the lstat; NONBLOCK so a FIFO cannot hold the open
995
- with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as fh:
995
+ with os.fdopen(
996
+ forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK),
997
+ "rb",
998
+ ) as fh:
996
999
  if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
997
1000
  raise Fail(not_regular)
998
1001
  raw = fh.read(STORE_MAX + 1)
@@ -1688,18 +1688,26 @@ run_worktree_setup() { # run_worktree_setup <plan> <repo> <wt> <tdir> <id>
1688
1688
  fi
1689
1689
  }
1690
1690
 
1691
+ add_task_worktree() { # add_task_worktree <repo> <wt> <br> <base>: on <br> when it exists, else a new <br> at <base>
1692
+ if (cd "$1" && git rev-parse --verify --quiet "$3" >/dev/null 2>&1); then
1693
+ (cd "$1" && git worktree add "$2" "$3")
1694
+ else
1695
+ (cd "$1" && git worktree add -b "$3" "$2" "$4")
1696
+ fi
1697
+ }
1698
+
1691
1699
  ensure_worktree() { # ensure_worktree <repo> <wt> <br> <base> <tdir> <plan> <id>
1692
1700
  local REPO="$1" wt="$2" br="$3" base="$4" tdir="$5" PLAN="$6" id="$7"
1693
- # A worktree directory deleted by hand leaves its registration behind, and that
1694
- # registration then blocks `worktree add` with "already exists". Prune first.
1695
- (cd "$REPO" && git worktree prune >/dev/null 2>&1)
1696
- if [ -e "$wt/.git" ]; then
1697
- return 0
1698
- elif (cd "$REPO" && git rev-parse --verify --quiet "$br" >/dev/null 2>&1); then
1699
- (cd "$REPO" && git worktree add "$wt" "$br") >"$tdir/worktree.out" 2>&1
1700
- else
1701
- (cd "$REPO" && git worktree add -b "$br" "$wt" "$base") >"$tdir/worktree.out" 2>&1
1702
- fi || return 1
1701
+ [ ! -e "$wt/.git" ] || return 0
1702
+ # A worktree directory deleted by hand leaves its registration behind, and that registration
1703
+ # blocks `worktree add` with "already exists": prune, then add again. Only after a failed add:
1704
+ # tasks start together, and a prune while another task's add is midway removes that task's
1705
+ # half-made registration ("could not open '.git/worktrees/<id>/gitdir'"). The second add also
1706
+ # recovers from a prune that another forge process ran at that moment.
1707
+ add_task_worktree "$REPO" "$wt" "$br" "$base" >"$tdir/worktree.out" 2>&1 || {
1708
+ (cd "$REPO" && git worktree prune >/dev/null 2>&1)
1709
+ add_task_worktree "$REPO" "$wt" "$br" "$base" >>"$tdir/worktree.out" 2>&1
1710
+ } || return 1
1703
1711
  forge_worktree_event created "$PLAN" "$REPO" "$wt" "$br" task "$id"
1704
1712
  run_worktree_setup "$PLAN" "$REPO" "$wt" "$tdir" "$id"
1705
1713
  }
@@ -455,15 +455,41 @@ def check_graph(tasks: list):
455
455
  visit(t['id'], [t['id']])
456
456
 
457
457
 
458
+ MAX_JSON_DEPTH = 64 # a plan is a few levels deep; anything near this is not a plan
459
+ MAX_INT_DIGITS = 4300 # Python's own limit from 3.11 (and late 3.9/3.10 patch releases); not in 3.9.13 or Apple's 3.9.6
460
+
461
+
462
+ def bounded_int(text: str) -> int:
463
+ """int() for json.loads, refusing the very long integers that recent Pythons refuse too."""
464
+ if len(text.lstrip('-')) > MAX_INT_DIGITS:
465
+ raise ValueError(f'an integer of more than {MAX_INT_DIGITS} digits')
466
+ return int(text)
467
+
468
+
469
+ def nested_deeper_than(value, limit: int) -> bool:
470
+ """Whether lists and objects nest more than `limit` levels, checked without recursion."""
471
+ stack = [(value, 1)]
472
+ while stack:
473
+ item, depth = stack.pop()
474
+ if isinstance(item, (dict, list)):
475
+ if depth > limit:
476
+ return True
477
+ stack.extend((child, depth + 1) for child in (item.values() if isinstance(item, dict) else item))
478
+ return False
479
+
480
+
458
481
  def parse_reply(reply: str):
459
482
  """(tasks, groups). groups is None when the reply has no groups key, else a list (maybe empty)."""
460
483
  body = extract_block(reply)
461
484
  try:
462
- data = json.loads(body, object_pairs_hook=no_duplicate_keys)
485
+ data = json.loads(body, object_pairs_hook=no_duplicate_keys, parse_int=bounded_int)
463
486
  except (ValueError, RecursionError) as err:
464
487
  # JSONDecodeError is a ValueError; so is Python's limit on integer digits. Nesting deeper
465
- # than the interpreter allows raises RecursionError.
488
+ # than the interpreter allows raises RecursionError (up to Python 3.11; from 3.12 the
489
+ # parser goes much deeper, hence the explicit limit below).
466
490
  raise Refusal(f'the forge-plan body is not valid JSON: {type(err).__name__}: {str(err)[:200]}')
491
+ if nested_deeper_than(data, MAX_JSON_DEPTH):
492
+ raise Refusal(f'the forge-plan body is not valid JSON: nested more than {MAX_JSON_DEPTH} levels deep')
467
493
  check_keys(data, ('tasks',), 'the forge-plan body', ('groups',))
468
494
  tasks = data['tasks']
469
495
  if not isinstance(tasks, list) or not 1 <= len(tasks) <= MAX_TASKS:
@@ -54,6 +54,11 @@ import sys
54
54
  import tempfile
55
55
  import time
56
56
 
57
+ _SCRIPTS = str(Path(__file__).resolve().parent)
58
+ if _SCRIPTS not in sys.path:
59
+ sys.path.insert(0, _SCRIPTS)
60
+ import forge_proc # noqa: E402
61
+
57
62
  _SPEC = importlib.util.spec_from_file_location('forge_fail_first', Path(__file__).resolve().parent / 'forge-fail-first.py')
58
63
  failfirst = importlib.util.module_from_spec(_SPEC)
59
64
  _SPEC.loader.exec_module(failfirst)
@@ -228,10 +233,12 @@ class Slot:
228
233
  fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
229
234
  except FileExistsError:
230
235
  try:
231
- os.kill(int(path.read_text().strip() or 0), 0)
232
- except (ProcessLookupError, ValueError):
233
- path.unlink(missing_ok=True) # its holder is gone
234
- except (OSError, PermissionError):
236
+ holder = int(path.read_text().strip() or 0)
237
+ if holder != 0 and not forge_proc.pid_alive(holder):
238
+ path.unlink(missing_ok=True) # its holder is gone
239
+ except ValueError:
240
+ path.unlink(missing_ok=True)
241
+ except OSError:
235
242
  pass
236
243
  continue
237
244
  with os.fdopen(fd, 'w') as handle:
@@ -10,9 +10,15 @@ import shutil
10
10
  import signal
11
11
  import subprocess
12
12
  import tempfile
13
+ import threading
13
14
  import time
14
15
  import sys
15
16
 
17
+ _SCRIPTS = str(Path(__file__).resolve().parent)
18
+ if _SCRIPTS not in sys.path:
19
+ sys.path.insert(0, _SCRIPTS)
20
+ import forge_proc # noqa: E402
21
+
16
22
 
17
23
  def resolve():
18
24
  binary = shutil.which('ripwire')
@@ -22,40 +28,80 @@ def resolve():
22
28
  return str(Path(binary).resolve()) if binary else None
23
29
 
24
30
 
31
+ def _bounded_windows(process, deadline, limit):
32
+ output = [bytearray(), bytearray()]
33
+ exceeded = threading.Event()
34
+
35
+ def _drain(idx, pipe):
36
+ try:
37
+ fd = pipe.fileno()
38
+ while True:
39
+ chunk = os.read(fd, 4096)
40
+ if not chunk:
41
+ break
42
+ output[idx].extend(chunk)
43
+ if sum(map(len, output)) > limit:
44
+ exceeded.set()
45
+ break
46
+ except OSError:
47
+ pass
48
+
49
+ threads = [
50
+ threading.Thread(target=_drain, args=(0, process.stdout), daemon=True),
51
+ threading.Thread(target=_drain, args=(1, process.stderr), daemon=True),
52
+ ]
53
+ for t in threads:
54
+ t.start()
55
+ while any(t.is_alive() for t in threads) or process.poll() is None:
56
+ if exceeded.is_set():
57
+ raise RuntimeError('excessive output')
58
+ remaining = deadline - time.monotonic()
59
+ if remaining <= 0:
60
+ raise RuntimeError('timeout')
61
+ time.sleep(min(remaining, 0.05))
62
+ for t in threads:
63
+ t.join(timeout=0.5)
64
+ if exceeded.is_set():
65
+ raise RuntimeError('excessive output')
66
+ return output
67
+
68
+
25
69
  def bounded(command, cwd, deadline, limit=16384):
26
70
  process = subprocess.Popen(command, cwd=cwd, stdin=subprocess.DEVNULL,
27
71
  stdout=subprocess.PIPE, stderr=subprocess.PIPE,
28
- start_new_session=True)
29
- streams = selectors.DefaultSelector()
72
+ **forge_proc.popen_group_kwargs())
73
+ streams = None if forge_proc.IS_WINDOWS else selectors.DefaultSelector()
30
74
  output = [bytearray(), bytearray()]
31
- for i, pipe in enumerate((process.stdout, process.stderr)):
32
- os.set_blocking(pipe.fileno(), False)
33
- streams.register(pipe, selectors.EVENT_READ, i)
75
+ if streams is not None:
76
+ for i, pipe in enumerate((process.stdout, process.stderr)):
77
+ os.set_blocking(pipe.fileno(), False)
78
+ streams.register(pipe, selectors.EVENT_READ, i)
34
79
  try:
35
- while streams.get_map() or process.poll() is None:
36
- remaining = deadline - time.monotonic()
37
- if remaining <= 0:
38
- raise RuntimeError('timeout')
39
- for key, _ in streams.select(min(remaining, .1)):
40
- chunk = os.read(key.fileobj.fileno(), 4096)
41
- if not chunk:
42
- streams.unregister(key.fileobj)
43
- else:
44
- output[key.data].extend(chunk)
45
- if sum(map(len, output)) > limit:
46
- raise RuntimeError('excessive output')
80
+ if streams is None:
81
+ output = _bounded_windows(process, deadline, limit)
82
+ else:
83
+ while streams.get_map() or process.poll() is None:
84
+ remaining = deadline - time.monotonic()
85
+ if remaining <= 0:
86
+ raise RuntimeError('timeout')
87
+ for key, _ in streams.select(min(remaining, .1)):
88
+ chunk = os.read(key.fileobj.fileno(), 4096)
89
+ if not chunk:
90
+ streams.unregister(key.fileobj)
91
+ else:
92
+ output[key.data].extend(chunk)
93
+ if sum(map(len, output)) > limit:
94
+ raise RuntimeError('excessive output')
47
95
  if process.returncode:
48
96
  detail = output[1].decode('utf-8', 'replace').strip().replace('\n', ' ')[:180]
49
97
  raise RuntimeError(f'exit {process.returncode}: {detail}')
50
98
  return bytes(output[0]).decode('utf-8', 'replace')
51
99
  finally:
52
100
  # Also kill descendants that closed their pipes before the parent exited.
53
- try:
54
- os.killpg(process.pid, signal.SIGKILL)
55
- except (ProcessLookupError, PermissionError): # macOS: EPERM for a group of zombies only
56
- pass
101
+ forge_proc.kill_tree(process.pid, force=True)
57
102
  process.wait()
58
- streams.close()
103
+ if streams is not None:
104
+ streams.close()
59
105
  process.stdout.close()
60
106
  process.stderr.close()
61
107
 
@@ -99,7 +99,6 @@ from __future__ import annotations
99
99
  import argparse
100
100
  import contextlib
101
101
  import errno
102
- import fcntl
103
102
  import hashlib
104
103
  import json
105
104
  import math
@@ -116,6 +115,10 @@ from pathlib import Path
116
115
 
117
116
  TIERS = ('low', 'medium', 'high')
118
117
  SCRIPTS = Path(__file__).resolve().parent
118
+ if str(SCRIPTS) not in sys.path:
119
+ sys.path.insert(0, str(SCRIPTS))
120
+ import forge_flock as fcntl # noqa: E402
121
+ import forge_posix # noqa: E402
119
122
  REGISTRY = SCRIPTS.parent / 'registry.tsv'
120
123
  FAILED = ('FAIL', 'TIMEOUT', 'BOUNCED', 'INCOMPLETE') # a judgment against the spec that ran
121
124
  NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT', 'NEEDS_DECISION', 'STALE') # say nothing about it
@@ -938,7 +941,11 @@ def _task_dir(plan: Path, task: str):
938
941
 
939
942
  @contextlib.contextmanager
940
943
  def _control_lock(plan: Path):
941
- fd = os.open(str(plan / 'control.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644)
944
+ fd = forge_posix.open_nofollow(
945
+ str(plan / 'control.lock'),
946
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_CLOEXEC,
947
+ 0o644,
948
+ )
942
949
  try:
943
950
  if not stat.S_ISREG(os.fstat(fd).st_mode):
944
951
  raise OSError(errno.EINVAL, 'control.lock is not a regular file')
@@ -1155,7 +1162,7 @@ def _record(args, name: str, after=None) -> int:
1155
1162
  parent, _leaf = control._open_parent(plan, rel)
1156
1163
  if parent is None:
1157
1164
  return 1
1158
- os.close(parent)
1165
+ forge_posix.close_dir(parent)
1159
1166
  if args.probe:
1160
1167
  control.probe(plan, rel)
1161
1168
  else:
@@ -49,6 +49,7 @@ import time
49
49
  SKILL = Path(__file__).resolve().parent.parent
50
50
  sys.path.insert(0, str(SKILL / 'scripts'))
51
51
 
52
+ import forge_proc # noqa: E402
52
53
  import forge_storage # noqa: E402
53
54
 
54
55
  OK, REFUSED, BUSY, FAILED = 0, 2, 3, 4
@@ -293,8 +294,8 @@ def start_check(args) -> int:
293
294
  if args.exclude:
294
295
  argv += ['--exclude', args.exclude]
295
296
  with open(log, 'ab') as sink:
296
- subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=sink, stderr=sink, start_new_session=True,
297
- close_fds=True)
297
+ subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=sink, stderr=sink,
298
+ close_fds=True, **forge_proc.popen_group_kwargs(detached=True))
298
299
  except Exception: # noqa: BLE001 -- a run never fails over its storage check
299
300
  pass
300
301
  return OK
@@ -45,7 +45,6 @@ from __future__ import annotations
45
45
 
46
46
  import argparse
47
47
  import errno
48
- import fcntl
49
48
  import hashlib
50
49
  import itertools
51
50
  import json
@@ -59,6 +58,13 @@ import sys
59
58
  import time
60
59
  from pathlib import Path
61
60
 
61
+ _SCRIPTS = str(Path(__file__).resolve().parent)
62
+ if _SCRIPTS not in sys.path:
63
+ sys.path.insert(0, _SCRIPTS)
64
+ import forge_flock as fcntl # noqa: E402
65
+ import forge_posix # noqa: E402
66
+ import forge_proc # noqa: E402
67
+
62
68
  SKILL = Path(__file__).resolve().parent.parent
63
69
  sys.path.insert(0, str(SKILL / 'scripts'))
64
70
 
@@ -210,7 +216,7 @@ def locate(arg):
210
216
  def read_text(path, cap=READ_MAX):
211
217
  """A run file's text: None if absent, Refused if it is not a plain readable file. Never follows a link."""
212
218
  try:
213
- fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
219
+ fd = forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NONBLOCK | forge_posix.O_NOFOLLOW)
214
220
  except FileNotFoundError:
215
221
  return None
216
222
  except OSError as error:
@@ -324,23 +330,17 @@ def scheduler_pid(run):
324
330
  pid = json.loads(read_text(os.path.join(run.path, 'scheduler.live'), 64 * 1024) or '')['pid']
325
331
  except (ValueError, KeyError, TypeError, Refused):
326
332
  return None
327
- if type(pid) is not int or pid <= 0:
328
- return None
329
- try:
330
- os.kill(pid, 0)
331
- except ProcessLookupError:
332
- return None
333
- except PermissionError:
334
- return pid
335
- except (OSError, OverflowError):
336
- return None
337
- return pid
333
+ return pid if forge_proc.pid_alive(pid) else None
338
334
 
339
335
 
340
336
  def take_lock(run):
341
337
  """The run's operation lock, non-blocking, as the runners take it. Returns the open fd."""
342
338
  try:
343
- fd = os.open(run.lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o644)
339
+ fd = forge_posix.open_nofollow(
340
+ run.lock_path,
341
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
342
+ 0o644,
343
+ )
344
344
  except OSError as error:
345
345
  raise Failed('cannot open %s: %s' % (run.lock_path, error.strerror or error))
346
346
  try:
@@ -15,6 +15,11 @@ import sys
15
15
  import time
16
16
  import uuid
17
17
 
18
+ _SCRIPTS = str(Path(__file__).resolve().parent)
19
+ if _SCRIPTS not in sys.path:
20
+ sys.path.insert(0, _SCRIPTS)
21
+ import forge_proc # noqa: E402
22
+
18
23
 
19
24
  def write_json(path: Path, value: dict) -> None:
20
25
  temporary = path.with_name(path.name + '.' + uuid.uuid4().hex)
@@ -65,10 +70,20 @@ def capability_help(cache: str, registry: str, recipe: str, command: list[str])
65
70
  return result.stdout.decode(errors='replace')
66
71
 
67
72
 
73
+ def shared_clock() -> float:
74
+ """Seconds from a point every process on this machine shares. begin and each phase run as separate
75
+ processes and subtract each other's readings, which time.monotonic() does not promise: on macOS,
76
+ Python 3.9 starts it at zero in every process, so every phase there measured about 0s."""
77
+ try:
78
+ return time.clock_gettime(time.CLOCK_MONOTONIC)
79
+ except (AttributeError, OSError): # Windows has no clock_gettime; its monotonic() is system-wide
80
+ return time.monotonic()
81
+
82
+
68
83
  def begin(root: str, role: str) -> Path:
69
84
  attempt = Path(root) / 'attempts' / (role + '-' + uuid.uuid4().hex)
70
85
  attempt.mkdir(parents=True)
71
- now = time.monotonic()
86
+ now = shared_clock()
72
87
  write_json(attempt / 'metrics.json', {
73
88
  'role': role, 'started': now, 'wall_started': time.time(),
74
89
  'phase': 'preparation', 'phase_started': now,
@@ -87,7 +102,7 @@ def begin(root: str, role: str) -> Path:
87
102
  def phase(attempt: str, name: str, rc: str | None = None) -> None:
88
103
  path = Path(attempt) / 'metrics.json'
89
104
  data = json.loads(path.read_text())
90
- now = time.monotonic()
105
+ now = shared_clock()
91
106
  previous = data['phase']
92
107
  duration = now - data['phase_started']
93
108
  data['elapsed_s'][previous] = data['elapsed_s'].get(previous, 0) + duration
@@ -124,17 +139,15 @@ def clock(log: str, out: str, every: str | None = None) -> None:
124
139
  def sample() -> None:
125
140
  nonlocal last
126
141
  # A TERM waits until the line is whole: it is delivered when the mask is lifted.
127
- signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
128
- try:
129
- size = os.stat(log).st_size
130
- if size != last:
131
- with open(out, 'a') as stream:
132
- stream.write('%.3f %d\n' % (time.time(), size))
133
- last = size
134
- except OSError:
135
- pass
136
- finally:
137
- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGTERM})
142
+ with forge_proc.mask_sigterm():
143
+ try:
144
+ size = os.stat(log).st_size
145
+ if size != last:
146
+ with open(out, 'a') as stream:
147
+ stream.write('%.3f %d\n' % (time.time(), size))
148
+ last = size
149
+ except OSError:
150
+ pass
138
151
 
139
152
  try:
140
153
  while os.getppid() == parent and not os.path.exists(stop_file):
@@ -792,12 +805,16 @@ def settle(log: str, grace: str, pid: str) -> None:
792
805
  poll = min(SETTLE_POLL_S, max(grace_s / 4, 0.05))
793
806
  size, since, judged = None, time.monotonic(), None
794
807
  while True:
795
- try:
796
- os.kill(target, 0)
797
- except ProcessLookupError:
798
- sys.exit(1)
799
- except PermissionError:
800
- pass
808
+ if forge_proc.IS_WINDOWS:
809
+ if not forge_proc.pid_alive(target):
810
+ sys.exit(1)
811
+ else:
812
+ try:
813
+ os.kill(target, 0)
814
+ except ProcessLookupError:
815
+ sys.exit(1)
816
+ except PermissionError:
817
+ pass
801
818
  try:
802
819
  now = os.stat(log).st_size
803
820
  except OSError: