giwon 0.1.2__tar.gz → 0.1.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: giwon
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Observe provenance around one experiment execution.
5
5
  Requires-Dist: tyro>=1.0.16
6
6
  Requires-Dist: pyyaml
@@ -2,7 +2,7 @@
2
2
  # pins development dependencies; running an experiment never installs packages.
3
3
  [project]
4
4
  name = "giwon"
5
- version = "0.1.2"
5
+ version = "0.1.3"
6
6
  description = "Observe provenance around one experiment execution."
7
7
  requires-python = ">=3.11"
8
8
  dependencies = ["tyro>=1.0.16", "PyYAML", "xxhash", "GitPython"]
@@ -27,6 +27,7 @@ class Run:
27
27
  )
28
28
  max_patch_bytes: int | None = None
29
29
  patch_context: int | None = None
30
+ fail_on_untracked: bool | None = None
30
31
  hash_outputs: bool | None = None
31
32
  slurm_probes: bool | None = None
32
33
 
@@ -44,6 +44,7 @@ DEFAULTS: dict[str, Any] = {
44
44
  "record_env": list(DEFAULT_RECORD_ENV),
45
45
  "max_patch_bytes": 1_048_576,
46
46
  "patch_context": 3,
47
+ "fail_on_untracked": False,
47
48
  "sample_bytes": 1_073_741_824,
48
49
  "hash_outputs": False,
49
50
  "slurm_probes": True,
@@ -82,6 +83,15 @@ def _discover(cwd, boundary):
82
83
  def load(
83
84
  cwd: Path, overrides: dict[str, Any], *, git_root: Path | None = None
84
85
  ) -> dict[str, Any]:
86
+ """Combine defaults, project settings, and invocation overrides.
87
+
88
+ A project file can be reused from different working directories, so paths
89
+ in it are relative to its parent directory. CLI paths are relative to cwd.
90
+
91
+ Defaults, file settings, and CLI overrides apply in that order. The last
92
+ supplied scalar wins. For hash_inputs and record_env, each source adds
93
+ entries in order, keeping the first occurrence of each value.
94
+ """
85
95
  cwd = Path(os.path.abspath(cwd))
86
96
  selected = overrides.get("config")
87
97
  selected = (
@@ -0,0 +1,23 @@
1
+ """Report hardware and system facts from one allocation node."""
2
+
3
+ import json
4
+ import os
5
+
6
+ from giwon.discovery import hardware, system
7
+
8
+
9
+ def main():
10
+ print(
11
+ json.dumps(
12
+ {
13
+ "node": os.environ.get("SLURMD_NODENAME"),
14
+ "hardware": hardware.collect(),
15
+ "environment": system.collect(),
16
+ }
17
+ ),
18
+ flush=True,
19
+ )
20
+
21
+
22
+ if __name__ == "__main__":
23
+ main()
@@ -113,20 +113,22 @@ def _submodules(repo, path, stack, submodule_number):
113
113
 
114
114
 
115
115
  def collect(
116
- root: Path, directory: Path, max_patch_bytes: int, patch_context: int
116
+ root: Path,
117
+ directory: Path,
118
+ max_patch_bytes: int,
119
+ patch_context: int,
120
+ *,
121
+ fail_on_untracked: bool = False,
117
122
  ) -> dict[str, Any]:
118
123
  """Capture a repository and its nested submodules under one patch budget.
119
124
 
120
- Submodules may be staged without .gitmodules entries and can contain nested
121
- submodules. Read current-index gitlinks through Git instead of repo.submodules,
122
- and traverse initialized checkouts depth-first with a stack of (path, record,
123
- patch filename), seeded with the root. Child records are attached to their
124
- parent before being pushed, so processing a stack entry fills the same nested
125
- record. Uninitialized children retain only path/reference; all captured
126
- checkouts consume the same patch budget.
125
+ Submodules may be staged without .gitmodules entries, so discover them from
126
+ gitlinks in the index. Uninitialized submodules retain only their path and
127
+ index reference.
127
128
  """
128
129
  import git
129
130
 
131
+ directory = directory.resolve()
130
132
  facts: dict[str, Any] = {"root": str(root)}
131
133
  stack = [(root, facts, "git.patch")]
132
134
  patches = []
@@ -146,7 +148,17 @@ def collect(
146
148
  if entry is facts: # runs on first iteration
147
149
  entry["remotes"] = _remotes(repo)
148
150
 
149
- entry["untracked_files"] = _untracked_files(repo)
151
+ # We already created files in the run's folder, need to exclude them
152
+ untracked = []
153
+ for name in _untracked_files(repo):
154
+ if not (path / name).is_relative_to(directory):
155
+ untracked.append(name)
156
+
157
+ if fail_on_untracked and untracked:
158
+ raise ValueError(f"untracked files in {path}: {untracked!r}")
159
+
160
+ entry["untracked_files"] = untracked
161
+
150
162
  patch = directory / filename
151
163
  size = _patch(repo, entry["commit"], patch, remaining, patch_context)
152
164
  entry["patch"] = filename if size else None
@@ -1,8 +1,8 @@
1
1
  """Observe a node's CPUs, GPUs, memory and collecting-process affinity.
2
2
 
3
- Slurm sends this file as Python source, so it uses only the standard library and
4
- must run without the Giwon package. Scheduler GPU selectors are not device
5
- observations; absent GPU facts do not imply no devices.
3
+ Slurm ships this collector with its probe, so it uses only the standard library.
4
+ Scheduler GPU selectors are not device observations; absent GPU facts do not
5
+ imply no devices.
6
6
  Explicit unavailable markers such as N/A are retained, including in numeric
7
7
  fields; absent values are omitted rather than replaced with a marker.
8
8
  """
@@ -10,7 +10,6 @@ fields; absent values are omitted rather than replaced with a marker.
10
10
  import json
11
11
  import os
12
12
  import platform
13
- import signal
14
13
  import socket
15
14
  import subprocess
16
15
  import sys
@@ -316,11 +315,3 @@ def collect() -> dict:
316
315
  elif system == "Darwin":
317
316
  facts.update(_collect_mac())
318
317
  return facts
319
-
320
-
321
- if __name__ == "__main__":
322
- signal.alarm(15)
323
- print(
324
- json.dumps({"node": os.environ.get("SLURMD_NODENAME"), "hardware": collect()}),
325
- flush=True,
326
- )
@@ -0,0 +1,104 @@
1
+ """Report versions of native libraries visible to this process."""
2
+
3
+ import ctypes
4
+ import ctypes.util
5
+ import json
6
+ import os
7
+ import platform
8
+ import sys
9
+
10
+ # Ponytail: loader lookup misses private wheel and executable RPATH libraries.
11
+ # Experiment-side reporting is needed to identify those and establish actual use.
12
+
13
+
14
+ def _emit(name, value):
15
+ print(json.dumps({name: value}), flush=True)
16
+
17
+
18
+ def _library(name):
19
+ path = ctypes.util.find_library(name)
20
+ return ctypes.CDLL(path) if path else None
21
+
22
+
23
+ def _integer(library, symbol, *arguments):
24
+ function = getattr(library, symbol)
25
+ function.argtypes = [ctypes.c_int] * len(arguments) + [ctypes.POINTER(ctypes.c_int)]
26
+ function.restype = ctypes.c_int
27
+ value = ctypes.c_int()
28
+ status = function(*arguments, ctypes.byref(value))
29
+ if status:
30
+ raise ValueError(f"{symbol} returned {status}")
31
+ return value.value
32
+
33
+
34
+ def main():
35
+ try:
36
+ name, version = platform.libc_ver()
37
+ if name and version:
38
+ _emit("libc", f"{name} {version}")
39
+ except OSError as error:
40
+ print(f"giwon: unavailable libc: {error}", file=sys.stderr)
41
+
42
+ try:
43
+ if library := _library("cudart"):
44
+ value = _integer(library, "cudaRuntimeGetVersion")
45
+ if value <= 0:
46
+ raise ValueError("unknown CUDA runtime version")
47
+ _emit("cuda_runtime", f"{value // 1000}.{value % 1000 // 10}")
48
+ except (OSError, AttributeError, ValueError) as error:
49
+ print(f"giwon: unavailable cuda_runtime: {error}", file=sys.stderr)
50
+
51
+ for name in ("cublas", "cudnn"):
52
+ try:
53
+ if library := _library(name):
54
+ parts = [
55
+ _integer(library, f"{name}GetProperty", part) for part in range(3)
56
+ ]
57
+ if parts[0] <= 0 or min(parts) < 0:
58
+ raise ValueError("unknown library version")
59
+ _emit(name, ".".join(map(str, parts)))
60
+ except (OSError, AttributeError, ValueError) as error:
61
+ print(f"giwon: unavailable {name}: {error}", file=sys.stderr)
62
+
63
+ try:
64
+ if library := _library("nccl"):
65
+ value = _integer(library, "ncclGetVersion")
66
+ if value < 10000:
67
+ raise ValueError("unknown NCCL version encoding")
68
+ _emit("nccl", f"{value // 10000}.{value % 10000 // 100}.{value % 100}")
69
+ except (OSError, AttributeError, ValueError) as error:
70
+ print(f"giwon: unavailable nccl: {error}", file=sys.stderr)
71
+
72
+ try:
73
+ if library := _library("openblas"):
74
+ function = library.openblas_get_config
75
+ function.argtypes = []
76
+ function.restype = ctypes.c_char_p
77
+ _emit("openblas", function().decode().split()[1])
78
+ except (OSError, AttributeError, ValueError, IndexError) as error:
79
+ print(f"giwon: unavailable openblas: {error}", file=sys.stderr)
80
+
81
+ try:
82
+ if library := _library("mkl_rt"):
83
+ function = library.MKL_Get_Version_String
84
+ function.argtypes = [ctypes.POINTER(ctypes.c_char), ctypes.c_int]
85
+ function.restype = None
86
+ buffer = ctypes.create_string_buffer(256)
87
+ function(buffer, len(buffer))
88
+ _emit("mkl", buffer.value.decode().partition("Version ")[2].split()[0])
89
+ except (OSError, AttributeError, ValueError, IndexError) as error:
90
+ print(f"giwon: unavailable mkl: {error}", file=sys.stderr)
91
+
92
+ # OpenMP exposes no portable version API; keep runtime names rather than
93
+ # presenting their ABI sonames as software versions.
94
+ for name in ("gomp", "omp", "iomp5"):
95
+ try:
96
+ path = ctypes.util.find_library(name)
97
+ if path:
98
+ _emit(name, os.path.basename(path))
99
+ except OSError as error:
100
+ print(f"giwon: unavailable {name}: {error}", file=sys.stderr)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
@@ -0,0 +1,35 @@
1
+ """Run a shipped allocation probe without installing Giwon.
2
+
3
+ Compute nodes may have no Giwon installation or shared source path. Import the
4
+ supplied source archive from a temporary directory so the collectors can use
5
+ normal module imports, including resource reads for the native-library worker.
6
+ """
7
+
8
+ import base64
9
+ import runpy
10
+ import signal
11
+ import sys
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+
16
+ def _timeout(number, frame):
17
+ """Stop the probe at its deadline.
18
+
19
+ Collectors catch ordinary observation failures. SystemExit escapes those
20
+ handlers while still unwinding the temporary archive's context manager.
21
+ """
22
+ raise SystemExit("giwon: allocation probe timed out")
23
+
24
+
25
+ def main():
26
+ signal.signal(signal.SIGALRM, _timeout)
27
+ signal.alarm(15)
28
+ with tempfile.TemporaryDirectory(prefix="giwon-probe-") as directory:
29
+ archive = Path(directory) / "probe.zip"
30
+ archive.write_bytes(base64.b64decode(sys.argv[1]))
31
+ runpy.run_path(str(archive), run_name="__main__")
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
@@ -4,6 +4,8 @@ Job names and submission commands can contain whitespace and key=value text.
4
4
  Read controller JSON so those values cannot be confused with allocation facts.
5
5
  """
6
6
 
7
+ import base64
8
+ import io
7
9
  import json
8
10
  import os
9
11
  import re
@@ -12,9 +14,8 @@ import subprocess
12
14
  import sys
13
15
  from collections.abc import Mapping
14
16
  from datetime import UTC, datetime
15
- from pathlib import Path
16
-
17
- from giwon.discovery import hardware
17
+ from importlib.resources import files
18
+ from zipfile import ZIP_DEFLATED, ZipFile
18
19
 
19
20
  _CONNECTION_VARIABLES = {
20
21
  "SLURM_CONF",
@@ -89,13 +90,19 @@ def _launcher_environment(env):
89
90
 
90
91
 
91
92
  def _query(arguments, env):
93
+ """Query scheduler metadata with a bounded controller deadline.
94
+
95
+ Scheduler queries include a controller round trip and loading Slurm's JSON
96
+ plugin. Allow more startup latency than local hardware utilities so a slow
97
+ first query does not discard the verified allocation.
98
+ """
92
99
  result = subprocess.run(
93
100
  ["scontrol", *arguments],
94
101
  env=env,
95
102
  stdin=subprocess.DEVNULL,
96
103
  capture_output=True,
97
104
  text=True,
98
- timeout=3,
105
+ timeout=10,
99
106
  check=True,
100
107
  )
101
108
  return result.stdout
@@ -206,7 +213,27 @@ def _allocation(job, env):
206
213
 
207
214
 
208
215
  def _probe_command(job_id, nodes):
209
- payload = Path(hardware.__file__).read_text(encoding="utf-8")
216
+ """Build standalone probes with the wrapper's native-library environment.
217
+
218
+ Loaded modules can supply library paths, while the wrapper's GPU selectors
219
+ refer to its own node. Export only executable and loader settings so those
220
+ libraries remain visible without propagating another node's GPU selection.
221
+ """
222
+ sources = files("giwon")
223
+ payload = io.BytesIO()
224
+ with ZipFile(payload, "w", compression=ZIP_DEFLATED) as archive:
225
+ archive.writestr(
226
+ "__main__.py",
227
+ sources.joinpath("discovery/allocation_probe.py").read_bytes(),
228
+ )
229
+ for name in (
230
+ "__init__.py",
231
+ "discovery/__init__.py",
232
+ "discovery/hardware.py",
233
+ "discovery/system.py",
234
+ "discovery/library_probe.py",
235
+ ):
236
+ archive.writestr(f"giwon/{name}", sources.joinpath(name).read_bytes())
210
237
  return [
211
238
  "srun",
212
239
  f"--jobid={job_id}",
@@ -224,12 +251,13 @@ def _probe_command(job_id, nodes):
224
251
  "--kill-on-bad-exit=0",
225
252
  "--time=1",
226
253
  "--chdir=/",
227
- "--export=NONE",
254
+ "--export=PATH,LD_LIBRARY_PATH,LD_PRELOAD",
228
255
  sys.executable,
229
256
  "-I",
230
257
  "-S",
231
258
  "-c",
232
- payload,
259
+ sources.joinpath("discovery/probe_bootstrap.py").read_text(encoding="utf-8"),
260
+ base64.b64encode(payload.getvalue()).decode("ascii"),
233
261
  ]
234
262
 
235
263
 
@@ -284,6 +312,11 @@ def _probe(command, env):
284
312
 
285
313
 
286
314
  def _responses(output, nodes, local, env):
315
+ """Validate probe responses and retain each node's observations.
316
+
317
+ A clean probe can see different libraries on the wrapper's host. Preserve
318
+ that environment too, without repeating the already observed local hardware.
319
+ """
287
320
  observed = []
288
321
  seen = set()
289
322
  local_name = env.get("SLURMD_NODENAME")
@@ -292,7 +325,12 @@ def _responses(output, nodes, local, env):
292
325
  response = json.loads(line)
293
326
  node = response["node"]
294
327
  facts = response["hardware"]
295
- if node not in nodes or not isinstance(facts, dict):
328
+ environment = response["environment"]
329
+ if (
330
+ node not in nodes
331
+ or not isinstance(facts, dict)
332
+ or not isinstance(environment, dict)
333
+ ):
296
334
  raise ValueError("response is outside the verified allocation")
297
335
  if not isinstance(facts.get("hostname"), str) or not facts["hostname"]:
298
336
  raise ValueError("response has no hostname")
@@ -300,8 +338,10 @@ def _responses(output, nodes, local, env):
300
338
  continue
301
339
  seen.add(node)
302
340
  if node == local_name or facts["hostname"] == local.get("hostname"):
303
- continue
341
+ facts = {"hostname": facts["hostname"]}
304
342
  facts["scope"] = "allocation_probe"
343
+ environment["scope"] = "allocation_probe"
344
+ facts["environment"] = environment
305
345
  observed.append(facts)
306
346
  except (ValueError, TypeError, KeyError) as error:
307
347
  print(f"giwon: invalid Slurm probe response: {error}", file=sys.stderr)
@@ -317,17 +357,13 @@ def _responses(output, nodes, local, env):
317
357
  def collect(
318
358
  env: Mapping[str, str], local: dict, *, probe_nodes: bool = True
319
359
  ) -> tuple[dict | None, list]:
320
- """Collect current-job facts and additional observed nodes.
360
+ """Collect current-job facts and allocation-probe observations.
321
361
 
322
362
  Slurm tools may be installed outside an allocation. Without a numeric runtime
323
363
  job ID, return (None, []) without issuing commands. Otherwise retain the job
324
364
  identity even when the controller or JSON plugin is unavailable. A probe
325
365
  additionally requires one matching job record, current ownership, running
326
366
  state and an expanded allocation whose size matches the controller's count.
327
-
328
- Pass the prepared child environment and its local hardware observations.
329
- Return (job facts, additional nodes), excluding the local node from results.
330
- With probe_nodes=False, collect only current-job metadata.
331
367
  """
332
368
  value = env.get("SLURM_JOB_ID", env.get("SLURM_JOBID", ""))
333
369
  if not re.fullmatch(r"[1-9][0-9]{0,9}", value):
@@ -0,0 +1,86 @@
1
+ """Capture the operating system and a small summary of visible native libraries.
2
+
3
+ Native version queries execute library code. Isolate them in a bounded process
4
+ so a crash or hang cannot prevent the experiment from launching; retain facts
5
+ flushed before a failure. These are collector observations, not evidence of
6
+ which libraries the experiment loads.
7
+ """
8
+
9
+ import json
10
+ import os
11
+ import platform
12
+ import subprocess
13
+ import sys
14
+ from importlib.resources import files
15
+
16
+
17
+ def _libraries():
18
+ output = b""
19
+ try:
20
+ result = subprocess.run(
21
+ [
22
+ sys.executable,
23
+ "-I",
24
+ "-S",
25
+ "-c",
26
+ files("giwon.discovery")
27
+ .joinpath("library_probe.py")
28
+ .read_text(encoding="utf-8"),
29
+ ],
30
+ stdin=subprocess.DEVNULL,
31
+ capture_output=True,
32
+ timeout=3,
33
+ env=dict(
34
+ os.environ,
35
+ OPENBLAS_NUM_THREADS="1",
36
+ MKL_NUM_THREADS="1",
37
+ OMP_NUM_THREADS="1",
38
+ ),
39
+ check=False,
40
+ )
41
+ output = result.stdout
42
+ if result.stderr:
43
+ print(result.stderr.decode(errors="replace").strip(), file=sys.stderr)
44
+ if result.returncode:
45
+ print(
46
+ f"giwon: library probe exited with {result.returncode}", file=sys.stderr
47
+ )
48
+ except subprocess.TimeoutExpired as error:
49
+ output = error.output or b""
50
+ print("giwon: library probe timed out", file=sys.stderr)
51
+ except OSError as error:
52
+ print(f"giwon: unavailable library probe: {error}", file=sys.stderr)
53
+
54
+ facts = {}
55
+ for line in output.splitlines():
56
+ try:
57
+ observation = json.loads(line)
58
+ if not isinstance(observation, dict) or not all(
59
+ isinstance(key, str) and isinstance(value, str) and value
60
+ for key, value in observation.items()
61
+ ):
62
+ raise ValueError("expected library names and versions")
63
+ facts.update(observation)
64
+ except (ValueError, TypeError) as error:
65
+ print(f"giwon: invalid library observation: {error}", file=sys.stderr)
66
+ return facts
67
+
68
+
69
+ def collect() -> dict:
70
+ facts = {"scope": "local_process"}
71
+ for key, observe in (
72
+ ("os", platform.system),
73
+ ("release", platform.release),
74
+ ("architecture", platform.machine),
75
+ ):
76
+ try:
77
+ value = observe()
78
+ if value:
79
+ facts[key] = value
80
+ else:
81
+ print(f"giwon: unavailable {key}", file=sys.stderr)
82
+ except Exception as error: # noqa: BLE001
83
+ print(f"giwon: unavailable {key}: {error}", file=sys.stderr)
84
+ if libraries := _libraries():
85
+ facts["libraries"] = libraries
86
+ return facts
@@ -81,15 +81,22 @@ def size(entries: list[dict]) -> int:
81
81
 
82
82
 
83
83
  def _ranges(total, budget):
84
+ """Yield byte ranges spread across the content.
85
+
86
+ When content exceeds the budget, distribute omitted bytes between sampled
87
+ ranges. This uses the exact budget and touches both ends for budgets of at
88
+ least two bytes. A one-byte budget samples the first byte.
89
+ """
84
90
  if budget == 1:
85
91
  yield 0, 1
86
92
  return
87
93
 
88
94
  count = max(2, (budget + _BLOCK_BYTES - 1) // _BLOCK_BYTES)
89
95
  for index in range(count):
90
- prefix = index * budget // count
91
- length = (index + 1) * budget // count - prefix
92
- offset = prefix + index * (total - budget) // (count - 1)
96
+ sampled_before = index * budget // count
97
+ length = (index + 1) * budget // count - sampled_before
98
+ skipped_before = index * (total - budget) // (count - 1)
99
+ offset = sampled_before + skipped_before
93
100
  yield offset, length
94
101
 
95
102
 
@@ -177,7 +184,8 @@ def fingerprint_inventory(
177
184
  else:
178
185
  result = files[0]["hash"]
179
186
  else:
180
- # Blockwise hashing if file size exceeds configured threshold
187
+ # File contents in sorted path order form one byte stream, so a range
188
+ # can cross file boundaries.
181
189
  blocks = []
182
190
  index = 0
183
191
  start = 0
@@ -8,6 +8,7 @@ giwon:
8
8
  config: null
9
9
  max_patch_bytes: null
10
10
  patch_context: null
11
+ fail_on_untracked: null
11
12
  sample_bytes: null
12
13
  hash_outputs: null
13
14
  slurm_probes: null
@@ -41,15 +42,43 @@ image:
41
42
  registry:
42
43
  reference: null
43
44
  environment:
45
+ scope: null
44
46
  os: null
45
47
  release: null
46
48
  architecture: null
49
+ libraries:
50
+ libc: null
51
+ cuda_runtime: null
52
+ cublas: null
53
+ cudnn: null
54
+ nccl: null
55
+ openblas: null
56
+ mkl: null
57
+ gomp: null
58
+ omp: null
59
+ iomp5: null
47
60
  executable: null
48
61
  variables_file: null
49
62
  hardware:
50
63
  nodes:
51
64
  - hostname: null
52
65
  scope: null
66
+ environment:
67
+ scope: null
68
+ os: null
69
+ release: null
70
+ architecture: null
71
+ libraries:
72
+ libc: null
73
+ cuda_runtime: null
74
+ cublas: null
75
+ cudnn: null
76
+ nccl: null
77
+ openblas: null
78
+ mkl: null
79
+ gomp: null
80
+ omp: null
81
+ iomp5: null
53
82
  memory_bytes: null
54
83
  cpus: []
55
84
  cpu_affinity: []
@@ -49,11 +49,11 @@ class _LaunchError(Exception):
49
49
  super().__init__(str(error))
50
50
 
51
51
 
52
- def _foreground(fd, group):
53
- # Ignore if parent process wants to write to terminal or change its settings
52
+ def _set_foreground_group(tty_fd, group):
53
+ # Reclaiming the terminal from the background would otherwise stop the wrapper.
54
54
  previous = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
55
55
  try:
56
- os.tcsetpgrp(fd, group) # Set control group of descriptor
56
+ os.tcsetpgrp(tty_fd, group)
57
57
  finally:
58
58
  signal.signal(signal.SIGTTOU, previous)
59
59
 
@@ -71,71 +71,64 @@ def _supervise(command: list[str], env: dict[str, str]) -> tuple[int, int]:
71
71
  child = None
72
72
  pending = []
73
73
  previous_handlers = {}
74
- fd = None # file descriptor of us
75
- foreground = None
74
+ tty_fd = None
75
+ restore_pgid = None
76
76
 
77
77
  def forward(n, _frame):
78
78
  # On resume, only hand over the terminal if the shell foregrounded us.
79
- nonlocal foreground
79
+ nonlocal restore_pgid
80
80
  if child is None:
81
81
  pending.append(n)
82
82
  return
83
- if n == signal.SIGCONT and fd is not None:
84
- current = os.tcgetpgrp(fd)
83
+ if n == signal.SIGCONT and tty_fd is not None:
84
+ current = os.tcgetpgrp(tty_fd)
85
85
  if current != child.pid:
86
- foreground = os.getpgrp() if current == os.getpgrp() else None
87
- if foreground is not None:
88
- _foreground(fd, child.pid)
86
+ restore_pgid = current if current == os.getpgrp() else None
87
+ if restore_pgid is not None:
88
+ _set_foreground_group(tty_fd, child.pid)
89
89
  try:
90
- os.killpg(child.pid, n) # Send signal
90
+ os.killpg(child.pid, n)
91
91
  except ProcessLookupError:
92
92
  pass
93
93
 
94
94
  try:
95
- # Find the controlling terminal of the runner (us)
96
95
  try:
97
- fd = os.dup(0) if os.isatty(0) else os.open("/dev/tty", os.O_RDWR)
98
- foreground = os.tcgetpgrp(fd)
99
- if foreground != os.getpgrp():
100
- foreground = None
96
+ tty_fd = os.dup(0) if os.isatty(0) else os.open("/dev/tty", os.O_RDWR)
97
+ current = os.tcgetpgrp(tty_fd)
98
+ if current == os.getpgrp():
99
+ restore_pgid = current
101
100
  except OSError:
102
- if fd is not None:
103
- os.close(fd)
104
- fd = None
101
+ if tty_fd is not None:
102
+ os.close(tty_fd)
103
+ tty_fd = None
105
104
 
106
- # Forward signals
107
105
  for number in SIGNALS:
108
106
  previous_handlers[number] = signal.signal(number, forward)
109
107
 
110
108
  try:
111
- # Open child process as independent process group
112
109
  child = subprocess.Popen(command, env=env, process_group=0)
113
110
  except (OSError, TypeError, ValueError, IndexError) as error:
114
111
  raise _LaunchError(error) from error
115
112
 
116
- if fd is not None and foreground is not None:
117
- _foreground(fd, child.pid)
113
+ if tty_fd is not None and restore_pgid is not None:
114
+ _set_foreground_group(tty_fd, child.pid)
118
115
  for number in pending:
119
116
  forward(number, None)
120
117
 
121
- # Wait for the command, following shell stop/resume
122
118
  while True:
123
- # WUNTRACED -> return even if child is stopped
124
119
  _, status = os.waitpid(child.pid, os.WUNTRACED)
125
120
  if os.WIFSTOPPED(status):
126
- # Child might be quick and attempt to read before we've given it control
127
- # of the foreground terminal. In this case termianl control will stop
128
- # with SIGTTIN, so we foreground the process and send SIGCONT. Otherwise
129
- # we stop ourselves, and continue the child aftewards.
121
+ # A child that reads before the terminal handoff can receive SIGTTIN.
122
+ # Give it the terminal and resume it without suspending the wrapper.
130
123
  if (
131
- fd is not None
132
- and foreground is not None
124
+ tty_fd is not None
125
+ and restore_pgid is not None
133
126
  and os.WSTOPSIG(status) == signal.SIGTTIN
134
127
  ):
135
- _foreground(fd, child.pid)
128
+ _set_foreground_group(tty_fd, child.pid)
136
129
  else:
137
- if fd is not None and foreground is not None:
138
- _foreground(fd, foreground)
130
+ if tty_fd is not None and restore_pgid is not None:
131
+ _set_foreground_group(tty_fd, restore_pgid)
139
132
  os.kill(os.getpid(), signal.SIGSTOP)
140
133
  os.killpg(child.pid, signal.SIGCONT)
141
134
  continue
@@ -143,17 +136,16 @@ def _supervise(command: list[str], env: dict[str, str]) -> tuple[int, int]:
143
136
  child.returncode = os.waitstatus_to_exitcode(status)
144
137
  return child.pid, child.returncode
145
138
  finally:
146
- # Restore terminal and handlers
147
139
  try:
148
- if fd is not None:
140
+ if tty_fd is not None:
149
141
  try:
150
- if foreground is not None:
151
- _foreground(fd, foreground)
142
+ if restore_pgid is not None:
143
+ _set_foreground_group(tty_fd, restore_pgid)
152
144
  except OSError as error:
153
145
  # A lost terminal must not erase an already reaped result.
154
146
  print(f"giwon: cannot restore terminal: {error}", file=sys.stderr)
155
147
  finally:
156
- os.close(fd)
148
+ os.close(tty_fd)
157
149
  finally:
158
150
  for number, previous in previous_handlers.items():
159
151
  signal.signal(number, previous)
@@ -179,6 +171,7 @@ def _prepare_record(command, cwd, settings, purpose):
179
171
  for key in (
180
172
  "max_patch_bytes",
181
173
  "patch_context",
174
+ "fail_on_untracked",
182
175
  "sample_bytes",
183
176
  "hash_outputs",
184
177
  "slurm_probes",
@@ -252,6 +245,13 @@ def run(
252
245
  purpose: str | None = None,
253
246
  image: str | None = None,
254
247
  ) -> int:
248
+ """Run a command and return its exit status.
249
+
250
+ Before launch, failure to write the snapshot, hash a requested input, or
251
+ capture a detected Git repository prevents the command from running.
252
+ Discovery probes can report unavailable observations and return partial facts.
253
+ Once the child exits, Giwon returns its status even if snapshot finalization fails.
254
+ """
255
255
  path = None
256
256
  try:
257
257
  if image is not None and (not image or "\0" in image):
@@ -317,6 +317,7 @@ def run(
317
317
  path.parent,
318
318
  settings["max_patch_bytes"],
319
319
  settings["patch_context"],
320
+ fail_on_untracked=settings["fail_on_untracked"],
320
321
  )
321
322
 
322
323
  record["execution"].update(status="launched", launched_at=_now())
@@ -1,22 +0,0 @@
1
- """Capture facts about the operating system."""
2
-
3
- import platform
4
- import sys
5
-
6
-
7
- def collect() -> dict[str, str]:
8
- facts = {}
9
- for key, observe in (
10
- ("os", platform.system),
11
- ("release", platform.release),
12
- ("architecture", platform.machine),
13
- ):
14
- try:
15
- value = observe()
16
- if value:
17
- facts[key] = value
18
- else:
19
- print(f"giwon: unavailable {key}", file=sys.stderr)
20
- except Exception as error: # noqa: BLE001
21
- print(f"giwon: unavailable {key}: {error}", file=sys.stderr)
22
- return facts
File without changes
File without changes