giwon 0.1.0__tar.gz → 0.1.2__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.0
3
+ Version: 0.1.2
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.0"
5
+ version = "0.1.2"
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"]
@@ -0,0 +1,35 @@
1
+ """Capture provenance around experiment executions."""
2
+
3
+ import os
4
+ from collections.abc import Iterable
5
+
6
+
7
+ # Keep the docstring as API documentation; put design notes in comments below.
8
+ def register_output(
9
+ *,
10
+ path: str | os.PathLike[str] | Iterable[str | os.PathLike[str]] = (),
11
+ url: str | Iterable[str] = (),
12
+ ) -> None:
13
+ """Register local artifacts and result links in the current Giwon run.
14
+
15
+ When called outside a Giwon run, this is a no-op.
16
+
17
+ Args:
18
+ path: A file or directory path, or an iterable of paths. Accepts strings
19
+ and path-like objects. Relative paths use the caller's current
20
+ working directory; the artifacts need not exist yet.
21
+ url: A result URL or an iterable of URLs, stored as supplied.
22
+
23
+ Both arguments may be supplied together. Registration does not copy,
24
+ inspect, or hash artifacts, but this is done after the run ends.
25
+
26
+ Example:
27
+ register_output(path=["ckpt.pt", "results.csv"], url="https://example.com/run")
28
+ """
29
+ snapshot_path = os.environ.get("GIWON_FILE")
30
+ if not snapshot_path:
31
+ return
32
+
33
+ from giwon import snapshot
34
+
35
+ snapshot.register_output(snapshot_path, path=path, url=url)
@@ -0,0 +1,129 @@
1
+ """Run experiments, register outputs, and hash artifacts from the command line."""
2
+
3
+ import os
4
+ import signal
5
+ import sys
6
+ from dataclasses import asdict, dataclass, field
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import tyro
11
+
12
+
13
+ @dataclass
14
+ class Run:
15
+ """Launch an experiment."""
16
+
17
+ purpose: str | None = None
18
+ image: str | None = None
19
+ config: Path | None = None
20
+ record_root: Path | None = None
21
+ hash_inputs: Annotated[
22
+ list[Path], tyro.conf.UseAppendAction, tyro.conf.arg(name="hash-input")
23
+ ] = field(default_factory=list)
24
+ sample_bytes: int | None = None
25
+ record_env: Annotated[list[str], tyro.conf.UseAppendAction] = field(
26
+ default_factory=list
27
+ )
28
+ max_patch_bytes: int | None = None
29
+ patch_context: int | None = None
30
+ hash_outputs: bool | None = None
31
+ slurm_probes: bool | None = None
32
+
33
+
34
+ @dataclass
35
+ class RegisterOutput:
36
+ """Register output paths and URLs in the selected run."""
37
+
38
+ path: Annotated[list[str], tyro.conf.UseAppendAction] = field(default_factory=list)
39
+ url: Annotated[list[str], tyro.conf.UseAppendAction] = field(default_factory=list)
40
+
41
+
42
+ @dataclass
43
+ class Hash:
44
+ """Print the full XXH3-128 output hash of a file or directory."""
45
+
46
+ path: Annotated[Path, tyro.conf.Positional]
47
+
48
+
49
+ def parse(argv: list[str]) -> tuple[Run | RegisterOutput | Hash, list[str]]:
50
+ def usage_error(message: str) -> None:
51
+ print(f"giwon: {message}", file=sys.stderr)
52
+ raise SystemExit(2)
53
+
54
+ split = argv.index("--") if "--" in argv else len(argv)
55
+ options = tyro.cli(
56
+ Run | RegisterOutput | Hash,
57
+ args=argv[:split],
58
+ prog="giwon",
59
+ config=(tyro.conf.DisallowNone,),
60
+ )
61
+ command = argv[split + 1 :]
62
+ if isinstance(options, RegisterOutput):
63
+ if command:
64
+ usage_error("register-output does not accept a command")
65
+ if not options.path and not options.url:
66
+ usage_error("register-output needs at least one path or url")
67
+ elif isinstance(options, Hash):
68
+ if split != len(argv):
69
+ usage_error("hash does not accept --")
70
+ elif not command:
71
+ usage_error("expected a command after --")
72
+
73
+ return options, command
74
+
75
+
76
+ def _register(options: RegisterOutput) -> None:
77
+ from giwon import register_output
78
+
79
+ try:
80
+ register_output(path=options.path, url=options.url)
81
+ except Exception as error: # noqa: BLE001
82
+ print(f"giwon: cannot register output: {error}", file=sys.stderr)
83
+ raise SystemExit(1) from None
84
+
85
+
86
+ def _hash(options: Hash) -> None:
87
+ from giwon import hashing
88
+
89
+ try:
90
+ result = hashing.fingerprint(options.path)
91
+ except (OSError, ValueError) as error:
92
+ print(f"giwon: cannot hash {options.path}: {error}", file=sys.stderr)
93
+ raise SystemExit(1) from None
94
+ print(result)
95
+
96
+
97
+ def _run(options: Run, command: list[str]) -> None:
98
+ """Run the experiment from command-line arguments and reproduce its exit status.
99
+
100
+ A numeric exit code does not tell the parent shell that a process died
101
+ from a signal. After finalization, re-deliver the child's terminating signal
102
+ to this wrapper so the shell observes the same termination.
103
+ """
104
+ from giwon import run
105
+
106
+ values = asdict(options)
107
+ purpose = values.pop("purpose")
108
+ image = values.pop("image")
109
+ result = run.run(command, values, purpose=purpose, image=image)
110
+
111
+ if result < 0:
112
+ number = -result
113
+ if number not in {signal.SIGKILL, signal.SIGSTOP}:
114
+ signal.signal(number, signal.SIG_DFL)
115
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {number})
116
+ os.kill(os.getpid(), number)
117
+ result = 128 + number
118
+
119
+ raise SystemExit(result)
120
+
121
+
122
+ def main() -> None:
123
+ options, command = parse(sys.argv[1:])
124
+ if isinstance(options, RegisterOutput):
125
+ _register(options)
126
+ elif isinstance(options, Hash):
127
+ _hash(options)
128
+ else:
129
+ _run(options, command)
@@ -1,8 +1,8 @@
1
1
  """Run an experiment and capture provenance before and after its execution.
2
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.
3
+ Experiment workers register outputs under a shared snapshot lock. The wrapper
4
+ leaves the record untouched during execution and takes that same lock when
5
+ finalizing after reaping the child.
6
6
  """
