agent-bios 0.19.4 → 0.20.0
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 +19 -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 +4 -3
- package/claude/guides/gpt-prompting.md +235 -136
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +4 -3
- package/codex/guides/gpt-prompting.md +235 -136
- 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 +4 -0
- package/docs/releases/0.20.0.md +102 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +17 -7
- 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 +7939 -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 +38 -7
- 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,1965 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""What a run directory holds, and the rules stages keep over it.
|
|
3
|
+
|
|
4
|
+
`run.json` is the declaration (S0). It changes only through an amendment, which appends one
|
|
5
|
+
line to `amendments.jsonl` and advances `declaration_seq`. That log also binds every
|
|
6
|
+
`declaration_seq` to the sha256 of the run.json authorized at it (seq 0 is the declaration
|
|
7
|
+
itself), so a `run.json` edited by hand is found by comparing it with the log, whether or not
|
|
8
|
+
a stage has read it yet. Every stage S1-S12 leaves
|
|
9
|
+
`stages/<stage>/record.json` pinning the declaration it read (hash and sequence), the inputs
|
|
10
|
+
it consumed with the stage and sequence that produced each, and its outputs with their
|
|
11
|
+
hashes. A stage refuses to start when an input is partial, stale or invalid, or when the
|
|
12
|
+
declaration it would read is not the one its inputs were produced under, unless an amendment
|
|
13
|
+
licenses the difference (design §4, §4.1).
|
|
14
|
+
|
|
15
|
+
A stage's items fail under the run's posture (design §4): in production a failing item is
|
|
16
|
+
quarantined with the items sharing its unit, route or test configuration and the others
|
|
17
|
+
continue; in development and rehearsal the first failure stops the stage by name. An input
|
|
18
|
+
that is partial, stale or invalid is refused whatever the posture.
|
|
19
|
+
|
|
20
|
+
Failures are named by their first word: DECLARATION_DRIFT, INPUT_STALE, INPUT_PARTIAL,
|
|
21
|
+
INPUT_INVALID, OUTPUT_OUTSIDE_RUN, RUN_PATH_ESCAPE (`stagelock.confine`: no write leaves the run
|
|
22
|
+
directory, through a symlink or otherwise), ITEM_FAILED, ITEMS_JOBS_INVALID, SET_MISMATCH. Predicates return their
|
|
23
|
+
violations as a list; the ones that guard starting a stage or running its items raise `Refused`.
|
|
24
|
+
|
|
25
|
+
records.py --self-test
|
|
26
|
+
"""
|
|
27
|
+
import concurrent.futures
|
|
28
|
+
import contextlib
|
|
29
|
+
import copy
|
|
30
|
+
import datetime
|
|
31
|
+
import hashlib
|
|
32
|
+
import importlib.util
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import pathlib
|
|
36
|
+
import sys
|
|
37
|
+
import tempfile
|
|
38
|
+
import threading
|
|
39
|
+
|
|
40
|
+
if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
|
|
41
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
42
|
+
from runlib import stagelock
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
JSONL_LINES = pathlib.Path(__file__).resolve().parents[2] / "wrappers" / "jsonl_lines.py"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _load_jsonl_lines():
|
|
49
|
+
"""wrappers/jsonl_lines.py, loaded by path from this checkout: the one JSONL splitter, shipped
|
|
50
|
+
(shipped readers use it too) and imported here, never copied; runlib's readers reach it as
|
|
51
|
+
records.jsonl_lines (a text) and records.jsonl_read (a file, its bytes decoded here)."""
|
|
52
|
+
if not JSONL_LINES.is_file():
|
|
53
|
+
raise FileNotFoundError(f"JSONL_SPLITTER_MISSING {JSONL_LINES}: the one JSONL splitter is not there")
|
|
54
|
+
spec = importlib.util.spec_from_file_location("agent_bios_jsonl_lines", JSONL_LINES)
|
|
55
|
+
module = importlib.util.module_from_spec(spec)
|
|
56
|
+
spec.loader.exec_module(module)
|
|
57
|
+
return module
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
_jsonl = _load_jsonl_lines()
|
|
61
|
+
jsonl_lines, jsonl_read = _jsonl.split, _jsonl.read
|
|
62
|
+
|
|
63
|
+
# S0 is the declaration itself (run.json); these are the stages that read it and leave a record.
|
|
64
|
+
STAGES = ("S1", "S2", "S3", "S4", "S5", "S5b", "S6", "S7", "S7b", "S8", "S9", "S9b", "S10", "S10b", "S11",
|
|
65
|
+
"S12")
|
|
66
|
+
# S5b (WP-11b) sits between S5 and S6 rather than at the end: `declare.py` derives an amendment's
|
|
67
|
+
# invalidation range from `STAGES.index` and sorts by it, so a stage appended after S12 would be
|
|
68
|
+
# invalidated last and ordered last whatever it actually runs before.
|
|
69
|
+
# The stages whose one record holds more than one producer, and the parts each has. A stage absent
|
|
70
|
+
# here keeps the single-producer record shape exactly as it was, and its readers do not change: S2
|
|
71
|
+
# produces the reading views and the inventory of the library, which neither calls the other nor
|
|
72
|
+
# may overwrite the other's record (design §6.1, §6.3). S10 parses the owner's decisions and, for a 판정, adjudicates
|
|
73
|
+
# them (design §10.1, §10.2; plan WP-20): two producers whose outputs neither may replace. S10b builds the final set
|
|
74
|
+
# the owner confirms and reads the owner's confirmation of it (design §10.3; plan WP-20 K6): the confirmation reads
|
|
75
|
+
# the build's manifest as its input, so the two are parts of one record rather than one producer replacing itself.
|
|
76
|
+
STAGE_PARTS = {"S2": ("views", "inventory"), "S10": ("parse", "adjudicate"), "S10b": ("build", "confirm"),
|
|
77
|
+
"S11": ("plan", "effects")}
|
|
78
|
+
# A part a stage MAY have. It is written and read like any other part, and counts toward the stage's status only
|
|
79
|
+
# when it is there: S11's destination manifest (`destinations.write`) is not made by release 1's apply, which
|
|
80
|
+
# writes the declared checkout alone, so its absence must not leave a finished apply `partial`.
|
|
81
|
+
STAGE_OPTIONAL_PARTS = {"S11": ("destinations",)}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parts_of(stage):
|
|
85
|
+
return tuple(STAGE_PARTS.get(stage, ())) + tuple(STAGE_OPTIONAL_PARTS.get(stage, ()))
|
|
86
|
+
STATUSES = ("running", "complete", "partial", "failed")
|
|
87
|
+
OUTCOMES = ("retained", "merged", "rejected", "quarantined") # design §3.2 item 5
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Refused(Exception):
|
|
91
|
+
"""A driver refusal; the message starts with the named code."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class RunStopped(Refused):
|
|
95
|
+
"""A refusal that stops the run, not an item (W review of WP-08e r2, F2; lead decision): a call that stopped the run
|
|
96
|
+
(INPUT_BOUND_EXCEEDED, CLAIM_EXCEEDED) or a dispatch refused while a stop stands (RUN_STOPPED). No posture quarantines
|
|
97
|
+
it: `run_items` raises it as it is, under production too, and lets no item start after it, so the stage ends
|
|
98
|
+
failed rather than complete with its units quarantined."""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def now():
|
|
102
|
+
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def sha256_bytes(data):
|
|
106
|
+
return hashlib.sha256(data).hexdigest()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def sha256_file(path):
|
|
110
|
+
return sha256_bytes(pathlib.Path(path).read_bytes())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def json_text(obj):
|
|
114
|
+
return json.dumps(obj, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def bound_digest(obj):
|
|
118
|
+
"""The sha256 `write_json` gives a file holding `obj`: what the declaration log binds."""
|
|
119
|
+
return sha256_bytes(json_text(obj).encode("utf-8"))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def write_text(run_dir, path, text):
|
|
123
|
+
"""Whole-file replace through a temporary in the same directory: a reader sees the old
|
|
124
|
+
file or the complete new one. `path` is confined beneath `run_dir` first."""
|
|
125
|
+
# Reached from the run directory's own descriptor (`stagelock.beneath`): confining the path and then opening
|
|
126
|
+
# it by name let a directory swapped for a link in between take the temporary and the rename outside the run.
|
|
127
|
+
with stagelock.beneath(run_dir, path) as (parent, name):
|
|
128
|
+
temporary = f".{name}.{os.urandom(8).hex()}"
|
|
129
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
|
130
|
+
try:
|
|
131
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
132
|
+
handle.write(text)
|
|
133
|
+
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
|
134
|
+
except BaseException:
|
|
135
|
+
try:
|
|
136
|
+
os.unlink(temporary, dir_fd=parent)
|
|
137
|
+
except OSError:
|
|
138
|
+
pass
|
|
139
|
+
raise
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def write_json(run_dir, path, obj):
|
|
143
|
+
write_text(run_dir, path, json_text(obj))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# The member names a stage record carries, which is what a refusal about one may name. A key outside
|
|
147
|
+
# this set is reported by its ordinal, so a name missing here costs a readable location and nothing
|
|
148
|
+
# more (`projection.document_location`).
|
|
149
|
+
RECORD_KEYS = frozenset((
|
|
150
|
+
"stage", "parts", "status", "run_json_sha256", "declaration_seq", "started", "ended",
|
|
151
|
+
"inputs", "outputs", "calls", "quarantined", "usage", "artifact", "sha256", "producer_stage",
|
|
152
|
+
"producer_seq", "id", "reason", "because", "unit", "route", "test_config",
|
|
153
|
+
"measured", "provisional", "unresolved", "complete",
|
|
154
|
+
))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _floor():
|
|
158
|
+
"""`runlib.projection`, imported on use.
|
|
159
|
+
|
|
160
|
+
`projection` imports this module for `jsonl_read`, so the two cannot both import at module
|
|
161
|
+
level; the dependency that matters is this direction, because the floor is where a record is
|
|
162
|
+
judged before it is published."""
|
|
163
|
+
from runlib import projection
|
|
164
|
+
return projection
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def record_disclosures(document):
|
|
168
|
+
"""What a stage record would disclose, through the floor's one entry point.
|
|
169
|
+
|
|
170
|
+
A stage record is a document this run writes, so it answers the question every written document
|
|
171
|
+
answers — and it answers it BEFORE the bytes land, not after the stage completed. The earlier
|
|
172
|
+
code checked only after `cmd_inventory` finished successfully, which left the `running` document
|
|
173
|
+
and every failure record unchecked; an item's quarantine reason is an exception message, and an
|
|
174
|
+
exception message is a path more often than not (GC#6)."""
|
|
175
|
+
return _floor().document_disclosures(document, str(pathlib.Path.home()), schema=RECORD_KEYS)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def publish_record(run_dir, stage, document, failing=None):
|
|
179
|
+
"""THE publication of a stage record: judged by the floor, then written.
|
|
180
|
+
|
|
181
|
+
Every write of `stages/<stage>/record.json` goes through here — the `running` document, the
|
|
182
|
+
final one, the failure one, and the one carrying another part's preserved entry — so a control
|
|
183
|
+
observes the real writer rather than a helper beside it.
|
|
184
|
+
|
|
185
|
+
`failing` is the exception already on its way out, when there is one: the final publication runs
|
|
186
|
+
in a `finally`, and a refusal there replaces what was in flight. The disclosure is the graver
|
|
187
|
+
fact, so it is the one raised, but the failure it ran beside is carried in the message rather
|
|
188
|
+
than swallowed."""
|
|
189
|
+
problems = record_disclosures(document)
|
|
190
|
+
if problems:
|
|
191
|
+
floor = _floor()
|
|
192
|
+
beside = ""
|
|
193
|
+
if failing is not None:
|
|
194
|
+
beside = (f" (raised while {type(failing).__name__}: "
|
|
195
|
+
f"{floor.diagnostic(failing, str(pathlib.Path.home()))} was in flight)")
|
|
196
|
+
raise Refused(f"RECORD_DISCLOSES {stage}: {'; '.join(problems[:4])}"
|
|
197
|
+
+ (f" (+{len(problems) - 4} more)" if len(problems) > 4 else "")
|
|
198
|
+
+ f"; the stage record is not written{beside}")
|
|
199
|
+
write_json(run_dir, record_path(run_dir, stage), document)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def read_json(path):
|
|
203
|
+
try:
|
|
204
|
+
return json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
|
|
205
|
+
except (OSError, ValueError) as exc:
|
|
206
|
+
raise Refused(f"RECORD_UNREADABLE {path}: {exc}") from exc
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# The one place the fixture tree is located. A suite asks `fixture_root`, never recomputes the path, so a tree
|
|
210
|
+
# without the fixtures - a copy of the shipped files - ends every suite that needs them by name.
|
|
211
|
+
FIXTURE_ROOT = pathlib.Path(__file__).resolve().parents[1] / "fixtures"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def fixture_root(*parts):
|
|
215
|
+
"""`session-distill/fixtures/`, or the directory `parts` names inside it, for a self-test - refused by name
|
|
216
|
+
(`FIXTURES_ABSENT <path>`) when that directory is not there, rather than read until a file open fails."""
|
|
217
|
+
path = FIXTURE_ROOT.joinpath(*parts)
|
|
218
|
+
if not path.is_dir():
|
|
219
|
+
raise Refused(f"FIXTURES_ABSENT {path}: this tree carries no {'/'.join(('fixtures',) + parts)} directory, which "
|
|
220
|
+
"this self-test's fixtures are read from")
|
|
221
|
+
return path
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def run_json_path(run_dir):
|
|
225
|
+
return pathlib.Path(run_dir) / "run.json"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def amendments_path(run_dir):
|
|
229
|
+
return pathlib.Path(run_dir) / "amendments.jsonl"
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def record_path(run_dir, stage):
|
|
233
|
+
return pathlib.Path(run_dir) / "stages" / stage / "record.json"
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def append_amendment(run_dir, amendment):
|
|
237
|
+
path = stagelock.confine(run_dir, amendments_path(run_dir))
|
|
238
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
239
|
+
with open(path, "a", encoding="utf-8") as handle:
|
|
240
|
+
handle.write(json.dumps(amendment, sort_keys=True, ensure_ascii=False) + "\n")
|
|
241
|
+
handle.flush()
|
|
242
|
+
os.fsync(handle.fileno())
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def read_log(run_dir):
|
|
246
|
+
"""Every line of `amendments.jsonl`: seq 0 is the declaration, seq 1.. the amendments."""
|
|
247
|
+
path = amendments_path(run_dir)
|
|
248
|
+
if not path.is_file():
|
|
249
|
+
return []
|
|
250
|
+
try:
|
|
251
|
+
return [json.loads(line) for line in jsonl_read(path) if line.strip()]
|
|
252
|
+
except ValueError as exc:
|
|
253
|
+
raise Refused(f"RECORD_UNREADABLE {path}: {exc}") from exc
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def read_amendments(run_dir):
|
|
257
|
+
return [entry for entry in read_log(run_dir) if entry.get("seq", 0) >= 1]
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def rebind(run_dir, digest):
|
|
261
|
+
"""Rebind the last log entry (the declaration at seq 0, before any stage has read it) to the
|
|
262
|
+
run.json that `declare --set` has just written."""
|
|
263
|
+
log = read_log(run_dir)
|
|
264
|
+
log[-1] = {**log[-1], "run_json_sha256": digest}
|
|
265
|
+
write_text(run_dir, amendments_path(run_dir), "".join(json.dumps(e, sort_keys=True, ensure_ascii=False) + "\n" for e in log))
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def stage_records(run_dir):
|
|
269
|
+
found = {}
|
|
270
|
+
for stage in STAGES:
|
|
271
|
+
path = record_path(run_dir, stage)
|
|
272
|
+
if path.is_file():
|
|
273
|
+
found[stage] = read_json(path)
|
|
274
|
+
return found
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def confine_declaration(run_dir):
|
|
278
|
+
"""Both files of a declaration, run.json and the log, confined to the run directory before
|
|
279
|
+
either is read or written: a mutator that logs and then finds run.json linked away would
|
|
280
|
+
otherwise leave the two disagreeing."""
|
|
281
|
+
for destination in (run_json_path(run_dir), amendments_path(run_dir)):
|
|
282
|
+
stagelock.confine(run_dir, destination)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def declaration_state(run_dir, who="declare"):
|
|
286
|
+
"""(run, run_json_sha256, amendments) of a run whose run.json is the declaration the log
|
|
287
|
+
authorized: the log is numbered 0..n, `declaration_seq` is n, and the sha256 of run.json is
|
|
288
|
+
the one bound to n. Anything else means run.json or the log was changed outside `declare`,
|
|
289
|
+
and `who` (a stage, or declare) is told so by name. It confines both files first
|
|
290
|
+
(RUN_PATH_ESCAPE), so every mutator that calls it under the declaration lock has done so
|
|
291
|
+
before its first write."""
|
|
292
|
+
confine_declaration(run_dir)
|
|
293
|
+
path = run_json_path(run_dir)
|
|
294
|
+
if not path.is_file():
|
|
295
|
+
raise Refused(f"RUN_UNDECLARED {run_dir}: no run.json")
|
|
296
|
+
run, log = read_json(path), read_log(run_dir)
|
|
297
|
+
if not log:
|
|
298
|
+
raise Refused(f"DECLARATION_DRIFT {who}: no declaration is bound to {path} (the log has no seq-0 entry)")
|
|
299
|
+
if [entry.get("seq") for entry in log] != list(range(len(log))):
|
|
300
|
+
raise Refused(f"DECLARATION_DRIFT {who}: the declaration log is not numbered 0..{len(log) - 1}")
|
|
301
|
+
if run.get("declaration_seq") != len(log) - 1:
|
|
302
|
+
raise Refused(f"DECLARATION_DRIFT {who}: run.json is at declaration_seq "
|
|
303
|
+
f"{run.get('declaration_seq')} but the declaration log ends at {len(log) - 1}")
|
|
304
|
+
digest = sha256_file(path)
|
|
305
|
+
if digest != log[-1].get("run_json_sha256"):
|
|
306
|
+
raise Refused(f"DECLARATION_DRIFT {who}: run.json is not the declaration authorized at seq "
|
|
307
|
+
f"{len(log) - 1}: its sha256 is {digest[:12]}, the log bound {str(log[-1].get('run_json_sha256'))[:12]}")
|
|
308
|
+
return run, digest, log[1:]
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def check_declaration_order(consumer, consumer_seq, producer, producer_seq, amendments):
|
|
312
|
+
"""Whether `consumer`, which read declaration `consumer_seq`, may consume the results of
|
|
313
|
+
`producer`, produced under `producer_seq` (design §4.1). Violations, empty when it may.
|
|
314
|
+
|
|
315
|
+
Equal sequences pass. Otherwise some amendment in (producer_seq, consumer_seq] must list
|
|
316
|
+
the consumer in `scope[]`, and none may list the producer in `invalidates[]`. No amendment
|
|
317
|
+
between, none that lists the consumer, or a consumer that read an older declaration than
|
|
318
|
+
its producer, is a silent advance."""
|
|
319
|
+
if consumer_seq == producer_seq:
|
|
320
|
+
return []
|
|
321
|
+
between = [a for a in amendments if producer_seq < a["seq"] <= consumer_seq]
|
|
322
|
+
errors = [f"INPUT_STALE {producer}: amendment {a['seq']} invalidates it" for a in between
|
|
323
|
+
if producer in a["invalidates"]]
|
|
324
|
+
if not between:
|
|
325
|
+
errors.append(f"DECLARATION_DRIFT {consumer}: read declaration {consumer_seq} but consumed "
|
|
326
|
+
f"{producer}, produced under {producer_seq}, with no amendment between")
|
|
327
|
+
elif not any(consumer in a["scope"] for a in between):
|
|
328
|
+
errors.append(f"DECLARATION_DRIFT {consumer}: no amendment between {producer_seq} and "
|
|
329
|
+
f"{consumer_seq} lists it in scope")
|
|
330
|
+
return errors
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# The containment test of `stagelock.confine`, for paths that are read or merely named (artifacts, run ids).
|
|
334
|
+
contained = stagelock.contained
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# What two items can share for one's failure to take the other with it (design §4).
|
|
338
|
+
SHARED_KEYS = ("unit", "route", "test_config")
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def run_items(posture, items, work, jobs=1, stop=None):
|
|
342
|
+
"""Run `work(item)` over `items` under a failure posture (design §4).
|
|
343
|
+
|
|
344
|
+
An item is `{id, unit, route, test_config}`; a key it does not have shares nothing. In
|
|
345
|
+
`production` an item whose work raises is quarantined together with every other item that
|
|
346
|
+
shares its unit, route or test configuration, those not yet run are skipped and those
|
|
347
|
+
already done are moved to the quarantine, and the independent items continue. Under any
|
|
348
|
+
other posture the first failure stops by name (ITEM_FAILED), and so does a missing posture.
|
|
349
|
+
Returns `{done: [ids], quarantined: [{id, reason, because}]}`; `because` is the failing item
|
|
350
|
+
that took the item with it, None for the failing item itself.
|
|
351
|
+
|
|
352
|
+
With `jobs` above one, the items run that many at a time and the posture's rules hold as they do one at a time
|
|
353
|
+
(WP-08 commit 5b): items joined by a shared unit, route or test configuration, directly or through others, run in
|
|
354
|
+
one sequence in their order, so a failure skips and quarantines the others of its sequence exactly as above, and
|
|
355
|
+
sequences that share nothing run side by side. Under any posture but production a failure sets `stop` (an event a
|
|
356
|
+
caller may hold) and lets no item start after it; the items already running finish, and the earliest failure in
|
|
357
|
+
`items` order is the one named. `done`
|
|
358
|
+
and the quarantine are in `items` order. A `jobs` that is not a positive integer is refused (ITEMS_JOBS_INVALID).
|
|
359
|
+
|
|
360
|
+
A `RunStopped` is not an item's failure: under every posture it is raised as it is, and no item starts after it."""
|
|
361
|
+
expect_set(item["id"] for item in items)
|
|
362
|
+
if isinstance(jobs, bool) or not isinstance(jobs, int) or jobs < 1:
|
|
363
|
+
raise Refused(f"ITEMS_JOBS_INVALID {jobs!r}: items run one or more at a time")
|
|
364
|
+
if jobs == 1:
|
|
365
|
+
return _run_sequence(posture, items, work)
|
|
366
|
+
order = {item["id"]: n for n, item in enumerate(items)}
|
|
367
|
+
stop, failed = stop if stop is not None else threading.Event(), []
|
|
368
|
+
|
|
369
|
+
def sequence(group):
|
|
370
|
+
try:
|
|
371
|
+
return _run_sequence(posture, group, work, stop)
|
|
372
|
+
except RunStopped:
|
|
373
|
+
raise # it has set `stop`; it passes through by its class, never by its words
|
|
374
|
+
except Refused as exc:
|
|
375
|
+
if not str(exc).startswith("ITEM_FAILED "):
|
|
376
|
+
raise
|
|
377
|
+
stop.set()
|
|
378
|
+
failed.append((min(n for i, n in order.items() if str(exc).startswith(f"ITEM_FAILED {i} (")), exc))
|
|
379
|
+
return {"done": [], "quarantined": []}
|
|
380
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool:
|
|
381
|
+
outcomes = [future.result() for future in [pool.submit(sequence, group) for group in sharing_groups(items)]]
|
|
382
|
+
if failed:
|
|
383
|
+
raise min(failed, key=lambda pair: pair[0])[1]
|
|
384
|
+
done = {i for outcome in outcomes for i in outcome["done"]}
|
|
385
|
+
chunks = {} # a failure and the items it took with it, in the order one at a time would list them
|
|
386
|
+
for outcome in outcomes:
|
|
387
|
+
for entry in outcome["quarantined"]:
|
|
388
|
+
chunks.setdefault(entry["because"] or entry["id"], []).append(entry)
|
|
389
|
+
return {"done": [item["id"] for item in items if item["id"] in done],
|
|
390
|
+
"quarantined": [entry for key in sorted(chunks, key=order.get) for entry in chunks[key]]}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def sharing_groups(items):
|
|
394
|
+
"""`items` split into the sequences that share a unit, route or test configuration, directly or through others,
|
|
395
|
+
each in `items` order, ordered by their first item."""
|
|
396
|
+
parent = list(range(len(items)))
|
|
397
|
+
|
|
398
|
+
def find(n):
|
|
399
|
+
while parent[n] != n:
|
|
400
|
+
parent[n] = parent[parent[n]]
|
|
401
|
+
n = parent[n]
|
|
402
|
+
return n
|
|
403
|
+
first = {}
|
|
404
|
+
for n, item in enumerate(items):
|
|
405
|
+
for key in SHARED_KEYS:
|
|
406
|
+
if item.get(key) is not None:
|
|
407
|
+
held = first.setdefault((key, item[key]), n)
|
|
408
|
+
parent[find(n)] = find(held)
|
|
409
|
+
groups = {}
|
|
410
|
+
for n, item in enumerate(items):
|
|
411
|
+
groups.setdefault(find(n), []).append(item)
|
|
412
|
+
return list(groups.values()) # keyed in the order their first items come
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _run_sequence(posture, items, work, stop=None):
|
|
416
|
+
"""One sequence of `run_items`, one item at a time; with `stop`, no item starts once it is set."""
|
|
417
|
+
done, quarantined = [], {}
|
|
418
|
+
for item in items:
|
|
419
|
+
if stop is not None and stop.is_set():
|
|
420
|
+
break
|
|
421
|
+
if item["id"] in quarantined:
|
|
422
|
+
continue
|
|
423
|
+
try:
|
|
424
|
+
work(item)
|
|
425
|
+
except RunStopped:
|
|
426
|
+
if stop is not None:
|
|
427
|
+
stop.set()
|
|
428
|
+
raise
|
|
429
|
+
except Exception as exc:
|
|
430
|
+
# The reason is published in the stage record, and an exception's message is a path
|
|
431
|
+
# often enough — an OSError's message IS one. It passes the floor here, where the text
|
|
432
|
+
# is made, rather than at the seam that would then have to refuse the whole record.
|
|
433
|
+
floor = _floor()
|
|
434
|
+
reason = f"{type(exc).__name__}: {floor.project(str(exc), floor.CURRENT, str(pathlib.Path.home()))}"
|
|
435
|
+
if posture != "production":
|
|
436
|
+
raise Refused(f"ITEM_FAILED {item['id']} ({posture}): {reason}") from exc
|
|
437
|
+
quarantined[item["id"]] = {"id": item["id"], "reason": reason, "because": None}
|
|
438
|
+
for other in items:
|
|
439
|
+
shared = [key for key in SHARED_KEYS
|
|
440
|
+
if item.get(key) is not None and item.get(key) == other.get(key)]
|
|
441
|
+
if other["id"] != item["id"] and shared and other["id"] not in quarantined:
|
|
442
|
+
shared_value = floor.project(repr(item[shared[0]]), floor.CURRENT, str(pathlib.Path.home()))
|
|
443
|
+
quarantined[other["id"]] = {"id": other["id"], "because": item["id"],
|
|
444
|
+
"reason": f"shares {shared[0]} {shared_value} with {item['id']}, which failed"}
|
|
445
|
+
done = [i for i in done if i not in quarantined]
|
|
446
|
+
else:
|
|
447
|
+
done.append(item["id"])
|
|
448
|
+
return {"done": done, "quarantined": list(quarantined.values())}
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
class StageRun:
|
|
452
|
+
"""The record of a running stage; the stage adds its outputs, runs its items under the
|
|
453
|
+
run's posture, and may mark itself partial. `declaration` is the run.json the stage was
|
|
454
|
+
admitted against, read under the declaration lock: a stage takes what it needs of the
|
|
455
|
+
declaration from here, never from a read of its own made before admission, which an
|
|
456
|
+
amendment could have overtaken (X review of WP-08 r1)."""
|
|
457
|
+
|
|
458
|
+
def __init__(self, run_dir, record, posture, declaration=None):
|
|
459
|
+
self.run_dir, self.record, self.posture = pathlib.Path(run_dir), record, posture
|
|
460
|
+
self.declaration = declaration
|
|
461
|
+
|
|
462
|
+
def admitted(self, early):
|
|
463
|
+
"""`early`, a declaration a stage read before admission so that it could refuse before writing a record, when it
|
|
464
|
+
is the one this stage was admitted against; refused by name otherwise (DECLARATION_MOVED), because an amendment
|
|
465
|
+
landed between the read and the admission (X review of WP-08 r2)."""
|
|
466
|
+
if bound_digest(early) != self.record["run_json_sha256"]:
|
|
467
|
+
raise Refused(f"DECLARATION_MOVED {self.record['stage']}: the declaration read before admission "
|
|
468
|
+
f"({bound_digest(early)[:12]}) is not the one the stage was admitted against "
|
|
469
|
+
f"({self.record['run_json_sha256'][:12]}, declaration_seq {self.record['declaration_seq']}); "
|
|
470
|
+
"run the stage again")
|
|
471
|
+
return early
|
|
472
|
+
|
|
473
|
+
def output(self, artifact):
|
|
474
|
+
path = contained(self.run_dir, artifact)
|
|
475
|
+
if path is None:
|
|
476
|
+
raise Refused(f"OUTPUT_OUTSIDE_RUN {artifact}: leaves the run directory")
|
|
477
|
+
self.record["outputs"].append({"artifact": artifact, "sha256": sha256_file(path)})
|
|
478
|
+
|
|
479
|
+
def run_items(self, items, work, jobs=1):
|
|
480
|
+
"""`run_items` under this run's posture, `jobs` at a time; the quarantined items are listed in the record."""
|
|
481
|
+
result = run_items(self.posture, items, work, jobs)
|
|
482
|
+
self.record["quarantined"].extend(result["quarantined"])
|
|
483
|
+
return result
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _legacy_part(stage, record):
|
|
487
|
+
"""Which declared part a pre-parts record belongs to, from the artifacts it recorded.
|
|
488
|
+
|
|
489
|
+
A record written before a stage had parts names no producer, but its outputs do: `views.json`
|
|
490
|
+
was written by the views part and by nothing else. A record whose outputs match no part's
|
|
491
|
+
artifacts keeps no part name, and the caller decides what to do with it."""
|
|
492
|
+
produced = {row.get("artifact") for row in record.get("outputs") or []}
|
|
493
|
+
for label in parts_of(stage):
|
|
494
|
+
if any(str(artifact).startswith(label) or str(artifact).startswith(f"{label}.")
|
|
495
|
+
or str(artifact).startswith(f"{label}/") for artifact in produced):
|
|
496
|
+
return label
|
|
497
|
+
return None
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def producing_part(record, artifact):
|
|
501
|
+
"""`(label, entry)` of the part of a stage record that produced `artifact`.
|
|
502
|
+
|
|
503
|
+
A record with no `parts` is the single-producer shape and answers for itself, so every reader
|
|
504
|
+
written before parts existed keeps working unchanged."""
|
|
505
|
+
parts = record.get("parts")
|
|
506
|
+
if not isinstance(parts, dict):
|
|
507
|
+
return record.get("stage"), record
|
|
508
|
+
for label in sorted(parts):
|
|
509
|
+
entry = parts[label]
|
|
510
|
+
if any(row.get("artifact") == artifact for row in entry.get("outputs", [])):
|
|
511
|
+
return label, entry
|
|
512
|
+
return None, None
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def derived_status(record):
|
|
516
|
+
"""A stage's status, derived from its parts and never written on its own: complete only when
|
|
517
|
+
every declared part is complete."""
|
|
518
|
+
parts = record.get("parts")
|
|
519
|
+
if not isinstance(parts, dict):
|
|
520
|
+
return record.get("status")
|
|
521
|
+
declared = tuple(STAGE_PARTS.get(record.get("stage"), ())) + tuple(
|
|
522
|
+
label for label in STAGE_OPTIONAL_PARTS.get(record.get("stage"), ()) if label in parts)
|
|
523
|
+
states = [parts.get(label, {}).get("status") for label in declared]
|
|
524
|
+
if "failed" in states:
|
|
525
|
+
return "failed"
|
|
526
|
+
if "running" in states:
|
|
527
|
+
return "running"
|
|
528
|
+
if all(state == "complete" for state in states):
|
|
529
|
+
return "complete"
|
|
530
|
+
return "partial"
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _check_input(run_dir, stage, spec, seq, amendments, records):
|
|
534
|
+
"""(pinned input, violations) for one declared input `{artifact, producer_stage}`."""
|
|
535
|
+
artifact, producer = spec["artifact"], spec["producer_stage"]
|
|
536
|
+
produced = records.get(producer)
|
|
537
|
+
if produced is None:
|
|
538
|
+
return None, [f"INPUT_INVALID {producer}: no record for the stage that produces {artifact}"]
|
|
539
|
+
# An input is judged against the PART that produced it: the inventory failing says nothing
|
|
540
|
+
# about views.json, and views being partial says everything about it.
|
|
541
|
+
label, produced = producing_part(produced, artifact)
|
|
542
|
+
if produced is None:
|
|
543
|
+
return None, [f"INPUT_INVALID {producer}: no part of its record produced {artifact}"]
|
|
544
|
+
producer_label = f"{producer}.{label}" if label and label != producer else producer
|
|
545
|
+
if produced.get("status") in ("running", "partial"):
|
|
546
|
+
return None, [f"INPUT_PARTIAL {producer_label}: its record is {produced['status']}, so {artifact} is incomplete"]
|
|
547
|
+
if produced.get("status") != "complete":
|
|
548
|
+
return None, [f"INPUT_INVALID {producer_label}: its record is {produced.get('status')!r}"]
|
|
549
|
+
path = contained(run_dir, artifact)
|
|
550
|
+
if path is None:
|
|
551
|
+
return None, [f"INPUT_INVALID {producer}: {artifact} leaves the run directory"]
|
|
552
|
+
if not path.is_file():
|
|
553
|
+
return None, [f"INPUT_INVALID {producer}: {artifact} is not a file"]
|
|
554
|
+
digest = sha256_file(path)
|
|
555
|
+
if {o["artifact"]: o["sha256"] for o in produced["outputs"]}.get(artifact) != digest:
|
|
556
|
+
return None, [f"INPUT_INVALID {producer_label}: {artifact} is not the output {producer_label} recorded"]
|
|
557
|
+
errors = check_declaration_order(stage, seq, producer, produced["declaration_seq"], amendments)
|
|
558
|
+
return {"artifact": artifact, "sha256": digest, "producer_stage": producer,
|
|
559
|
+
"producer_seq": produced["declaration_seq"]}, errors
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def provenance_problems(stage, pinned, records):
|
|
563
|
+
"""INPUT_STALE for each producer of an admitted input that read another artifact this stage admits now, in bytes
|
|
564
|
+
other than those it admits (W review of WP-09 r1, F2; lead decision). An output's own digest says the producer
|
|
565
|
+
wrote it and nothing has changed it since; it does not say the producer read what is there now. A producer run
|
|
566
|
+
again at the same declaration sequence leaves its consumers' inputs each valid alone and stale together: S1 run
|
|
567
|
+
again under S3's results, which S4 would otherwise read beside the new census."""
|
|
568
|
+
admitted = {entry["artifact"]: entry["sha256"] for entry in pinned}
|
|
569
|
+
errors = {}
|
|
570
|
+
for entry in pinned:
|
|
571
|
+
label, produced = producing_part(records[entry["producer_stage"]], entry["artifact"])
|
|
572
|
+
producer = entry["producer_stage"] + (f".{label}" if label and label != entry["producer_stage"] else "")
|
|
573
|
+
for read in (produced or {}).get("inputs") or []:
|
|
574
|
+
now_at = admitted.get(read["artifact"])
|
|
575
|
+
if now_at is not None and read["sha256"] != now_at:
|
|
576
|
+
errors[f"INPUT_STALE {producer}: it read {read['artifact']} at {read['sha256'][:12]}, and {stage} admits "
|
|
577
|
+
f"{read['artifact']} at {now_at[:12]}; {producer} is run again over what is there now"] = True
|
|
578
|
+
return list(errors)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
@contextlib.contextmanager
|
|
582
|
+
def run_stage(run_dir, stage, inputs=(), part=None, admit=None):
|
|
583
|
+
"""Hold the stage's lock, refuse to start on a stale, partial or invalid input or a
|
|
584
|
+
declaration edited outside `declare`, write the record as `running`, and finish it as
|
|
585
|
+
`complete` (or as `partial` when the stage said so, or `failed` on an exception).
|
|
586
|
+
|
|
587
|
+
`inputs` are `{artifact, producer_stage}`: the artifact's path under the run directory.
|
|
588
|
+
|
|
589
|
+
`part` names one producer of a stage that has several (`STAGE_PARTS`). The record is still one
|
|
590
|
+
file and one lock; this call reads it, replaces its own part's entry, and leaves every other
|
|
591
|
+
part's entry exactly as it found it. The stage's own status is derived from the parts rather
|
|
592
|
+
than written, so no producer can declare a stage complete on another's behalf."""
|
|
593
|
+
if stage not in STAGES:
|
|
594
|
+
raise Refused(f"STAGE_UNKNOWN {stage}: not one of {', '.join(STAGES)}")
|
|
595
|
+
if part is not None and part not in parts_of(stage):
|
|
596
|
+
raise Refused(f"STAGE_PART_UNKNOWN {stage}.{part}: the parts of {stage} are "
|
|
597
|
+
f"{list(parts_of(stage)) or 'none'}")
|
|
598
|
+
if part is None and stage in STAGE_PARTS:
|
|
599
|
+
# A part-less write to a stage that HAS parts replaces the whole record, whatever is there.
|
|
600
|
+
# Refusing only when another part's entry already exists made the rule depend on the order
|
|
601
|
+
# the producers happened to run in (GC#9).
|
|
602
|
+
raise Refused(f"STAGE_PART_REQUIRED {stage}: it has the parts {list(STAGE_PARTS[stage])}, so a "
|
|
603
|
+
f"writer names the part it produces")
|
|
604
|
+
with stagelock.pinned(run_dir), stagelock.hold(run_dir, f"stage-{stage}"):
|
|
605
|
+
# (the pin: every record this stage writes, its failure record among them, is anchored in the run
|
|
606
|
+
# directory it was admitted in - `stagelock.PINNED`)
|
|
607
|
+
# the declaration lock makes "read the declaration, check, pin it" one step: `declare`
|
|
608
|
+
# cannot edit or amend between the check and the record
|
|
609
|
+
with stagelock.hold(run_dir, "declaration"):
|
|
610
|
+
run, digest, amendments = declaration_state(run_dir, stage)
|
|
611
|
+
seq, records, errors, pinned = run["declaration_seq"], stage_records(run_dir), [], []
|
|
612
|
+
for spec in inputs:
|
|
613
|
+
entry, problems = _check_input(run_dir, stage, spec, seq, amendments, records)
|
|
614
|
+
errors.extend(problems)
|
|
615
|
+
if entry:
|
|
616
|
+
pinned.append(entry)
|
|
617
|
+
errors.extend(provenance_problems(stage, pinned, records))
|
|
618
|
+
if errors:
|
|
619
|
+
raise Refused("\n".join(errors))
|
|
620
|
+
if admit is not None:
|
|
621
|
+
# the stage's own last refusal, under the stage's lock and before the record that is there is
|
|
622
|
+
# replaced: a check made before the lock can be passed by two invocations in turn, and one
|
|
623
|
+
# made after the record is written has already replaced a complete record with a running one
|
|
624
|
+
admit()
|
|
625
|
+
record = {"stage": stage, "run_json_sha256": digest, "declaration_seq": seq, "started": now(),
|
|
626
|
+
"ended": None, "status": "running", "inputs": pinned, "outputs": [], "calls": [],
|
|
627
|
+
"quarantined": [], "usage": {"measured": 0, "provisional": 0, "unresolved": 0, "complete": False}}
|
|
628
|
+
document = record
|
|
629
|
+
existing = read_json(record_path(run_dir, stage)) if record_path(run_dir, stage).is_file() else {}
|
|
630
|
+
if part is not None:
|
|
631
|
+
parts = dict(existing.get("parts") or {})
|
|
632
|
+
if not parts and existing.get("outputs") is not None:
|
|
633
|
+
# A record written before this stage had parts is one producer's record. Which
|
|
634
|
+
# producer is decided by the artifacts it carries, and it is kept: adding a part
|
|
635
|
+
# beside it must not take `views.json` away from the stage that made it (GB#11).
|
|
636
|
+
kept = _legacy_part(stage, existing)
|
|
637
|
+
if kept is None:
|
|
638
|
+
# A running or failed record with no outputs names no producer, and its
|
|
639
|
+
# artifacts cannot name one either. Discarding it silently is what GB#11
|
|
640
|
+
# forbids, so the ambiguity is refused rather than resolved (GC#9).
|
|
641
|
+
raise Refused(f"STAGE_PART_AMBIGUOUS {stage}: the record already here names no part "
|
|
642
|
+
f"and its outputs identify none (status "
|
|
643
|
+
f"{existing.get('status')!r}, {len(existing.get('outputs') or [])} "
|
|
644
|
+
f"output(s)); close or remove it before a part writes")
|
|
645
|
+
if kept != part:
|
|
646
|
+
parts[kept] = existing
|
|
647
|
+
parts[part] = record
|
|
648
|
+
document = {"stage": stage, "parts": parts}
|
|
649
|
+
document["status"] = derived_status(document)
|
|
650
|
+
elif existing.get("parts"):
|
|
651
|
+
raise Refused(f"STAGE_PART_REQUIRED {stage}: its record already holds the parts "
|
|
652
|
+
f"{sorted(existing['parts'])}, and a writer that names no part would "
|
|
653
|
+
f"replace all of them")
|
|
654
|
+
publish_record(run_dir, stage, document)
|
|
655
|
+
try:
|
|
656
|
+
yield StageRun(run_dir, record, run.get("posture"), copy.deepcopy(run))
|
|
657
|
+
except BaseException:
|
|
658
|
+
record["status"] = "failed"
|
|
659
|
+
raise
|
|
660
|
+
else:
|
|
661
|
+
if record["status"] == "running":
|
|
662
|
+
record["status"] = "complete"
|
|
663
|
+
finally:
|
|
664
|
+
record["ended"] = now()
|
|
665
|
+
if part is not None:
|
|
666
|
+
document["status"] = derived_status(document)
|
|
667
|
+
publish_record(run_dir, stage, document, sys.exc_info()[1])
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
@contextlib.contextmanager
|
|
671
|
+
def fx_amended_at_admission(stage, assignments, when="before"):
|
|
672
|
+
"""Self-test fixture: while it is held, `run_stage` of `stage` has an amendment of `assignments` land just before its
|
|
673
|
+
admission (`before`) or just after it (`after`) - the two places a stage that reads the declaration on its own can
|
|
674
|
+
be overtaken (X review of WP-08 r1 and r2). Every stage's race control uses it, so the two cases are the same two
|
|
675
|
+
cases everywhere. `run_stage` is restored on exit."""
|
|
676
|
+
from runlib import declare # declare imports this module, so the fixture imports it when it runs
|
|
677
|
+
if when not in ("before", "after"):
|
|
678
|
+
raise ValueError(f"when: {when!r}")
|
|
679
|
+
module, admitted = sys.modules[__name__], run_stage
|
|
680
|
+
|
|
681
|
+
@contextlib.contextmanager
|
|
682
|
+
def racing(run_dir, name, inputs=(), part=None):
|
|
683
|
+
if name == stage and when == "before":
|
|
684
|
+
declare.amend(run_dir, assignments, f"an amendment just before {stage}'s admission")
|
|
685
|
+
with admitted(run_dir, name, inputs, part=part) as held:
|
|
686
|
+
if name == stage and when == "after":
|
|
687
|
+
declare.amend(run_dir, assignments, f"an amendment just after {stage}'s admission")
|
|
688
|
+
yield held
|
|
689
|
+
module.run_stage = racing
|
|
690
|
+
try:
|
|
691
|
+
yield
|
|
692
|
+
finally:
|
|
693
|
+
module.run_stage = admitted
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
# The structural guard of the declaration a stage reads (X review of WP-08 r2; the shape three reviews found one stage at
|
|
697
|
+
# a time): a stage builds from the declaration it was admitted against, `StageRun.declaration`, so outside the sites
|
|
698
|
+
# listed here nothing reads run.json - takes its path, reads its state, or spells its name. Each site is a module and its
|
|
699
|
+
# top-level function, or a class's method, with the reason it may. A site not listed, a listed site that no longer reads
|
|
700
|
+
# the declaration, and a scan that found no module or no site fail by name: DECLARATION_READ_UNLISTED,
|
|
701
|
+
# DECLARATION_READ_STALE, DECLARATION_READ_UNSCANNED. Every Python module of session-distill is scanned, the pipeline
|
|
702
|
+
# beside distill.py included. The guard sees a read where it is spelled: a listed site that hands what it read to its
|
|
703
|
+
# caller hands on the declaration, so each reason says what the site does with it.
|
|
704
|
+
DECLARATION_FILE = "run.json"
|
|
705
|
+
DECLARATION_READS = frozenset(("run_json_path", "declaration_state"))
|
|
706
|
+
DECLARATION_MODULES = ("*.py", "runlib/*.py")
|
|
707
|
+
DECLARATION_READERS = {
|
|
708
|
+
("runlib/records.py", "<module>"): "this guard's own DECLARATION_FILE, the name it looks for",
|
|
709
|
+
("runlib/records.py", "run_json_path"): "the one place the declaration's path is spelled",
|
|
710
|
+
("runlib/records.py", "confine_declaration"): "confines the declaration's path beneath the run before anything reads it",
|
|
711
|
+
("runlib/records.py", "declaration_state"): "the declaration's reader, which takes no lock itself and checks that run.json "
|
|
712
|
+
"is the one the log binds. Its callers hold different locks: run_stage's "
|
|
713
|
+
"stage admission and dispatch's stop stamp (_stop_run) hold the declaration "
|
|
714
|
+
"lock; dispatch's reservation (reserve) holds the supervisor's lock alone, "
|
|
715
|
+
"and so does the standing-stop check (_blocked) where reserve and a call's "
|
|
716
|
+
"launch make it; that check as a call first makes it and the seat admission "
|
|
717
|
+
"(_admit_seat), both before the call takes the supervisor's lock, and the "
|
|
718
|
+
"read-only budget query (remaining) hold neither. A read without the "
|
|
719
|
+
"declaration lock that lands "
|
|
720
|
+
"mid-amendment is refused by name (DECLARATION_DRIFT) rather than believed",
|
|
721
|
+
("runlib/records.py", "run_stage"): "admits a stage: what it reads under the lock is the StageRun.declaration the stage "
|
|
722
|
+
"builds from",
|
|
723
|
+
("runlib/destinations.py", "_self_test_body"): "reads back the run.json its own fixture just wrote, to judge the "
|
|
724
|
+
"manifest against the roots a real declaration carries rather than a "
|
|
725
|
+
"shape invented in the suite. The module itself never reads the "
|
|
726
|
+
"declaration from disk: `document` and `write` are handed it by their "
|
|
727
|
+
"caller, which is what lets apply resolve destinations before it opens "
|
|
728
|
+
"any stage record. The suite's own body carries the "
|
|
729
|
+
"read because a dying-control wrapper owns the name "
|
|
730
|
+
"`self_test`, and this allowlist is keyed by the "
|
|
731
|
+
"FUNCTION that reads, not by the file",
|
|
732
|
+
("runlib/declare.py", "create"): "the declaration's writer (S0): writes run.json under the declaration lock",
|
|
733
|
+
("runlib/declare.py", "set_fields"): "the declaration's writer: an amendment's fields, read and written under the lock",
|
|
734
|
+
("runlib/declare.py", "amend"): "the declaration's writer: an amendment, read and written under the lock",
|
|
735
|
+
("runlib/census.py", "run"): "S1 reads the declaration before admission for the coverage base and originator table it "
|
|
736
|
+
"pins; StageRun.admitted refuses that read unless it is byte for byte the declaration S1 was "
|
|
737
|
+
"admitted against (DECLARATION_MOVED)",
|
|
738
|
+
("runlib/dispatch.py", "Supervisor.remaining"): "the budget a stage has left, read against the declaration current "
|
|
739
|
+
"when it is asked, as a reservation reads it",
|
|
740
|
+
("runlib/dispatch.py", "Supervisor.reserve"): "a call's reservation reads the budget current at the call, under the "
|
|
741
|
+
"dispatcher's lock: a call's admission, not a stage's build",
|
|
742
|
+
("runlib/dispatch.py", "Supervisor._admit_seat"): "a call's seat and host allowance are admitted against the "
|
|
743
|
+
"declaration current when it is made",
|
|
744
|
+
("runlib/dispatch.py", "Supervisor._blocked"): "whether an amendment lifts the run's standing stop is read from the "
|
|
745
|
+
"declaration's log as it stands",
|
|
746
|
+
("runlib/dispatch.py", "Supervisor._stop_run"): "a run's stop is stamped with the declaration and amendments current "
|
|
747
|
+
"when it stops",
|
|
748
|
+
("runlib/inventory.py", "<module>"): "RUN_MARKERS names the declaration's file to recognise a run directory, and reads "
|
|
749
|
+
"nothing of it",
|
|
750
|
+
("distill.py", "self_test"): "the CLI's self-test reads the declarations its scratch runs made, to check what each "
|
|
751
|
+
"command declared and recorded",
|
|
752
|
+
("runlib/records.py", "self_test"): "the records self-test reads the declarations it plants",
|
|
753
|
+
("runlib/declare.py", "self_test"): "the declaration's own self-test reads what its writer wrote",
|
|
754
|
+
("runlib/census.py", "controls"): "the census self-test's body reads its scratch runs' declarations, to check what S1 "
|
|
755
|
+
"recorded against them",
|
|
756
|
+
("runlib/dispatch.py", "self_test"): "the dispatcher's self-test plants and reads its scratch runs' declarations",
|
|
757
|
+
("runlib/views.py", "self_test"): "the S2 self-test reads its scratch runs' declarations, to check what S2 recorded",
|
|
758
|
+
("runlib/stage_review_korean.py", "_self_test_all"): "the S9b suite reads the seats its golden run declares, to amend them "
|
|
759
|
+
"with the stage's two seats (a dotted key is assigned as a whole map)",
|
|
760
|
+
("runlib/stage_adjudicate.py", "_self_test_all"): "the S10 suite reads the seats its golden run declares, to amend "
|
|
761
|
+
"them with the second pass's two seats (a dotted key is assigned as "
|
|
762
|
+
"a whole map)",
|
|
763
|
+
("runlib/stage_apply.py", "_held_declaration"): "S11's effects part takes the declaration's lock around every "
|
|
764
|
+
"write and reads the declaration again under it, held to the one "
|
|
765
|
+
"it was admitted under: admission releases that lock, so an "
|
|
766
|
+
"amendment could otherwise land while files are being written",
|
|
767
|
+
("runlib/stage_close.py", "_self_test_body"): "the S12 suite reads the declaration of the run S3's own fixture made, "
|
|
768
|
+
"to fold its results as the stage does under its admission",
|
|
769
|
+
("runlib/stage_read.py", "fx_reader"): "the S3 fixture reads the seat its golden run declared, to seed the supervisor "
|
|
770
|
+
"before S3 runs",
|
|
771
|
+
("runlib/stage_read.py", "self_test"): "the S3 self-test reads its scratch runs' declarations, to check what S3 "
|
|
772
|
+
"recorded against them",
|
|
773
|
+
("runlib/stage_delivery.py", "standing_stop"): "S5b asks whether a stop still stands before it writes an evidence "
|
|
774
|
+
"document that would be read as whole, and only a later amendment of "
|
|
775
|
+
"a stop's own key lifts one: the read is of the log alone, outside "
|
|
776
|
+
"the stage's admission, and a declaration it cannot read holds every "
|
|
777
|
+
"recorded stop standing rather than reading the run open",
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def declaration_texts(root=None):
|
|
782
|
+
"""The sources `declaration_reads` judges: every module of `DECLARATION_MODULES`, by path relative to session-distill."""
|
|
783
|
+
root = pathlib.Path(root) if root is not None else pathlib.Path(__file__).resolve().parents[1]
|
|
784
|
+
return {path.relative_to(root).as_posix(): path.read_text(encoding="utf-8")
|
|
785
|
+
for pattern in DECLARATION_MODULES for path in sorted(root.glob(pattern))}
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def declaration_reads(texts, allowed=None):
|
|
789
|
+
"""`(violations, sites)` of the declaration guard over `texts` (`{relative path: source}`). A site is where code
|
|
790
|
+
names `run_json_path` or `declaration_state`, under any name it imported them as, or the literal "run.json"; it is
|
|
791
|
+
keyed by its module and top-level function, a class's method as `Class.method`, or `<module>`."""
|
|
792
|
+
import ast
|
|
793
|
+
allowed = DECLARATION_READERS if allowed is None else allowed
|
|
794
|
+
sites = {}
|
|
795
|
+
for rel, text in sorted(texts.items()):
|
|
796
|
+
tree = ast.parse(text)
|
|
797
|
+
names = set(DECLARATION_READS) | {a.asname for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)
|
|
798
|
+
for a in n.names if a.name in DECLARATION_READS and a.asname}
|
|
799
|
+
units = []
|
|
800
|
+
for top in tree.body:
|
|
801
|
+
if isinstance(top, ast.ClassDef):
|
|
802
|
+
units += [(f"{top.name}.{m.name}" if isinstance(m, (ast.FunctionDef, ast.AsyncFunctionDef)) else top.name, m)
|
|
803
|
+
for m in top.body]
|
|
804
|
+
else:
|
|
805
|
+
units.append((top.name if isinstance(top, (ast.FunctionDef, ast.AsyncFunctionDef)) else "<module>", top))
|
|
806
|
+
for name, unit in units:
|
|
807
|
+
for node in ast.walk(unit):
|
|
808
|
+
if (isinstance(node, ast.Constant) and node.value == DECLARATION_FILE) \
|
|
809
|
+
or (isinstance(node, ast.Name) and node.id in names) \
|
|
810
|
+
or (isinstance(node, ast.Attribute) and node.attr in DECLARATION_READS):
|
|
811
|
+
sites.setdefault((rel, name), node.lineno)
|
|
812
|
+
violations = [f"DECLARATION_READ_UNLISTED {rel}:{line} ({name}): reads the declaration where no stage's admission "
|
|
813
|
+
"carries it; a stage builds from StageRun.declaration, and a site that must read run.json is listed in "
|
|
814
|
+
"records.DECLARATION_READERS with its reason" for (rel, name), line in sorted(sites.items())
|
|
815
|
+
if (rel, name) not in allowed]
|
|
816
|
+
violations += [f"DECLARATION_READ_STALE {rel} ({name}): listed in records.DECLARATION_READERS, and it no longer reads "
|
|
817
|
+
"the declaration" for rel, name in sorted(set(allowed) - set(sites))]
|
|
818
|
+
if not texts or not sites:
|
|
819
|
+
violations.append(f"DECLARATION_READ_UNSCANNED: {len(texts)} modules scanned and {len(sites)} sites found; a "
|
|
820
|
+
"guard that judged nothing is not clean")
|
|
821
|
+
return violations, set(sites)
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def expect_set(ids):
|
|
825
|
+
"""The ids a transformation must account for, each once."""
|
|
826
|
+
ids = list(ids)
|
|
827
|
+
repeated = sorted({i for i in ids if ids.count(i) > 1})
|
|
828
|
+
if repeated:
|
|
829
|
+
raise Refused(f"SET_MISMATCH expected ids repeat: {repeated}")
|
|
830
|
+
return frozenset(ids)
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def observe_set(expected, outcomes):
|
|
834
|
+
"""Violations of the set accounting of design §3.2 item 5, empty when it holds.
|
|
835
|
+
|
|
836
|
+
Every expected id must appear exactly once as `retained`, `rejected` (with a `reason`),
|
|
837
|
+
`quarantined`, or inside the `members` of a `merged` output. An outcome is
|
|
838
|
+
`{id, outcome[, reason][, members]}`; for `merged`, `id` names the merged output and
|
|
839
|
+
`members` the input ids it absorbs. An outcome of any other kind, a merge without
|
|
840
|
+
members and a rejection without a reason account for nothing."""
|
|
841
|
+
accounted, invalid, output_ids = [], [], []
|
|
842
|
+
for item in outcomes:
|
|
843
|
+
kind, reason, members = item.get("outcome"), item.get("reason"), item.get("members")
|
|
844
|
+
output_ids.append(item.get("id"))
|
|
845
|
+
if kind == "merged" and members:
|
|
846
|
+
accounted.extend(members)
|
|
847
|
+
elif kind in ("retained", "quarantined") or (kind == "rejected" and reason):
|
|
848
|
+
accounted.append(item.get("id"))
|
|
849
|
+
else:
|
|
850
|
+
invalid.append(item.get("id"))
|
|
851
|
+
missing = sorted(expected - set(accounted))
|
|
852
|
+
extra = sorted(set(accounted) - expected)
|
|
853
|
+
repeated = sorted({i for i in accounted if accounted.count(i) > 1}
|
|
854
|
+
| {i for i in output_ids if output_ids.count(i) > 1})
|
|
855
|
+
if missing or extra or repeated or invalid:
|
|
856
|
+
return [f"SET_MISMATCH missing={missing} extra={extra} repeated={repeated} invalid={sorted(invalid)}"]
|
|
857
|
+
return []
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def broad_handlers(src, module):
|
|
861
|
+
"""Every handler of production code in `src` that a RunStopped can meet - one catching a class of its MRO, or bare -
|
|
862
|
+
as `(key, reraises)` (the lead's verification of WP-08e commit 4, finding 3). `key` is `module:function:caught#n`,
|
|
863
|
+
n counting the same catch in the same function, so a line moving never renames a site. `reraises` is structural: a
|
|
864
|
+
handler of the same `try` before it catches RunStopped and ends in a bare `raise`, or the handler itself always
|
|
865
|
+
ends in one (its last statement, with no return, break or continue anywhere in it). A `self_test`, a
|
|
866
|
+
`_self_test…` body it delegates to, and what is nested in either is not production code."""
|
|
867
|
+
import ast
|
|
868
|
+
catches = {cls.__name__ for cls in RunStopped.__mro__} - {"object"}
|
|
869
|
+
|
|
870
|
+
def caught(handler):
|
|
871
|
+
if handler.type is None:
|
|
872
|
+
return ["<bare>"]
|
|
873
|
+
elts = handler.type.elts if isinstance(handler.type, ast.Tuple) else [handler.type]
|
|
874
|
+
return [ast.unparse(e).split(".")[-1] for e in elts]
|
|
875
|
+
|
|
876
|
+
def always_raises(handler):
|
|
877
|
+
nodes = [n for stmt in handler.body for n in ast.walk(stmt)]
|
|
878
|
+
return (bool(handler.body) and isinstance(handler.body[-1], ast.Raise) and handler.body[-1].exc is None
|
|
879
|
+
and not any(isinstance(n, (ast.Return, ast.Break, ast.Continue)) for n in nodes))
|
|
880
|
+
|
|
881
|
+
out, seen = [], {}
|
|
882
|
+
|
|
883
|
+
def walk(node, path):
|
|
884
|
+
for child in ast.iter_child_nodes(node):
|
|
885
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
886
|
+
# The suite, whatever it is called: a module whose `self_test` is a wrapper that
|
|
887
|
+
# reports a dying control keeps its body in `_self_test_body`, and that body's
|
|
888
|
+
# handlers are the suite's as much as the wrapper's are.
|
|
889
|
+
if child.name == "self_test" or child.name.startswith("_self_test"):
|
|
890
|
+
continue
|
|
891
|
+
walk(child, path + [child.name])
|
|
892
|
+
continue
|
|
893
|
+
if isinstance(child, ast.Try):
|
|
894
|
+
passed = False # an earlier handler of this try re-raises a RunStopped
|
|
895
|
+
for handler in child.handlers:
|
|
896
|
+
names = caught(handler)
|
|
897
|
+
if "RunStopped" in names and always_raises(handler):
|
|
898
|
+
passed = True
|
|
899
|
+
continue
|
|
900
|
+
if any(n in catches or n == "<bare>" for n in names):
|
|
901
|
+
where = f"{module}:{'.'.join(path) or '<module>'}:{'|'.join(names)}"
|
|
902
|
+
seen[where] = seen.get(where, 0) + 1
|
|
903
|
+
out.append((f"{where}#{seen[where]}", passed or always_raises(handler)))
|
|
904
|
+
walk(child, path)
|
|
905
|
+
walk(ast.parse(src), [])
|
|
906
|
+
return out
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def self_test():
|
|
910
|
+
failures = []
|
|
911
|
+
|
|
912
|
+
def expect(label, errors, *needles):
|
|
913
|
+
"""`errors` must name every needle; with no needle it must be empty."""
|
|
914
|
+
if not needles and errors:
|
|
915
|
+
failures.append(f"{label}: expected no violation, got {errors}")
|
|
916
|
+
for needle in needles:
|
|
917
|
+
if not any(needle in line for line in errors):
|
|
918
|
+
failures.append(f"{label}: expected {needle!r} in {errors}")
|
|
919
|
+
|
|
920
|
+
def amend(seq, scope=("S2", "S3"), invalidates=()):
|
|
921
|
+
return {"seq": seq, "at": now(), "reason": "fixture", "scope": list(scope),
|
|
922
|
+
"invalidates": list(invalidates), "diff": {}}
|
|
923
|
+
|
|
924
|
+
# check_declaration_order (WP-01 done-when 2). Positive controls first.
|
|
925
|
+
expect("equal sequences", check_declaration_order("S2", 0, "S1", 0, []))
|
|
926
|
+
expect("amended, scope covers, producer not invalidated",
|
|
927
|
+
check_declaration_order("S2", 1, "S1", 0, [amend(1, scope=("S2",))]))
|
|
928
|
+
expect("two amendments, both license the consumer",
|
|
929
|
+
check_declaration_order("S3", 2, "S1", 0, [amend(1), amend(2)]))
|
|
930
|
+
expect("silently advanced", check_declaration_order("S2", 1, "S1", 0, []),
|
|
931
|
+
"DECLARATION_DRIFT S2", "with no amendment between")
|
|
932
|
+
expect("amendment outside the range does not count",
|
|
933
|
+
check_declaration_order("S2", 1, "S1", 0, [amend(2)]), "DECLARATION_DRIFT S2")
|
|
934
|
+
expect("the producer's own declaration is not between",
|
|
935
|
+
check_declaration_order("S3", 2, "S2", 1, [amend(1, scope=("S3",))]), "DECLARATION_DRIFT S3")
|
|
936
|
+
expect("producer invalidated", check_declaration_order("S2", 1, "S1", 0, [amend(1, invalidates=("S1",))]),
|
|
937
|
+
"INPUT_STALE S1")
|
|
938
|
+
expect("amendment does not list the consumer",
|
|
939
|
+
check_declaration_order("S4", 1, "S1", 0, [amend(1, scope=("S2",))]), "DECLARATION_DRIFT S4")
|
|
940
|
+
expect("one amendment licenses the consumer, a later one is about another stage",
|
|
941
|
+
check_declaration_order("S3", 2, "S1", 0, [amend(1, scope=("S3",)), amend(2, scope=("S2",))]))
|
|
942
|
+
expect("the licence comes after an amendment about another stage",
|
|
943
|
+
check_declaration_order("S3", 2, "S1", 0, [amend(1, scope=("S2",)), amend(2, scope=("S3",))]))
|
|
944
|
+
expect("amendments between, none lists the consumer",
|
|
945
|
+
check_declaration_order("S3", 2, "S1", 0, [amend(1, scope=("S2",)), amend(2, scope=("S2",))]),
|
|
946
|
+
"DECLARATION_DRIFT S3", "lists it in scope")
|
|
947
|
+
expect("a licence does not outlive a later invalidation of the producer",
|
|
948
|
+
check_declaration_order("S3", 2, "S1", 0, [amend(1, scope=("S3",)),
|
|
949
|
+
amend(2, scope=("S2",), invalidates=("S1",))]),
|
|
950
|
+
"INPUT_STALE S1")
|
|
951
|
+
expect("consumer read an older declaration than its producer",
|
|
952
|
+
check_declaration_order("S2", 0, "S1", 1, [amend(1)]), "DECLARATION_DRIFT S2")
|
|
953
|
+
|
|
954
|
+
# set accounting (done-when 4)
|
|
955
|
+
expected = expect_set(["a", "b", "c"])
|
|
956
|
+
expect("equal sets", observe_set(expected, [{"id": i, "outcome": "retained"} for i in "abc"]))
|
|
957
|
+
expect("every outcome kind", observe_set(expected, [
|
|
958
|
+
{"id": "a", "outcome": "retained"}, {"id": "m", "outcome": "merged", "members": ["b", "c"]}]))
|
|
959
|
+
expect("rejected with a reason and quarantined", observe_set(expected, [
|
|
960
|
+
{"id": "a", "outcome": "rejected", "reason": "duplicate"}, {"id": "b", "outcome": "quarantined"},
|
|
961
|
+
{"id": "c", "outcome": "retained"}]))
|
|
962
|
+
expect("one id missing", observe_set(expected, [{"id": i, "outcome": "retained"} for i in "ab"]),
|
|
963
|
+
"SET_MISMATCH", "missing=['c']")
|
|
964
|
+
expect("one extra id", observe_set(expected, [{"id": i, "outcome": "retained"} for i in "abcd"]),
|
|
965
|
+
"SET_MISMATCH", "extra=['d']")
|
|
966
|
+
expect("one missing and one extra, both named",
|
|
967
|
+
observe_set(expected, [{"id": i, "outcome": "retained"} for i in "abd"]),
|
|
968
|
+
"missing=['c']", "extra=['d']")
|
|
969
|
+
expect("an id accounted twice",
|
|
970
|
+
observe_set(expected, [{"id": i, "outcome": "retained"} for i in "abcc"]), "repeated=['c']")
|
|
971
|
+
expect("a member also retained", observe_set(expected, [
|
|
972
|
+
{"id": "a", "outcome": "retained"}, {"id": "b", "outcome": "retained"},
|
|
973
|
+
{"id": "m", "outcome": "merged", "members": ["b", "c"]}]), "repeated=['b']")
|
|
974
|
+
expect("merge without members", observe_set(expected, [
|
|
975
|
+
{"id": "a", "outcome": "retained"}, {"id": "b", "outcome": "retained"},
|
|
976
|
+
{"id": "c", "outcome": "merged", "members": []}]), "invalid=['c']")
|
|
977
|
+
expect("rejection without a reason", observe_set(expected, [
|
|
978
|
+
{"id": "a", "outcome": "retained"}, {"id": "b", "outcome": "retained"},
|
|
979
|
+
{"id": "c", "outcome": "rejected"}]), "missing=['c']", "invalid=['c']")
|
|
980
|
+
expect("an outcome outside the four", observe_set(expected, [
|
|
981
|
+
{"id": i, "outcome": "dropped"} for i in "abc"]), "invalid=['a', 'b', 'c']")
|
|
982
|
+
try:
|
|
983
|
+
expect_set(["a", "a"])
|
|
984
|
+
failures.append("an expected set with a repeated id was accepted")
|
|
985
|
+
except Refused as exc:
|
|
986
|
+
expect("repeated expected id", [str(exc)], "SET_MISMATCH")
|
|
987
|
+
|
|
988
|
+
# the failure posture over items (design §4): production quarantines with dependants and goes on
|
|
989
|
+
def item(name, **keys):
|
|
990
|
+
return {"id": name, **keys}
|
|
991
|
+
|
|
992
|
+
batch = [item("A", unit="U1"), item("B", unit="U1", route="R1", test_config="T1"), item("C", route="R1", unit="U5"),
|
|
993
|
+
item("D", test_config="T1"), item("E", unit="U2"), item("F"), item("G", route="R3"), item("X", unit="U5")]
|
|
994
|
+
|
|
995
|
+
def run_batch(posture, items, fails=("B",)):
|
|
996
|
+
calls = []
|
|
997
|
+
|
|
998
|
+
def work(it):
|
|
999
|
+
calls.append(it["id"])
|
|
1000
|
+
if it["id"] in fails:
|
|
1001
|
+
raise ValueError(f"{it['id']} failed")
|
|
1002
|
+
try:
|
|
1003
|
+
return run_items(posture, items, work), calls
|
|
1004
|
+
except Refused as exc: # production that stopped is reported under its own controls, not a crash
|
|
1005
|
+
return ({"done": [], "quarantined": [], "stopped": str(exc)} if posture == "production" else str(exc)), calls
|
|
1006
|
+
|
|
1007
|
+
def run_batch_jobs(posture, items, jobs, fails=("B",)):
|
|
1008
|
+
calls, calls_lock = [], threading.Lock()
|
|
1009
|
+
|
|
1010
|
+
def work(it):
|
|
1011
|
+
with calls_lock:
|
|
1012
|
+
calls.append(it["id"])
|
|
1013
|
+
if it["id"] in fails:
|
|
1014
|
+
raise ValueError(f"{it['id']} failed")
|
|
1015
|
+
try:
|
|
1016
|
+
return run_items(posture, items, work, jobs=jobs), calls
|
|
1017
|
+
except Refused as exc:
|
|
1018
|
+
return ({"done": [], "quarantined": [], "stopped": str(exc)} if posture == "production" else str(exc)), calls
|
|
1019
|
+
|
|
1020
|
+
result, calls = run_batch("production", batch)
|
|
1021
|
+
expect("production: the failing item and its dependants are quarantined, the rest continue",
|
|
1022
|
+
[] if sorted(q["id"] for q in result["quarantined"]) == ["A", "B", "C", "D"]
|
|
1023
|
+
and result["done"] == ["E", "F", "G", "X"] else [f"{result}"])
|
|
1024
|
+
expect("production: a dependant that was not yet run is skipped, not run", [] if "C" not in calls and "D" not in calls
|
|
1025
|
+
else [f"calls {calls}"])
|
|
1026
|
+
expect("production: a dependant already done is moved to the quarantine",
|
|
1027
|
+
[] if "A" in calls and any(q["id"] == "A" and q["because"] == "B" and "unit 'U1'" in q["reason"]
|
|
1028
|
+
for q in result["quarantined"]) else [f"{result}, calls {calls}"])
|
|
1029
|
+
expect("production: the failing item says why and is not its own dependant",
|
|
1030
|
+
[] if {"id": "B", "reason": "ValueError: B failed", "because": None} in result["quarantined"]
|
|
1031
|
+
else [f"{result}"])
|
|
1032
|
+
expect("production: sharing is one hop, a dependant's other unit takes no one else",
|
|
1033
|
+
[] if "X" in result["done"] else [f"{result}"])
|
|
1034
|
+
result, calls = run_batch("production", [item("P"), item("Q"), item("R", unit="U1")], fails=("P",))
|
|
1035
|
+
expect("production: items with no shared key are independent",
|
|
1036
|
+
[] if result["done"] == ["Q", "R"] and [q["id"] for q in result["quarantined"]] == ["P"] else [f"{result}"])
|
|
1037
|
+
result, calls = run_batch("production", batch, fails=())
|
|
1038
|
+
expect("production: no failure, nothing quarantined", [] if result["quarantined"] == [] and len(result["done"]) == 8
|
|
1039
|
+
else [f"{result}"])
|
|
1040
|
+
for posture in ("development", "rehearsal", None):
|
|
1041
|
+
message, calls = run_batch(posture, batch)
|
|
1042
|
+
expect(f"{posture}: the first failure stops by name and nothing after it runs",
|
|
1043
|
+
[message] if isinstance(message, str) else [f"{message}"],
|
|
1044
|
+
f"ITEM_FAILED B ({posture}): ValueError: B failed")
|
|
1045
|
+
if calls != ["A", "B"]:
|
|
1046
|
+
failures.append(f"{posture}: work continued past the failure: {calls}")
|
|
1047
|
+
message, _calls = run_batch("production", [item("A"), item("A")])
|
|
1048
|
+
expect("items with a repeated id", [message] if isinstance(message, str) else [f"{message}"], "SET_MISMATCH")
|
|
1049
|
+
|
|
1050
|
+
# W r2, F2: a refusal that stops the run is not an item's failure, under production too
|
|
1051
|
+
stopped_calls = []
|
|
1052
|
+
|
|
1053
|
+
def run_stops(it):
|
|
1054
|
+
stopped_calls.append(it["id"])
|
|
1055
|
+
if it["id"] == "B":
|
|
1056
|
+
raise RunStopped("CLAIM_EXCEEDED r-S3-B-a1: 3 main requests, at most 2")
|
|
1057
|
+
for posture, jobs in (("production", 1), ("production", 4), ("development", 1)):
|
|
1058
|
+
stopped_calls.clear()
|
|
1059
|
+
try:
|
|
1060
|
+
run_items(posture, batch, run_stops, jobs=jobs)
|
|
1061
|
+
raised = None
|
|
1062
|
+
except RunStopped as exc:
|
|
1063
|
+
raised = str(exc)
|
|
1064
|
+
except Exception as exc: # noqa: BLE001 - a quarantine or another refusal fails the control by name
|
|
1065
|
+
raised = f"{type(exc).__name__}: {exc}"
|
|
1066
|
+
expect(f"W r2 F2: a run stop raised by an item ends run_items as itself under {posture}, {jobs} at a time, "
|
|
1067
|
+
"and quarantines nothing",
|
|
1068
|
+
[] if raised == "CLAIM_EXCEEDED r-S3-B-a1: 3 main requests, at most 2"
|
|
1069
|
+
and (jobs > 1 or stopped_calls == ["A", "B"]) else [f"{raised} calls {stopped_calls}"])
|
|
1070
|
+
|
|
1071
|
+
# the lead's verification of commit 4, finding 3: every handler a RunStopped can meet re-raises it or is named here
|
|
1072
|
+
# with its reason. A module is scanned when its code names RunStopped or a supervisor - the only places one is
|
|
1073
|
+
# raised or passes; census and views run stages through `run_stage` and `run_items` with no supervisor, so none
|
|
1074
|
+
# arises in them. A site re-raising by structure (`broad_handlers`) needs no entry; an unnamed one fails by name.
|
|
1075
|
+
cannot_see = "its try body calls no supervisor, item or stage, so no RunStopped is raised inside it"
|
|
1076
|
+
stop_sites = {
|
|
1077
|
+
"dispatch:Supervisor._stop_run:Exception#1": f"taking the declaration lock; {cannot_see}",
|
|
1078
|
+
"dispatch:Supervisor._stop_run:Exception#2": f"reading the declaration to stamp the stop; {cannot_see}",
|
|
1079
|
+
"dispatch:Supervisor._stop_run:Exception#3": f"stamping the stop, this code's arithmetic; {cannot_see}",
|
|
1080
|
+
"dispatch:Supervisor._now:Exception#1": f"the run's clock; {cannot_see}",
|
|
1081
|
+
"dispatch:Supervisor._now:Exception#2": f"the fallback clock; {cannot_see}",
|
|
1082
|
+
"dispatch:Supervisor._rows_snapshot:Exception#1": f"copying the monitor's rows; {cannot_see}",
|
|
1083
|
+
"dispatch:Supervisor._offer_stop:Exception#1": "deciding and recording one obligation's stop (_bound_entry, "
|
|
1084
|
+
f"_claim_entry, _stop_run), which raise none; {cannot_see}",
|
|
1085
|
+
"dispatch:Supervisor._bound_entry:Exception#1": f"serializing the stop entry; {cannot_see}",
|
|
1086
|
+
"dispatch:Supervisor._record_stop:Exception#1": f"writing the call's own record of its stop; {cannot_see}",
|
|
1087
|
+
"dispatch:Supervisor.call:OSError|Refused#1": f"reading the server policy record; {cannot_see}",
|
|
1088
|
+
"dispatch:Supervisor.call:Exception#1": "offering the stop on the failure path; _offer_stop raises none and the "
|
|
1089
|
+
"enclosing handler re-raises the original failure",
|
|
1090
|
+
"dispatch:Supervisor.item:Refused#1": f"building the expected packet to size the reservation; {cannot_see}",
|
|
1091
|
+
"dispatch:Supervisor.reusable:Refused#1": f"the gate's refusal of an earlier attempt; {cannot_see}",
|
|
1092
|
+
"stage_form:origin_of:Refused#1": f"storing an origin block as evidence; {cannot_see}",
|
|
1093
|
+
"stage_read:keep:Refused#1": f"locating one quote in the view; {cannot_see}",
|
|
1094
|
+
}
|
|
1095
|
+
import ast as _ast
|
|
1096
|
+
here = pathlib.Path(__file__).resolve().parent
|
|
1097
|
+
suite_src = ("def _self_test_body(failures, ran):\n try:\n pass\n except Refused:\n pass\n"
|
|
1098
|
+
"def run():\n try:\n pass\n except Refused:\n pass\n")
|
|
1099
|
+
expect("a handler in a suite's delegated body is the suite's, and the same handler in production code is not",
|
|
1100
|
+
[] if [key for key, _r in broad_handlers(suite_src, "m")] == ["m:run:Refused#1"]
|
|
1101
|
+
else [f"{broad_handlers(suite_src, 'm')}"])
|
|
1102
|
+
|
|
1103
|
+
def stop_modules(read):
|
|
1104
|
+
"""The runlib modules whose code names RunStopped or a supervisor: `{stem: source}`."""
|
|
1105
|
+
out = {}
|
|
1106
|
+
for path in sorted(here.glob("*.py")):
|
|
1107
|
+
src = read(path)
|
|
1108
|
+
tree = _ast.parse(src)
|
|
1109
|
+
ids = ({n.attr for n in _ast.walk(tree) if isinstance(n, _ast.Attribute)}
|
|
1110
|
+
| {n.id for n in _ast.walk(tree) if isinstance(n, _ast.Name)})
|
|
1111
|
+
if ids & {"RunStopped", "Supervisor", "supervisor"}:
|
|
1112
|
+
out[path.stem] = src
|
|
1113
|
+
return out
|
|
1114
|
+
|
|
1115
|
+
def stop_site_problems(modules, named):
|
|
1116
|
+
found = [site for stem, src in modules.items() for site in broad_handlers(src, stem)]
|
|
1117
|
+
unnamed = [key for key, reraises in found if not reraises and key not in named]
|
|
1118
|
+
stale = sorted(set(named) - {key for key, reraises in found if not reraises})
|
|
1119
|
+
return ([f"STOP_HANDLER_UNNAMED {key}: catches a RunStopped and neither re-raises it nor is named" for key in unnamed]
|
|
1120
|
+
+ [f"STOP_HANDLER_STALE {key}: named, and no handler that keeps a RunStopped is there" for key in stale]
|
|
1121
|
+
+ ([] if found else ["STOP_HANDLER_NONE: the scan found no handler at all"]))
|
|
1122
|
+
live_modules = stop_modules(lambda path: path.read_text(encoding="utf-8"))
|
|
1123
|
+
expect("lead v4 3: the modules a RunStopped passes through are scanned - dispatch, records, stage_form, stage_read",
|
|
1124
|
+
[] if {"dispatch", "records", "stage_form", "stage_read"} <= set(live_modules) else [sorted(live_modules)])
|
|
1125
|
+
expect("lead v4 3: every handler a RunStopped can meet re-raises it or is named with its reason",
|
|
1126
|
+
stop_site_problems(live_modules, stop_sites))
|
|
1127
|
+
reraising = [key for stem, src in live_modules.items() for key, rr in broad_handlers(src, stem) if rr]
|
|
1128
|
+
expect("lead v4 3: the re-raising sites are found as such - run_items' two sequences, run_stage, the call's own",
|
|
1129
|
+
[] if {"records:_run_sequence:Exception#1", "records:run_items.sequence:Refused#1",
|
|
1130
|
+
"records:run_stage:BaseException#1", "dispatch:Supervisor.call:BaseException#1"} <= set(reraising)
|
|
1131
|
+
else [sorted(reraising)])
|
|
1132
|
+
planted = dict(live_modules)
|
|
1133
|
+
planted["dispatch"] = planted["dispatch"].replace(
|
|
1134
|
+
" except breakers.Deferred as exc:\n return {\"item\": item, \"outcome\": \"deferred\"",
|
|
1135
|
+
" except Refused:\n return None\n except breakers.Deferred as exc:\n"
|
|
1136
|
+
" return {\"item\": item, \"outcome\": \"deferred\"", 1)
|
|
1137
|
+
expect("control, lead v4 3: a handler planted around the supervisor's call that swallows a refusal fails by name",
|
|
1138
|
+
stop_site_problems(planted, stop_sites) if planted["dispatch"] != live_modules["dispatch"] else ["not planted"],
|
|
1139
|
+
"STOP_HANDLER_UNNAMED dispatch:Supervisor.item:Refused#2")
|
|
1140
|
+
unpassed = dict(live_modules)
|
|
1141
|
+
unpassed["records"] = unpassed["records"].replace(
|
|
1142
|
+
" except RunStopped:\n if stop is not None:\n stop.set()\n raise\n", "", 1)
|
|
1143
|
+
expect("control, lead v4 3: _run_sequence without its RunStopped pass fails by name - its Exception handler then "
|
|
1144
|
+
"keeps the stop",
|
|
1145
|
+
stop_site_problems(unpassed, stop_sites) if unpassed["records"] != live_modules["records"] else ["not planted"],
|
|
1146
|
+
"STOP_HANDLER_UNNAMED records:_run_sequence:Exception#1")
|
|
1147
|
+
expect("control, lead v4 3: a named site that no longer keeps a RunStopped is stale, by name",
|
|
1148
|
+
stop_site_problems(live_modules, {**stop_sites, "dispatch:Supervisor.gone:Refused#1": "x"}),
|
|
1149
|
+
"STOP_HANDLER_STALE dispatch:Supervisor.gone:Refused#1")
|
|
1150
|
+
expect("control, lead v4 3: a scan over nothing reports nothing found", stop_site_problems({}, {}),
|
|
1151
|
+
"STOP_HANDLER_NONE")
|
|
1152
|
+
|
|
1153
|
+
# WP-08 commit 5b: items run `jobs` at a time under the same rules
|
|
1154
|
+
one_at_a_time, calls_one = run_batch("production", batch)
|
|
1155
|
+
side_by_side, calls_many = run_batch_jobs("production", batch, 4)
|
|
1156
|
+
expect("jobs: production over the batch four at a time quarantines and keeps what one at a time does, in its order",
|
|
1157
|
+
[] if side_by_side == one_at_a_time else [f"{side_by_side} != {one_at_a_time}"])
|
|
1158
|
+
expect("jobs: a dependant not yet run is skipped four at a time too, because items that share run in one sequence",
|
|
1159
|
+
[] if "C" not in calls_many and "D" not in calls_many and sorted(calls_many) == sorted(calls_one)
|
|
1160
|
+
else [f"calls {calls_many}"])
|
|
1161
|
+
expect("jobs: the sequences are the items joined by a shared key, directly or through others, in items order",
|
|
1162
|
+
[] if [[i["id"] for i in g] for g in sharing_groups(batch)] == [["A", "B", "C", "D", "X"], ["E"], ["F"], ["G"]]
|
|
1163
|
+
else [f"{[[i['id'] for i in g] for g in sharing_groups(batch)]}"])
|
|
1164
|
+
both_running = {"B": threading.Event(), "F": threading.Event()}
|
|
1165
|
+
many_fail_calls, many_fail_lock = [], threading.Lock()
|
|
1166
|
+
|
|
1167
|
+
def two_fail(it):
|
|
1168
|
+
with many_fail_lock:
|
|
1169
|
+
many_fail_calls.append(it["id"])
|
|
1170
|
+
if it["id"] in both_running: # B and F each fail only once the other runs: both failures are made
|
|
1171
|
+
both_running[it["id"]].set()
|
|
1172
|
+
both_running["F" if it["id"] == "B" else "B"].wait(timeout=30)
|
|
1173
|
+
raise ValueError(f"{it['id']} failed")
|
|
1174
|
+
try:
|
|
1175
|
+
run_items("development", batch, two_fail, jobs=4)
|
|
1176
|
+
many_fail = "ran through"
|
|
1177
|
+
except Refused as exc:
|
|
1178
|
+
many_fail = str(exc)
|
|
1179
|
+
expect("jobs: under development four at a time the earliest failure in items order is named",
|
|
1180
|
+
[many_fail] if isinstance(many_fail, str) else [f"{many_fail}"], "ITEM_FAILED B (development): ValueError: B failed")
|
|
1181
|
+
expect("jobs: and nothing of the failing sequence runs after its failure",
|
|
1182
|
+
[] if "C" not in many_fail_calls and "D" not in many_fail_calls and "X" not in many_fail_calls
|
|
1183
|
+
else [f"calls {many_fail_calls}"])
|
|
1184
|
+
widest, in_flight, flight_lock, thirteen = [0], [0], threading.Lock(), []
|
|
1185
|
+
gate_12, gate_13 = threading.Barrier(12), threading.Barrier(13)
|
|
1186
|
+
|
|
1187
|
+
def flying(it):
|
|
1188
|
+
with flight_lock:
|
|
1189
|
+
in_flight[0] += 1
|
|
1190
|
+
widest[0] = max(widest[0], in_flight[0])
|
|
1191
|
+
try:
|
|
1192
|
+
if int(it["id"][1:]) < 13: # thirteen at once would meet here; twelve workers wait it out and it breaks
|
|
1193
|
+
try:
|
|
1194
|
+
gate_13.wait(timeout=2)
|
|
1195
|
+
thirteen.append(it["id"])
|
|
1196
|
+
except threading.BrokenBarrierError:
|
|
1197
|
+
pass
|
|
1198
|
+
if int(it["id"][1:]) < 12: # the first twelve meet: only twelve running at once can pass
|
|
1199
|
+
gate_12.wait(timeout=30)
|
|
1200
|
+
finally:
|
|
1201
|
+
with flight_lock:
|
|
1202
|
+
in_flight[0] -= 1
|
|
1203
|
+
try:
|
|
1204
|
+
flown = run_items("production", [item(f"i{n}") for n in range(30)], flying, jobs=12)
|
|
1205
|
+
except Refused as exc:
|
|
1206
|
+
flown = {"done": [], "quarantined": [], "refused": str(exc)}
|
|
1207
|
+
expect("jobs: twelve at a time runs twelve independent items at once and never a thirteenth",
|
|
1208
|
+
[] if widest[0] == 12 and not thirteen and len(flown["done"]) == 30 and not flown["quarantined"]
|
|
1209
|
+
else [f"widest {widest[0]}, thirteen met {thirteen}, {flown}"])
|
|
1210
|
+
stopped, q1_running, ran_after = threading.Event(), threading.Event(), []
|
|
1211
|
+
|
|
1212
|
+
def failing_first(it):
|
|
1213
|
+
if it["id"] == "P":
|
|
1214
|
+
q1_running.wait(timeout=30) # P fails while Q1 runs
|
|
1215
|
+
raise ValueError("P failed")
|
|
1216
|
+
if it["id"] == "Q1":
|
|
1217
|
+
q1_running.set()
|
|
1218
|
+
stopped.wait(timeout=30) # Q1 outlasts the failure: run_items sets the stop when P fails
|
|
1219
|
+
ran_after.append(it["id"])
|
|
1220
|
+
try:
|
|
1221
|
+
run_items("development", [item("P", unit="UP"), item("Q1", unit="UQ"), item("Q2", unit="UQ")], failing_first,
|
|
1222
|
+
jobs=2, stop=stopped)
|
|
1223
|
+
stop_message = "ran through"
|
|
1224
|
+
except Refused as exc:
|
|
1225
|
+
stop_message = str(exc)
|
|
1226
|
+
expect("jobs: under development a failure lets no item start after it, in any sequence",
|
|
1227
|
+
[] if stop_message.startswith("ITEM_FAILED P ") and stopped.is_set() and ran_after == ["Q1"]
|
|
1228
|
+
else [f"{stop_message} stopped={stopped.is_set()} ran {ran_after}"])
|
|
1229
|
+
for bad_jobs in (0, True, "2"):
|
|
1230
|
+
try:
|
|
1231
|
+
run_items("production", [item("A")], lambda it: None, jobs=bad_jobs)
|
|
1232
|
+
got_jobs = "ran"
|
|
1233
|
+
except Refused as exc:
|
|
1234
|
+
got_jobs = str(exc)
|
|
1235
|
+
expect(f"jobs: {bad_jobs!r} is refused", [got_jobs], "ITEMS_JOBS_INVALID")
|
|
1236
|
+
|
|
1237
|
+
def interrupted(it):
|
|
1238
|
+
raise KeyboardInterrupt
|
|
1239
|
+
try:
|
|
1240
|
+
run_items("production", [item("A")], interrupted)
|
|
1241
|
+
failures.append("an interrupt was quarantined as an item failure")
|
|
1242
|
+
except KeyboardInterrupt:
|
|
1243
|
+
pass
|
|
1244
|
+
|
|
1245
|
+
# a record ends at "\n" only; JSON allows U+2028 and U+2029 raw inside a string, and
|
|
1246
|
+
# str.splitlines() would cut there
|
|
1247
|
+
with tempfile.TemporaryDirectory() as td:
|
|
1248
|
+
held = {"seq": 0, "reason": "before\u2028between\u2029after"}
|
|
1249
|
+
amendments_path(td).write_text(json.dumps(held, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
1250
|
+
try:
|
|
1251
|
+
got = read_log(td)
|
|
1252
|
+
except Refused as exc:
|
|
1253
|
+
got = str(exc)
|
|
1254
|
+
if got != [held]:
|
|
1255
|
+
failures.append(f"jsonl-line-separators-inside-a-string-read-whole (read_log): {got!r}")
|
|
1256
|
+
# a bare CR is JSON whitespace, which text-mode reading would turn into a line break; CRLF still ends a record
|
|
1257
|
+
later = {"seq": 1, "reason": "after a bare CR"}
|
|
1258
|
+
amendments_path(td).write_bytes(("{\r" + json.dumps(held)[1:] + "\r\n" + json.dumps(later) + "\n").encode("utf-8"))
|
|
1259
|
+
try:
|
|
1260
|
+
got = read_log(td)
|
|
1261
|
+
except Refused as exc:
|
|
1262
|
+
got = str(exc)
|
|
1263
|
+
if got != [held, later]:
|
|
1264
|
+
failures.append(f"jsonl-bare-cr-whitespace-and-crlf-read-whole (read_log): {got!r}")
|
|
1265
|
+
|
|
1266
|
+
# stage records on real files under a scratch run directory
|
|
1267
|
+
with tempfile.TemporaryDirectory() as td:
|
|
1268
|
+
run_dir = pathlib.Path(td) / "r1"
|
|
1269
|
+
def by_hand(path, obj):
|
|
1270
|
+
"""An edit made outside the driver: no lock, no binding, no confinement."""
|
|
1271
|
+
pathlib.Path(path).write_text(json_text(obj), encoding="utf-8")
|
|
1272
|
+
|
|
1273
|
+
def declare_fixture(directory, run):
|
|
1274
|
+
"""A declaration as `declare` leaves it: the seq-0 binding in the log, then run.json."""
|
|
1275
|
+
append_amendment(directory, {"seq": 0, "at": now(), "reason": "declaration", "scope": [],
|
|
1276
|
+
"invalidates": [], "diff": {}, "run_json_sha256": bound_digest(run)})
|
|
1277
|
+
write_json(directory, run_json_path(directory), run)
|
|
1278
|
+
|
|
1279
|
+
def amend_fixture(directory, run, entry):
|
|
1280
|
+
"""An amendment as `declare` leaves it: the log line binding the new run.json, then run.json."""
|
|
1281
|
+
append_amendment(directory, {**entry, "run_json_sha256": bound_digest(run)})
|
|
1282
|
+
write_json(directory, run_json_path(directory), run)
|
|
1283
|
+
|
|
1284
|
+
base = {"declaration_seq": 0, "question": "fixture", "posture": "production"}
|
|
1285
|
+
declare_fixture(run_dir, base)
|
|
1286
|
+
|
|
1287
|
+
def start(stage, inputs=(), part=None):
|
|
1288
|
+
try:
|
|
1289
|
+
with run_stage(run_dir, stage, inputs, part=part) as st:
|
|
1290
|
+
(run_dir / f"{stage}.out").write_text(f"{stage} output\n", encoding="utf-8")
|
|
1291
|
+
st.output(f"{stage}.out")
|
|
1292
|
+
return []
|
|
1293
|
+
except Refused as exc:
|
|
1294
|
+
return str(exc).splitlines()
|
|
1295
|
+
except stagelock.Locked:
|
|
1296
|
+
raise
|
|
1297
|
+
except Exception as exc: # a reverted check fails by its control's name, not by a traceback
|
|
1298
|
+
return [f"RAISED {exc!r}"]
|
|
1299
|
+
|
|
1300
|
+
def part_run_elsewhere(directory):
|
|
1301
|
+
"""A part named for a stage that declares none: refused by name."""
|
|
1302
|
+
try:
|
|
1303
|
+
with run_stage(directory, "S1", part="views"):
|
|
1304
|
+
pass
|
|
1305
|
+
return []
|
|
1306
|
+
except Refused as exc:
|
|
1307
|
+
return str(exc).splitlines()
|
|
1308
|
+
|
|
1309
|
+
def start_in(other_dir, stage="S1", inputs=()):
|
|
1310
|
+
try:
|
|
1311
|
+
with run_stage(other_dir, stage, inputs):
|
|
1312
|
+
pass
|
|
1313
|
+
return []
|
|
1314
|
+
except Refused as exc:
|
|
1315
|
+
return str(exc).splitlines()
|
|
1316
|
+
except Exception as exc:
|
|
1317
|
+
return [f"RAISED {exc!r}"]
|
|
1318
|
+
|
|
1319
|
+
def produce(stage, status="complete"):
|
|
1320
|
+
with run_stage(run_dir, stage) as st:
|
|
1321
|
+
(run_dir / f"{stage}.out").write_text(f"{stage} output\n", encoding="utf-8")
|
|
1322
|
+
st.output(f"{stage}.out")
|
|
1323
|
+
st.record["status"] = status
|
|
1324
|
+
return read_json(record_path(run_dir, stage))
|
|
1325
|
+
|
|
1326
|
+
first = produce("S1")
|
|
1327
|
+
expect("stage record fields", [k for k in ("stage", "run_json_sha256", "declaration_seq", "started", "ended",
|
|
1328
|
+
"status", "inputs", "outputs", "calls", "quarantined", "usage")
|
|
1329
|
+
if k not in first])
|
|
1330
|
+
if first["status"] != "complete" or first["run_json_sha256"] != sha256_file(run_json_path(run_dir)):
|
|
1331
|
+
failures.append(f"S1 record does not pin the declaration it read: {first}")
|
|
1332
|
+
expect("complete input accepted", start("S3", [{"artifact": "S1.out", "producer_stage": "S1"}]))
|
|
1333
|
+
# Guard the subject: when the run above was refused there is no record to read, and the
|
|
1334
|
+
# control that named the refusal has already fired.
|
|
1335
|
+
pinned = (read_json(record_path(run_dir, "S3")).get("inputs")
|
|
1336
|
+
if record_path(run_dir, "S3").is_file() else "no S3 record was written")
|
|
1337
|
+
if pinned != [{"artifact": "S1.out", "sha256": sha256_file(run_dir / "S1.out"),
|
|
1338
|
+
"producer_stage": "S1", "producer_seq": 0}]:
|
|
1339
|
+
failures.append(f"S3 record does not pin its input: {pinned}")
|
|
1340
|
+
produce("S4", status="partial")
|
|
1341
|
+
expect("partial input is refused under the production posture", start("S5", [{"artifact": "S4.out", "producer_stage": "S4"}]), "INPUT_PARTIAL S4")
|
|
1342
|
+
expect("no producer record", start("S7", [{"artifact": "S6.out", "producer_stage": "S6"}]), "INPUT_INVALID S6")
|
|
1343
|
+
(run_dir / "S1.out").write_text("tampered\n", encoding="utf-8")
|
|
1344
|
+
expect("input changed since its producer recorded it",
|
|
1345
|
+
start("S3", [{"artifact": "S1.out", "producer_stage": "S1"}]), "INPUT_INVALID S1")
|
|
1346
|
+
(run_dir / "S1.out").write_text("S1 output\n", encoding="utf-8")
|
|
1347
|
+
try:
|
|
1348
|
+
with run_stage(run_dir, "S6"):
|
|
1349
|
+
raise RuntimeError("stage failed")
|
|
1350
|
+
except RuntimeError:
|
|
1351
|
+
pass
|
|
1352
|
+
if read_json(record_path(run_dir, "S6"))["status"] != "failed":
|
|
1353
|
+
failures.append("a stage that raised was not recorded failed")
|
|
1354
|
+
expect("failed input", start("S8", [{"artifact": "S6.out", "producer_stage": "S6"}]), "INPUT_INVALID S6")
|
|
1355
|
+
expect("unknown stage", start("S0"), "STAGE_UNKNOWN S0")
|
|
1356
|
+
# W review of WP-09 r1, F2 (lead decision): a producer's own inputs are held to what the consumer admits
|
|
1357
|
+
prov = pathlib.Path(td) / "prov"
|
|
1358
|
+
declare_fixture(prov, base)
|
|
1359
|
+
|
|
1360
|
+
def made(stage, inputs, text):
|
|
1361
|
+
with run_stage(prov, stage, inputs) as st:
|
|
1362
|
+
(prov / f"{stage}.out").write_text(text, encoding="utf-8")
|
|
1363
|
+
st.output(f"{stage}.out")
|
|
1364
|
+
both = [{"artifact": "S3.out", "producer_stage": "S3"}, {"artifact": "S1.out", "producer_stage": "S1"}]
|
|
1365
|
+
made("S1", [], "census as S3 read it\n")
|
|
1366
|
+
made("S3", [{"artifact": "S1.out", "producer_stage": "S1"}], "results over that census\n")
|
|
1367
|
+
expect("a consumer admitting what its producer read is admitted", start_in(prov, "S4", both))
|
|
1368
|
+
made("S1", [], "census made again at the same sequence\n")
|
|
1369
|
+
expect("a producer run again at the same sequence under its consumer's other input is INPUT_STALE",
|
|
1370
|
+
start_in(prov, "S4", both), "INPUT_STALE S3: it read S1.out")
|
|
1371
|
+
expect("an input whose producer read nothing the consumer admits is held to its own record alone",
|
|
1372
|
+
start_in(prov, "S4", [{"artifact": "S3.out", "producer_stage": "S3"}]))
|
|
1373
|
+
# a declaration edited outside `declare`: same sequence, different bytes
|
|
1374
|
+
by_hand(run_json_path(run_dir), {**base, "question": "edited by hand"})
|
|
1375
|
+
expect("run.json edited without an amendment", start("S9"), "DECLARATION_DRIFT S9")
|
|
1376
|
+
by_hand(run_json_path(run_dir), base)
|
|
1377
|
+
expect("restored declaration", start("S9"))
|
|
1378
|
+
# a sequence that outran the amendment log
|
|
1379
|
+
by_hand(run_json_path(run_dir), {**base, "declaration_seq": 1})
|
|
1380
|
+
expect("declaration_seq ahead of the declaration log", start("S9b"), "DECLARATION_DRIFT S9b",
|
|
1381
|
+
"but the declaration log ends at 0")
|
|
1382
|
+
amend_fixture(run_dir, {**base, "declaration_seq": 1}, amend(1, scope=("S10",)))
|
|
1383
|
+
expect("amendment licenses S10, producer S1 not invalidated",
|
|
1384
|
+
start("S10", [{"artifact": "S1.out", "producer_stage": "S1"}], part="parse"))
|
|
1385
|
+
# S10 has parts (STAGE_PARTS), so its pinned inputs are its part's
|
|
1386
|
+
held_s10 = read_json(record_path(run_dir, "S10")) if record_path(run_dir, "S10").is_file() else {}
|
|
1387
|
+
pinned_s10 = ((held_s10.get("parts") or {}).get("parse") or held_s10).get("inputs") or []
|
|
1388
|
+
if [row.get("producer_seq") for row in pinned_s10] != [0]:
|
|
1389
|
+
failures.append(f"S10 pinned its producer's sequence as its own: {pinned_s10}")
|
|
1390
|
+
# S10b has parts too (STAGE_PARTS), so the start names one; the declaration is judged before the part is
|
|
1391
|
+
expect("amendment does not list S10b",
|
|
1392
|
+
start("S10b", [{"artifact": "S1.out", "producer_stage": "S1"}], part="build"), "DECLARATION_DRIFT S10b")
|
|
1393
|
+
# a log that is not a numbered sequence, or not readable, is named
|
|
1394
|
+
good_log = amendments_path(run_dir).read_text(encoding="utf-8")
|
|
1395
|
+
amendments_path(run_dir).write_text(good_log.splitlines()[0] + "\n" + json.dumps(amend(2)) + "\n", encoding="utf-8")
|
|
1396
|
+
expect("declaration log skips a number", start("S12"), "DECLARATION_DRIFT S12", "not numbered 0..1")
|
|
1397
|
+
amendments_path(run_dir).write_text("", encoding="utf-8")
|
|
1398
|
+
expect("declaration log without a seq-0 entry", start("S12"), "DECLARATION_DRIFT S12", "no declaration is bound")
|
|
1399
|
+
amendments_path(run_dir).write_text("{not json\n", encoding="utf-8")
|
|
1400
|
+
try:
|
|
1401
|
+
read_amendments(run_dir)
|
|
1402
|
+
failures.append("an unreadable amendment log was read")
|
|
1403
|
+
except Refused as exc:
|
|
1404
|
+
expect("unreadable amendment log", [str(exc)], "RECORD_UNREADABLE")
|
|
1405
|
+
expect("no declaration at all", start_in(pathlib.Path(td) / "r2"), "RUN_UNDECLARED")
|
|
1406
|
+
amendments_path(run_dir).write_text(good_log, encoding="utf-8")
|
|
1407
|
+
# a held stage lock refuses a second runner by name
|
|
1408
|
+
with stagelock.hold(run_dir, "stage-S12"):
|
|
1409
|
+
try:
|
|
1410
|
+
start("S12")
|
|
1411
|
+
failures.append("a stage started while its lock was held")
|
|
1412
|
+
except stagelock.Locked as exc:
|
|
1413
|
+
expect("held stage lock", [str(exc)], "STAGE_LOCKED stage-S12")
|
|
1414
|
+
# a declaration being written holds a stage back: it neither reads nor pins half an amendment
|
|
1415
|
+
with stagelock.hold(run_dir, "declaration"):
|
|
1416
|
+
try:
|
|
1417
|
+
start("S12")
|
|
1418
|
+
failures.append("a stage started while the declaration lock was held")
|
|
1419
|
+
except stagelock.Locked as exc:
|
|
1420
|
+
expect("held declaration lock", [str(exc)], "STAGE_LOCKED declaration")
|
|
1421
|
+
# an unreadable record is named, not skipped
|
|
1422
|
+
record_path(run_dir, "S12").parent.mkdir(parents=True)
|
|
1423
|
+
record_path(run_dir, "S12").write_text("{not json", encoding="utf-8")
|
|
1424
|
+
try:
|
|
1425
|
+
stage_records(run_dir)
|
|
1426
|
+
failures.append("an unreadable stage record was skipped")
|
|
1427
|
+
except Refused as exc:
|
|
1428
|
+
expect("unreadable record", [str(exc)], "RECORD_UNREADABLE")
|
|
1429
|
+
|
|
1430
|
+
# a rerun checks the stage's own previous pin before it replaces the record
|
|
1431
|
+
again = pathlib.Path(td) / "r5"
|
|
1432
|
+
declare_fixture(again, base)
|
|
1433
|
+
expect("first run of the only stage", start_in(again, "S1"))
|
|
1434
|
+
expect("rerun under the unchanged declaration", start_in(again, "S1"))
|
|
1435
|
+
by_hand(run_json_path(again), {**base, "question": "edited by hand"})
|
|
1436
|
+
pin = record_path(again, "S1").read_bytes()
|
|
1437
|
+
expect("the only recorded stage rerun after an unamended edit", start_in(again, "S1"), "DECLARATION_DRIFT S1")
|
|
1438
|
+
if record_path(again, "S1").read_bytes() != pin:
|
|
1439
|
+
failures.append("the refused rerun overwrote the pin it was checked against")
|
|
1440
|
+
|
|
1441
|
+
# a declaration seq is bound to the run.json authorized at it, not to what a stage happened to read
|
|
1442
|
+
def amended_run(name):
|
|
1443
|
+
directory = pathlib.Path(td) / name
|
|
1444
|
+
declare_fixture(directory, {**base, "checks": {"view_complete_share_min": 0.9}})
|
|
1445
|
+
with run_stage(directory, "S3") as stage_run:
|
|
1446
|
+
(directory / "S3.out").write_text("S3 output\n", encoding="utf-8")
|
|
1447
|
+
stage_run.output("S3.out")
|
|
1448
|
+
amend_fixture(directory, {**base, "checks": {"view_complete_share_min": 0.9}, "declaration_seq": 1,
|
|
1449
|
+
"budget": {"reserve": 0.2}}, amend(1, scope=("S4",))) # a budget amendment: nobody invalidated
|
|
1450
|
+
return directory
|
|
1451
|
+
|
|
1452
|
+
consume_s3 = [{"artifact": "S3.out", "producer_stage": "S3"}]
|
|
1453
|
+
clean = amended_run("r7")
|
|
1454
|
+
expect("a clean amended run lets the next stage consume across the amendment",
|
|
1455
|
+
start_in(clean, "S4", consume_s3))
|
|
1456
|
+
edited = amended_run("r8")
|
|
1457
|
+
run_before, s3_before = run_json_path(edited).read_bytes(), record_path(edited, "S3").read_bytes()
|
|
1458
|
+
hand_edited = read_json(run_json_path(edited))
|
|
1459
|
+
hand_edited["checks"]["view_complete_share_min"] = 0.5 # the criteria, by hand; the seq stays 1
|
|
1460
|
+
by_hand(run_json_path(edited), hand_edited)
|
|
1461
|
+
expect("a hand edit of checks before any stage at the new seq", start_in(edited, "S4", consume_s3),
|
|
1462
|
+
"DECLARATION_DRIFT S4: run.json is not the declaration authorized at seq 1")
|
|
1463
|
+
if record_path(edited, "S4").exists() or record_path(edited, "S3").read_bytes() != s3_before:
|
|
1464
|
+
failures.append("the refused stage start wrote or overwrote a record")
|
|
1465
|
+
run_json_path(edited).write_bytes(run_before)
|
|
1466
|
+
expect("the authorized run.json lets the stage start again", start_in(edited, "S4", consume_s3))
|
|
1467
|
+
|
|
1468
|
+
# the run directory is a boundary: an artifact outside it is refused for that reason alone,
|
|
1469
|
+
# every one of them existing and matching the hash its producer recorded
|
|
1470
|
+
bound = pathlib.Path(td) / "r6"
|
|
1471
|
+
declare_fixture(bound, base)
|
|
1472
|
+
outside = pathlib.Path(td) / "outside.out"
|
|
1473
|
+
outside.write_text("outside\n", encoding="utf-8")
|
|
1474
|
+
(bound / "sub").mkdir(parents=True)
|
|
1475
|
+
(bound / "sub" / "ok.out").write_text("inside\n", encoding="utf-8")
|
|
1476
|
+
(bound / "sub" / "link.out").symlink_to(outside)
|
|
1477
|
+
expect("first run of the producer", start_in(bound, "S1"))
|
|
1478
|
+
producer = read_json(record_path(bound, "S1"))
|
|
1479
|
+
listed = {"sub/ok.out": sha256_file(bound / "sub" / "ok.out"), "sub/gone.out": sha256_bytes(b"gone"),
|
|
1480
|
+
"../outside.out": sha256_file(outside), str(outside): sha256_file(outside),
|
|
1481
|
+
"sub/link.out": sha256_file(outside)}
|
|
1482
|
+
producer["outputs"] = [{"artifact": name, "sha256": digest} for name, digest in listed.items()]
|
|
1483
|
+
by_hand(record_path(bound, "S1"), producer)
|
|
1484
|
+
|
|
1485
|
+
def consume(name):
|
|
1486
|
+
return start_in(bound, "S3", [{"artifact": name, "producer_stage": "S1"}])
|
|
1487
|
+
|
|
1488
|
+
expect("a contained artifact is accepted", consume("sub/ok.out")) # the positive case, before any escape
|
|
1489
|
+
expect("a contained artifact that is not a file", consume("sub/gone.out"), "INPUT_INVALID S1: sub/gone.out is not a file")
|
|
1490
|
+
for escape in ("../outside.out", str(outside), "sub/link.out"):
|
|
1491
|
+
lines = consume(escape)
|
|
1492
|
+
expect(f"artifact {escape} leaves the run directory", lines, f"INPUT_INVALID S1: {escape} leaves the run directory")
|
|
1493
|
+
if len(lines) != 1:
|
|
1494
|
+
failures.append(f"artifact {escape}: containment was not the only violation: {lines}")
|
|
1495
|
+
with run_stage(bound, "S3") as stage_run:
|
|
1496
|
+
stage_run.output("sub/ok.out")
|
|
1497
|
+
for escape in ("../outside.out", "sub/link.out"):
|
|
1498
|
+
try:
|
|
1499
|
+
with run_stage(bound, "S4") as stage_run:
|
|
1500
|
+
stage_run.output(escape)
|
|
1501
|
+
failures.append(f"output {escape} outside the run directory was recorded")
|
|
1502
|
+
except Refused as exc:
|
|
1503
|
+
expect(f"output {escape} leaves the run directory", [str(exc)], f"OUTPUT_OUTSIDE_RUN {escape}")
|
|
1504
|
+
except Exception as exc:
|
|
1505
|
+
failures.append(f"output {escape} outside the run directory raised {exc!r} instead of being refused")
|
|
1506
|
+
|
|
1507
|
+
# the failure posture inside a stage: production lists the quarantine and completes, development stops
|
|
1508
|
+
def fail_b(it):
|
|
1509
|
+
if it["id"] == "B":
|
|
1510
|
+
raise ValueError("B failed")
|
|
1511
|
+
|
|
1512
|
+
for posture in ("production", "development"):
|
|
1513
|
+
posted = pathlib.Path(td) / f"items-{posture}"
|
|
1514
|
+
declare_fixture(posted, {**base, "posture": posture})
|
|
1515
|
+
try:
|
|
1516
|
+
with run_stage(posted, "S3") as stage_run:
|
|
1517
|
+
stage_run.run_items(batch, fail_b)
|
|
1518
|
+
outcome = "completed"
|
|
1519
|
+
except Refused as exc:
|
|
1520
|
+
outcome = str(exc)
|
|
1521
|
+
recorded = read_json(record_path(posted, "S3"))
|
|
1522
|
+
if posture == "production":
|
|
1523
|
+
expect("stage in production: the quarantine is listed in the record and the stage completes",
|
|
1524
|
+
[] if outcome == "completed" and recorded["status"] == "complete"
|
|
1525
|
+
and sorted(q["id"] for q in recorded["quarantined"]) == ["A", "B", "C", "D"]
|
|
1526
|
+
else [f"{outcome} {recorded['status']} {recorded['quarantined']}"])
|
|
1527
|
+
else:
|
|
1528
|
+
expect("stage in development: the first failing item stops the stage by name",
|
|
1529
|
+
[outcome], "ITEM_FAILED B (development)")
|
|
1530
|
+
expect("stage in development: the record says failed and lists no quarantine",
|
|
1531
|
+
[] if recorded["status"] == "failed" and recorded["quarantined"] == [] else [f"{recorded}"])
|
|
1532
|
+
|
|
1533
|
+
# a symlink inside the run directory cannot redirect a metadata write out of it: a clean run
|
|
1534
|
+
# first, then each internal link, each pointing at a fixture-owned target that must stay as it was
|
|
1535
|
+
def escape(action, *args):
|
|
1536
|
+
try:
|
|
1537
|
+
action(*args)
|
|
1538
|
+
return []
|
|
1539
|
+
except stagelock.Escaped as exc:
|
|
1540
|
+
return [str(exc)]
|
|
1541
|
+
except Exception as exc:
|
|
1542
|
+
return [f"RAISED {exc!r}"]
|
|
1543
|
+
|
|
1544
|
+
def under_run(directory, stage):
|
|
1545
|
+
with run_stage(directory, stage):
|
|
1546
|
+
pass
|
|
1547
|
+
|
|
1548
|
+
def link_run(name):
|
|
1549
|
+
directory, target = pathlib.Path(td) / name, pathlib.Path(td) / f"{name}-external"
|
|
1550
|
+
target.mkdir()
|
|
1551
|
+
declare_fixture(directory, base)
|
|
1552
|
+
return directory, target
|
|
1553
|
+
|
|
1554
|
+
clean_dir, clean_target = link_run("r9")
|
|
1555
|
+
expect("a clean run writes its log, locks and stage records", escape(under_run, clean_dir, "S1"))
|
|
1556
|
+
if record_path(clean_dir, "S1").is_file() is not True or list(clean_target.iterdir()):
|
|
1557
|
+
failures.append("the clean run did not write its record inside the run directory")
|
|
1558
|
+
|
|
1559
|
+
dangling, target = link_run("r10")
|
|
1560
|
+
(dangling / "stages").mkdir(exist_ok=True)
|
|
1561
|
+
amendments_path(dangling).unlink()
|
|
1562
|
+
amendments_path(dangling).symlink_to(target / "log.jsonl") # dangling: nothing is there yet
|
|
1563
|
+
expect("a dangling amendments.jsonl", escape(append_amendment, dangling, {"seq": 1}), "RUN_PATH_ESCAPE")
|
|
1564
|
+
if list(target.iterdir()):
|
|
1565
|
+
failures.append(f"a dangling amendments.jsonl was created through: {list(target.iterdir())}")
|
|
1566
|
+
|
|
1567
|
+
kept, target = link_run("r11")
|
|
1568
|
+
external_log = json.dumps({"seq": 0, "run_json_sha256": "outside"}) + "\n" # a log someone else owns
|
|
1569
|
+
(target / "log.jsonl").write_text(external_log, encoding="utf-8")
|
|
1570
|
+
amendments_path(kept).unlink()
|
|
1571
|
+
amendments_path(kept).symlink_to(target / "log.jsonl")
|
|
1572
|
+
expect("an amendments.jsonl linked to an existing external file", escape(append_amendment, kept, {"seq": 1}),
|
|
1573
|
+
"RUN_PATH_ESCAPE")
|
|
1574
|
+
expect("the declaration log rebound through a link", escape(rebind, kept, "0" * 64), "RUN_PATH_ESCAPE")
|
|
1575
|
+
if (target / "log.jsonl").read_text(encoding="utf-8") != external_log or [p.name for p in target.iterdir()] != ["log.jsonl"]:
|
|
1576
|
+
failures.append("an external file behind amendments.jsonl was changed")
|
|
1577
|
+
|
|
1578
|
+
# The swap AFTER confinement: `confine` is made to answer as it would have before a directory on the
|
|
1579
|
+
# way became a link, and the write must still not leave the run (`stagelock.beneath`).
|
|
1580
|
+
swapped, target = link_run("r12b")
|
|
1581
|
+
(swapped / "apply").symlink_to(target)
|
|
1582
|
+
real_confine = stagelock.confine
|
|
1583
|
+
stagelock.confine = lambda run, destination: pathlib.Path(run).resolve() / pathlib.Path(
|
|
1584
|
+
destination).relative_to(run)
|
|
1585
|
+
try:
|
|
1586
|
+
expect("a directory swapped for a link after the path was confined",
|
|
1587
|
+
escape(write_text, swapped, swapped / "apply" / "plan.json", "x"), "RUN_PATH_ESCAPE")
|
|
1588
|
+
finally:
|
|
1589
|
+
stagelock.confine = real_confine
|
|
1590
|
+
if list(target.iterdir()):
|
|
1591
|
+
failures.append(f"a record was written through a directory swapped for a link: {list(target.iterdir())}")
|
|
1592
|
+
|
|
1593
|
+
locks, target = link_run("r12")
|
|
1594
|
+
(locks / "locks").symlink_to(target)
|
|
1595
|
+
expect("a symlinked locks directory", escape(under_run, locks, "S1"), "RUN_PATH_ESCAPE")
|
|
1596
|
+
if list(target.iterdir()):
|
|
1597
|
+
failures.append(f"a lock was created through a symlinked locks directory: {list(target.iterdir())}")
|
|
1598
|
+
|
|
1599
|
+
parent, target = link_run("r13")
|
|
1600
|
+
(parent / "stages").mkdir()
|
|
1601
|
+
(parent / "stages" / "S1").symlink_to(target)
|
|
1602
|
+
expect("a symlinked stages/<stage> parent", escape(under_run, parent, "S1"), "RUN_PATH_ESCAPE")
|
|
1603
|
+
if list(target.iterdir()):
|
|
1604
|
+
failures.append(f"a stage record was written through a symlinked stage directory: {list(target.iterdir())}")
|
|
1605
|
+
|
|
1606
|
+
stages, target = link_run("r14")
|
|
1607
|
+
(stages / "stages").symlink_to(target)
|
|
1608
|
+
expect("a symlinked stages directory", escape(under_run, stages, "S1"), "RUN_PATH_ESCAPE")
|
|
1609
|
+
if list(target.iterdir()):
|
|
1610
|
+
failures.append(f"a stage record was written through a symlinked stages directory: {list(target.iterdir())}")
|
|
1611
|
+
|
|
1612
|
+
# ---- a stage with several producers: one record, one lock, one part each
|
|
1613
|
+
parts_dir = pathlib.Path(td) / "parts"
|
|
1614
|
+
declare_fixture(parts_dir, base)
|
|
1615
|
+
|
|
1616
|
+
def part_run(label, artifact, status="complete", raising=False, body=None):
|
|
1617
|
+
try:
|
|
1618
|
+
with run_stage(parts_dir, "S2", part=label) as st:
|
|
1619
|
+
(parts_dir / artifact).write_text(body or f"{label} output\n", encoding="utf-8")
|
|
1620
|
+
st.output(artifact)
|
|
1621
|
+
st.record["status"] = status
|
|
1622
|
+
if raising:
|
|
1623
|
+
raise RuntimeError(f"{label} failed")
|
|
1624
|
+
except RuntimeError:
|
|
1625
|
+
pass
|
|
1626
|
+
except Refused as exc:
|
|
1627
|
+
return str(exc).splitlines()
|
|
1628
|
+
return []
|
|
1629
|
+
|
|
1630
|
+
expect("the first part of a stage runs", part_run("views", "views.json"))
|
|
1631
|
+
expect("the second part runs beside it", part_run("inventory", "inventory.json"))
|
|
1632
|
+
both = read_json(record_path(parts_dir, "S2"))
|
|
1633
|
+
if sorted(both.get("parts", {})) != ["inventory", "views"]:
|
|
1634
|
+
failures.append(f"the second part clobbered the first: {sorted(both.get('parts', {}))}")
|
|
1635
|
+
both.setdefault("parts", {}).setdefault("views", {"outputs": [], "started": None})
|
|
1636
|
+
both["parts"].setdefault("inventory", {"outputs": [], "started": None})
|
|
1637
|
+
if [o["artifact"] for o in both["parts"]["views"].get("outputs", [])] != ["views.json"]:
|
|
1638
|
+
failures.append(f"the views part lost its own outputs: {sorted(both['parts']['views'])}")
|
|
1639
|
+
if both.get("status") != "complete":
|
|
1640
|
+
failures.append(f"a stage whose every part is complete is not complete: {both.get('status')}")
|
|
1641
|
+
started = both["parts"]["views"].get("started")
|
|
1642
|
+
expect("a part reruns", part_run("inventory", "inventory.json", body="a second inventory\n"))
|
|
1643
|
+
again = read_json(record_path(parts_dir, "S2"))
|
|
1644
|
+
again_parts = again.get("parts", {})
|
|
1645
|
+
if again_parts.get("views") != both["parts"]["views"] or again_parts.get("views", {}).get("started") != started:
|
|
1646
|
+
failures.append("rerunning one part rewrote the other part's entry")
|
|
1647
|
+
if again_parts.get("inventory", {}).get("outputs") == both["parts"]["inventory"].get("outputs"):
|
|
1648
|
+
failures.append("rerunning a part did not replace its own entry")
|
|
1649
|
+
part_run("inventory", "inventory.json", raising=True)
|
|
1650
|
+
derived = read_json(record_path(parts_dir, "S2"))
|
|
1651
|
+
if derived.get("status") != "failed" or derived.get("parts", {}).get("views", {}).get("status") != "complete":
|
|
1652
|
+
failures.append(f"the stage status is not derived from its parts: {derived.get('status')} "
|
|
1653
|
+
f"/ {derived.get('parts', {}).get('views', {}).get('status')}")
|
|
1654
|
+
expect("a downstream input is admitted by the part that produced it",
|
|
1655
|
+
start_in(parts_dir, "S3", [{"artifact": "views.json", "producer_stage": "S2"}]))
|
|
1656
|
+
expect("an artifact no part of the stage produced",
|
|
1657
|
+
start_in(parts_dir, "S4", [{"artifact": "nobody.json", "producer_stage": "S2"}]),
|
|
1658
|
+
"INPUT_INVALID S2", "no part of its record produced")
|
|
1659
|
+
expect("a downstream input whose producing part failed",
|
|
1660
|
+
start_in(parts_dir, "S5", [{"artifact": "inventory.json", "producer_stage": "S2"}]),
|
|
1661
|
+
"INPUT_INVALID S2.inventory")
|
|
1662
|
+
part_run("views", "views.json", status="partial")
|
|
1663
|
+
expect("a downstream input whose producing part is partial",
|
|
1664
|
+
start_in(parts_dir, "S6", [{"artifact": "views.json", "producer_stage": "S2"}]),
|
|
1665
|
+
"INPUT_PARTIAL S2.views")
|
|
1666
|
+
expect("a part the stage does not declare", part_run("census", "census.json"),
|
|
1667
|
+
"STAGE_PART_UNKNOWN S2.census")
|
|
1668
|
+
expect("a writer that names no part of a stage that has them",
|
|
1669
|
+
start_in(parts_dir, "S2", []), "STAGE_PART_REQUIRED S2")
|
|
1670
|
+
# the same refusal before any part has run: a fresh part-less write is the same violation
|
|
1671
|
+
fresh_dir = pathlib.Path(td) / "fresh-parts"
|
|
1672
|
+
declare_fixture(fresh_dir, base)
|
|
1673
|
+
expect("a part-less writer to a stage with parts, before any part has run",
|
|
1674
|
+
start_in(fresh_dir, "S2", []), "STAGE_PART_REQUIRED S2")
|
|
1675
|
+
if record_path(fresh_dir, "S2").is_file():
|
|
1676
|
+
failures.append("a refused part-less write still left an S2 record")
|
|
1677
|
+
# The second half of the same rule, and the one `STAGE_PARTS` does not reach: a stage this
|
|
1678
|
+
# version declares NO parts for, whose record on disk nevertheless holds some — an older
|
|
1679
|
+
# run's, or a later version's. A part-less write there would replace every part's entry at
|
|
1680
|
+
# once, so it is refused by what the record HOLDS rather than by the table. This was a
|
|
1681
|
+
# control-audit survivor: removing the refusal left every suite green.
|
|
1682
|
+
held_dir = pathlib.Path(td) / "parts-held-by-record"
|
|
1683
|
+
declare_fixture(held_dir, base)
|
|
1684
|
+
held_record = {"stage": "S3", "status": "complete", "declaration_seq": 1,
|
|
1685
|
+
"parts": {"a-producer": {"stage": "S3", "status": "complete", "outputs": []}}}
|
|
1686
|
+
write_json(held_dir, record_path(held_dir, "S3"), held_record)
|
|
1687
|
+
expect("a part-less writer to a stage whose record already holds parts",
|
|
1688
|
+
start_in(held_dir, "S3", []), "STAGE_PART_REQUIRED S3", "already holds the parts")
|
|
1689
|
+
if read_json(record_path(held_dir, "S3")) != held_record:
|
|
1690
|
+
failures.append("the refused part-less write replaced the parts the record held")
|
|
1691
|
+
if "S3" in STAGE_PARTS:
|
|
1692
|
+
failures.append("S3 has declared parts, so this control is the table's refusal again")
|
|
1693
|
+
# An optional part counts toward the stage's status only when it is there.
|
|
1694
|
+
done = {"status": "complete"}
|
|
1695
|
+
got = [derived_status({"stage": "S11", "parts": {"plan": done, "effects": done}}),
|
|
1696
|
+
derived_status({"stage": "S11", "parts": {"plan": done}}),
|
|
1697
|
+
derived_status({"stage": "S11", "parts": {"plan": done, "effects": done,
|
|
1698
|
+
"destinations": {"status": "failed"}}}),
|
|
1699
|
+
"destinations" in parts_of("S11"), "destinations" in STAGE_PARTS["S11"]]
|
|
1700
|
+
if got != ["complete", "partial", "failed", True, False]:
|
|
1701
|
+
failures.append(f"an optional part: absent it must not hold the stage partial, present it counts: {got}")
|
|
1702
|
+
# a legacy record whose outputs identify no part: refused, not silently replaced
|
|
1703
|
+
ambiguous_dir = pathlib.Path(td) / "ambiguous-legacy"
|
|
1704
|
+
declare_fixture(ambiguous_dir, base)
|
|
1705
|
+
write_json(ambiguous_dir, record_path(ambiguous_dir, "S2"),
|
|
1706
|
+
{"stage": "S2", "status": "failed", "outputs": [], "declaration_seq": 1})
|
|
1707
|
+
def legacy_ambiguous():
|
|
1708
|
+
try:
|
|
1709
|
+
with run_stage(ambiguous_dir, "S2", part="inventory"):
|
|
1710
|
+
pass
|
|
1711
|
+
return []
|
|
1712
|
+
except Refused as exc:
|
|
1713
|
+
return str(exc).splitlines()
|
|
1714
|
+
except Exception as exc:
|
|
1715
|
+
return [f"RAISED {exc!r}"]
|
|
1716
|
+
|
|
1717
|
+
expect("a legacy record whose outputs identify no producer", legacy_ambiguous(),
|
|
1718
|
+
"STAGE_PART_AMBIGUOUS S2")
|
|
1719
|
+
if read_json(record_path(ambiguous_dir, "S2")).get("status") != "failed":
|
|
1720
|
+
failures.append("the ambiguous legacy record was overwritten after all")
|
|
1721
|
+
# a record written before the stage had parts keeps its producer when a part is added
|
|
1722
|
+
legacy_dir = pathlib.Path(td) / "legacy"
|
|
1723
|
+
declare_fixture(legacy_dir, base)
|
|
1724
|
+
# Built directly, not through the writer API: the writer now refuses a part-less write to a
|
|
1725
|
+
# stage with parts, so a fixture made with it would be a record this version can produce
|
|
1726
|
+
# rather than the one an older version left behind (GC#9).
|
|
1727
|
+
(legacy_dir / "views.json").write_text("the legacy views output\n", encoding="utf-8")
|
|
1728
|
+
write_json(legacy_dir, record_path(legacy_dir, "S2"), {
|
|
1729
|
+
"stage": "S2", "run_json_sha256": sha256_file(legacy_dir / "run.json"),
|
|
1730
|
+
"declaration_seq": read_json(legacy_dir / "run.json")["declaration_seq"],
|
|
1731
|
+
"started": now(), "ended": now(), "status": "complete", "inputs": [],
|
|
1732
|
+
"outputs": [{"artifact": "views.json", "sha256": sha256_file(legacy_dir / "views.json")}],
|
|
1733
|
+
"calls": [], "quarantined": [],
|
|
1734
|
+
"usage": {"measured": 0, "provisional": 0, "unresolved": 0, "complete": True}})
|
|
1735
|
+
with run_stage(legacy_dir, "S2", part="inventory") as st:
|
|
1736
|
+
(legacy_dir / "inventory.json").write_text("the inventory output\n", encoding="utf-8")
|
|
1737
|
+
st.output("inventory.json")
|
|
1738
|
+
moved = read_json(record_path(legacy_dir, "S2"))
|
|
1739
|
+
if sorted(moved.get("parts", {})) != ["inventory", "views"]:
|
|
1740
|
+
failures.append(f"adding a part discarded the legacy producer: {sorted(moved.get('parts', {}))}")
|
|
1741
|
+
kept_label, kept_entry = producing_part(moved, "views.json")
|
|
1742
|
+
if kept_label != "views" or not kept_entry:
|
|
1743
|
+
failures.append(f"the legacy producer's artifact lost its producing part: {kept_label}")
|
|
1744
|
+
expect("a downstream input on the artifact the legacy producer made",
|
|
1745
|
+
start_in(legacy_dir, "S3", [{"artifact": "views.json", "producer_stage": "S2"}]))
|
|
1746
|
+
expect("a stage that declares no parts refuses one",
|
|
1747
|
+
part_run_elsewhere(parts_dir), "STAGE_PART_UNKNOWN S1.views")
|
|
1748
|
+
# the record written before parts existed still reads, and is still its own producer
|
|
1749
|
+
legacy = read_json(record_path(run_dir, "S1"))
|
|
1750
|
+
if "parts" in legacy or derived_status(legacy) != legacy.get("status"):
|
|
1751
|
+
failures.append(f"a single-producer record did not keep its shape: {sorted(legacy)}")
|
|
1752
|
+
try:
|
|
1753
|
+
label, entry = producing_part(legacy, "S1.out")
|
|
1754
|
+
except Exception as exc: # the control names the rule, not a traceback
|
|
1755
|
+
label, entry = f"RAISED {exc!r}", None
|
|
1756
|
+
if label != "S1" or entry is not legacy:
|
|
1757
|
+
failures.append(f"a record written before parts existed no longer answers for its own output: {label}")
|
|
1758
|
+
|
|
1759
|
+
# ---- GC#6: every stage-record publication crosses the disclosure boundary FIRST, and the
|
|
1760
|
+
# controls observe the real writer — `run_stage`'s own two writes — rather than a helper.
|
|
1761
|
+
home = str(pathlib.Path.home())
|
|
1762
|
+
secret_path = f"{home}/Documents/not-a-real-file"
|
|
1763
|
+
|
|
1764
|
+
def published(directory, stage, body, part=None):
|
|
1765
|
+
"""What `run_stage` left on disk, and what it raised: the writer itself, not a filter."""
|
|
1766
|
+
try:
|
|
1767
|
+
with run_stage(directory, stage, part=part) as stage_run:
|
|
1768
|
+
body(stage_run)
|
|
1769
|
+
raised = ""
|
|
1770
|
+
except Refused as exc:
|
|
1771
|
+
raised = str(exc)
|
|
1772
|
+
except Exception as exc:
|
|
1773
|
+
raised = f"RAISED {exc!r}"
|
|
1774
|
+
path = record_path(directory, stage)
|
|
1775
|
+
return raised, (path.read_text(encoding="utf-8") if path.is_file() else "")
|
|
1776
|
+
|
|
1777
|
+
# (1) a failure record: an item's quarantine reason is an exception message, and an OSError's
|
|
1778
|
+
# message IS a path. The record is published, and what it publishes is the projection.
|
|
1779
|
+
failing_dir = pathlib.Path(td) / "disclose-items"
|
|
1780
|
+
declare_fixture(failing_dir, base)
|
|
1781
|
+
|
|
1782
|
+
def fail_with_path(item):
|
|
1783
|
+
if item["id"] == "B":
|
|
1784
|
+
raise OSError(f"cannot read {secret_path}")
|
|
1785
|
+
raised, text = published(failing_dir, "S3", lambda st: st.run_items(batch, fail_with_path))
|
|
1786
|
+
if secret_path in text or home in text:
|
|
1787
|
+
failures.append(f"a quarantine reason published the owner's home path: {raised} {text[:200]}")
|
|
1788
|
+
if "<HOME>" not in text or '"quarantined"' not in text:
|
|
1789
|
+
failures.append(f"the failure record was not published with the reason projected: {raised} {text[:200]}")
|
|
1790
|
+
|
|
1791
|
+
# (2) a preserved part: the record already on disk is carried into `parts` by the FIRST
|
|
1792
|
+
# (running) publication, so the boundary has to be crossed there and not after the stage.
|
|
1793
|
+
kept_dir = pathlib.Path(td) / "disclose-preserved"
|
|
1794
|
+
declare_fixture(kept_dir, base)
|
|
1795
|
+
(kept_dir / "views.json").write_text("the legacy views output\n", encoding="utf-8")
|
|
1796
|
+
planted = {"stage": "S2", "run_json_sha256": sha256_file(kept_dir / "run.json"),
|
|
1797
|
+
"declaration_seq": read_json(kept_dir / "run.json")["declaration_seq"],
|
|
1798
|
+
"started": now(), "ended": now(), "status": "complete", "inputs": [],
|
|
1799
|
+
"outputs": [{"artifact": "views.json", "sha256": sha256_file(kept_dir / "views.json")}],
|
|
1800
|
+
"calls": [{"api_key": "shortpass"}], "quarantined": [],
|
|
1801
|
+
"usage": {"measured": 0, "provisional": 0, "unresolved": 0, "complete": True}}
|
|
1802
|
+
write_json(kept_dir, record_path(kept_dir, "S2"), planted)
|
|
1803
|
+
before = record_path(kept_dir, "S2").read_text(encoding="utf-8")
|
|
1804
|
+
raised, text = published(kept_dir, "S2", lambda st: None, part="inventory")
|
|
1805
|
+
expect("a preserved part carrying a credential is refused before the record is published",
|
|
1806
|
+
[raised], "RECORD_DISCLOSES S2", "a credential-named member")
|
|
1807
|
+
if text != before:
|
|
1808
|
+
failures.append("the refused publication replaced the record anyway")
|
|
1809
|
+
if "shortpass" in raised:
|
|
1810
|
+
failures.append(f"the refusal repeated the credential it objected to: {raised}")
|
|
1811
|
+
|
|
1812
|
+
# (3) the final publication: a stage that puts a raw path in its own record is refused there,
|
|
1813
|
+
# and the refusal carries the stage's own failure when one was already in flight.
|
|
1814
|
+
late_dir = pathlib.Path(td) / "disclose-final"
|
|
1815
|
+
declare_fixture(late_dir, base)
|
|
1816
|
+
|
|
1817
|
+
def leak_late(stage_run):
|
|
1818
|
+
stage_run.record["calls"].append({"note": secret_path})
|
|
1819
|
+
raised, text = published(late_dir, "S3", leak_late)
|
|
1820
|
+
expect("a stage record that would publish a raw path is refused at its final publication",
|
|
1821
|
+
[raised], "RECORD_DISCLOSES S3", "the string discloses a home path")
|
|
1822
|
+
if secret_path in text:
|
|
1823
|
+
failures.append(f"the refused final publication wrote the path anyway: {text[:200]}")
|
|
1824
|
+
|
|
1825
|
+
def leak_and_fail(stage_run):
|
|
1826
|
+
stage_run.record["calls"].append({"note": secret_path})
|
|
1827
|
+
raise ValueError("the stage itself failed")
|
|
1828
|
+
both_dir = pathlib.Path(td) / "disclose-final-failing"
|
|
1829
|
+
declare_fixture(both_dir, base)
|
|
1830
|
+
raised, _text = published(both_dir, "S3", leak_and_fail)
|
|
1831
|
+
expect("a refusal in the finally names the failure that was already in flight",
|
|
1832
|
+
[raised], "RECORD_DISCLOSES S3", "ValueError", "was in flight")
|
|
1833
|
+
|
|
1834
|
+
# The structural guard (X review of WP-08 r2): outside the listed sites nothing reads run.json. Positive control first,
|
|
1835
|
+
# on the real tree: every site is listed and every listed site still reads the declaration.
|
|
1836
|
+
texts = declaration_texts()
|
|
1837
|
+
found, sites = declaration_reads(texts)
|
|
1838
|
+
expect("the real tree reads the declaration only where DECLARATION_READERS says why", found)
|
|
1839
|
+
if sites != set(DECLARATION_READERS) or not {"distill.py", "census.py", "runlib/records.py"} <= set(texts):
|
|
1840
|
+
failures.append(f"the guard judged {len(texts)} modules and {sorted(sites)} sites, not every module of "
|
|
1841
|
+
"session-distill and every listed site")
|
|
1842
|
+
|
|
1843
|
+
def planted(rel, function, line):
|
|
1844
|
+
"""`texts` with `line` as the first statement of `function` in `rel`: a read before the stage's admission."""
|
|
1845
|
+
import ast
|
|
1846
|
+
node = next(n for n in ast.parse(texts[rel]).body if isinstance(n, ast.FunctionDef) and n.name == function)
|
|
1847
|
+
lines = texts[rel].splitlines(keepends=True)
|
|
1848
|
+
at = node.body[0].lineno - 1
|
|
1849
|
+
return {**texts, rel: "".join(lines[:at] + [" " * node.body[0].col_offset + line + "\n"] + lines[at:])}
|
|
1850
|
+
|
|
1851
|
+
for label, plant, code in (
|
|
1852
|
+
("S2 reading the declaration before its admission",
|
|
1853
|
+
planted("runlib/views.py", "run", "early = records.read_json(records.run_json_path(run_dir))"),
|
|
1854
|
+
"DECLARATION_READ_UNLISTED runlib/views.py:"),
|
|
1855
|
+
("S3 spelling the declaration's file itself",
|
|
1856
|
+
planted("runlib/stage_read.py", "run", 'early = json.loads((run_dir / "run.json").read_text())'),
|
|
1857
|
+
"DECLARATION_READ_UNLISTED runlib/stage_read.py:"),
|
|
1858
|
+
("S2 reading the declaration's state under another name",
|
|
1859
|
+
{**planted("runlib/views.py", "run", "early = state_of(run_dir)"),
|
|
1860
|
+
"runlib/views.py": "from runlib.records import declaration_state as state_of\n"
|
|
1861
|
+
+ planted("runlib/views.py", "run", "early = state_of(run_dir)")["runlib/views.py"]},
|
|
1862
|
+
"DECLARATION_READ_UNLISTED runlib/views.py:")):
|
|
1863
|
+
found_here = declaration_reads(plant)[0]
|
|
1864
|
+
expect(f"{label} is named", found_here, code, "(run)")
|
|
1865
|
+
unlisted = {key: why for key, why in DECLARATION_READERS.items() if key != ("runlib/census.py", "run")}
|
|
1866
|
+
expect("S1's pre-admission read with its entry removed is named", declaration_reads(texts, unlisted)[0],
|
|
1867
|
+
"DECLARATION_READ_UNLISTED runlib/census.py:", "(run)")
|
|
1868
|
+
expect("an entry whose site no longer reads the declaration is named",
|
|
1869
|
+
declaration_reads(texts, {**DECLARATION_READERS, ("runlib/views.py", "run"): "fixture"})[0],
|
|
1870
|
+
"DECLARATION_READ_STALE runlib/views.py (run)")
|
|
1871
|
+
with tempfile.TemporaryDirectory() as td:
|
|
1872
|
+
moved = declaration_texts(td)
|
|
1873
|
+
expect("a scan that found no module is not clean", declaration_reads(moved, {})[0], "DECLARATION_READ_UNSCANNED: 0 modules")
|
|
1874
|
+
expect("a scan that found no site is not clean", declaration_reads({"runlib/views.py": "def run():\n pass\n"}, {})[0],
|
|
1875
|
+
"DECLARATION_READ_UNSCANNED: 1 modules scanned and 0 sites")
|
|
1876
|
+
|
|
1877
|
+
# the fixture tree has one locator (lead, after lane L's measurement of the shipped tree): every suite that reads
|
|
1878
|
+
# fixtures asks `fixture_root`, and a tree without fixtures/ ends each of them by name
|
|
1879
|
+
# over a fixture tree of its own, so this suite needs none of the checkout's fixtures
|
|
1880
|
+
expect("the locator is this checkout's fixtures/", [] if FIXTURE_ROOT == pathlib.Path(__file__).resolve().parents[1]
|
|
1881
|
+
/ "fixtures" else [str(FIXTURE_ROOT)])
|
|
1882
|
+
held_locator = FIXTURE_ROOT
|
|
1883
|
+
with tempfile.TemporaryDirectory(prefix="records-fixtures-") as own:
|
|
1884
|
+
globals()["FIXTURE_ROOT"] = pathlib.Path(own) / "fixtures"
|
|
1885
|
+
try:
|
|
1886
|
+
(pathlib.Path(own) / "fixtures" / "replay").mkdir(parents=True)
|
|
1887
|
+
expect("the fixture root, and a directory inside it named by its parts",
|
|
1888
|
+
[] if (fixture_root(), fixture_root("replay")) == (pathlib.Path(own) / "fixtures",
|
|
1889
|
+
pathlib.Path(own) / "fixtures" / "replay")
|
|
1890
|
+
else ["moved"])
|
|
1891
|
+
try:
|
|
1892
|
+
absent = fixture_root("absent")
|
|
1893
|
+
except Refused as exc:
|
|
1894
|
+
absent = str(exc)
|
|
1895
|
+
expect("control: a fixture directory that is not there is refused by name", [str(absent)],
|
|
1896
|
+
f"FIXTURES_ABSENT {pathlib.Path(own) / 'fixtures' / 'absent'}: this tree carries no fixtures/absent "
|
|
1897
|
+
"directory")
|
|
1898
|
+
finally:
|
|
1899
|
+
globals()["FIXTURE_ROOT"] = held_locator
|
|
1900
|
+
import ast as _fx_ast
|
|
1901
|
+
|
|
1902
|
+
def fixture_spellings(texts):
|
|
1903
|
+
"""`FIXTURE_PATH_RECOMPUTED <file>:<line>` for every path built from a `"fixtures"` literal outside this
|
|
1904
|
+
module: the literal as an operand of `/`, or as an argument of `joinpath`."""
|
|
1905
|
+
out = []
|
|
1906
|
+
for rel, src in sorted(texts.items()):
|
|
1907
|
+
for node in _fx_ast.walk(_fx_ast.parse(src)):
|
|
1908
|
+
operands = ([node.left, node.right] if isinstance(node, _fx_ast.BinOp) and isinstance(node.op, _fx_ast.Div)
|
|
1909
|
+
else list(node.args) if isinstance(node, _fx_ast.Call) and isinstance(node.func, _fx_ast.Attribute)
|
|
1910
|
+
and node.func.attr == "joinpath" else [])
|
|
1911
|
+
if any(isinstance(o, _fx_ast.Constant) and o.value == "fixtures" for o in operands):
|
|
1912
|
+
out.append(f"FIXTURE_PATH_RECOMPUTED {rel}:{node.lineno}: the fixture tree is located by records.fixture_root")
|
|
1913
|
+
return out
|
|
1914
|
+
runlib_texts = {f"runlib/{path.name}": path.read_text(encoding="utf-8")
|
|
1915
|
+
for path in sorted(pathlib.Path(__file__).resolve().parent.glob("*.py")) if path.name != "records.py"}
|
|
1916
|
+
expect("no runlib module but this one builds the fixture tree's path", fixture_spellings(runlib_texts))
|
|
1917
|
+
expect("control: a module that recomputes it is named",
|
|
1918
|
+
fixture_spellings({**runlib_texts, "runlib/breaker.py": runlib_texts["runlib/breaker.py"]
|
|
1919
|
+
+ "\nREPLAY = pathlib.Path(__file__).resolve().parents[1] / \"fixtures\" / \"replay\"\n"}),
|
|
1920
|
+
"FIXTURE_PATH_RECOMPUTED runlib/breaker.py:")
|
|
1921
|
+
expect("the spelling scan read the modules it judges", [] if len(runlib_texts) > 5 else [sorted(runlib_texts)])
|
|
1922
|
+
# each suite entered in THIS process (a suite is never handed to a child: dispatch's DISPATCH_SELF_TEST_ARGV)
|
|
1923
|
+
# with the locator pointed at a directory that holds no fixtures/: it returns 1 and says FIXTURES_ABSENT by name,
|
|
1924
|
+
# and raises nothing - which is what its `__main__` turns into an exit without a traceback
|
|
1925
|
+
import io
|
|
1926
|
+
from runlib import breaker as _fx_breaker, dispatch as _fx_dispatch, gate as _fx_gate
|
|
1927
|
+
from runlib import monitor as _fx_monitor, views as _fx_views
|
|
1928
|
+
# the suites read the locator of the module they import, `runlib.records` - which is not this one when this file
|
|
1929
|
+
# runs as `__main__` - so that module's root is the one pointed away
|
|
1930
|
+
from runlib import records as _fx_records
|
|
1931
|
+
held_root = _fx_records.FIXTURE_ROOT
|
|
1932
|
+
with tempfile.TemporaryDirectory(prefix="records-nofix-") as nofix:
|
|
1933
|
+
_fx_records.FIXTURE_ROOT = pathlib.Path(nofix) / "fixtures"
|
|
1934
|
+
try:
|
|
1935
|
+
for name, suite in (("gate", _fx_gate.self_test), ("dispatch", _fx_dispatch.self_test),
|
|
1936
|
+
("views", _fx_views.self_test), ("breaker", _fx_breaker.self_test),
|
|
1937
|
+
("monitor", _fx_monitor.self_test)):
|
|
1938
|
+
said = io.StringIO()
|
|
1939
|
+
try:
|
|
1940
|
+
with contextlib.redirect_stdout(said):
|
|
1941
|
+
code = suite()
|
|
1942
|
+
except BaseException as exc: # noqa: BLE001 - a suite that raises fails this control by name
|
|
1943
|
+
code = f"raised {type(exc).__name__}: {str(exc)[:200]}"
|
|
1944
|
+
expect(f"control: {name}'s suite over a tree without fixtures/ ends with FIXTURES_ABSENT by name and "
|
|
1945
|
+
"raises nothing", [] if code == 1 and said.getvalue().startswith(
|
|
1946
|
+
f"{name} --self-test: FIXTURES_ABSENT {pathlib.Path(nofix) / 'fixtures'}") else
|
|
1947
|
+
[f"{code!r} {said.getvalue()[-300:]!r}"])
|
|
1948
|
+
finally:
|
|
1949
|
+
_fx_records.FIXTURE_ROOT = held_root
|
|
1950
|
+
|
|
1951
|
+
for failure in failures:
|
|
1952
|
+
print(f"records --self-test [FAIL] {failure}")
|
|
1953
|
+
if failures:
|
|
1954
|
+
return 1
|
|
1955
|
+
print("records --self-test: OK (declaration order: equal, amended, silently advanced, invalidated, "
|
|
1956
|
+
"unlicensed, reversed; set accounting; the failure posture over items; stage records pin the "
|
|
1957
|
+
"declaration, inputs and outputs, refuse partial, invalid, stale and drifted declarations and "
|
|
1958
|
+
"paths that leave the run directory; run.json is read only where DECLARATION_READERS says why)")
|
|
1959
|
+
return 0
|
|
1960
|
+
|
|
1961
|
+
|
|
1962
|
+
if __name__ == "__main__":
|
|
1963
|
+
if "--self-test" not in sys.argv[1:]:
|
|
1964
|
+
sys.exit("usage: records.py --self-test")
|
|
1965
|
+
sys.exit(self_test())
|