@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.
- package/CHANGELOG.md +16 -0
- package/README.md +7 -0
- package/VERSION +1 -1
- package/docs/README.md +1 -0
- package/docs/development.md +1 -1
- package/package.json +1 -1
- package/scripts/forge-config.py +10 -9
- package/scripts/forge-control.py +51 -35
- package/scripts/forge-group.py +2 -1
- package/scripts/forge-guard.py +71 -33
- package/scripts/forge-handoff.py +14 -17
- package/scripts/forge-issues.py +5 -2
- package/scripts/forge-parallel.sh +18 -10
- package/scripts/forge-planner.py +28 -2
- package/scripts/forge-pre-review.py +11 -4
- package/scripts/forge-ripwire.py +68 -22
- package/scripts/forge-route.py +10 -3
- package/scripts/forge-runs-compact.py +3 -2
- package/scripts/forge-runs-rm.py +14 -14
- package/scripts/forge-runtime.py +36 -19
- package/scripts/forge-schedule.py +72 -55
- package/scripts/forge-shadow.py +16 -9
- package/scripts/forge-summarize.py +7 -3
- package/scripts/forge-sweep.py +7 -2
- package/scripts/forge-ui.py +8 -13
- package/scripts/forge-verify.py +29 -23
- package/scripts/forge_brief/__init__.py +1 -1
- package/scripts/forge_brief/proposals.py +7 -2
- package/scripts/forge_decide/budget.py +6 -1
- package/scripts/forge_decide/replay.py +6 -1
- package/scripts/forge_findings/apply.py +2 -1
- package/scripts/forge_findings/store.py +16 -4
- package/scripts/forge_findings/triage.py +6 -15
- package/scripts/forge_flock.py +87 -0
- package/scripts/forge_fractal/__init__.py +7 -3
- package/scripts/forge_fractal/cli.py +7 -2
- package/scripts/forge_fractal/execution.py +14 -14
- package/scripts/forge_fractal/invocation.py +3 -2
- package/scripts/forge_fractal/pipeline.py +2 -1
- package/scripts/forge_fractal/selection.py +2 -1
- package/scripts/forge_identity.py +2 -1
- package/scripts/forge_locations.py +14 -4
- package/scripts/forge_posix.py +108 -0
- package/scripts/forge_proc.py +399 -0
- package/scripts/forge_registry.py +15 -6
- package/scripts/forge_retro/__init__.py +8 -2
- package/scripts/forge_retro/issues.py +2 -1
- package/scripts/forge_side/__init__.py +19 -10
- package/scripts/forge_storage.py +11 -1
- package/ui/forge_ui/control.py +35 -12
- package/ui/forge_ui/reader.py +18 -17
- package/ui/forge_ui/server.py +10 -1
package/scripts/forge-verify.py
CHANGED
|
@@ -53,6 +53,12 @@ import sys
|
|
|
53
53
|
import tempfile
|
|
54
54
|
import time
|
|
55
55
|
|
|
56
|
+
_SCRIPTS = str(Path(__file__).resolve().parent)
|
|
57
|
+
if _SCRIPTS not in sys.path:
|
|
58
|
+
sys.path.insert(0, _SCRIPTS)
|
|
59
|
+
import forge_posix # noqa: E402
|
|
60
|
+
import forge_proc # noqa: E402
|
|
61
|
+
|
|
56
62
|
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
|
57
63
|
import forge_verify_reports as reports # noqa: E402 next to this script
|
|
58
64
|
|
|
@@ -204,7 +210,7 @@ def run_stoppable(argv: list[str], stopped=None, **kwargs) -> tuple[int, bytes,
|
|
|
204
210
|
"""Run a command in its own process group and wait for it, stopping the group (TERM, then
|
|
205
211
|
KILL after KILL_AFTER seconds) and raising Stopped as soon as ``stopped()`` is true."""
|
|
206
212
|
proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
207
|
-
stderr=subprocess.PIPE,
|
|
213
|
+
stderr=subprocess.PIPE, **forge_proc.popen_group_kwargs(), **kwargs)
|
|
208
214
|
while True:
|
|
209
215
|
try:
|
|
210
216
|
out, err = proc.communicate(timeout=TICK)
|
|
@@ -212,11 +218,8 @@ def run_stoppable(argv: list[str], stopped=None, **kwargs) -> tuple[int, bytes,
|
|
|
212
218
|
except subprocess.TimeoutExpired:
|
|
213
219
|
if stopped is None or not stopped():
|
|
214
220
|
continue
|
|
215
|
-
for
|
|
216
|
-
|
|
217
|
-
os.killpg(proc.pid, sig)
|
|
218
|
-
except (ProcessLookupError, PermissionError):
|
|
219
|
-
pass
|
|
221
|
+
for force, wait in ((False, KILL_AFTER), (True, KILL_AFTER)):
|
|
222
|
+
forge_proc.kill_tree(proc.pid, force=force)
|
|
220
223
|
try:
|
|
221
224
|
proc.communicate(timeout=wait)
|
|
222
225
|
break
|
|
@@ -264,7 +267,7 @@ def fingerprint(checkout: str, command: str | None, stopped=None) -> str:
|
|
|
264
267
|
"""The checkout's fingerprint; Stopped when ``stopped()`` turns true meanwhile."""
|
|
265
268
|
if not command:
|
|
266
269
|
return default_fingerprint(checkout, stopped)
|
|
267
|
-
rc, out, err = run_stoppable(
|
|
270
|
+
rc, out, err = run_stoppable(forge_proc.bash_cmd('-c', command), stopped, cwd=checkout)
|
|
268
271
|
if rc != 0:
|
|
269
272
|
raise RuntimeError(f'fingerprint command exited {rc}: {_text(err)}')
|
|
270
273
|
return _text(out)
|
|
@@ -430,12 +433,16 @@ class Verification:
|
|
|
430
433
|
try:
|
|
431
434
|
if os.path.islink(log):
|
|
432
435
|
os.unlink(log) # the log name is ours: never written through a link left in --out
|
|
433
|
-
fd =
|
|
436
|
+
fd = forge_posix.open_nofollow(
|
|
437
|
+
log,
|
|
438
|
+
os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW,
|
|
439
|
+
0o666,
|
|
440
|
+
)
|
|
434
441
|
with os.fdopen(fd, 'ab') as fh:
|
|
435
442
|
offset = fh.tell()
|
|
436
|
-
proc = subprocess.Popen(
|
|
443
|
+
proc = subprocess.Popen(forge_proc.bash_cmd('-c', lane['command']), cwd=self.checkout,
|
|
437
444
|
stdin=subprocess.DEVNULL, stdout=fh,
|
|
438
|
-
stderr=subprocess.STDOUT,
|
|
445
|
+
stderr=subprocess.STDOUT, **forge_proc.popen_group_kwargs())
|
|
439
446
|
except (OSError, ValueError) as exc: # ValueError: an embedded NUL in the command
|
|
440
447
|
with open(log, 'ab') as fh:
|
|
441
448
|
fh.write(f'forge-verify: cannot start lane: {exc}\n'.encode())
|
|
@@ -462,7 +469,7 @@ class Verification:
|
|
|
462
469
|
lane = self.by_name[name]
|
|
463
470
|
rc = live.proc.poll()
|
|
464
471
|
if rc is None: # still there after the KILL: a process stuck in the kernel
|
|
465
|
-
rc = -
|
|
472
|
+
rc = -forge_proc.SIGKILL
|
|
466
473
|
self._pump({name: live}) # what is left to read, capped; an interrupt still gets through
|
|
467
474
|
live.close()
|
|
468
475
|
self._end(lane, lane['runs'][-1], rc if rc >= 0 else 128 - rc, interrupted)
|
|
@@ -644,7 +651,7 @@ class Verification:
|
|
|
644
651
|
if live.exists() and not kept.exists():
|
|
645
652
|
shutil.copyfile(live, kept)
|
|
646
653
|
if truncate:
|
|
647
|
-
os.close(
|
|
654
|
+
os.close(forge_posix.open_nofollow(live, os.O_WRONLY | os.O_TRUNC | forge_posix.O_NOFOLLOW))
|
|
648
655
|
except OSError as exc:
|
|
649
656
|
print(f'forge-verify: cannot keep {kept.name}: {exc}', file=sys.stderr)
|
|
650
657
|
|
|
@@ -670,7 +677,7 @@ class Verification:
|
|
|
670
677
|
time.sleep(TICK)
|
|
671
678
|
for pgid in groups:
|
|
672
679
|
if self._group_alive(pgid):
|
|
673
|
-
self._signal(pgid,
|
|
680
|
+
self._signal(pgid, forge_proc.SIGKILL)
|
|
674
681
|
deadline = time.monotonic() + 3 * KILL_AFTER # SIGKILL cannot be caught; do not hang on D state
|
|
675
682
|
while time.monotonic() < deadline and any(self._group_alive(g) for g in groups):
|
|
676
683
|
time.sleep(TICK)
|
|
@@ -685,26 +692,25 @@ class Verification:
|
|
|
685
692
|
if not self._group_alive(pgid) or now >= give_up:
|
|
686
693
|
continue
|
|
687
694
|
if now >= deadline:
|
|
688
|
-
self._signal(pgid,
|
|
695
|
+
self._signal(pgid, forge_proc.SIGKILL)
|
|
689
696
|
keep.append((pgid, deadline, group, give_up))
|
|
690
697
|
self.lingering = keep
|
|
691
698
|
|
|
692
699
|
@staticmethod
|
|
693
700
|
def _signal(pgid: int, sig: int) -> None:
|
|
694
|
-
|
|
695
|
-
os.killpg(pgid, sig)
|
|
696
|
-
except (ProcessLookupError, PermissionError):
|
|
697
|
-
pass
|
|
701
|
+
forge_proc.kill_tree(pgid, force=(sig == forge_proc.SIGKILL))
|
|
698
702
|
|
|
699
703
|
def _group_alive(self, pgid: int) -> bool:
|
|
700
704
|
for live in self.running.values():
|
|
701
705
|
if live.proc.pid == pgid:
|
|
702
706
|
live.proc.poll() # reap a leader that exited, or it stays a zombie of the group
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
707
|
+
if not forge_proc.IS_WINDOWS:
|
|
708
|
+
try:
|
|
709
|
+
os.killpg(pgid, 0)
|
|
710
|
+
except (ProcessLookupError, PermissionError):
|
|
711
|
+
return False
|
|
712
|
+
return True
|
|
713
|
+
return forge_proc.group_alive(pgid)
|
|
708
714
|
|
|
709
715
|
# the whole verification ------------------------------------------------------------
|
|
710
716
|
|
|
@@ -34,7 +34,6 @@ from __future__ import annotations
|
|
|
34
34
|
|
|
35
35
|
import concurrent.futures
|
|
36
36
|
import contextlib
|
|
37
|
-
import fcntl
|
|
38
37
|
import json
|
|
39
38
|
import os
|
|
40
39
|
from pathlib import Path
|
|
@@ -48,6 +47,7 @@ SCRIPTS = Path(__file__).resolve().parent.parent
|
|
|
48
47
|
if str(SCRIPTS) not in sys.path:
|
|
49
48
|
sys.path.insert(0, str(SCRIPTS))
|
|
50
49
|
|
|
50
|
+
import forge_flock as fcntl # noqa: E402
|
|
51
51
|
import forge_groups # noqa: E402
|
|
52
52
|
import forge_side # noqa: E402
|
|
53
53
|
|
|
@@ -79,7 +79,6 @@ import argparse
|
|
|
79
79
|
import contextlib
|
|
80
80
|
import difflib
|
|
81
81
|
import io
|
|
82
|
-
import fcntl
|
|
83
82
|
import hashlib
|
|
84
83
|
import json
|
|
85
84
|
import os
|
|
@@ -87,10 +86,16 @@ from pathlib import Path
|
|
|
87
86
|
import re
|
|
88
87
|
import shlex
|
|
89
88
|
import subprocess
|
|
89
|
+
import sys
|
|
90
90
|
import tempfile
|
|
91
91
|
import calendar
|
|
92
92
|
import time
|
|
93
93
|
|
|
94
|
+
_SCRIPTS = str(Path(__file__).resolve().parents[1])
|
|
95
|
+
if _SCRIPTS not in sys.path:
|
|
96
|
+
sys.path.insert(0, _SCRIPTS)
|
|
97
|
+
import forge_flock as fcntl # noqa: E402
|
|
98
|
+
import forge_proc # noqa: E402
|
|
94
99
|
import forge_brief
|
|
95
100
|
import forge_brief.answers as answers
|
|
96
101
|
import forge_groups
|
|
@@ -858,7 +863,7 @@ def _recompute_waves(plan) -> str | None:
|
|
|
858
863
|
return None # an unplanned plan gains nothing, and waves.tsv is what marks one as planned
|
|
859
864
|
script = Path(forge_brief.SCRIPTS) / 'forge-parallel.sh'
|
|
860
865
|
try:
|
|
861
|
-
done = subprocess.run(
|
|
866
|
+
done = subprocess.run(forge_proc.bash_cmd(script, '_waves', str(plan)), stdin=subprocess.DEVNULL,
|
|
862
867
|
capture_output=True, text=True, timeout=120)
|
|
863
868
|
except (OSError, subprocess.SubprocessError) as error:
|
|
864
869
|
return 'waves.tsv was not refreshed: %s' % error
|
|
@@ -16,13 +16,18 @@ library only.
|
|
|
16
16
|
"""
|
|
17
17
|
from __future__ import annotations
|
|
18
18
|
|
|
19
|
-
import fcntl
|
|
20
19
|
import json
|
|
21
20
|
import math
|
|
22
21
|
import os
|
|
23
22
|
from pathlib import Path
|
|
23
|
+
import sys
|
|
24
24
|
import time
|
|
25
25
|
|
|
26
|
+
_SCRIPTS = str(Path(__file__).resolve().parents[1])
|
|
27
|
+
if _SCRIPTS not in sys.path:
|
|
28
|
+
sys.path.insert(0, _SCRIPTS)
|
|
29
|
+
import forge_flock as fcntl # noqa: E402
|
|
30
|
+
|
|
26
31
|
from . import state_dir
|
|
27
32
|
|
|
28
33
|
RUN_FILE = 'decide.budget.json'
|
|
@@ -19,14 +19,19 @@ from __future__ import annotations
|
|
|
19
19
|
|
|
20
20
|
from concurrent.futures import ThreadPoolExecutor
|
|
21
21
|
from dataclasses import dataclass, field
|
|
22
|
-
import fcntl
|
|
23
22
|
import json
|
|
24
23
|
import os
|
|
25
24
|
from pathlib import Path
|
|
25
|
+
import sys
|
|
26
26
|
import threading
|
|
27
27
|
import time
|
|
28
28
|
from urllib.parse import quote
|
|
29
29
|
|
|
30
|
+
_SCRIPTS = str(Path(__file__).resolve().parents[1])
|
|
31
|
+
if _SCRIPTS not in sys.path:
|
|
32
|
+
sys.path.insert(0, _SCRIPTS)
|
|
33
|
+
import forge_flock as fcntl # noqa: E402
|
|
34
|
+
|
|
30
35
|
from . import _save, providers, state_dir
|
|
31
36
|
from . import labels, metrics, sites
|
|
32
37
|
|
|
@@ -28,6 +28,7 @@ if str(SCRIPTS) not in sys.path:
|
|
|
28
28
|
sys.path.insert(0, str(SCRIPTS))
|
|
29
29
|
|
|
30
30
|
import forge_identity # noqa: E402
|
|
31
|
+
import forge_posix # noqa: E402
|
|
31
32
|
import forge_side # noqa: E402
|
|
32
33
|
from forge_findings import store, triage # noqa: E402
|
|
33
34
|
|
|
@@ -320,7 +321,7 @@ def _restore(ident, captured):
|
|
|
320
321
|
except FileNotFoundError:
|
|
321
322
|
pass
|
|
322
323
|
return
|
|
323
|
-
fd =
|
|
324
|
+
fd = forge_posix.open_nofollow(log, os.O_WRONLY | forge_posix.O_NOFOLLOW)
|
|
324
325
|
try:
|
|
325
326
|
os.ftruncate(fd, size)
|
|
326
327
|
finally:
|
|
@@ -17,7 +17,6 @@ from __future__ import annotations
|
|
|
17
17
|
|
|
18
18
|
import contextlib
|
|
19
19
|
import errno
|
|
20
|
-
import fcntl
|
|
21
20
|
import json
|
|
22
21
|
import os
|
|
23
22
|
import re
|
|
@@ -30,7 +29,9 @@ from pathlib import Path
|
|
|
30
29
|
_SCRIPTS = str(Path(__file__).resolve().parents[1])
|
|
31
30
|
if _SCRIPTS not in sys.path:
|
|
32
31
|
sys.path.insert(0, _SCRIPTS)
|
|
32
|
+
import forge_flock as fcntl # noqa: E402
|
|
33
33
|
import forge_identity # noqa: E402
|
|
34
|
+
import forge_posix # noqa: E402
|
|
34
35
|
import forge_registry # noqa: E402
|
|
35
36
|
|
|
36
37
|
STATUSES = ("open", "to-file", "filed", "fixed", "dismissed", "duplicate")
|
|
@@ -131,7 +132,11 @@ def lock(ident):
|
|
|
131
132
|
key = _key(ident)
|
|
132
133
|
path = _store_dir(create=True) / f"{key}.lock"
|
|
133
134
|
try:
|
|
134
|
-
fd =
|
|
135
|
+
fd = forge_posix.open_nofollow(
|
|
136
|
+
path,
|
|
137
|
+
os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
|
|
138
|
+
0o600,
|
|
139
|
+
)
|
|
135
140
|
except OSError as exc:
|
|
136
141
|
raise Corrupt(f"{path}: cannot open the repository lock ({exc.strerror}); it must not be a symlink")
|
|
137
142
|
try:
|
|
@@ -162,7 +167,10 @@ def _read_json(path: Path, noun: str):
|
|
|
162
167
|
if not stat.S_ISREG(os.lstat(path).st_mode):
|
|
163
168
|
raise Corrupt(not_regular)
|
|
164
169
|
# NOFOLLOW again for a swap after the lstat; NONBLOCK so a FIFO cannot hold the open
|
|
165
|
-
with os.fdopen(
|
|
170
|
+
with os.fdopen(
|
|
171
|
+
forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK),
|
|
172
|
+
"rb",
|
|
173
|
+
) as fh:
|
|
166
174
|
if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
|
|
167
175
|
raise Corrupt(not_regular)
|
|
168
176
|
raw = fh.read(FILE_MAX + 1)
|
|
@@ -314,7 +322,11 @@ def _append_log(ident, lines: list) -> None:
|
|
|
314
322
|
try:
|
|
315
323
|
base = _store_dir(create=True)
|
|
316
324
|
path = base / f"{_key(ident)}.record.log.jsonl"
|
|
317
|
-
fd =
|
|
325
|
+
fd = forge_posix.open_nofollow(
|
|
326
|
+
path,
|
|
327
|
+
os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
|
|
328
|
+
0o600,
|
|
329
|
+
)
|
|
318
330
|
try:
|
|
319
331
|
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
320
332
|
return
|
|
@@ -12,7 +12,6 @@ done, and the dispatch's own side.last / side.resolved.
|
|
|
12
12
|
"""
|
|
13
13
|
from __future__ import annotations
|
|
14
14
|
|
|
15
|
-
import fcntl
|
|
16
15
|
import hashlib
|
|
17
16
|
import importlib.util
|
|
18
17
|
import json
|
|
@@ -27,6 +26,8 @@ SCRIPTS = Path(__file__).resolve().parent.parent
|
|
|
27
26
|
if str(SCRIPTS) not in sys.path:
|
|
28
27
|
sys.path.insert(0, str(SCRIPTS))
|
|
29
28
|
|
|
29
|
+
import forge_flock as fcntl # noqa: E402
|
|
30
|
+
import forge_proc # noqa: E402
|
|
30
31
|
import forge_side # noqa: E402
|
|
31
32
|
|
|
32
33
|
DISPATCH = SCRIPTS / "forge-dispatch.sh"
|
|
@@ -156,17 +157,7 @@ def read_json(path):
|
|
|
156
157
|
|
|
157
158
|
|
|
158
159
|
def alive(pid) -> bool:
|
|
159
|
-
|
|
160
|
-
return False
|
|
161
|
-
try:
|
|
162
|
-
os.kill(pid, 0)
|
|
163
|
-
except ProcessLookupError:
|
|
164
|
-
return False
|
|
165
|
-
except PermissionError:
|
|
166
|
-
return True
|
|
167
|
-
except OSError:
|
|
168
|
-
return False
|
|
169
|
-
return True
|
|
160
|
+
return forge_proc.pid_alive(pid)
|
|
170
161
|
|
|
171
162
|
|
|
172
163
|
class _Lock:
|
|
@@ -453,7 +444,7 @@ def reason_of(error) -> str:
|
|
|
453
444
|
|
|
454
445
|
def preflight(spec) -> None:
|
|
455
446
|
"""`forge-dispatch.sh doctor --spec S --role side`. Raises Refused with its message."""
|
|
456
|
-
argv =
|
|
447
|
+
argv = forge_proc.bash_cmd(DISPATCH, "doctor", "--spec", str(spec), "--role", "side")
|
|
457
448
|
try:
|
|
458
449
|
result = subprocess.run(argv, capture_output=True, text=True, stdin=subprocess.DEVNULL,
|
|
459
450
|
timeout=DOCTOR_TIMEOUT)
|
|
@@ -521,9 +512,9 @@ def detach(dest, argv):
|
|
|
521
512
|
done = dest / "done"
|
|
522
513
|
wrapper = '"${@:2}"; rc=$?; printf "%s\\n" "$rc" > "$1.tmp" && mv -f "$1.tmp" "$1"; exit "$rc"'
|
|
523
514
|
with open(dest / "triage.out", "ab") as out:
|
|
524
|
-
process = subprocess.Popen(
|
|
515
|
+
process = subprocess.Popen(forge_proc.bash_cmd("-c", wrapper, "forge-triage", str(done), *argv),
|
|
525
516
|
stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
|
|
526
|
-
|
|
517
|
+
close_fds=True, **forge_proc.popen_group_kwargs(detached=True))
|
|
527
518
|
with _Lock(dest / "state.lock"):
|
|
528
519
|
state = read_json(dest / "state.json")
|
|
529
520
|
if isinstance(state, dict) and state.get("state") == "running":
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Cross-platform advisory file locking with ``fcntl.flock`` semantics.
|
|
2
|
+
|
|
3
|
+
Uses ``fcntl.flock`` on POSIX and ``msvcrt.locking`` on Windows so callers in
|
|
4
|
+
``scripts/``, ``ui/forge_ui/``, and ``tests/`` share one locking interface.
|
|
5
|
+
On Windows, ``LOCK_SH`` is promoted to an exclusive lock and locks byte
|
|
6
|
+
``_LOCK_OFFSET`` (1 GiB) rather than byte 0 so non-locking readers of normal
|
|
7
|
+
file data are not blocked by mandatory Win32 byte-range locks; ``LOCK_UN`` on
|
|
8
|
+
an unlocked descriptor is a no-op matching POSIX ``flock``.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import errno
|
|
13
|
+
import os
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import fcntl as _fcntl
|
|
18
|
+
except ImportError:
|
|
19
|
+
_fcntl = None
|
|
20
|
+
|
|
21
|
+
if _fcntl is not None:
|
|
22
|
+
LOCK_SH = _fcntl.LOCK_SH
|
|
23
|
+
LOCK_EX = _fcntl.LOCK_EX
|
|
24
|
+
LOCK_NB = _fcntl.LOCK_NB
|
|
25
|
+
LOCK_UN = _fcntl.LOCK_UN
|
|
26
|
+
else:
|
|
27
|
+
import msvcrt as _msvcrt
|
|
28
|
+
|
|
29
|
+
LOCK_SH = 1
|
|
30
|
+
LOCK_EX = 2
|
|
31
|
+
LOCK_NB = 4
|
|
32
|
+
LOCK_UN = 8
|
|
33
|
+
|
|
34
|
+
_LOCK_OFFSET = 0x40000000 # 1 GiB sentinel byte; msvcrt does not extend file size
|
|
35
|
+
|
|
36
|
+
_BUSY_ERRNOS = frozenset(
|
|
37
|
+
getattr(errno, name)
|
|
38
|
+
for name in ('EACCES', 'EAGAIN', 'EWOULDBLOCK', 'EDEADLK')
|
|
39
|
+
if hasattr(errno, name)
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _fileno(fd_or_file) -> int:
|
|
44
|
+
return fd_or_file if isinstance(fd_or_file, int) else fd_or_file.fileno()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _msvcrt_lock_sentinel(fd: int, mode: int) -> None:
|
|
48
|
+
"""Lock or unlock ``_LOCK_OFFSET`` on ``fd`` while preserving seek offset."""
|
|
49
|
+
pos = os.lseek(fd, 0, os.SEEK_CUR)
|
|
50
|
+
try:
|
|
51
|
+
os.lseek(fd, _LOCK_OFFSET, os.SEEK_SET)
|
|
52
|
+
_msvcrt.locking(fd, mode, 1)
|
|
53
|
+
finally:
|
|
54
|
+
os.lseek(fd, pos, os.SEEK_SET)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def flock(fd_or_file, operation: int) -> None:
|
|
58
|
+
"""Acquire or release an advisory lock matching ``fcntl.flock`` semantics."""
|
|
59
|
+
if _fcntl is not None:
|
|
60
|
+
_fcntl.flock(fd_or_file, operation)
|
|
61
|
+
return
|
|
62
|
+
|
|
63
|
+
fd = _fileno(fd_or_file)
|
|
64
|
+
nonblocking = bool(operation & LOCK_NB)
|
|
65
|
+
base_op = operation & ~LOCK_NB
|
|
66
|
+
|
|
67
|
+
if base_op == LOCK_UN:
|
|
68
|
+
try:
|
|
69
|
+
_msvcrt_lock_sentinel(fd, _msvcrt.LK_UNLCK)
|
|
70
|
+
except OSError as exc:
|
|
71
|
+
if exc.errno not in (errno.EACCES, errno.EPERM, errno.EINVAL):
|
|
72
|
+
raise
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
if base_op not in (LOCK_EX, LOCK_SH):
|
|
76
|
+
raise ValueError(f'unsupported flock operation: {operation!r}')
|
|
77
|
+
|
|
78
|
+
while True:
|
|
79
|
+
try:
|
|
80
|
+
_msvcrt_lock_sentinel(fd, _msvcrt.LK_NBLCK)
|
|
81
|
+
return
|
|
82
|
+
except OSError as exc:
|
|
83
|
+
if exc.errno not in _BUSY_ERRNOS:
|
|
84
|
+
raise
|
|
85
|
+
if nonblocking:
|
|
86
|
+
raise BlockingIOError(errno.EAGAIN, exc.strerror or 'Resource temporarily unavailable') from exc
|
|
87
|
+
time.sleep(0.05)
|
|
@@ -2,15 +2,19 @@
|
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
4
|
import contextlib
|
|
5
|
-
import fcntl
|
|
6
5
|
import importlib.util
|
|
7
6
|
import json
|
|
8
7
|
import os
|
|
9
8
|
from pathlib import Path
|
|
10
9
|
import re
|
|
11
10
|
import subprocess
|
|
11
|
+
import sys
|
|
12
12
|
|
|
13
13
|
SCRIPTS = Path(__file__).resolve().parents[1]
|
|
14
|
+
if str(SCRIPTS) not in sys.path:
|
|
15
|
+
sys.path.insert(0, str(SCRIPTS))
|
|
16
|
+
import forge_flock as fcntl # noqa: E402
|
|
17
|
+
import forge_proc # noqa: E402
|
|
14
18
|
REVISION = '18793200c0d7e8cdb2db369ea3abe5647a1e15e4'
|
|
15
19
|
VERSION = '1.2.0'
|
|
16
20
|
ARCHIVE_SHA256 = '3f7714ee0baec05af8d856db2b00d63398026fae2fcf50edbee542671126072c'
|
|
@@ -80,5 +84,5 @@ def command(argv: list, *, cwd: Path | None = None, timeout: float = 120, input:
|
|
|
80
84
|
|
|
81
85
|
|
|
82
86
|
def artifact(verb: str, *args: object) -> str:
|
|
83
|
-
return command(
|
|
84
|
-
|
|
87
|
+
return command(forge_proc.bash_cmd('-c', 'source "$1"; shift; "$@"', 'forge',
|
|
88
|
+
SCRIPTS / 'forge-artifact.sh', verb, *args)).decode().strip()
|
|
@@ -142,11 +142,16 @@ def internal(argv: list[str]) -> int:
|
|
|
142
142
|
remember(managed_run(Path(os.environ['FORGE_FRACTAL_RUN']).name), argv[1:])
|
|
143
143
|
return 0
|
|
144
144
|
if argv[0] == '_lock':
|
|
145
|
-
|
|
145
|
+
_scripts = str(Path(__file__).resolve().parents[1])
|
|
146
|
+
if _scripts not in sys.path:
|
|
147
|
+
sys.path.insert(0, _scripts)
|
|
148
|
+
import forge_flock as fcntl
|
|
149
|
+
import forge_proc
|
|
146
150
|
handle = (Path(argv[1]) / 'pipeline.lock').open('a')
|
|
147
151
|
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
148
152
|
os.set_inheritable(handle.fileno(), True)
|
|
149
|
-
|
|
153
|
+
forge_proc.exec_or_exit(forge_proc.bash_cmd(*argv[2:]), env=dict(os.environ, FORGE_SOLO_LOCK=argv[1]),
|
|
154
|
+
inherit_fds=True)
|
|
150
155
|
raise ValueError('Unknown internal command')
|
|
151
156
|
|
|
152
157
|
|
|
@@ -22,6 +22,7 @@ import time
|
|
|
22
22
|
import uuid
|
|
23
23
|
|
|
24
24
|
from . import SCRIPTS, artifact, command, identifier, lock, managed_run, read_json, runtime_python, write_json
|
|
25
|
+
import forge_proc
|
|
25
26
|
|
|
26
27
|
PROTOCOL = '''
|
|
27
28
|
Forge owns coordination and independent QA. Implement and run requested checks.
|
|
@@ -64,17 +65,17 @@ def terminate(process: subprocess.Popen) -> None:
|
|
|
64
65
|
# Every managed invocation is its own session; never signal an arbitrary PID.
|
|
65
66
|
if process.poll() is not None:
|
|
66
67
|
return
|
|
67
|
-
|
|
68
|
-
os.killpg(process.pid, signal.SIGTERM)
|
|
68
|
+
forge_proc.kill_tree(process.pid, force=False)
|
|
69
69
|
try:
|
|
70
70
|
process.wait(timeout=2)
|
|
71
71
|
except subprocess.TimeoutExpired:
|
|
72
|
-
|
|
73
|
-
os.killpg(process.pid, signal.SIGKILL)
|
|
72
|
+
forge_proc.kill_tree(process.pid, force=True)
|
|
74
73
|
process.wait(timeout=2)
|
|
75
74
|
|
|
76
75
|
|
|
77
76
|
def process_identity(pid: int) -> str:
|
|
77
|
+
if forge_proc.IS_WINDOWS:
|
|
78
|
+
return forge_proc.process_start_time(pid) or ''
|
|
78
79
|
return subprocess.run(['ps', '-p', str(pid), '-o', 'lstart=,comm='], capture_output=True, text=True).stdout.strip()
|
|
79
80
|
|
|
80
81
|
|
|
@@ -83,8 +84,7 @@ def reap_recorded(task: Path) -> None:
|
|
|
83
84
|
recorded = read_json(path)
|
|
84
85
|
pid = recorded['pid']
|
|
85
86
|
if recorded['identity'] and process_identity(pid) == recorded['identity']:
|
|
86
|
-
|
|
87
|
-
os.killpg(pid, signal.SIGKILL)
|
|
87
|
+
forge_proc.kill_tree(pid, force=True)
|
|
88
88
|
|
|
89
89
|
|
|
90
90
|
@contextlib.contextmanager
|
|
@@ -111,9 +111,9 @@ def bridge(step: Path, prompt: Path, model: str) -> int:
|
|
|
111
111
|
role = config.get('role', 'dwarf')
|
|
112
112
|
if role not in ('dwarf', 'planner'):
|
|
113
113
|
raise ValueError('Unsupported Fractal bridge role')
|
|
114
|
-
argv =
|
|
115
|
-
|
|
116
|
-
|
|
114
|
+
argv = forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', role, model,
|
|
115
|
+
'--repo', config['workspace'], '--run-dir', str(step), '--prompt-file', str(prompt),
|
|
116
|
+
'--timeout', str(max(1, math.ceil(config['remaining']))), '--output', 'summary')
|
|
117
117
|
if config['yolo'] and role == 'dwarf':
|
|
118
118
|
argv.append('--yolo')
|
|
119
119
|
# Stay in the bridge session so its entire descendant group is reapable.
|
|
@@ -460,7 +460,7 @@ def supervise(run: Path, task: Path) -> int:
|
|
|
460
460
|
limit = read_json(run / 'run.json')['limits']['deadline']
|
|
461
461
|
elapsed = read_json(task / 'state.json').get('elapsed', 0)
|
|
462
462
|
process = subprocess.Popen([str(runtime_python()), str(SCRIPTS / 'forge-fractal.py'),
|
|
463
|
-
'_worker', run.name, task.name],
|
|
463
|
+
'_worker', run.name, task.name], **forge_proc.popen_group_kwargs())
|
|
464
464
|
previous = time.monotonic()
|
|
465
465
|
try:
|
|
466
466
|
while process.poll() is None:
|
|
@@ -575,7 +575,7 @@ def dispatch(argv: list[str]) -> int:
|
|
|
575
575
|
|
|
576
576
|
def limited_dispatch(run: Path, argv: list[str]) -> int:
|
|
577
577
|
if argv[0] == 'doctor':
|
|
578
|
-
return subprocess.call(
|
|
578
|
+
return subprocess.call(forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', *argv))
|
|
579
579
|
limit = read_json(run / 'run.json')['limits']['deadline']
|
|
580
580
|
output = Path(argv[argv.index('--run-dir') + 1])
|
|
581
581
|
review = Path(argv[argv.index('--repo') + 1])
|
|
@@ -632,13 +632,13 @@ def qa_dispatch(run: Path, task: Path, argv: list[str], limit: int) -> int:
|
|
|
632
632
|
if record.exists():
|
|
633
633
|
old = read_json(record)
|
|
634
634
|
if old['identity'] and process_identity(old['pid']) == old['identity']:
|
|
635
|
-
|
|
636
|
-
os.killpg(old['pid'], signal.SIGKILL)
|
|
635
|
+
forge_proc.kill_tree(old['pid'], force=True)
|
|
637
636
|
while True:
|
|
638
637
|
try:
|
|
639
638
|
with slot(run, check):
|
|
640
639
|
check()
|
|
641
|
-
process = subprocess.Popen(
|
|
640
|
+
process = subprocess.Popen(forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', *argv),
|
|
641
|
+
**forge_proc.popen_group_kwargs())
|
|
642
642
|
write_json(record, dict(pid=process.pid, identity=process_identity(process.pid)))
|
|
643
643
|
try:
|
|
644
644
|
while process.poll() is None:
|
|
@@ -6,7 +6,8 @@ import threading
|
|
|
6
6
|
import time
|
|
7
7
|
import uuid
|
|
8
8
|
|
|
9
|
-
from . import read_json, write_json
|
|
9
|
+
from . import SCRIPTS, read_json, write_json
|
|
10
|
+
import forge_proc
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
def _dataset_step(task, node: dict, directory: Path, **values) -> None:
|
|
@@ -54,7 +55,7 @@ def run_step(tree, node: dict, workspace: Path, prompt: str, *, phase: str = 'im
|
|
|
54
55
|
cost = None
|
|
55
56
|
try:
|
|
56
57
|
with output.open('w') as stream:
|
|
57
|
-
process = agent.spawn(invocation,
|
|
58
|
+
process = agent.spawn(invocation, **forge_proc.popen_group_kwargs())
|
|
58
59
|
write_json(directory / 'process.json', dict(pid=process.pid, identity=process_identity(process.pid)))
|
|
59
60
|
def drain():
|
|
60
61
|
for line in process.stdout:
|
|
@@ -8,13 +8,14 @@ import subprocess
|
|
|
8
8
|
import time
|
|
9
9
|
|
|
10
10
|
from . import artifact, lock, read_json, write_json
|
|
11
|
+
import forge_proc
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
def remember(run: Path, argv: list[str]) -> None:
|
|
14
15
|
with lock(run / 'pipeline-record.lock'):
|
|
15
16
|
config = read_json(run / 'run.json')
|
|
16
17
|
if 'pipeline_argv' not in config:
|
|
17
|
-
config.update(pipeline_argv=
|
|
18
|
+
config.update(pipeline_argv=forge_proc.bash_cmd(*argv), pipeline_cwd=str(Path.cwd()))
|
|
18
19
|
write_json(run / 'run.json', config)
|
|
19
20
|
|
|
20
21
|
|
|
@@ -8,6 +8,7 @@ from pathlib import Path
|
|
|
8
8
|
import sys
|
|
9
9
|
|
|
10
10
|
from . import DEFAULTS, SCRIPTS, command, managed_run, read_json, state_root, write_json
|
|
11
|
+
import forge_proc
|
|
11
12
|
from .install import doctor, install
|
|
12
13
|
|
|
13
14
|
|
|
@@ -17,7 +18,7 @@ def resolve(spec: str, role: str, yolo: bool = False, dry: bool = False) -> dict
|
|
|
17
18
|
root = Path(tmp)
|
|
18
19
|
prompt = root / 'input'
|
|
19
20
|
prompt.write_text('Offline resolution')
|
|
20
|
-
argv =
|
|
21
|
+
argv = forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh')
|
|
21
22
|
if dry:
|
|
22
23
|
argv += [role, spec, '--run-dir', root, '--prompt-file', prompt, '--dry-run']
|
|
23
24
|
else:
|
|
@@ -20,6 +20,7 @@ import stat
|
|
|
20
20
|
import subprocess
|
|
21
21
|
|
|
22
22
|
import forge_locations
|
|
23
|
+
import forge_posix
|
|
23
24
|
import forge_registry
|
|
24
25
|
|
|
25
26
|
# A file in <run>/tasks/<id>/ sits three directories under the run dir.
|
|
@@ -254,7 +255,7 @@ def _first_line(path: str) -> str | None:
|
|
|
254
255
|
def _read_bytes(path, limit: int) -> bytes | None:
|
|
255
256
|
"""The start of a regular file. A FIFO, a directory or a missing path is unknown, and never blocks."""
|
|
256
257
|
try:
|
|
257
|
-
fd = os.open(os.fspath(path), os.O_RDONLY |
|
|
258
|
+
fd = os.open(os.fspath(path), os.O_RDONLY | forge_posix.O_NONBLOCK)
|
|
258
259
|
except OSError:
|
|
259
260
|
return None
|
|
260
261
|
try:
|