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/__init__.py +1 -0
- giwon/cli.py +67 -0
- giwon/config.py +128 -0
- giwon/discovery/__init__.py +1 -0
- giwon/discovery/apptainer.py +47 -0
- giwon/discovery/docker.py +158 -0
- giwon/discovery/environment.py +42 -0
- giwon/discovery/git.py +165 -0
- giwon/discovery/hardware.py +326 -0
- giwon/discovery/image.py +119 -0
- giwon/discovery/pyxis.py +45 -0
- giwon/discovery/slurm.py +376 -0
- giwon/discovery/system.py +22 -0
- giwon/hashing.py +216 -0
- giwon/record.yaml +89 -0
- giwon/run.py +347 -0
- giwon/snapshot.py +134 -0
- giwon-0.1.0.dist-info/METADATA +9 -0
- giwon-0.1.0.dist-info/RECORD +21 -0
- giwon-0.1.0.dist-info/WHEEL +4 -0
- giwon-0.1.0.dist-info/entry_points.txt +3 -0
giwon/discovery/slurm.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""Observe the current Slurm job and probe its verified allocation.
|
|
2
|
+
|
|
3
|
+
Job names and submission commands can contain whitespace and key=value text.
|
|
4
|
+
Read controller JSON so those values cannot be confused with allocation facts.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import signal
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from collections.abc import Mapping
|
|
14
|
+
from datetime import UTC, datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from giwon.discovery import hardware
|
|
18
|
+
|
|
19
|
+
_CONNECTION_VARIABLES = {
|
|
20
|
+
"SLURM_CONF",
|
|
21
|
+
"SLURM_CONF_SERVER",
|
|
22
|
+
"SLURM_JWT",
|
|
23
|
+
"SLURM_WORKING_CLUSTER",
|
|
24
|
+
}
|
|
25
|
+
_LAUNCH_OPTION_PREFIXES = (
|
|
26
|
+
"SLURM_",
|
|
27
|
+
"SLURMD_",
|
|
28
|
+
"SRUN_",
|
|
29
|
+
"SBATCH_",
|
|
30
|
+
"SALLOC_",
|
|
31
|
+
"SPANK_",
|
|
32
|
+
"_SLURM_SPANK_",
|
|
33
|
+
"PYXIS_",
|
|
34
|
+
"ENROOT_",
|
|
35
|
+
"APPTAINER_",
|
|
36
|
+
"SINGULARITY_",
|
|
37
|
+
"PMI_",
|
|
38
|
+
"PMIX_",
|
|
39
|
+
)
|
|
40
|
+
_JOB_STRING_FIELDS = (
|
|
41
|
+
"cluster",
|
|
42
|
+
"name",
|
|
43
|
+
"partition",
|
|
44
|
+
"account",
|
|
45
|
+
"qos",
|
|
46
|
+
"submit_line",
|
|
47
|
+
"command",
|
|
48
|
+
"current_working_directory",
|
|
49
|
+
"dependency",
|
|
50
|
+
"nodes",
|
|
51
|
+
"tres_req_str",
|
|
52
|
+
"tres_alloc_str",
|
|
53
|
+
"standard_output",
|
|
54
|
+
"standard_error",
|
|
55
|
+
)
|
|
56
|
+
_JOB_NUMBER_FIELDS = (
|
|
57
|
+
"restart_cnt",
|
|
58
|
+
"time_limit",
|
|
59
|
+
"cpus_per_task",
|
|
60
|
+
"tasks",
|
|
61
|
+
"array_job_id",
|
|
62
|
+
"array_task_id",
|
|
63
|
+
)
|
|
64
|
+
_TERMINAL_STATES = {
|
|
65
|
+
"BOOT_FAIL",
|
|
66
|
+
"CANCELLED",
|
|
67
|
+
"COMPLETED",
|
|
68
|
+
"DEADLINE",
|
|
69
|
+
"FAILED",
|
|
70
|
+
"NODE_FAIL",
|
|
71
|
+
"OUT_OF_MEMORY",
|
|
72
|
+
"PREEMPTED",
|
|
73
|
+
"TIMEOUT",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _launcher_environment(env):
|
|
78
|
+
"""Remove inherited launch options while retaining Slurm connection settings.
|
|
79
|
+
|
|
80
|
+
Slurm and SPANK interpret options before task exports are applied. Keep only
|
|
81
|
+
connection variables from these namespaces so new resource/container options
|
|
82
|
+
cannot silently become probe defaults as launcher versions change.
|
|
83
|
+
"""
|
|
84
|
+
return {
|
|
85
|
+
key: value
|
|
86
|
+
for key, value in env.items()
|
|
87
|
+
if key in _CONNECTION_VARIABLES or not key.startswith(_LAUNCH_OPTION_PREFIXES)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _query(arguments, env):
|
|
92
|
+
result = subprocess.run(
|
|
93
|
+
["scontrol", *arguments],
|
|
94
|
+
env=env,
|
|
95
|
+
stdin=subprocess.DEVNULL,
|
|
96
|
+
capture_output=True,
|
|
97
|
+
text=True,
|
|
98
|
+
timeout=3,
|
|
99
|
+
check=True,
|
|
100
|
+
)
|
|
101
|
+
return result.stdout
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _number(value):
|
|
105
|
+
if isinstance(value, dict):
|
|
106
|
+
if not value.get("set") or value.get("infinite"):
|
|
107
|
+
return None
|
|
108
|
+
return value["number"]
|
|
109
|
+
return value
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# Todo: decide if additonal complexity is worth keeping. It transforms
|
|
113
|
+
# {set: bool, infinite: bool, number: int} -> Literal["set", "infinite"] | int
|
|
114
|
+
def _record_numbers(value):
|
|
115
|
+
"""Flatten Slurm numeric wrappers without losing unset or unlimited values.
|
|
116
|
+
|
|
117
|
+
Wrappers also occur inside resource records and lists. Normalize the recorded
|
|
118
|
+
tree separately from numeric extraction used by allocation checks. Infinite
|
|
119
|
+
takes precedence because Slurm can report it with set=False.
|
|
120
|
+
"""
|
|
121
|
+
if isinstance(value, dict):
|
|
122
|
+
if {"set", "number"} <= value.keys() <= {"set", "infinite", "number"}:
|
|
123
|
+
if value.get("infinite"):
|
|
124
|
+
return "infinite"
|
|
125
|
+
if not value["set"]:
|
|
126
|
+
return "unset"
|
|
127
|
+
return value["number"]
|
|
128
|
+
|
|
129
|
+
return {key: _record_numbers(item) for key, item in value.items()}
|
|
130
|
+
if isinstance(value, list):
|
|
131
|
+
return [_record_numbers(item) for item in value]
|
|
132
|
+
return value
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _job_facts(job):
|
|
136
|
+
facts = {}
|
|
137
|
+
|
|
138
|
+
for key in _JOB_STRING_FIELDS:
|
|
139
|
+
value = job.get(key)
|
|
140
|
+
if isinstance(value, str) and value:
|
|
141
|
+
facts[key] = value
|
|
142
|
+
facts.update({key: job[key] for key in _JOB_NUMBER_FIELDS if key in job})
|
|
143
|
+
|
|
144
|
+
if isinstance(job.get("requeue"), bool):
|
|
145
|
+
facts["requeue"] = job["requeue"]
|
|
146
|
+
|
|
147
|
+
if job.get("gres_detail"):
|
|
148
|
+
facts["gres_detail"] = job["gres_detail"]
|
|
149
|
+
|
|
150
|
+
# here we COULD capture a bunch of detail on the CPU layout, but this is extremely
|
|
151
|
+
# verbose and not useful enough to clutter up the snapshots
|
|
152
|
+
if job.get("job_resources"):
|
|
153
|
+
facts["job_resources"] = _record_numbers(job["job_resources"])
|
|
154
|
+
for node in facts["job_resources"].get("nodes", {}).get("allocation", []):
|
|
155
|
+
node.pop("sockets", None)
|
|
156
|
+
|
|
157
|
+
states = job.get("job_state", [])
|
|
158
|
+
if not isinstance(states, list) or not all(isinstance(s, str) for s in states):
|
|
159
|
+
raise ValueError("invalid Slurm job state")
|
|
160
|
+
if states:
|
|
161
|
+
facts["job_state"] = states
|
|
162
|
+
|
|
163
|
+
# Pending start times and unfinished jobs' end times can be predictions.
|
|
164
|
+
# Include these timestamps only when the state establishes an observed event.
|
|
165
|
+
timestamps = ["submit_time", "preempt_time"]
|
|
166
|
+
if "RUNNING" in states:
|
|
167
|
+
timestamps.append("start_time")
|
|
168
|
+
if _TERMINAL_STATES.intersection(states):
|
|
169
|
+
timestamps.append("start_time")
|
|
170
|
+
timestamps.append("end_time")
|
|
171
|
+
|
|
172
|
+
for key in timestamps:
|
|
173
|
+
if value := _number(job.get(key)):
|
|
174
|
+
facts[key] = (
|
|
175
|
+
datetime.fromtimestamp(value, UTC).isoformat().replace("+00:00", "Z")
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
return _record_numbers(facts)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _allocation(job, env):
|
|
182
|
+
if (
|
|
183
|
+
job.get("job_state") != ["RUNNING"]
|
|
184
|
+
or _number(job.get("user_id")) != os.getuid()
|
|
185
|
+
):
|
|
186
|
+
raise ValueError("probe needs a running job owned by the current user")
|
|
187
|
+
|
|
188
|
+
# Heterogeneous steps need component-specific launch semantics; add those
|
|
189
|
+
# before probing jobs whose resources span independently scheduled components.
|
|
190
|
+
if _number(job.get("het_job_id")):
|
|
191
|
+
raise ValueError("heterogeneous allocation probes are not supported")
|
|
192
|
+
|
|
193
|
+
expression = job.get("nodes")
|
|
194
|
+
count = _number(job.get("node_count"))
|
|
195
|
+
if not isinstance(expression, str) or not expression or not count:
|
|
196
|
+
raise ValueError("missing verified allocation nodes/count")
|
|
197
|
+
|
|
198
|
+
nodes = _query(["show", "hostnames", expression], env).splitlines()
|
|
199
|
+
if (
|
|
200
|
+
len(nodes) != count
|
|
201
|
+
or len(set(nodes)) != count
|
|
202
|
+
or not all(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", node) for node in nodes)
|
|
203
|
+
):
|
|
204
|
+
raise ValueError("allocation node names/count disagree")
|
|
205
|
+
return nodes
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _probe_command(job_id, nodes):
|
|
209
|
+
payload = Path(hardware.__file__).read_text(encoding="utf-8")
|
|
210
|
+
return [
|
|
211
|
+
"srun",
|
|
212
|
+
f"--jobid={job_id}",
|
|
213
|
+
f"--nodelist={','.join(nodes)}",
|
|
214
|
+
f"--nodes={len(nodes)}",
|
|
215
|
+
f"--ntasks={len(nodes)}",
|
|
216
|
+
"--ntasks-per-node=1",
|
|
217
|
+
"--overlap",
|
|
218
|
+
"--exact",
|
|
219
|
+
"--cpus-per-task=1",
|
|
220
|
+
"--mpi=none",
|
|
221
|
+
"--cpu-bind=none",
|
|
222
|
+
"--gpu-bind=none",
|
|
223
|
+
"--immediate=5",
|
|
224
|
+
"--kill-on-bad-exit=0",
|
|
225
|
+
"--time=1",
|
|
226
|
+
"--chdir=/",
|
|
227
|
+
"--export=NONE",
|
|
228
|
+
sys.executable,
|
|
229
|
+
"-I",
|
|
230
|
+
"-S",
|
|
231
|
+
"-c",
|
|
232
|
+
payload,
|
|
233
|
+
]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _probe(command, env):
|
|
237
|
+
"""Run one probe step and retain complete responses even after a timeout.
|
|
238
|
+
|
|
239
|
+
A launcher may have local descendants holding its pipes open. Isolate its
|
|
240
|
+
process group and bound cleanup too; never signal the enclosing job or step.
|
|
241
|
+
"""
|
|
242
|
+
process = subprocess.Popen(
|
|
243
|
+
command,
|
|
244
|
+
env=env,
|
|
245
|
+
stdin=subprocess.DEVNULL,
|
|
246
|
+
stdout=subprocess.PIPE,
|
|
247
|
+
stderr=subprocess.PIPE,
|
|
248
|
+
start_new_session=True,
|
|
249
|
+
)
|
|
250
|
+
assert process.stdout is not None and process.stderr is not None
|
|
251
|
+
stdout = stderr = b""
|
|
252
|
+
try:
|
|
253
|
+
try:
|
|
254
|
+
stdout, stderr = process.communicate(timeout=30)
|
|
255
|
+
except subprocess.TimeoutExpired as error:
|
|
256
|
+
stdout, stderr = error.output or b"", error.stderr or b""
|
|
257
|
+
print("giwon: Slurm probe timed out", file=sys.stderr)
|
|
258
|
+
try:
|
|
259
|
+
os.killpg(process.pid, signal.SIGTERM)
|
|
260
|
+
except ProcessLookupError:
|
|
261
|
+
pass
|
|
262
|
+
try:
|
|
263
|
+
stdout, stderr = process.communicate(timeout=5)
|
|
264
|
+
except subprocess.TimeoutExpired as error:
|
|
265
|
+
stdout, stderr = error.output or b"", error.stderr or b""
|
|
266
|
+
if process.returncode:
|
|
267
|
+
print(
|
|
268
|
+
f"giwon: Slurm probe exited with {process.returncode}", file=sys.stderr
|
|
269
|
+
)
|
|
270
|
+
finally:
|
|
271
|
+
try:
|
|
272
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
273
|
+
except ProcessLookupError:
|
|
274
|
+
pass
|
|
275
|
+
process.wait()
|
|
276
|
+
process.stdout.close()
|
|
277
|
+
process.stderr.close()
|
|
278
|
+
if stderr:
|
|
279
|
+
print(
|
|
280
|
+
f"giwon: Slurm probe: {stderr.decode(errors='replace').strip()}",
|
|
281
|
+
file=sys.stderr,
|
|
282
|
+
)
|
|
283
|
+
return stdout.decode(errors="replace")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _responses(output, nodes, local, env):
|
|
287
|
+
observed = []
|
|
288
|
+
seen = set()
|
|
289
|
+
local_name = env.get("SLURMD_NODENAME")
|
|
290
|
+
for line in output.splitlines():
|
|
291
|
+
try:
|
|
292
|
+
response = json.loads(line)
|
|
293
|
+
node = response["node"]
|
|
294
|
+
facts = response["hardware"]
|
|
295
|
+
if node not in nodes or not isinstance(facts, dict):
|
|
296
|
+
raise ValueError("response is outside the verified allocation")
|
|
297
|
+
if not isinstance(facts.get("hostname"), str) or not facts["hostname"]:
|
|
298
|
+
raise ValueError("response has no hostname")
|
|
299
|
+
if node in seen:
|
|
300
|
+
continue
|
|
301
|
+
seen.add(node)
|
|
302
|
+
if node == local_name or facts["hostname"] == local.get("hostname"):
|
|
303
|
+
continue
|
|
304
|
+
facts["scope"] = "allocation_probe"
|
|
305
|
+
observed.append(facts)
|
|
306
|
+
except (ValueError, TypeError, KeyError) as error:
|
|
307
|
+
print(f"giwon: invalid Slurm probe response: {error}", file=sys.stderr)
|
|
308
|
+
missing = set(nodes) - seen
|
|
309
|
+
if missing:
|
|
310
|
+
print(
|
|
311
|
+
f"giwon: no Slurm probe response from {', '.join(sorted(missing))}",
|
|
312
|
+
file=sys.stderr,
|
|
313
|
+
)
|
|
314
|
+
return observed
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def collect(
|
|
318
|
+
env: Mapping[str, str], local: dict, *, probe_nodes: bool = True
|
|
319
|
+
) -> tuple[dict | None, list]:
|
|
320
|
+
"""Collect current-job facts and additional observed nodes.
|
|
321
|
+
|
|
322
|
+
Slurm tools may be installed outside an allocation. Without a numeric runtime
|
|
323
|
+
job ID, return (None, []) without issuing commands. Otherwise retain the job
|
|
324
|
+
identity even when the controller or JSON plugin is unavailable. A probe
|
|
325
|
+
additionally requires one matching job record, current ownership, running
|
|
326
|
+
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
|
+
"""
|
|
332
|
+
value = env.get("SLURM_JOB_ID", env.get("SLURM_JOBID", ""))
|
|
333
|
+
if not re.fullmatch(r"[1-9][0-9]{0,9}", value):
|
|
334
|
+
return None, []
|
|
335
|
+
|
|
336
|
+
job_id = int(value)
|
|
337
|
+
facts = {"job_id": job_id}
|
|
338
|
+
launcher_env = _launcher_environment(env)
|
|
339
|
+
|
|
340
|
+
try:
|
|
341
|
+
output = _query(
|
|
342
|
+
["--local", "--json", "show", "job", str(job_id)],
|
|
343
|
+
launcher_env,
|
|
344
|
+
)
|
|
345
|
+
result = json.loads(output)
|
|
346
|
+
jobs = result["jobs"]
|
|
347
|
+
if (
|
|
348
|
+
not isinstance(jobs, list)
|
|
349
|
+
or len(jobs) != 1
|
|
350
|
+
or not isinstance(jobs[0], dict)
|
|
351
|
+
or _number(jobs[0].get("job_id")) != job_id
|
|
352
|
+
or result.get("errors")
|
|
353
|
+
):
|
|
354
|
+
raise ValueError("controller did not return exactly the current job")
|
|
355
|
+
|
|
356
|
+
job = jobs[0]
|
|
357
|
+
facts.update(_job_facts(job))
|
|
358
|
+
if not probe_nodes:
|
|
359
|
+
return facts, []
|
|
360
|
+
|
|
361
|
+
nodes = _allocation(job, launcher_env)
|
|
362
|
+
facts["allocated_nodes"] = nodes
|
|
363
|
+
launcher_env["SLURM_JOB_ID"] = str(job_id)
|
|
364
|
+
output = _probe(_probe_command(job_id, nodes), launcher_env)
|
|
365
|
+
return facts, _responses(output, nodes, local, env)
|
|
366
|
+
|
|
367
|
+
except (
|
|
368
|
+
OSError,
|
|
369
|
+
ValueError,
|
|
370
|
+
OverflowError,
|
|
371
|
+
TypeError,
|
|
372
|
+
KeyError,
|
|
373
|
+
subprocess.SubprocessError,
|
|
374
|
+
) as error:
|
|
375
|
+
print(f"giwon: unavailable Slurm collection: {error}", file=sys.stderr)
|
|
376
|
+
return facts, []
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
giwon/hashing.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Fingerprint files and directory trees with schema-defined XXH3-128 encoding.
|
|
2
|
+
|
|
3
|
+
Inventories stay in memory and retain every logical path, including aliases.
|
|
4
|
+
Metadata comparisons detect observed mutations, but cannot freeze a tree or
|
|
5
|
+
prove that content stayed unchanged between observations.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import stat
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import xxhash
|
|
14
|
+
|
|
15
|
+
_BLOCK_BYTES = 1_048_576
|
|
16
|
+
_READ_BYTES = 1_048_576
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SelfReferenceError(ValueError):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _identity(info):
|
|
24
|
+
return info.st_dev, info.st_ino
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _state(info):
|
|
28
|
+
return (
|
|
29
|
+
*_identity(info),
|
|
30
|
+
info.st_mode,
|
|
31
|
+
info.st_size,
|
|
32
|
+
info.st_mtime_ns,
|
|
33
|
+
info.st_ctime_ns,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _check(path, before, after):
|
|
38
|
+
if _state(before) != _state(after):
|
|
39
|
+
raise ValueError(f"path changed during hashing: {path}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def inventory(path: Path) -> tuple[list[dict], dict]:
|
|
43
|
+
"""Enumerate a logical tree and retain metadata for later mutation checks.
|
|
44
|
+
|
|
45
|
+
Symlink aliases count independently, so cycles are checked against ancestors
|
|
46
|
+
rather than a global visited set.
|
|
47
|
+
"""
|
|
48
|
+
entries = []
|
|
49
|
+
observations = {}
|
|
50
|
+
stack = [(path, "", frozenset())]
|
|
51
|
+
|
|
52
|
+
while stack:
|
|
53
|
+
current, relative, ancestors = stack.pop()
|
|
54
|
+
info = current.stat()
|
|
55
|
+
identity = _identity(info)
|
|
56
|
+
|
|
57
|
+
observations[current] = info
|
|
58
|
+
if stat.S_ISREG(info.st_mode):
|
|
59
|
+
entries.append(
|
|
60
|
+
{"path": relative, "kind": "file", "size_bytes": info.st_size}
|
|
61
|
+
)
|
|
62
|
+
elif stat.S_ISDIR(info.st_mode):
|
|
63
|
+
if identity in ancestors:
|
|
64
|
+
raise ValueError(f"directory cycle: {current}")
|
|
65
|
+
if relative:
|
|
66
|
+
entries.append({"path": relative, "kind": "directory"})
|
|
67
|
+
next_ancestors = ancestors | {identity}
|
|
68
|
+
with os.scandir(current) as children:
|
|
69
|
+
for child in children:
|
|
70
|
+
name = f"{relative}/{child.name}" if relative else child.name
|
|
71
|
+
stack.append((Path(child.path), name, next_ancestors))
|
|
72
|
+
else:
|
|
73
|
+
raise ValueError(f"unsupported filesystem object: {current}")
|
|
74
|
+
|
|
75
|
+
entries.sort(key=lambda entry: entry["path"])
|
|
76
|
+
return entries, observations
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def size(entries: list[dict]) -> int:
|
|
80
|
+
return sum(entry.get("size_bytes", 0) for entry in entries)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _ranges(total, budget):
|
|
84
|
+
if budget == 1:
|
|
85
|
+
yield 0, 1
|
|
86
|
+
return
|
|
87
|
+
|
|
88
|
+
count = max(2, (budget + _BLOCK_BYTES - 1) // _BLOCK_BYTES)
|
|
89
|
+
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)
|
|
93
|
+
yield offset, length
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _read(path, info, offset, length, hasher):
|
|
97
|
+
# TOCTOU: A regular file can be replaced by a FIFO after traversal. Nonblocking open
|
|
98
|
+
# lets fstat reject the replacement without hanging before the check.
|
|
99
|
+
descriptor = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
|
|
100
|
+
with os.fdopen(descriptor, "rb", buffering=0) as stream:
|
|
101
|
+
_check(path, info, os.fstat(stream.fileno()))
|
|
102
|
+
stream.seek(offset)
|
|
103
|
+
while length:
|
|
104
|
+
data = stream.read(min(length, _READ_BYTES))
|
|
105
|
+
if not data:
|
|
106
|
+
raise ValueError(f"file shortened during hashing: {path}")
|
|
107
|
+
hasher.update(data)
|
|
108
|
+
length -= len(data)
|
|
109
|
+
_check(path, info, os.fstat(stream.fileno()))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _scalar(hasher):
|
|
113
|
+
return f"xxh3-128:{hasher.hexdigest()}"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _encoded(value):
|
|
117
|
+
return json.dumps(
|
|
118
|
+
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
|
|
119
|
+
).encode("utf-8")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def fingerprint(
|
|
123
|
+
path: Path, *, sample_bytes: int | None = None, forbidden: Path | None = None
|
|
124
|
+
) -> str:
|
|
125
|
+
"""Return a fresh scalar hash, sampling only when a supplied budget is exceeded.
|
|
126
|
+
|
|
127
|
+
Input callers forbid the generated run directory, including inputs inside it.
|
|
128
|
+
Output callers forbid the snapshot itself. With no budget, outputs always
|
|
129
|
+
receive complete coverage using the same encoding as complete inputs.
|
|
130
|
+
"""
|
|
131
|
+
return fingerprint_inventory(
|
|
132
|
+
path, *inventory(path), sample_bytes=sample_bytes, forbidden=forbidden
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def fingerprint_inventory(
|
|
137
|
+
path: Path,
|
|
138
|
+
entries: list[dict],
|
|
139
|
+
observations: dict,
|
|
140
|
+
*,
|
|
141
|
+
sample_bytes: int | None = None,
|
|
142
|
+
forbidden: Path | None = None,
|
|
143
|
+
) -> str:
|
|
144
|
+
"""Hash an existing inventory and verify its observed metadata after reading.
|
|
145
|
+
|
|
146
|
+
Output inspection needs size even when hashing fails. Accept its inventory
|
|
147
|
+
so both observations describe the same tree without enumerating it again.
|
|
148
|
+
Complete hashing adds file hashes to the supplied inventory entries.
|
|
149
|
+
"""
|
|
150
|
+
if sample_bytes is not None and sample_bytes <= 0:
|
|
151
|
+
raise ValueError("sample_bytes must be positive")
|
|
152
|
+
|
|
153
|
+
if forbidden is not None:
|
|
154
|
+
blocked = forbidden.resolve(strict=True)
|
|
155
|
+
blocked_info = blocked.stat()
|
|
156
|
+
for current, info in observations.items():
|
|
157
|
+
is_relative_to = current.resolve(strict=True).is_relative_to(blocked)
|
|
158
|
+
is_blocked = _identity(info) == _identity(blocked_info)
|
|
159
|
+
if is_relative_to or is_blocked:
|
|
160
|
+
raise SelfReferenceError(f"self-referential path: {current}")
|
|
161
|
+
|
|
162
|
+
directory = stat.S_ISDIR(observations[path].st_mode)
|
|
163
|
+
files = [entry for entry in entries if entry["kind"] == "file"]
|
|
164
|
+
total = sum(entry["size_bytes"] for entry in files)
|
|
165
|
+
hasher = xxhash.xxh3_128(seed=0)
|
|
166
|
+
|
|
167
|
+
if sample_bytes is None or total <= sample_bytes:
|
|
168
|
+
for entry in files:
|
|
169
|
+
current = path / entry["path"] if directory else path
|
|
170
|
+
content = xxhash.xxh3_128(seed=0)
|
|
171
|
+
_read(current, observations[current], 0, entry["size_bytes"], content)
|
|
172
|
+
entry["hash"] = _scalar(content)
|
|
173
|
+
if directory:
|
|
174
|
+
hasher.update(b"giwon-directory-v1\0")
|
|
175
|
+
hasher.update(_encoded(entries))
|
|
176
|
+
result = _scalar(hasher)
|
|
177
|
+
else:
|
|
178
|
+
result = files[0]["hash"]
|
|
179
|
+
else:
|
|
180
|
+
# Blockwise hashing if file size exceeds configured threshold
|
|
181
|
+
blocks = []
|
|
182
|
+
index = 0
|
|
183
|
+
start = 0
|
|
184
|
+
for offset, length in _ranges(total, sample_bytes):
|
|
185
|
+
content = xxhash.xxh3_128(seed=0)
|
|
186
|
+
position = offset
|
|
187
|
+
remaining = length
|
|
188
|
+
while remaining:
|
|
189
|
+
entry = files[index]
|
|
190
|
+
end = start + entry["size_bytes"]
|
|
191
|
+
if position >= end:
|
|
192
|
+
index += 1
|
|
193
|
+
start = end
|
|
194
|
+
continue
|
|
195
|
+
current = path / entry["path"] if directory else path
|
|
196
|
+
count = min(remaining, end - position)
|
|
197
|
+
_read(current, observations[current], position - start, count, content)
|
|
198
|
+
position += count
|
|
199
|
+
remaining -= count
|
|
200
|
+
blocks.append(
|
|
201
|
+
{"offset": offset, "length": length, "hash": _scalar(content)}
|
|
202
|
+
)
|
|
203
|
+
hash_info = {
|
|
204
|
+
"format": "giwon-sampled-v1",
|
|
205
|
+
"root_kind": "directory" if directory else "file",
|
|
206
|
+
"sample_bytes": sample_bytes,
|
|
207
|
+
"entries": entries,
|
|
208
|
+
"blocks": blocks,
|
|
209
|
+
}
|
|
210
|
+
hasher.update(_encoded(hash_info))
|
|
211
|
+
result = f"sampled-{_scalar(hasher)}"
|
|
212
|
+
|
|
213
|
+
for current, info in observations.items():
|
|
214
|
+
_check(current, info, current.stat())
|
|
215
|
+
|
|
216
|
+
return result
|
giwon/record.yaml
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Canonical field order for execution records, not defaults or a validation schema.
|
|
2
|
+
# Null values are placeholders. Missing fields are never inserted; unknown fields
|
|
3
|
+
# follow known fields. The first list item guides every item's mapping order.
|
|
4
|
+
giwon:
|
|
5
|
+
version: null
|
|
6
|
+
python_version: null
|
|
7
|
+
settings:
|
|
8
|
+
config: null
|
|
9
|
+
max_patch_bytes: null
|
|
10
|
+
patch_context: null
|
|
11
|
+
sample_bytes: null
|
|
12
|
+
hash_outputs: null
|
|
13
|
+
slurm_probes: null
|
|
14
|
+
purpose: null
|
|
15
|
+
invocation:
|
|
16
|
+
argv: []
|
|
17
|
+
working_directory: null
|
|
18
|
+
git:
|
|
19
|
+
root: null
|
|
20
|
+
commit: null
|
|
21
|
+
remotes:
|
|
22
|
+
- name: null
|
|
23
|
+
fetch_urls: []
|
|
24
|
+
push_urls: []
|
|
25
|
+
patch: null
|
|
26
|
+
untracked_files: []
|
|
27
|
+
submodules:
|
|
28
|
+
- path: null
|
|
29
|
+
reference: null
|
|
30
|
+
commit: null
|
|
31
|
+
patch: null
|
|
32
|
+
untracked_files: []
|
|
33
|
+
submodules: []
|
|
34
|
+
inputs: []
|
|
35
|
+
image:
|
|
36
|
+
reference: null
|
|
37
|
+
hash: null
|
|
38
|
+
local:
|
|
39
|
+
id: null
|
|
40
|
+
repo_digests: []
|
|
41
|
+
registry:
|
|
42
|
+
reference: null
|
|
43
|
+
environment:
|
|
44
|
+
os: null
|
|
45
|
+
release: null
|
|
46
|
+
architecture: null
|
|
47
|
+
executable: null
|
|
48
|
+
variables_file: null
|
|
49
|
+
hardware:
|
|
50
|
+
nodes:
|
|
51
|
+
- hostname: null
|
|
52
|
+
scope: null
|
|
53
|
+
memory_bytes: null
|
|
54
|
+
cpus: []
|
|
55
|
+
cpu_affinity: []
|
|
56
|
+
gpus:
|
|
57
|
+
- uuid: null
|
|
58
|
+
model: null
|
|
59
|
+
memory_bytes: null
|
|
60
|
+
driver_version: null
|
|
61
|
+
pci_bus_id: null
|
|
62
|
+
mig_mode: null
|
|
63
|
+
partitions:
|
|
64
|
+
- kind: null
|
|
65
|
+
gpu_instance_id: null
|
|
66
|
+
compute_instance_id: null
|
|
67
|
+
memory_bytes: null
|
|
68
|
+
slurm:
|
|
69
|
+
cluster: null
|
|
70
|
+
job_id: null
|
|
71
|
+
array_job_id: null
|
|
72
|
+
array_task_id: null
|
|
73
|
+
allocated_nodes: []
|
|
74
|
+
execution:
|
|
75
|
+
run_id: null
|
|
76
|
+
directory: null
|
|
77
|
+
created_at: null
|
|
78
|
+
status: null
|
|
79
|
+
launched_at: null
|
|
80
|
+
ended_at: null
|
|
81
|
+
exit_code: null
|
|
82
|
+
pid: null
|
|
83
|
+
outputs:
|
|
84
|
+
# A registration uses either path or url; both appear here only to define order.
|
|
85
|
+
- path: null
|
|
86
|
+
url: null
|
|
87
|
+
exists: null
|
|
88
|
+
size_bytes: null
|
|
89
|
+
hash: null
|