7
7
 
8
8
  import os
@@ -27,9 +27,7 @@ from giwon.discovery import (
27
27
  slurm,
28
28
  system,
29
29
  )
30
- from giwon.discovery import (
31
- image as container_image,
32
- )
30
+ from giwon.discovery import image as container_image
33
31
 
34
32
  SIGNALS = (
35
33
  signal.SIGHUP,
@@ -227,17 +225,22 @@ def _finish(path, cwd, status, result, pid=None, *, hash_outputs=False):
227
225
  The experiment may have replaced its record while running. Reload it
228
226
  before finalization to preserve those edits; if it cannot be read, leave it
229
227
  intact instead of overwriting it with the wrapper's stale copy.
228
+
229
+ A surviving descendant may still hold the lock after the child exits.
230
+ Try without waiting so capture cannot indefinitely delay the child's result;
231
+ a busy lock leaves the record intact and reports a finalization failure.
230
232
  """
231
233
  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)
234
+ with snapshot.lock(path, blocking=False): # raises if not aquired
235
+ record = snapshot.load(path)
236
+ execution = record["execution"]
237
+ execution.update(status=status, ended_at=_now(), exit_code=result)
238
+ if pid is not None:
239
+ execution["pid"] = pid
240
+ snapshot.inspect_outputs(
241
+ record["outputs"], cwd, hash_outputs=hash_outputs, snapshot_path=path
242
+ )
243
+ snapshot.write(path, record)
241
244
  except Exception as error: # noqa: BLE001
242
245
  print(f"giwon: cannot finalize snapshot: {error}", file=sys.stderr)
243
246
 
@@ -1,8 +1,11 @@
1
1
  """Read and write execution records and inspect registered output files."""
2
2
 
3
+ import fcntl
3
4
  import os
4
5
  import sys
5
6
  import tempfile
7
+ from collections.abc import Iterable
8
+ from contextlib import contextmanager
6
9
  from importlib.resources import files
7
10
  from pathlib import Path
8
11
  from typing import Any
@@ -16,6 +19,20 @@ _TEMPLATE = yaml.safe_load(
16
19
  )
17
20
 
18
21
 
22
+ @contextmanager
23
+ def lock(path: Path, *, blocking: bool = True):
24
+ """Serialize snapshot updates across threads and processes.
25
+
26
+ Atomic replacement changes the snapshot inode. Lock a persistent sibling
27
+ instead, opening it independently for each caller and leaving it in place
28
+ so waiting writers always coordinate through the same inode. Closing the
29
+ descriptor releases its lock, including when the update raises.
30
+ """
31
+ with path.with_name(path.name + ".lock").open("a") as stream:
32
+ fcntl.flock(stream, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))
33
+ yield
34
+
35
+
19
36
  def _ordered(value, template):
20
37
  """Order record fields according to a template.
21
38
 
@@ -132,3 +149,48 @@ def inspect_outputs(
132
149
  if isinstance(error, hashing.SelfReferenceError):
133
150
  output.pop("hash", None)
134
151
  print(f"giwon: cannot inspect output {output!r}: {error}", file=sys.stderr)
152
+
153
+
154
+ def register_output(
155
+ snapshot_path: str | os.PathLike[str],
156
+ *,
157
+ path: str | os.PathLike[str] | Iterable[str | os.PathLike[str]] = (),
158
+ url: str | Iterable[str] = (),
159
+ ) -> None:
160
+ """Register local artifacts and result links in an existing snapshot.
161
+
162
+ Args:
163
+ snapshot_path: Path to a readable and writable snapshot YAML file
164
+ containing an outputs list. GIWON_FILE is not consulted.
165
+ path: A file or directory path, or an iterable of paths. Accepts strings
166
+ and path-like objects. Relative paths use the caller's current
167
+ working directory; the artifacts need not exist yet.
168
+ url: A result URL or an iterable of URLs, stored as supplied.
169
+
170
+ Append paths before URLs, preserving their order and any duplicates.
171
+ Registration does not copy, inspect, or hash artifacts. Any run status is
172
+ accepted. Returns None. Read, conversion, serialization, and write errors
173
+ propagate to the caller.
174
+
175
+ Example:
176
+ register_output("snapshot.yaml", path="checkpoint.pt", url="https://example.com/run")
177
+ """
178
+ paths = (path,) if isinstance(path, (str, os.PathLike)) else path
179
+ urls = (url,) if isinstance(url, str) else url
180
+ del path, url
181
+
182
+ outputs = []
183
+ for path in paths:
184
+ path = os.fspath(path)
185
+ path = str(Path(path).absolute())
186
+ outputs.append({"path": path})
187
+
188
+ for url in urls:
189
+ outputs.append({"url": url})
190
+
191
+ record_path = Path(snapshot_path)
192
+
193
+ with lock(record_path):
194
+ record = load(record_path)
195
+ record["outputs"].extend(outputs)
196
+ write(record_path, record)
@@ -1 +0,0 @@
1
- """Capture provenance around experiment executions."""
@@ -1,67 +0,0 @@
1
- """Parse Giwon options and launch the experiment command."""
2
-
3
- import os
4
- import signal
5
- import sys
6
- from dataclasses import asdict, dataclass, field
7
- from pathlib import Path
8
- from typing import Annotated
9
-
10
- import tyro
11
-
12
- from giwon import run
13
-
14
-
15
- @dataclass
16
- class Options:
17
- purpose: str | None = None
18
- image: str | None = None
19
- config: Path | None = None
20
- record_root: Path | None = None
21
- hash_inputs: Annotated[
22
- list[Path], tyro.conf.UseAppendAction, tyro.conf.arg(name="hash-input")
23
- ] = field(default_factory=list)
24
- sample_bytes: int | None = None
25
- record_env: Annotated[list[str], tyro.conf.UseAppendAction] = field(
26
- default_factory=list
27
- )
28
- max_patch_bytes: int | None = None
29
- patch_context: int | None = None
30
- hash_outputs: bool | None = None
31
- slurm_probes: bool | None = None
32
-
33
-
34
- def parse(argv: list[str]) -> tuple[Options, list[str]]:
35
- split = argv.index("--") if "--" in argv else len(argv)
36
- options = tyro.cli(
37
- Options, args=argv[:split], prog="giwon", config=(tyro.conf.DisallowNone,)
38
- )
39
- command = argv[split + 1 :]
40
- if not command:
41
- print("giwon: expected a command after --", file=sys.stderr)
42
- raise SystemExit(2)
43
- return options, command
44
-
45
-
46
- def main() -> None:
47
- """Run the experiment from command-line arguments and reproduce its exit status.
48
-
49
- A numeric exit code does not tell the parent shell that a process died
50
- from a signal. After finalization, re-deliver the child's terminating signal
51
- to this wrapper so the shell observes the same termination.
52
- """
53
- options, command = parse(sys.argv[1:])
54
- values = asdict(options)
55
- purpose = values.pop("purpose")
56
- image = values.pop("image")
57
- result = run.run(command, values, purpose=purpose, image=image)
58
-
59
- if result < 0:
60
- number = -result
61
- if number not in {signal.SIGKILL, signal.SIGSTOP}:
62
- signal.signal(number, signal.SIG_DFL)
63
- signal.pthread_sigmask(signal.SIG_UNBLOCK, {number})
64
- os.kill(os.getpid(), number)
65
- result = 128 + number
66
-
67
- raise SystemExit(result)
File without changes
File without changes
File without changes
File without changes