giwon 0.1.0__py3-none-any.whl

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.
giwon/run.py ADDED
@@ -0,0 +1,347 @@
1
+ """Run an experiment and capture provenance before and after its execution.
2
+
3
+ Experiments may edit their safe-YAML records directly without importing Giwon.
4
+ The wrapper owns the record before launch and after reaping the child; it leaves
5
+ that file untouched during execution so its writes cannot race experiment edits.
6
+ """
7
+
8
+ import os
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+ import uuid
13
+ from collections.abc import Iterable
14
+ from datetime import UTC, datetime
15
+ from importlib.metadata import version
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from giwon import config, hashing, snapshot
20
+ from giwon.discovery import (
21
+ apptainer,
22
+ docker,
23
+ environment,
24
+ git,
25
+ hardware,
26
+ pyxis,
27
+ slurm,
28
+ system,
29
+ )
30
+ from giwon.discovery import (
31
+ image as container_image,
32
+ )
33
+
34
+ SIGNALS = (
35
+ signal.SIGHUP,
36
+ signal.SIGINT,
37
+ signal.SIGQUIT,
38
+ signal.SIGTERM,
39
+ signal.SIGUSR1,
40
+ signal.SIGUSR2,
41
+ signal.SIGALRM,
42
+ signal.SIGTSTP,
43
+ signal.SIGCONT,
44
+ signal.SIGWINCH,
45
+ )
46
+
47
+
48
+ class _LaunchError(Exception):
49
+ def __init__(self, error: Exception):
50
+ self.code = 127 if isinstance(error, FileNotFoundError) else 126
51
+ super().__init__(str(error))
52
+
53
+
54
+ def _foreground(fd, group):
55
+ # Ignore if parent process wants to write to terminal or change its settings
56
+ previous = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
57
+ try:
58
+ os.tcsetpgrp(fd, group) # Set control group of descriptor
59
+ finally:
60
+ signal.signal(signal.SIGTTOU, previous)
61
+
62
+
63
+ def _supervise(command: list[str], env: dict[str, str]) -> tuple[int, int]:
64
+ """Run the child process with signal forwarding and terminal job control.
65
+
66
+ Experiments may spawn descendants and still need interactive job control.
67
+ A new session would lose the controlling terminal, so isolate the child's
68
+ process group within the existing session and hand it terminal ownership.
69
+
70
+ Signals can arrive before that group exists. Queue them until the child has
71
+ spawned so termination requests during launch are not lost.
72
+ """
73
+ child = None
74
+ pending = []
75
+ previous_handlers = {}
76
+ fd = None # file descriptor of us
77
+ foreground = None
78
+
79
+ def forward(n, _frame):
80
+ # On resume, only hand over the terminal if the shell foregrounded us.
81
+ nonlocal foreground
82
+ if child is None:
83
+ pending.append(n)
84
+ return
85
+ if n == signal.SIGCONT and fd is not None:
86
+ current = os.tcgetpgrp(fd)
87
+ if current != child.pid:
88
+ foreground = os.getpgrp() if current == os.getpgrp() else None
89
+ if foreground is not None:
90
+ _foreground(fd, child.pid)
91
+ try:
92
+ os.killpg(child.pid, n) # Send signal
93
+ except ProcessLookupError:
94
+ pass
95
+
96
+ try:
97
+ # Find the controlling terminal of the runner (us)
98
+ try:
99
+ fd = os.dup(0) if os.isatty(0) else os.open("/dev/tty", os.O_RDWR)
100
+ foreground = os.tcgetpgrp(fd)
101
+ if foreground != os.getpgrp():
102
+ foreground = None
103
+ except OSError:
104
+ if fd is not None:
105
+ os.close(fd)
106
+ fd = None
107
+
108
+ # Forward signals
109
+ for number in SIGNALS:
110
+ previous_handlers[number] = signal.signal(number, forward)
111
+
112
+ try:
113
+ # Open child process as independent process group
114
+ child = subprocess.Popen(command, env=env, process_group=0)
115
+ except (OSError, TypeError, ValueError, IndexError) as error:
116
+ raise _LaunchError(error) from error
117
+
118
+ if fd is not None and foreground is not None:
119
+ _foreground(fd, child.pid)
120
+ for number in pending:
121
+ forward(number, None)
122
+
123
+ # Wait for the command, following shell stop/resume
124
+ while True:
125
+ # WUNTRACED -> return even if child is stopped
126
+ _, status = os.waitpid(child.pid, os.WUNTRACED)
127
+ if os.WIFSTOPPED(status):
128
+ # Child might be quick and attempt to read before we've given it control
129
+ # of the foreground terminal. In this case termianl control will stop
130
+ # with SIGTTIN, so we foreground the process and send SIGCONT. Otherwise
131
+ # we stop ourselves, and continue the child aftewards.
132
+ if (
133
+ fd is not None
134
+ and foreground is not None
135
+ and os.WSTOPSIG(status) == signal.SIGTTIN
136
+ ):
137
+ _foreground(fd, child.pid)
138
+ else:
139
+ if fd is not None and foreground is not None:
140
+ _foreground(fd, foreground)
141
+ os.kill(os.getpid(), signal.SIGSTOP)
142
+ os.killpg(child.pid, signal.SIGCONT)
143
+ continue
144
+
145
+ child.returncode = os.waitstatus_to_exitcode(status)
146
+ return child.pid, child.returncode
147
+ finally:
148
+ # Restore terminal and handlers
149
+ try:
150
+ if fd is not None:
151
+ try:
152
+ if foreground is not None:
153
+ _foreground(fd, foreground)
154
+ except OSError as error:
155
+ # A lost terminal must not erase an already reaped result.
156
+ print(f"giwon: cannot restore terminal: {error}", file=sys.stderr)
157
+ finally:
158
+ os.close(fd)
159
+ finally:
160
+ for number, previous in previous_handlers.items():
161
+ signal.signal(number, previous)
162
+
163
+
164
+ def _now():
165
+ return datetime.now(UTC).isoformat().replace("+00:00", "Z")
166
+
167
+
168
+ def _prepare_record(command, cwd, settings, purpose):
169
+ created = _now()
170
+ run_id = str(uuid.uuid4())
171
+ directory = (
172
+ settings["record_root"] / f"{datetime.now(UTC):%Y%m%dT%H%M%S.%fZ}-{run_id}"
173
+ )
174
+ directory.parent.mkdir(parents=True, exist_ok=True)
175
+ directory.mkdir(mode=0o700)
176
+ path = directory / "snapshot.yaml"
177
+
178
+ # Build record
179
+ recorded_settings = {
180
+ key: settings[key]
181
+ for key in (
182
+ "max_patch_bytes",
183
+ "patch_context",
184
+ "sample_bytes",
185
+ "hash_outputs",
186
+ "slurm_probes",
187
+ )
188
+ }
189
+ if settings["config"] is not None:
190
+ recorded_settings["config"] = str(settings["config"])
191
+ record = {
192
+ "giwon": {
193
+ "version": version("giwon"),
194
+ "python_version": sys.version.split()[0],
195
+ "settings": recorded_settings,
196
+ },
197
+ "invocation": {"argv": command, "working_directory": str(cwd)},
198
+ "inputs": [],
199
+ "environment": {},
200
+ "execution": {
201
+ "run_id": run_id,
202
+ "directory": str(directory),
203
+ "created_at": created,
204
+ "status": "preparing",
205
+ },
206
+ "outputs": [],
207
+ }
208
+ if purpose is not None:
209
+ record["purpose"] = purpose
210
+ snapshot.write(path, record)
211
+ return path, record
212
+
213
+
214
+ def _prepare_environment(path, run_id):
215
+ env = dict(os.environ)
216
+ env.update(
217
+ GIWON_DIR=str(path.parent),
218
+ GIWON_FILE=str(path),
219
+ GIWON_RUN_ID=run_id,
220
+ )
221
+ return env
222
+
223
+
224
+ def _finish(path, cwd, status, result, pid=None, *, hash_outputs=False):
225
+ """Finalize the experiment record and inspect registered outputs.
226
+
227
+ The experiment may have replaced its record while running. Reload it
228
+ before finalization to preserve those edits; if it cannot be read, leave it
229
+ intact instead of overwriting it with the wrapper's stale copy.
230
+ """
231
+ try:
232
+ record = snapshot.load(path)
233
+ execution = record["execution"]
234
+ execution.update(status=status, ended_at=_now(), exit_code=result)
235
+ if pid is not None:
236
+ execution["pid"] = pid
237
+ snapshot.inspect_outputs(
238
+ record["outputs"], cwd, hash_outputs=hash_outputs, snapshot_path=path
239
+ )
240
+ snapshot.write(path, record)
241
+ except Exception as error: # noqa: BLE001
242
+ print(f"giwon: cannot finalize snapshot: {error}", file=sys.stderr)
243
+
244
+
245
+ def run(
246
+ command: Iterable[str],
247
+ overrides: dict[str, Any],
248
+ *,
249
+ purpose: str | None = None,
250
+ image: str | None = None,
251
+ ) -> int:
252
+ path = None
253
+ try:
254
+ if image is not None and (not image or "\0" in image):
255
+ raise ValueError("image must be nonempty and contain no NUL")
256
+ if isinstance(command, str):
257
+ raise TypeError("command must be an iterable of arguments, not a string")
258
+ command = list(command)
259
+ cwd = Path.cwd()
260
+ git_root = git.detect(cwd)
261
+ settings = config.load(cwd, overrides, git_root=git_root)
262
+
263
+ path, record = _prepare_record(command, cwd, settings, purpose)
264
+
265
+ env = _prepare_environment(path, record["execution"]["run_id"])
266
+ record["environment"].update(system.collect())
267
+ record["environment"].update(
268
+ environment.collect(command, env, path.parent, settings["record_env"])
269
+ )
270
+
271
+ local = hardware.collect()
272
+ record["hardware"] = {"nodes": [local]}
273
+ slurm_facts, nodes = slurm.collect(
274
+ env, local, probe_nodes=settings["slurm_probes"]
275
+ )
276
+ if slurm_facts is not None:
277
+ record["slurm"] = slurm_facts
278
+ record["hardware"]["nodes"].extend(nodes)
279
+
280
+ executable = record["environment"].get("executable")
281
+ docker_facts = docker.collect(cwd, env)
282
+ if docker_facts is not None:
283
+ record["docker"] = docker_facts
284
+ apptainer_facts = apptainer.collect(env)
285
+ if apptainer_facts is not None:
286
+ record["apptainer"] = apptainer_facts
287
+ pyxis_facts = pyxis.collect(env, slurm_facts)
288
+ if pyxis_facts is not None:
289
+ record["pyxis"] = pyxis_facts
290
+
291
+ reference = image
292
+ if reference is None:
293
+ reference = container_image.detect(command, executable)
294
+ if reference is not None:
295
+ record["image"] = container_image.collect(
296
+ reference, cwd, env, forbidden=path.parent
297
+ )
298
+
299
+ record["inputs"] = [
300
+ {
301
+ "path": str(selected),
302
+ "hash": hashing.fingerprint(
303
+ selected,
304
+ sample_bytes=settings["sample_bytes"],
305
+ forbidden=path.parent,
306
+ ),
307
+ }
308
+ for selected in settings["hash_inputs"]
309
+ ]
310
+
311
+ if git_root is not None:
312
+ record["git"] = git.collect(
313
+ git_root,
314
+ path.parent,
315
+ settings["max_patch_bytes"],
316
+ settings["patch_context"],
317
+ )
318
+
319
+ record["execution"].update(status="launched", launched_at=_now())
320
+ snapshot.write(path, record)
321
+ except Exception as error: # noqa: BLE001
322
+ print(f"giwon: preflight failed: {error}", file=sys.stderr)
323
+ if path is not None:
324
+ _finish(path, cwd, "preflight_failed", 2)
325
+ return 2
326
+
327
+ # Run the command
328
+ try:
329
+ pid, result = _supervise(command, env)
330
+ except _LaunchError as error:
331
+ print(f"giwon: launch failed: {error}", file=sys.stderr)
332
+ _finish(path, cwd, "launch_failed", error.code)
333
+ return error.code
334
+ except Exception as error: # noqa: BLE001
335
+ # The child might still own the YAML. Leave the launch boundary intact.
336
+ print(f"giwon: supervision failed: {error}", file=sys.stderr)
337
+ return 2
338
+
339
+ # Record the result and registered outputs
340
+ if result < 0:
341
+ status = "signaled"
342
+ exit_code = 128 - result
343
+ else:
344
+ status = "succeeded" if result == 0 else "failed"
345
+ exit_code = result
346
+ _finish(path, cwd, status, exit_code, pid, hash_outputs=settings["hash_outputs"])
347
+ return result
giwon/snapshot.py ADDED
@@ -0,0 +1,134 @@
1
+ """Read and write execution records and inspect registered output files."""
2
+
3
+ import os
4
+ import sys
5
+ import tempfile
6
+ from importlib.resources import files
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ from giwon import hashing
13
+
14
+ _TEMPLATE = yaml.safe_load(
15
+ files("giwon").joinpath("record.yaml").read_text(encoding="utf-8")
16
+ )
17
+
18
+
19
+ def _ordered(value, template):
20
+ """Order record fields according to a template.
21
+
22
+ Experiments can add fields that Giwon does not know about. Treat
23
+ record.yaml as an ordering guide only, preserving those additions without
24
+ using the template to validate values or insert defaults.
25
+ """
26
+ if isinstance(value, dict) and isinstance(template, dict):
27
+ keys = dict.fromkeys((*template, *value))
28
+ return {
29
+ key: _ordered(value[key], template.get(key)) for key in keys if key in value
30
+ }
31
+ if isinstance(value, list) and isinstance(template, list) and template:
32
+ return [_ordered(item, template[0]) for item in value]
33
+ return value
34
+
35
+
36
+ class _Loader(yaml.SafeLoader):
37
+ pass
38
+
39
+
40
+ _Loader.add_constructor("tag:yaml.org,2002:timestamp", _Loader.construct_scalar)
41
+
42
+
43
+ class _Dumper(yaml.SafeDumper):
44
+ """Keep integer index lists compact while leaving structured records in blocks."""
45
+
46
+ def represent_list(self, data):
47
+ return self.represent_sequence(
48
+ "tag:yaml.org,2002:seq",
49
+ data,
50
+ flow_style=all(type(value) is int for value in data),
51
+ )
52
+
53
+
54
+ _Dumper.add_representer(list, _Dumper.represent_list)
55
+
56
+
57
+ def load(path: Path) -> Any:
58
+ with path.open(encoding="utf-8") as stream:
59
+ return yaml.load(stream, Loader=_Loader)
60
+
61
+
62
+ def write(path: Path, record: dict, *, normalize: bool = True) -> None:
63
+ text = yaml.dump(
64
+ _ordered(record, _TEMPLATE) if normalize else record,
65
+ Dumper=_Dumper,
66
+ sort_keys=False,
67
+ allow_unicode=True,
68
+ )
69
+ name = None
70
+ try:
71
+ with tempfile.NamedTemporaryFile(
72
+ mode="w",
73
+ encoding="utf-8",
74
+ dir=path.parent,
75
+ prefix=f".{path.name}.",
76
+ delete=False,
77
+ ) as stream:
78
+ name = stream.name
79
+ stream.write(text)
80
+ stream.flush()
81
+ os.fsync(stream.fileno())
82
+ os.replace(name, path)
83
+ finally:
84
+ if name is not None:
85
+ Path(name).unlink(missing_ok=True)
86
+
87
+
88
+ def inspect_outputs(
89
+ outputs: list,
90
+ cwd: Path,
91
+ *,
92
+ hash_outputs: bool = False,
93
+ snapshot_path: Path | None = None,
94
+ ) -> None:
95
+ if not isinstance(outputs, list):
96
+ raise TypeError("snapshot outputs must be a list")
97
+
98
+ for output in outputs:
99
+ try:
100
+ if ("path" in output) == ("url" in output):
101
+ raise ValueError("registration needs exactly one path or url")
102
+ value = output.get("path", output.get("url"))
103
+ if not isinstance(value, str) or not value or "\0" in value:
104
+ raise ValueError("path or url must be a nonempty string without NUL")
105
+ if "url" in output:
106
+ continue
107
+
108
+ path = cwd / value
109
+ output.pop("exists", None)
110
+ output.pop("size_bytes", None)
111
+ try:
112
+ path.stat()
113
+ except (FileNotFoundError, NotADirectoryError):
114
+ output["exists"] = False
115
+ print(f"giwon: missing output: {path}", file=sys.stderr)
116
+ continue
117
+
118
+ output["exists"] = True
119
+ entries, observations = hashing.inventory(path)
120
+ output["size_bytes"] = hashing.size(entries)
121
+ if hash_outputs:
122
+ fresh = hashing.fingerprint_inventory(
123
+ path, entries, observations, forbidden=snapshot_path
124
+ )
125
+ if "hash" in output and output["hash"] != fresh:
126
+ print(
127
+ f"giwon: output hash disagrees with fresh hash: {path}",
128
+ file=sys.stderr,
129
+ )
130
+ output["hash"] = fresh
131
+ except (AttributeError, TypeError, OSError, ValueError) as error:
132
+ if isinstance(error, hashing.SelfReferenceError):
133
+ output.pop("hash", None)
134
+ print(f"giwon: cannot inspect output {output!r}: {error}", file=sys.stderr)
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.3
2
+ Name: giwon
3
+ Version: 0.1.0
4
+ Summary: Observe provenance around one experiment execution.
5
+ Requires-Dist: tyro>=1.0.16
6
+ Requires-Dist: pyyaml
7
+ Requires-Dist: xxhash
8
+ Requires-Dist: gitpython
9
+ Requires-Python: >=3.11
@@ -0,0 +1,21 @@
1
+ giwon/__init__.py,sha256=0AucRi9PCYBp3NLANF8rJwcP9PS985Vg-V6dC5rMLvk,55
2
+ giwon/cli.py,sha256=b3go9fXKVJn2aowPwDjwXI13he1llMIpfRjyUoen7II,2094
3
+ giwon/config.py,sha256=JKOUNZxFNyrjblFAP3SJgA0fqSiB0-TlZMuOIZvXVCM,3926
4
+ giwon/discovery/__init__.py,sha256=mQ-zJSYeadBQceb0OcmKJ2s8-6PbkDlZrlpsjOr_6yM,57
5
+ giwon/discovery/apptainer.py,sha256=_hxVFesCoPrlUUykMdSxhWp_eRHArVHbkYnZWMITA_g,1473
6
+ giwon/discovery/docker.py,sha256=0Tks0Ng5DiaUxvW5wZjMaaiG9dwtCD4RWFx5-9Nr_Ks,5361
7
+ giwon/discovery/environment.py,sha256=5bArG-8LOTFgeHNSRtBqdfM_Al9DsMYZe1Ivlq6kVYg,1462
8
+ giwon/discovery/git.py,sha256=GMoOaMOJ-e87FHYRyKQzS0u9hehAqy9fCBiz-KDFGKE,5844
9
+ giwon/discovery/hardware.py,sha256=TFTwZQXSTMJVce8bccUNBdKksVPEoWtdrm0t3M_afzs,10471
10
+ giwon/discovery/image.py,sha256=ky6TqgbBKSbSg4tbTksTWAkc20kiCOUWtG2AKpUQlqI,4266
11
+ giwon/discovery/pyxis.py,sha256=eGUAEfhu7oZjBFAcNnaxiSlCX1bpIHbpNlrVdo1gixU,1597
12
+ giwon/discovery/slurm.py,sha256=LwTkv2UHpjevnb_KDPSV-C6y3OZc_b5RagtwOrIuAA0,11821
13
+ giwon/discovery/system.py,sha256=pr3Ji451EAM_FL_0lwwykZWcKd5CB7n7B9STZn1Z88M,602
14
+ giwon/hashing.py,sha256=Naxc87HKQdPx1NQjz8E8M4gkiAsL4VuP6u_wmScdly0,7365
15
+ giwon/record.yaml,sha256=ZKTf535R79yl9PHb9kj4T4P1nOOejcXfDajUV-Hpa5Q,1869
16
+ giwon/run.py,sha256=Un_oznvNIi_bmH6FFnMjHLm3nArmRIKzr4DIaDdaGcY,11737
17
+ giwon/snapshot.py,sha256=c1SeANJO1GvYW_XduqwwoPlXjrQTjTjlLcOKQmaeVyI,4309
18
+ giwon-0.1.0.dist-info/WHEEL,sha256=eh7sammvW2TypMMMGKgsM83HyA_3qQ5Lgg3ynoecH3M,79
19
+ giwon-0.1.0.dist-info/entry_points.txt,sha256=VkUtKtZxrLcO6_Tl2QQxqRP7aOQopBBOvDwkP1dvpes,42
20
+ giwon-0.1.0.dist-info/METADATA,sha256=8AazsCHm82UKjTfx66TfMjbmKZWuoZTj1FPgbNyFg_4,231
21
+ giwon-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.8.24
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ giwon = giwon.cli:main
3
+