agent-bios 0.19.4 → 0.20.1
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/DEPENDENCIES.md +20 -5
- package/README.md +14 -19
- package/claude/agents/frontier.md +1 -1
- package/claude/guides/claude-prompting.md +475 -234
- package/claude/guides/cli-multi-model-workflow.md +8 -7
- package/claude/guides/gpt-prompting.md +319 -144
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/agents/frontier.toml +1 -1
- package/codex/agents/reviewer.toml +1 -1
- package/codex/agents/workhorse.toml +1 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +8 -7
- package/codex/guides/gpt-prompting.md +319 -144
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/docs/advanced-launch.md +5 -1
- package/docs/releases/0.20.0.md +102 -0
- package/docs/releases/0.20.1.md +76 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +28 -16
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +36 -3
- package/provenance.json +1 -1
- package/session-cost.py +80 -9
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7940 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +46 -15
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Locks and confinement for the driver's writers.
|
|
3
|
+
|
|
4
|
+
One run directory has one declaration (`run.json`, `amendments.jsonl`) and one record per
|
|
5
|
+
stage. A second process writing the same thing would interleave a read-modify-write, so
|
|
6
|
+
every writer holds the lock named for what it writes: `declaration`, or `stage-<id>`.
|
|
7
|
+
|
|
8
|
+
The lock is an `flock` on a file under `<run-dir>/locks/`. It belongs to the open file, so
|
|
9
|
+
the operating system drops it when the holder exits, however it exits; no lock file is ever
|
|
10
|
+
stale, and none is deleted.
|
|
11
|
+
|
|
12
|
+
Every write the driver makes inside a run directory — the lock files, `run.json`,
|
|
13
|
+
`amendments.jsonl`, the stage records — first passes `confine`: the destination is resolved
|
|
14
|
+
with every symlink in it followed (a dangling final link and symlinked parent directories
|
|
15
|
+
included) and must lie beneath the resolved run directory, or the write is refused by name
|
|
16
|
+
(RUN_PATH_ESCAPE) before anything is created or opened. `confine` judges the path the caller
|
|
17
|
+
is about to open, spelled as the caller spells it — absolute, or relative to the working
|
|
18
|
+
directory exactly as `run_dir` is — so a relative run directory and its absolute spelling
|
|
19
|
+
are one place.
|
|
20
|
+
|
|
21
|
+
stagelock.py --self-test
|
|
22
|
+
"""
|
|
23
|
+
import contextlib
|
|
24
|
+
import fcntl
|
|
25
|
+
import os
|
|
26
|
+
import pathlib
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
RETRY_S = 0.005 # between attempts of a waiting writer
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Locked(Exception):
|
|
35
|
+
"""The lock is held by another writer; the message starts with STAGE_LOCKED."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Escaped(Exception):
|
|
39
|
+
"""A destination resolves outside the run directory; the message starts with RUN_PATH_ESCAPE."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def contained(run_dir, name):
|
|
43
|
+
"""`name`, an artifact or run id spelled relative to `run_dir` (or absolute), resolved with
|
|
44
|
+
every symlink followed, when it lies strictly beneath the resolved `run_dir`; else None."""
|
|
45
|
+
root = pathlib.Path(run_dir).resolve()
|
|
46
|
+
resolved = (root / name).resolve()
|
|
47
|
+
return resolved if root in resolved.parents else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def confine(run_dir, destination):
|
|
51
|
+
"""`destination` — the path the caller is about to open, absolute or relative to the working
|
|
52
|
+
directory like `run_dir` — resolved with every symlink followed; `Escaped` by name unless it
|
|
53
|
+
lies strictly beneath the resolved `run_dir`. Every metadata and lock write goes through
|
|
54
|
+
here, and opens the path this returns."""
|
|
55
|
+
root = pathlib.Path(run_dir).resolve()
|
|
56
|
+
resolved = pathlib.Path(destination).resolve()
|
|
57
|
+
if root not in resolved.parents:
|
|
58
|
+
raise Escaped(f"RUN_PATH_ESCAPE {destination}: resolves to {resolved}, outside the run directory {root}")
|
|
59
|
+
return resolved
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _directory(piece, parent, destination):
|
|
63
|
+
"""One directory of the run, opened beneath `parent` without following a link, made when absent."""
|
|
64
|
+
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
65
|
+
try:
|
|
66
|
+
try:
|
|
67
|
+
return os.open(piece, flags, dir_fd=parent)
|
|
68
|
+
except FileNotFoundError:
|
|
69
|
+
try:
|
|
70
|
+
os.mkdir(piece, dir_fd=parent)
|
|
71
|
+
except FileExistsError:
|
|
72
|
+
pass
|
|
73
|
+
return os.open(piece, flags, dir_fd=parent)
|
|
74
|
+
except OSError as exc:
|
|
75
|
+
raise Escaped(f"RUN_PATH_ESCAPE {destination}: {piece!r} is not a directory of the run to open "
|
|
76
|
+
f"({exc.strerror}); a link put there after the path was confined is not followed") from exc
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# The run directories a stage is running in, by the path the stage was GIVEN: `{absolute path: [(device, inode),
|
|
80
|
+
# holders]}`. `beneath` resolves its run directory anew on every write, so a run directory replaced by a link
|
|
81
|
+
# after a stage was admitted resolved into whatever the link named, and the stage's later records - its failure
|
|
82
|
+
# record among them - were written there (the S12 review, round 2). While a stage holds the pin, the directory a
|
|
83
|
+
# write is anchored in must be the one the stage was admitted in.
|
|
84
|
+
PINNED = {}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@contextlib.contextmanager
|
|
88
|
+
def pinned(run_dir):
|
|
89
|
+
"""Hold `run_dir`'s identity for as long as the caller runs; `beneath` refuses a root that is another one."""
|
|
90
|
+
key = os.path.abspath(run_dir)
|
|
91
|
+
root = pathlib.Path(run_dir).resolve()
|
|
92
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
93
|
+
held = os.stat(root)
|
|
94
|
+
entry = PINNED.setdefault(key, [(held.st_dev, held.st_ino), 0])
|
|
95
|
+
entry[1] += 1
|
|
96
|
+
try:
|
|
97
|
+
yield
|
|
98
|
+
finally:
|
|
99
|
+
entry[1] -= 1
|
|
100
|
+
if entry[1] <= 0:
|
|
101
|
+
PINNED.pop(key, None)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@contextlib.contextmanager
|
|
105
|
+
def beneath(run_dir, destination):
|
|
106
|
+
"""`(parent descriptor, leaf name)` of `destination`, reached from the run directory's own descriptor.
|
|
107
|
+
|
|
108
|
+
`confine` answers where a path resolves NOW; a write that then opened that path by name would follow whatever a
|
|
109
|
+
directory on the way had been swapped for in between, and create or replace a file outside the run (the S11
|
|
110
|
+
review, 2026-11-13). So the directories between the run directory and the leaf are opened one component at a time,
|
|
111
|
+
each beneath the last and none through a link, and the caller creates, renames and unlinks the leaf relative to
|
|
112
|
+
the descriptor this yields. Missing directories are made."""
|
|
113
|
+
target = confine(run_dir, destination)
|
|
114
|
+
root = pathlib.Path(run_dir).resolve()
|
|
115
|
+
pieces = target.relative_to(root).parts
|
|
116
|
+
root.mkdir(parents=True, exist_ok=True) # the run directory itself is the anchor, made as it always was
|
|
117
|
+
# ... and opened WITHOUT following a link: `root` is resolved, so a link there now was put there since, and
|
|
118
|
+
# following it would anchor every write below in whatever it names (the S11 review, round 2).
|
|
119
|
+
try:
|
|
120
|
+
fds = [os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)]
|
|
121
|
+
except OSError as exc:
|
|
122
|
+
raise Escaped(f"RUN_PATH_ESCAPE {destination}: the run directory {root} is not a directory to open "
|
|
123
|
+
f"({exc.strerror}); a link put there after it was resolved is not followed") from exc
|
|
124
|
+
try:
|
|
125
|
+
admitted = PINNED.get(os.path.abspath(run_dir))
|
|
126
|
+
anchor = os.fstat(fds[0])
|
|
127
|
+
if admitted is not None and (anchor.st_dev, anchor.st_ino) != admitted[0]:
|
|
128
|
+
raise Escaped(f"RUN_PATH_ESCAPE {destination}: the run directory is not the one this stage was admitted "
|
|
129
|
+
f"in; it was replaced while the stage ran, and nothing is written in its place")
|
|
130
|
+
for piece in pieces[:-1]:
|
|
131
|
+
fds.append(_directory(piece, fds[-1], destination))
|
|
132
|
+
yield fds[-1], pieces[-1]
|
|
133
|
+
finally:
|
|
134
|
+
for held in fds:
|
|
135
|
+
try:
|
|
136
|
+
os.close(held)
|
|
137
|
+
except OSError:
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# Set to a callable by a test only, and called with the lock's name the first time an acquisition finds
|
|
142
|
+
# that lock held - the real contention, inside the real attempt. A control that needs to act at that
|
|
143
|
+
# instant (dispatch's stop against an amendment holding the declaration) has no other way to know the
|
|
144
|
+
# attempt has happened rather than being about to: a signal from the caller leaves a schedule in which
|
|
145
|
+
# the holder finishes first. None in production, where nothing reads it.
|
|
146
|
+
CONTENDED = None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@contextlib.contextmanager
|
|
150
|
+
def hold(run_dir, name, wait_s=0):
|
|
151
|
+
"""Hold the lock `name`; a held lock is refused at once, or after `wait_s` seconds of
|
|
152
|
+
retrying (the dispatch supervisor's reservations and breaker wait their turn)."""
|
|
153
|
+
path = confine(run_dir, pathlib.Path(run_dir) / "locks" / f"{name}.lock")
|
|
154
|
+
with beneath(run_dir, path) as (parent, leaf):
|
|
155
|
+
try:
|
|
156
|
+
fd = os.open(leaf, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
|
157
|
+
except OSError as exc:
|
|
158
|
+
raise Escaped(f"RUN_PATH_ESCAPE {path}: the lock file could not be opened beneath the run "
|
|
159
|
+
f"({exc.strerror})") from exc
|
|
160
|
+
contended = False
|
|
161
|
+
try:
|
|
162
|
+
for _attempt in range(int(wait_s / RETRY_S) + 1):
|
|
163
|
+
try:
|
|
164
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
165
|
+
break
|
|
166
|
+
except BlockingIOError:
|
|
167
|
+
if not contended:
|
|
168
|
+
contended = True
|
|
169
|
+
if CONTENDED is not None:
|
|
170
|
+
CONTENDED(name)
|
|
171
|
+
if wait_s:
|
|
172
|
+
time.sleep(RETRY_S)
|
|
173
|
+
else:
|
|
174
|
+
raise Locked(f"STAGE_LOCKED {name}: another writer holds {path}")
|
|
175
|
+
yield
|
|
176
|
+
finally:
|
|
177
|
+
os.close(fd) # closing the descriptor releases the lock
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def self_test():
|
|
181
|
+
import tempfile
|
|
182
|
+
failures = []
|
|
183
|
+
with tempfile.TemporaryDirectory() as td:
|
|
184
|
+
# positive control first: a free lock is taken, and is free again after release
|
|
185
|
+
with hold(td, "declaration"):
|
|
186
|
+
pass
|
|
187
|
+
with hold(td, "declaration"):
|
|
188
|
+
pass
|
|
189
|
+
# the contention hook fires inside the real attempt, with the lock's name, and only when the lock
|
|
190
|
+
# was actually held by someone else (a test's only way to act at that instant)
|
|
191
|
+
seen = []
|
|
192
|
+
globals()["CONTENDED"] = seen.append
|
|
193
|
+
try:
|
|
194
|
+
with hold(td, "declaration"):
|
|
195
|
+
try:
|
|
196
|
+
with hold(td, "declaration"):
|
|
197
|
+
failures.append("a held lock was taken twice")
|
|
198
|
+
except Locked:
|
|
199
|
+
pass
|
|
200
|
+
if seen != ["declaration"]:
|
|
201
|
+
failures.append(f"the contention hook did not fire once with the lock's name: {seen}")
|
|
202
|
+
with hold(td, "other-name"): # a free lock is no contention
|
|
203
|
+
pass
|
|
204
|
+
if seen != ["declaration"]:
|
|
205
|
+
failures.append(f"the contention hook fired for a free lock: {seen}")
|
|
206
|
+
finally:
|
|
207
|
+
globals()["CONTENDED"] = None
|
|
208
|
+
# the walk beneath the run's own descriptor: `confine` is made to answer as it would have BEFORE a directory
|
|
209
|
+
# on the way was swapped for a link, and the write must still not leave the run
|
|
210
|
+
import shutil
|
|
211
|
+
outside = pathlib.Path(tempfile.mkdtemp())
|
|
212
|
+
try:
|
|
213
|
+
run = pathlib.Path(td) / "swap"
|
|
214
|
+
run.mkdir()
|
|
215
|
+
os.symlink(outside, run / "locks")
|
|
216
|
+
real = confine
|
|
217
|
+
|
|
218
|
+
def before_the_swap(run_dir, destination):
|
|
219
|
+
root, held = pathlib.Path(run_dir).resolve(), pathlib.Path(destination)
|
|
220
|
+
return root / (held.relative_to(root) if root in held.parents else held.relative_to(run_dir))
|
|
221
|
+
globals()["confine"] = before_the_swap
|
|
222
|
+
try:
|
|
223
|
+
try:
|
|
224
|
+
with hold(run, "swapped"):
|
|
225
|
+
failures.append("a lock was taken through a directory swapped for a link")
|
|
226
|
+
except Escaped as exc:
|
|
227
|
+
if "RUN_PATH_ESCAPE" not in str(exc):
|
|
228
|
+
failures.append(f"the swapped directory was refused under another name: {exc}")
|
|
229
|
+
finally:
|
|
230
|
+
globals()["confine"] = real
|
|
231
|
+
if list(outside.iterdir()):
|
|
232
|
+
failures.append(f"a lock file was made outside the run: {sorted(p.name for p in outside.iterdir())}")
|
|
233
|
+
# the run directory replaced by a link WHILE a stage holds it: resolved anew, the link's target would
|
|
234
|
+
# be the new root, so the root is held to the one the stage was admitted in
|
|
235
|
+
moved = pathlib.Path(td).resolve() / "moved-run"
|
|
236
|
+
moved.mkdir()
|
|
237
|
+
elsewhere = pathlib.Path(tempfile.mkdtemp())
|
|
238
|
+
try:
|
|
239
|
+
with pinned(moved):
|
|
240
|
+
os.rename(moved, str(moved) + ".was")
|
|
241
|
+
os.symlink(elsewhere, moved)
|
|
242
|
+
try:
|
|
243
|
+
with beneath(moved, moved / "stages" / "record.json") as (_parent, _leaf):
|
|
244
|
+
failures.append("a run directory replaced while its stage ran was written in")
|
|
245
|
+
except Escaped as exc:
|
|
246
|
+
if "not the one this stage was admitted in" not in str(exc):
|
|
247
|
+
failures.append(f"the replaced run directory was refused for another reason: {exc}")
|
|
248
|
+
if list(elsewhere.iterdir()):
|
|
249
|
+
failures.append(f"a record was made where the link pointed: {sorted(p.name for p in elsewhere.iterdir())}")
|
|
250
|
+
if PINNED:
|
|
251
|
+
failures.append(f"a pin outlived its holder: {sorted(PINNED)}")
|
|
252
|
+
finally:
|
|
253
|
+
shutil.rmtree(elsewhere, ignore_errors=True)
|
|
254
|
+
# the run directory ITSELF swapped for a link after it was resolved
|
|
255
|
+
anchor = pathlib.Path(td).resolve() / "anchor"
|
|
256
|
+
os.symlink(outside, anchor)
|
|
257
|
+
real_resolve = pathlib.Path.resolve
|
|
258
|
+
pathlib.Path.resolve = lambda self, *a, **k: self # as it resolved before the swap
|
|
259
|
+
try:
|
|
260
|
+
try:
|
|
261
|
+
with beneath(anchor, anchor / "x.json") as (_parent, _leaf):
|
|
262
|
+
failures.append("a run directory swapped for a link was opened")
|
|
263
|
+
except Escaped as exc:
|
|
264
|
+
if "RUN_PATH_ESCAPE" not in str(exc):
|
|
265
|
+
failures.append(f"the swapped run directory was refused under another name: {exc}")
|
|
266
|
+
finally:
|
|
267
|
+
pathlib.Path.resolve = real_resolve
|
|
268
|
+
finally:
|
|
269
|
+
shutil.rmtree(outside, ignore_errors=True)
|
|
270
|
+
if CONTENDED is not None:
|
|
271
|
+
failures.append("the contention hook is left set, so production would call it")
|
|
272
|
+
|
|
273
|
+
# a held lock refuses a second writer by name, and only that name
|
|
274
|
+
with hold(td, "declaration"):
|
|
275
|
+
try:
|
|
276
|
+
with hold(td, "declaration"):
|
|
277
|
+
failures.append("a second writer took a held lock")
|
|
278
|
+
except Locked as exc:
|
|
279
|
+
if "STAGE_LOCKED declaration" not in str(exc):
|
|
280
|
+
failures.append(f"refusal does not carry its name: {exc}")
|
|
281
|
+
with hold(td, "stage-S1"):
|
|
282
|
+
pass
|
|
283
|
+
# an exception inside the block releases the lock
|
|
284
|
+
try:
|
|
285
|
+
with hold(td, "stage-S1"):
|
|
286
|
+
raise RuntimeError("stage failed")
|
|
287
|
+
except RuntimeError:
|
|
288
|
+
pass
|
|
289
|
+
with hold(td, "stage-S1"):
|
|
290
|
+
pass
|
|
291
|
+
if not (pathlib.Path(td) / "locks" / "declaration.lock").is_file():
|
|
292
|
+
failures.append("lock file is not kept under <run-dir>/locks/")
|
|
293
|
+
# a waiting writer takes the lock once the holder releases it, and gives up by name at its deadline
|
|
294
|
+
import threading
|
|
295
|
+
held, release = threading.Event(), threading.Event()
|
|
296
|
+
|
|
297
|
+
def holder():
|
|
298
|
+
with hold(td, "supervisor"):
|
|
299
|
+
held.set()
|
|
300
|
+
release.wait(5)
|
|
301
|
+
thread = threading.Thread(target=holder)
|
|
302
|
+
thread.start()
|
|
303
|
+
held.wait(5)
|
|
304
|
+
try:
|
|
305
|
+
with hold(td, "supervisor", wait_s=0.05):
|
|
306
|
+
failures.append("a waiting writer took a held lock before its holder released it")
|
|
307
|
+
except Locked as exc:
|
|
308
|
+
if "STAGE_LOCKED supervisor" not in str(exc):
|
|
309
|
+
failures.append(f"a timed-out wait was refused unnamed: {exc}")
|
|
310
|
+
threading.Timer(0.1, release.set).start()
|
|
311
|
+
try:
|
|
312
|
+
with hold(td, "supervisor", wait_s=5):
|
|
313
|
+
pass
|
|
314
|
+
except Locked:
|
|
315
|
+
failures.append("a waiting writer did not take the lock its holder released")
|
|
316
|
+
thread.join(5)
|
|
317
|
+
|
|
318
|
+
# confinement: a clean destination first, then each way a symlink can lead out of the run directory
|
|
319
|
+
with tempfile.TemporaryDirectory() as td:
|
|
320
|
+
run_dir, outside = pathlib.Path(td) / "run", pathlib.Path(td) / "outside"
|
|
321
|
+
(run_dir / "sub").mkdir(parents=True)
|
|
322
|
+
outside.mkdir()
|
|
323
|
+
(outside / "file").write_text("outside\n", encoding="utf-8")
|
|
324
|
+
(run_dir / "sub" / "inner").mkdir()
|
|
325
|
+
(run_dir / "link-inside").symlink_to(run_dir / "sub" / "inner")
|
|
326
|
+
(run_dir / "link-dangling").symlink_to(outside / "not-yet")
|
|
327
|
+
(run_dir / "link-file").symlink_to(outside / "file")
|
|
328
|
+
(run_dir / "link-dir").symlink_to(outside)
|
|
329
|
+
cases = [("a clean destination", "sub/new.json", True), ("a destination that does not exist yet", "a/b/c.json", True),
|
|
330
|
+
("a symlink that stays inside", "link-inside/new.json", True),
|
|
331
|
+
("a dangling symlink to a place outside", "link-dangling", False),
|
|
332
|
+
("a symlink to an existing file outside", "link-file", False),
|
|
333
|
+
("a symlinked parent directory", "link-dir/new.json", False),
|
|
334
|
+
("parent traversal", "../outside/new.json", False),
|
|
335
|
+
("an absolute path outside", str(outside / "new.json"), False),
|
|
336
|
+
("the run directory itself", ".", False)]
|
|
337
|
+
for label, destination, allowed in cases:
|
|
338
|
+
destination = run_dir / destination # an absolute destination stays itself
|
|
339
|
+
try:
|
|
340
|
+
got = confine(run_dir, destination)
|
|
341
|
+
if not allowed:
|
|
342
|
+
failures.append(f"{label}: {destination} was confined to {got}")
|
|
343
|
+
except Escaped as exc:
|
|
344
|
+
if allowed or "RUN_PATH_ESCAPE" not in str(exc) or str(destination) not in str(exc):
|
|
345
|
+
failures.append(f"{label}: refused wrongly or unnamed: {exc}")
|
|
346
|
+
if sorted(p.name for p in outside.iterdir()) != ["file"] or (outside / "file").read_text() != "outside\n":
|
|
347
|
+
failures.append("confine created or changed something outside the run directory")
|
|
348
|
+
(run_dir / "locks").symlink_to(outside)
|
|
349
|
+
try:
|
|
350
|
+
with hold(run_dir, "declaration"):
|
|
351
|
+
failures.append("a lock was taken through a symlinked locks directory")
|
|
352
|
+
except Escaped as exc:
|
|
353
|
+
if "RUN_PATH_ESCAPE" not in str(exc):
|
|
354
|
+
failures.append(f"symlinked locks directory refused unnamed: {exc}")
|
|
355
|
+
if sorted(p.name for p in outside.iterdir()) != ["file"]:
|
|
356
|
+
failures.append("a lock file was created through a symlinked locks directory")
|
|
357
|
+
|
|
358
|
+
# a relative run directory: the destination is judged where it is opened, never joined under the run
|
|
359
|
+
# directory a second time, and the relative and absolute spellings of one run directory are one place
|
|
360
|
+
with tempfile.TemporaryDirectory() as td:
|
|
361
|
+
here = os.getcwd()
|
|
362
|
+
os.chdir(td)
|
|
363
|
+
try:
|
|
364
|
+
root = pathlib.Path(os.getcwd()).resolve() # the resolved spelling of the scratch directory
|
|
365
|
+
pathlib.Path("run/sub").mkdir(parents=True)
|
|
366
|
+
pathlib.Path("elsewhere").mkdir()
|
|
367
|
+
got = confine("run", "run/sub/new.json")
|
|
368
|
+
if got != root / "run" / "sub" / "new.json":
|
|
369
|
+
failures.append(f"a relative destination under a relative run directory resolved to {got}")
|
|
370
|
+
for label, destination in (("a relative destination beside the run directory", "elsewhere/new.json"),
|
|
371
|
+
("a relative destination reaching out of the run directory", "run/../elsewhere/new.json"),
|
|
372
|
+
("the relative run directory itself", "run")):
|
|
373
|
+
try:
|
|
374
|
+
confine("run", destination)
|
|
375
|
+
failures.append(f"{label}: {destination} was confined")
|
|
376
|
+
except Escaped as exc:
|
|
377
|
+
if "RUN_PATH_ESCAPE" not in str(exc):
|
|
378
|
+
failures.append(f"{label}: refused unnamed: {exc}")
|
|
379
|
+
with hold("run", "declaration"):
|
|
380
|
+
pass
|
|
381
|
+
if not (root / "run" / "locks" / "declaration.lock").is_file() or (root / "run" / "run").exists():
|
|
382
|
+
failures.append("a relative run directory did not keep its lock file at run/locks/declaration.lock")
|
|
383
|
+
absolute = os.path.join(td, "run") # td may be a symlinked spelling of the same place
|
|
384
|
+
for first, second in (("run", absolute), (absolute, "run")):
|
|
385
|
+
with hold(first, "declaration"):
|
|
386
|
+
try:
|
|
387
|
+
with hold(second, "declaration"):
|
|
388
|
+
failures.append(f"{first!r} and {second!r} spell one run directory but did not contend for its lock")
|
|
389
|
+
except Locked as exc:
|
|
390
|
+
if "STAGE_LOCKED declaration" not in str(exc):
|
|
391
|
+
failures.append(f"contention between {first!r} and {second!r} was refused unnamed: {exc}")
|
|
392
|
+
if sorted(str(path.relative_to(root)) for path in root.rglob("*")) != [
|
|
393
|
+
"elsewhere", "run", "run/locks", "run/locks/declaration.lock", "run/sub"]:
|
|
394
|
+
failures.append("relative spellings created something besides run/locks/declaration.lock")
|
|
395
|
+
finally:
|
|
396
|
+
os.chdir(here)
|
|
397
|
+
for failure in failures:
|
|
398
|
+
print(f"stagelock --self-test [FAIL] {failure}")
|
|
399
|
+
if failures:
|
|
400
|
+
return 1
|
|
401
|
+
print("stagelock --self-test: OK (free lock taken, held lock refused by name, other names "
|
|
402
|
+
"independent, released after an exception, a waiting writer served after release and refused at its "
|
|
403
|
+
"deadline; confinement: clean and inside-symlink destinations "
|
|
404
|
+
"allowed, dangling link, linked file, linked parent, traversal and absolute escapes refused by name; "
|
|
405
|
+
"a relative run directory is one place with its absolute spelling)")
|
|
406
|
+
return 0
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
if __name__ == "__main__":
|
|
410
|
+
if "--self-test" not in sys.argv[1:]:
|
|
411
|
+
sys.exit("usage: stagelock.py --self-test")
|
|
412
|
+
sys.exit(self_test())
|