forgeproof-cli 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forge_gate/__init__.py +44 -0
- forge_gate/_deprecated_cli.py +16 -0
- forgeproof/__init__.py +3 -0
- forgeproof/catalog.py +110 -0
- forgeproof/cli.py +560 -0
- forgeproof/config.py +339 -0
- forgeproof/data/gate_catalog.json +66 -0
- forgeproof/data/host_sets.json +7 -0
- forgeproof/debug_caller.py +271 -0
- forgeproof/debug_core.py +368 -0
- forgeproof/fixture_engine.py +81 -0
- forgeproof/fixtures/__init__.py +19 -0
- forgeproof/fixtures/decision_tree_id3.py +90 -0
- forgeproof/fixtures/gradient_descent_momentum.py +73 -0
- forgeproof/fixtures/kmeans_clustering.py +98 -0
- forgeproof/fixtures/knn_classifier.py +79 -0
- forgeproof/fixtures/linear_regression_gd.py +77 -0
- forgeproof/fixtures/logistic_regression.py +85 -0
- forgeproof/fixtures/naive_bayes_text.py +114 -0
- forgeproof/fixtures/perceptron.py +84 -0
- forgeproof/fixtures/polynomial_regression.py +67 -0
- forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
- forgeproof/ledger.py +633 -0
- forgeproof/lens_tools/__init__.py +11 -0
- forgeproof/lens_tools/guard_lens.py +1250 -0
- forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
- forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
- forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
- forgeproof/lens_tools/invariant_gate.py +199 -0
- forgeproof/lens_tools/metamorphic/__init__.py +9 -0
- forgeproof/lens_tools/metamorphic/relations.py +962 -0
- forgeproof/lens_tools/metamorphic/runner.py +112 -0
- forgeproof/lens_tools/twin_consensus.py +395 -0
- forgeproof/lenses.py +923 -0
- forgeproof/paths.py +56 -0
- forgeproof/reference/ORIGIN.md +29 -0
- forgeproof/reference/decision_tree_id3.py +197 -0
- forgeproof/reference/gradient_descent_momentum.py +141 -0
- forgeproof/reference/kmeans_clustering.py +139 -0
- forgeproof/reference/knn_classifier.py +118 -0
- forgeproof/reference/linear_regression_gd.py +106 -0
- forgeproof/reference/logistic_regression.py +141 -0
- forgeproof/reference/naive_bayes_text.py +152 -0
- forgeproof/reference/perceptron.py +123 -0
- forgeproof/reference/polynomial_regression.py +125 -0
- forgeproof/reference/ridge_regression_normal_eq.py +165 -0
- forgeproof/runner.py +147 -0
- forgeproof/scout/__init__.py +7 -0
- forgeproof/scout/behaviour.py +365 -0
- forgeproof/scout/box.py +581 -0
- forgeproof/scout/cards.py +180 -0
- forgeproof/scout/contract.py +37 -0
- forgeproof/scout/corpus.py +104 -0
- forgeproof/scout/embed.py +217 -0
- forgeproof/scout/engines/__init__.py +1 -0
- forgeproof/scout/engines/chaos.py +454 -0
- forgeproof/scout/engines/chaos_port.py +1331 -0
- forgeproof/scout/engines/chaos_runner.py +178 -0
- forgeproof/scout/engines/executor_port.py +239 -0
- forgeproof/scout/envfit.py +54 -0
- forgeproof/scout/experience.py +161 -0
- forgeproof/scout/fetchproxy.py +368 -0
- forgeproof/scout/ghcache.py +395 -0
- forgeproof/scout/ghpool.py +253 -0
- forgeproof/scout/ghsearch.py +248 -0
- forgeproof/scout/ids.py +82 -0
- forgeproof/scout/intent_lens.py +170 -0
- forgeproof/scout/learn.py +583 -0
- forgeproof/scout/meaning_lens.py +231 -0
- forgeproof/scout/outcomes.py +42 -0
- forgeproof/scout/plant.py +327 -0
- forgeproof/scout/ratify.py +214 -0
- forgeproof/scout/report.py +448 -0
- forgeproof/scout/rule2.py +177 -0
- forgeproof/scout/shape.py +107 -0
- forgeproof/scout/shape_lens.py +71 -0
- forgeproof/scout/signature.py +52 -0
- forgeproof/scout/slots.py +39 -0
- forgeproof/scout/upstream_facts.py +536 -0
- forgeproof/unsupported.py +83 -0
- forgeproof/verifier.py +208 -0
- forgeproof/view_coverage.py +166 -0
- forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
- forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
- forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
- forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
- forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
- forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
- forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
"""Scout's chaos engine (build step 6b-2; design v1.4.5 §4.3; decision L3, the maintainer 2026-11-13).
|
|
2
|
+
|
|
3
|
+
A chaos PASS card makes a row **hard**. There is no human countersign in that path (§4.3). So
|
|
4
|
+
a scout chaos PASS must mean exactly what the validator's ``chaos_scan.py`` PASS means, and it
|
|
5
|
+
must never be easier to get. The semantics, read and measured, are in
|
|
6
|
+
``~/aura-docs/Forge Gate/CHAOS-SEMANTICS-6b2-20261113.md``. In short:
|
|
7
|
+
|
|
8
|
+
- The validator's chaos is a CLOSED list of 19 hand-written probes. Each probe is tied to one
|
|
9
|
+
library file and paired with a negative control (NC), an unsafe twin that must die to the same
|
|
10
|
+
fault. A file the list does not name gets no chaos card at all.
|
|
11
|
+
- DOMAIN. Scout probes a corpus item only when its bytes are IDENTICAL to one of those 19
|
|
12
|
+
library files as pinned below (library 4b65044b). The validator would give exactly those bytes
|
|
13
|
+
the same probe. Any other file gets ``BLIND(no validator chaos probe for these bytes)``.
|
|
14
|
+
- Probing crew code by API shape would be more complete, but it skips the human choice of
|
|
15
|
+
"this file faces this probe" that the validator's PASS rests on. It is not built
|
|
16
|
+
(named conflict; the maintainer decides).
|
|
17
|
+
- RACE / TIMING probes (threads, sleeps, SIGKILL timing) are always BLIND: their verdict
|
|
18
|
+
depends on scheduling, so parity with the validator cannot be shown.
|
|
19
|
+
- THE GATE. Every run executes ALL 19 NCs first, as the validator's ``main()`` does, and does it
|
|
20
|
+
3 times (chaos_runner.GATE_RUNS): a race NC that dies only sometimes must die every time.
|
|
21
|
+
- If any NC survived, the validator writes no report (ABORT). Scout says BLIND.
|
|
22
|
+
- Scout is stricter: an NC whose "death" was a raise, a compile failure, a missing rustc or a
|
|
23
|
+
timeout is not clean, and gives BLIND (see engines/chaos_runner.py).
|
|
24
|
+
- HOST HISTORY (parent review, 2026-11-13). The gate is a race on some hosts, so 3 clean runs
|
|
25
|
+
only bound the odds; they cannot make one file's verdict identical to the validator's own run.
|
|
26
|
+
Every gate run is recorded per host in ``$FORGE_GATE_SCOUT_DIR/chaos_gate_history.json``. Once
|
|
27
|
+
any NC has survived on a host, chaos is BLIND for every probe there, and stays BLIND until an
|
|
28
|
+
operator archives the file. A host whose gate is unreliable is an input class where parity
|
|
29
|
+
cannot be shown. A history that cannot be read is BLIND too (fail closed).
|
|
30
|
+
- VERDICT. The card comes from the port's own ``scan()``. Validator PASS -> PASS.
|
|
31
|
+
INVALID-CANDIDATE -> FAIL. FLAG (harness error) -> BLIND. Nothing else is ever PASS.
|
|
32
|
+
- FUNCTIONS. A card backs a function only if it is the probe's SUBJECT (the function whose
|
|
33
|
+
survival the predicate measures, hand-read per probe below) AND the run recorded the probe
|
|
34
|
+
reading it on the pattern module. A function the probe only uses to measure (PITR ``vals``) or to
|
|
35
|
+
inject the fault (ETL ``stable_checksum``) is not a subject (6b-2 review F1). Every other
|
|
36
|
+
function gets BLIND.
|
|
37
|
+
- WHAT RUNS. Only pinned library bytes and the validator's own NC code, in a child process with
|
|
38
|
+
a time cap. Crew code that is not byte-identical to a pinned file is never executed.
|
|
39
|
+
"""
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import hashlib
|
|
43
|
+
import json
|
|
44
|
+
import os
|
|
45
|
+
import datetime as _dt
|
|
46
|
+
import platform
|
|
47
|
+
import re
|
|
48
|
+
import shutil
|
|
49
|
+
import signal
|
|
50
|
+
import socket
|
|
51
|
+
import subprocess
|
|
52
|
+
import sys
|
|
53
|
+
import tempfile
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
|
|
56
|
+
from ... import config
|
|
57
|
+
from .chaos_runner import GATE_ONLY, GATE_RUNS # GATE_ONLY: calibration mode, the gate without a probe
|
|
58
|
+
|
|
59
|
+
KIND = "chaos"
|
|
60
|
+
LIBRARY_COMMIT = "4b65044b"
|
|
61
|
+
SOURCE = "tools/pattern-scoring/validator/chaos_scan.py"
|
|
62
|
+
SOURCE_BLOB = "fab0bdd27d7f56a5db534f6bca59b20b46933683"
|
|
63
|
+
RUNNER = Path(__file__).with_name("chaos_runner.py")
|
|
64
|
+
PORT = Path(__file__).with_name("chaos_port.py")
|
|
65
|
+
# KD-12 (j), the maintainer 2026-11-14: a corpus item that IS a pinned library file adds no evidence (its
|
|
66
|
+
# verdict is the library's own), so learn gives it BLIND. A constant, not config: only tests flip
|
|
67
|
+
# it, to exercise the parity machinery that a future engine will feed with other inputs.
|
|
68
|
+
LEARN_LIBRARY_COPIES = False
|
|
69
|
+
# KD-12 (c)/(m): clean gate runs needed per (machine, configuration) before any verdict. Measured
|
|
70
|
+
# 2026-11-14 (ai-lab/fg6b2/calib): the dev machine seqlock NC survived 1 of 391 gate runs, the deploy host 399 of 400.
|
|
71
|
+
# To catch a machine at the dev machine's rate with 95% confidence: ln(0.05)/ln(1-1/391) = 1170 -> 1200.
|
|
72
|
+
CALIBRATION_N = 1200
|
|
73
|
+
HISTORY_VERSION = 2
|
|
74
|
+
TIMEOUT_S = 900 # the whole child (19 NCs + 1 probe); measured ~4-10 s per run on both hosts
|
|
75
|
+
|
|
76
|
+
# probe name -> (library path, sha256 of that file at library commit 4b65044b). The 19 entries of
|
|
77
|
+
# the validator's PROBES list, in its order. Unchanged at library HEAD on both hosts (2026-11-13).
|
|
78
|
+
PINNED = {
|
|
79
|
+
"atomic_write_temp_rename": ("python/system-administration/filesystem-integrity/atomic_write_temp_rename.py",
|
|
80
|
+
"800f18ecd2174c74175fcb501c8b3ab8e013541ac91c171a978527fa51c8f3a8"),
|
|
81
|
+
"write_ahead_log": ("python/programming/persistence/write_ahead_log.py",
|
|
82
|
+
"079a678b6c5fde2f3f35f1d7e4695c5035c1250bd4b6083de3192a5e776a0431"),
|
|
83
|
+
"checkpoint_resume": ("python/system-administration/data-pipeline-ops/checkpoint_resume.py",
|
|
84
|
+
"21c752c27f233465cf2680893cbf147ddd1a59a302708d7e6862b44bd0f744be"),
|
|
85
|
+
"segmented_wal": ("python/programming/persistence/segmented_wal.py",
|
|
86
|
+
"7fcee0ce7dc7e4834e3b75924720daab85793641bd87dd199630dc33503c5159"),
|
|
87
|
+
"journaled_write": ("python/system-administration/state-db-durability/journaled_write.py",
|
|
88
|
+
"e19eef5fe33f12454763c1d878b6b48f40dd6e89b5e02657448fea83a3561380"),
|
|
89
|
+
"point_in_time_restore": ("python/system-administration/state-db-durability/point_in_time_restore.py",
|
|
90
|
+
"fb62f375e860264b889967442636e50a177c9d82ee5eb60c743c212e42e0f2ae"),
|
|
91
|
+
"idempotent_etl_step": ("python/system-administration/data-pipeline-ops/idempotent_etl_step.py",
|
|
92
|
+
"1ebdead816050a0f61feb14622b57a1ac652d3fa180c47e14f450f692af4daee"),
|
|
93
|
+
"idempotent_replication": ("python/system-administration/mesh-distributed/idempotent_replication.py",
|
|
94
|
+
"43bfd541a11359121aa5beae645e78e262fa80d5737eac5e082c8b7d9cafc1a9"),
|
|
95
|
+
"idempotent_once_guard": ("python/system-administration/concurrency-locking/idempotent_once_guard.py",
|
|
96
|
+
"4471c4b5cfde3c8b7bc87f6f4b8cbad77f3441d69042e083dad2bd9153c1c9a4"),
|
|
97
|
+
"transaction_rollback": ("python/system-administration/state-db-durability/transaction_rollback.py",
|
|
98
|
+
"dc00296c92b2d7539ccf2540191b07832340b84c5cab847c888dd2f19af870a6"),
|
|
99
|
+
"migration_with_rollback": ("python/system-administration/state-db-durability/migration_with_rollback.py",
|
|
100
|
+
"8d5160e6f865169113b0ab15aabd935a2b3a052005254685392ff0d274f41431"),
|
|
101
|
+
"wal_append_replay": ("rust/composed-systems/wal_append_replay.rs",
|
|
102
|
+
"e53348115edab0145b22b85fd754700b21caeccc49d2cd4930a55d08925e8019"),
|
|
103
|
+
"tamper_evident_log": ("rust/composed-systems/tamper_evident_log.rs",
|
|
104
|
+
"275af71afc55f1c0235862f364eeec40cf3cc0a5fab8c579c862c0f4429cc287"),
|
|
105
|
+
"content_addressed_store": ("rust/composed-systems/content_addressed_store.rs",
|
|
106
|
+
"1ab542c1f462c93e2878e91c2162e99b3391624aabebfcda2d52a46657350fb7"),
|
|
107
|
+
"rotating_log_checksum": ("rust/composed-systems/rotating_log_checksum.rs",
|
|
108
|
+
"0ba75b1a24fec23d7389315d6461f90792de1c980992a2557b2d4ae291134766"),
|
|
109
|
+
"signed_snapshot": ("rust/composed-systems/signed_snapshot.rs",
|
|
110
|
+
"c3f6692c60455c6fafaac09b8ddc892c80f5f6dcdd39f1edcd79d03ec065d1e2"),
|
|
111
|
+
"hmac_signed_url": ("rust/security-crypto/hmac_signed_url.rs",
|
|
112
|
+
"dd618ec1b5d810520216a4dc4aaeb3d309d38796d4ab32618c33737e90a382f8"),
|
|
113
|
+
"seqlock_snapshot": ("rust/concurrency-resilience/seqlock_snapshot.rs",
|
|
114
|
+
"481e93d3d5a395536f8b49466cc69f819cd5252f85ba0b83772f9ab0a8bf962d"),
|
|
115
|
+
"double_buffer": ("rust/concurrency-resilience/double_buffer.rs",
|
|
116
|
+
"55528afee0d59dc83a092c8c5df48d87da0c2000718099b64db376bd4082564f"),
|
|
117
|
+
}
|
|
118
|
+
# Threads, sleeps or SIGKILL timing in the probe or its helpers (AST scan of each probe's call
|
|
119
|
+
# closure, 2026-11-13). seqlock_snapshot is also the NC that aborts the validator on the deploy host.
|
|
120
|
+
RACE = frozenset({"idempotent_once_guard", "transaction_rollback", "migration_with_rollback",
|
|
121
|
+
"seqlock_snapshot", "double_buffer"})
|
|
122
|
+
assert RACE <= set(PINNED) and len(PINNED) == 19
|
|
123
|
+
_BY_SHA = {sha: name for name, (_rel, sha) in PINNED.items()}
|
|
124
|
+
|
|
125
|
+
# probe -> the top-level functions whose survival its predicate measures (read from each probe's
|
|
126
|
+
# body in chaos_scan.py at 4b65044b, 2026-11-13, review F1). Classes (WAL, ReplicatedStore) and the
|
|
127
|
+
# Rust probes have none: scout's rows are top-level functions only, so those back no row.
|
|
128
|
+
SUBJECT = {
|
|
129
|
+
"atomic_write_temp_rename": frozenset({"atomic_write"}), # m.atomic_write under the crash
|
|
130
|
+
"write_ahead_log": frozenset(), # class WAL
|
|
131
|
+
"checkpoint_resume": frozenset({"process_batch_with_checkpoint"}), # crashed, then resumed
|
|
132
|
+
"segmented_wal": frozenset({"recover_from_crash"}), # recovers the torn segment
|
|
133
|
+
"journaled_write": frozenset({"recover_from_journal"}), # recovers after the crash
|
|
134
|
+
"point_in_time_restore": frozenset({"restore_to"}), # NOT vals: the measuring tool
|
|
135
|
+
"idempotent_etl_step": frozenset({"idempotent_transform"}), # NOT stable_checksum: the fault site
|
|
136
|
+
"idempotent_replication": frozenset(), # class ReplicatedStore
|
|
137
|
+
**{n: frozenset() for n in PINNED if n.startswith(("wal_", "tamper", "content", "rotating",
|
|
138
|
+
"signed", "hmac"))},
|
|
139
|
+
**{n: frozenset() for n in RACE}, # never reached: BLIND first
|
|
140
|
+
}
|
|
141
|
+
assert set(SUBJECT) == set(PINNED)
|
|
142
|
+
|
|
143
|
+
# Validator card verdict -> scout verdict. FLAG and anything unknown are BLIND, never a verdict.
|
|
144
|
+
VERDICT_MAP = {"PASS": "PASS", "INVALID-CANDIDATE": "FAIL"}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class Blind(Exception):
|
|
148
|
+
"""The run cannot give a verdict; the message is the BLIND reason. ``partial_gate`` carries
|
|
149
|
+
the gate runs a child finished before it died, so the caller records them (review F2)."""
|
|
150
|
+
|
|
151
|
+
def __init__(self, reason: str = "", partial_gate: dict | None = None):
|
|
152
|
+
super().__init__(reason)
|
|
153
|
+
self.partial_gate = partial_gate
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def probe_for(body: bytes):
|
|
157
|
+
"""The validator probe these exact bytes would face, or None."""
|
|
158
|
+
return _BY_SHA.get(hashlib.sha256(body).hexdigest())
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def stage_library(lib_dir: Path, dest: Path) -> None:
|
|
162
|
+
"""Copy the 19 pinned files from ``lib_dir`` into ``dest`` and check every copy's sha256.
|
|
163
|
+
The NCs and probes read the library, so the whole pinned set must be present and exact."""
|
|
164
|
+
for name, (rel, sha) in PINNED.items():
|
|
165
|
+
src = Path(lib_dir) / rel
|
|
166
|
+
out = dest / rel
|
|
167
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
168
|
+
try:
|
|
169
|
+
shutil.copyfile(src, out)
|
|
170
|
+
except OSError as e:
|
|
171
|
+
raise Blind(f"library file {rel} unreadable: {type(e).__name__}") from None
|
|
172
|
+
if hashlib.sha256(out.read_bytes()).hexdigest() != sha:
|
|
173
|
+
raise Blind(f"library file {rel} is not at the pinned bytes (library {LIBRARY_COMMIT})")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def run_child(lib_root: Path, probe: str, work: Path, timeout: float = TIMEOUT_S) -> dict:
|
|
177
|
+
"""Run the runner once (19 NCs + the one probe) against ``lib_root``; return its JSON."""
|
|
178
|
+
out = work / "result.json"
|
|
179
|
+
env = {k: v for k, v in os.environ.items() if not k.startswith("PYTHON")}
|
|
180
|
+
env["TMPDIR"] = str(work) # the probes' own mkdtemp() calls land here, never in /tmp
|
|
181
|
+
# Own process group: on a timeout (and after every run) the whole group is killed, so no
|
|
182
|
+
# rustc, probe binary or SIGKILL-family child outlives the run (review F4).
|
|
183
|
+
child = subprocess.Popen([sys.executable, "-I", str(RUNNER), str(lib_root), probe, str(out)],
|
|
184
|
+
cwd=work, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
|
185
|
+
stderr=subprocess.DEVNULL, start_new_session=True)
|
|
186
|
+
timed_out = False
|
|
187
|
+
try:
|
|
188
|
+
child.wait(timeout=timeout)
|
|
189
|
+
except subprocess.TimeoutExpired:
|
|
190
|
+
timed_out = True
|
|
191
|
+
finally:
|
|
192
|
+
try:
|
|
193
|
+
os.killpg(child.pid, signal.SIGKILL)
|
|
194
|
+
except (ProcessLookupError, PermissionError):
|
|
195
|
+
pass
|
|
196
|
+
child.wait()
|
|
197
|
+
try:
|
|
198
|
+
res = json.loads(out.read_text())
|
|
199
|
+
except (OSError, ValueError):
|
|
200
|
+
res = None
|
|
201
|
+
if timed_out:
|
|
202
|
+
raise Blind(f"chaos run timed out after {timeout:g} s", partial_gate=_partial(res))
|
|
203
|
+
if not isinstance(res, dict) or ("gate" not in res and "error" not in res):
|
|
204
|
+
raise Blind("chaos run wrote no result", partial_gate=_partial(res))
|
|
205
|
+
return res
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _gate_shape(g) -> bool:
|
|
209
|
+
return (isinstance(g, dict) and isinstance(g.get("runs"), int) and g["runs"] > 0
|
|
210
|
+
and isinstance(g.get("survived"), list) and all(isinstance(x, str) for x in g["survived"])
|
|
211
|
+
and isinstance(g.get("unclean"), dict))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _partial(res):
|
|
215
|
+
"""The gate runs a child finished before it died or errored, if it wrote any."""
|
|
216
|
+
g = res.get("partial_gate") if isinstance(res, dict) else None
|
|
217
|
+
return g if _gate_shape(g) else None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _not_clean(g: dict) -> dict:
|
|
221
|
+
"""A partial gate's runs and survivals count; its runs are never clean."""
|
|
222
|
+
return {"ok": False, "survived": list(g["survived"]), "runs": g["runs"],
|
|
223
|
+
"unclean": {**g["unclean"], "_child": "the child did not finish this gate"}}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _run_recorded(lib: Path, probe: str, work: Path, path: Path) -> dict:
|
|
227
|
+
"""run_child, recording every gate run the child finished BEFORE anything raises: a full
|
|
228
|
+
gate as it is, a partial one (child died, hung or errored) as not clean (review F2)."""
|
|
229
|
+
try:
|
|
230
|
+
res = run_child(lib, probe, work)
|
|
231
|
+
except Blind as e:
|
|
232
|
+
if e.partial_gate is not None:
|
|
233
|
+
record_gate(path, _not_clean(e.partial_gate))
|
|
234
|
+
raise
|
|
235
|
+
if isinstance(res.get("gate"), dict):
|
|
236
|
+
record_gate(path, res["gate"])
|
|
237
|
+
elif _partial(res) is not None:
|
|
238
|
+
record_gate(path, _not_clean(res["partial_gate"]))
|
|
239
|
+
return res
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def file_verdict(res: dict, probe: str):
|
|
243
|
+
"""(verdict, card) for the whole FILE from one child result, or raise Blind. The order is
|
|
244
|
+
the validator's: the gate first (an ABORT writes no card at all), then the card. This is
|
|
245
|
+
what the parity test compares with the validator's own run on the same file."""
|
|
246
|
+
if "error" in res:
|
|
247
|
+
raise Blind(f"chaos harness error: {res['error']}")
|
|
248
|
+
gate = res.get("gate") or {}
|
|
249
|
+
if gate.get("survived"):
|
|
250
|
+
raise Blind("negative controls did not all die, so the validator ABORTs here: "
|
|
251
|
+
+ ", ".join(gate["survived"]))
|
|
252
|
+
if gate.get("unclean"):
|
|
253
|
+
raise Blind("a negative control did not run cleanly: "
|
|
254
|
+
+ "; ".join(f"{k}: {v}" for k, v in sorted(gate["unclean"].items())))
|
|
255
|
+
if gate.get("ok") is not True:
|
|
256
|
+
raise Blind("the negative-control gate did not pass")
|
|
257
|
+
if gate.get("runs") != GATE_RUNS:
|
|
258
|
+
raise Blind(f"the negative-control gate ran {gate.get('runs')!r} times, not {GATE_RUNS}")
|
|
259
|
+
card = res.get("card") or {}
|
|
260
|
+
if (res.get("probe") != probe or card.get("pattern") != PINNED[probe][0]
|
|
261
|
+
or card.get("oracle_coverage_kind") != KIND):
|
|
262
|
+
raise Blind("chaos result does not belong to this probe")
|
|
263
|
+
v = card.get("verdict")
|
|
264
|
+
if v == "FLAG":
|
|
265
|
+
raise Blind(f"chaos harness error: {str(card.get('actual', ''))[:200]}")
|
|
266
|
+
if v not in VERDICT_MAP:
|
|
267
|
+
raise Blind(f"unknown validator verdict {v!r}")
|
|
268
|
+
return VERDICT_MAP[v], card
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def decide(res: dict, probe: str, entry: str):
|
|
272
|
+
"""(verdict, card) for one FUNCTION: the file's verdict, and only for the probe's subject
|
|
273
|
+
that the run recorded it driving. Raises Blind otherwise."""
|
|
274
|
+
verdict, card = file_verdict(res, probe)
|
|
275
|
+
if entry not in SUBJECT[probe] or entry not in (res.get("touched") or ()):
|
|
276
|
+
raise Blind(f"{entry} is not a subject the {probe} probe drove")
|
|
277
|
+
return verdict, card
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
HISTORY_NAME = "chaos_gate_history.json"
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def host() -> str:
|
|
284
|
+
"""The hostname: a LABEL in the history, never its key (it changes with a rename or a network)."""
|
|
285
|
+
return socket.gethostname()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def machine_id() -> str:
|
|
289
|
+
"""A stable id that survives a rename (KD-12 m): /etc/machine-id on Linux, IOPlatformUUID on
|
|
290
|
+
macOS. Unknown -> Blind (a machine scout cannot name is never calibrated)."""
|
|
291
|
+
mid = ""
|
|
292
|
+
try:
|
|
293
|
+
if sys.platform.startswith("linux"):
|
|
294
|
+
mid = Path("/etc/machine-id").read_text(encoding="ascii").strip()
|
|
295
|
+
elif sys.platform == "darwin":
|
|
296
|
+
out = subprocess.run(["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
|
|
297
|
+
capture_output=True, text=True, timeout=30).stdout
|
|
298
|
+
m = re.search(r'"IOPlatformUUID" = "([0-9A-Fa-f-]+)"', out)
|
|
299
|
+
mid = m.group(1) if m else ""
|
|
300
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
301
|
+
mid = ""
|
|
302
|
+
if not re.fullmatch(r"[0-9A-Fa-f-]{16,64}", mid):
|
|
303
|
+
raise Blind("machine identity unknown: chaos stays BLIND")
|
|
304
|
+
return mid.lower()
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def fingerprint() -> dict:
|
|
308
|
+
"""What the race NCs' behaviour depends on. A change starts a fresh calibration (KD-12 m).
|
|
309
|
+
``rustc -V`` runs from the scratch dir, where the child runs, so a ``rust-toolchain.toml``
|
|
310
|
+
in the caller's cwd cannot name a compiler the child does not use (review F3)."""
|
|
311
|
+
try:
|
|
312
|
+
cwd = config.scratch_dir()
|
|
313
|
+
except config.NotConfigured as e:
|
|
314
|
+
raise Blind(f"not configured: {e}") from None
|
|
315
|
+
try:
|
|
316
|
+
rustc = subprocess.run(["rustc", "-V"], capture_output=True, text=True, timeout=60,
|
|
317
|
+
cwd=cwd).stdout.strip()
|
|
318
|
+
except (OSError, subprocess.SubprocessError):
|
|
319
|
+
rustc = ""
|
|
320
|
+
return {"python": platform.python_version(), "rustc": rustc or "none",
|
|
321
|
+
"port_md5": hashlib.md5(PORT.read_bytes()).hexdigest(),
|
|
322
|
+
"cpu": f"{platform.machine()} x{os.cpu_count()}", "os": f"{platform.system()} {platform.release()}"}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def config_key(fp: dict) -> str:
|
|
326
|
+
return hashlib.sha256(json.dumps(fp, sort_keys=True).encode()).hexdigest()[:16]
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _history_path() -> Path:
|
|
330
|
+
try:
|
|
331
|
+
return config.scout_dir() / HISTORY_NAME
|
|
332
|
+
except config.NotConfigured as e:
|
|
333
|
+
raise Blind(f"not configured: {e}") from None
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def load_history(path: Path) -> dict:
|
|
337
|
+
"""{"version": 2, "machines": {machine_id: {"hostname", "survived": {nc: n}, "first_survival",
|
|
338
|
+
"configs": {config_key: {"fingerprint", "gate_runs", "clean_runs"}}}}}.
|
|
339
|
+
Missing -> empty. Anything unreadable, or another version -> Blind (a history scout cannot read
|
|
340
|
+
never says clean). A symlink at the path, dangling or not, is Blind: ``exists()`` follows links,
|
|
341
|
+
so a dangling one read as "missing" and lost a recorded survival (crew review 2026-11-14, 5S F1)."""
|
|
342
|
+
if path.is_symlink():
|
|
343
|
+
raise Blind(f"chaos gate history {path} is a symlink: chaos stays BLIND")
|
|
344
|
+
if not path.exists():
|
|
345
|
+
return {"version": HISTORY_VERSION, "machines": {}}
|
|
346
|
+
try:
|
|
347
|
+
h = json.loads(path.read_text(encoding="utf-8"))
|
|
348
|
+
assert isinstance(h, dict) and h.get("version") == HISTORY_VERSION
|
|
349
|
+
assert isinstance(h.get("machines"), dict)
|
|
350
|
+
for m in h["machines"].values():
|
|
351
|
+
assert isinstance(m.get("survived"), dict) and isinstance(m.get("configs"), dict)
|
|
352
|
+
for c in m["configs"].values():
|
|
353
|
+
assert isinstance(c.get("gate_runs"), int) and isinstance(c.get("clean_runs"), int)
|
|
354
|
+
return h
|
|
355
|
+
except (OSError, ValueError, AssertionError, AttributeError):
|
|
356
|
+
raise Blind(f"chaos gate history {path} is unreadable: chaos stays BLIND") from None
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def record_gate(path: Path, gate: dict) -> None:
|
|
360
|
+
"""Add one child run's gate to this machine's record (atomic replace). A gate counts as clean
|
|
361
|
+
only if every run was ok with no survival and no unclean NC. learn and chaos-calibrate hold
|
|
362
|
+
learn's singleton lock while they run, so two writers never meet."""
|
|
363
|
+
h = load_history(path)
|
|
364
|
+
mid, fp = machine_id(), fingerprint()
|
|
365
|
+
m = h["machines"].setdefault(mid, {"survived": {}, "configs": {}})
|
|
366
|
+
m["hostname"] = host()
|
|
367
|
+
c = m["configs"].setdefault(config_key(fp), {"fingerprint": fp, "gate_runs": 0, "clean_runs": 0})
|
|
368
|
+
runs = int(gate.get("runs") or 0)
|
|
369
|
+
c["gate_runs"] += runs
|
|
370
|
+
if gate.get("ok") is True and not gate.get("survived") and not gate.get("unclean"):
|
|
371
|
+
c["clean_runs"] += runs
|
|
372
|
+
now = _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat()
|
|
373
|
+
for nc in gate.get("survived") or ():
|
|
374
|
+
m["survived"][nc] = m["survived"].get(nc, 0) + 1
|
|
375
|
+
m.setdefault("first_survival", now)
|
|
376
|
+
fd, tmp = tempfile.mkstemp(prefix=HISTORY_NAME + ".", suffix=".tmp", dir=path.parent)
|
|
377
|
+
try:
|
|
378
|
+
os.fchmod(fd, 0o644)
|
|
379
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
380
|
+
json.dump(h, fh, indent=1, sort_keys=True)
|
|
381
|
+
fh.write("\n")
|
|
382
|
+
fh.flush()
|
|
383
|
+
os.fsync(fh.fileno())
|
|
384
|
+
os.replace(tmp, path)
|
|
385
|
+
except BaseException:
|
|
386
|
+
Path(tmp).unlink(missing_ok=True)
|
|
387
|
+
raise
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def check_host() -> None:
|
|
391
|
+
"""Raise Blind unless this machine is calibrated and has never seen an NC survive.
|
|
392
|
+
1. Any survival ever recorded for this MACHINE (any configuration) -> Blind (the latch).
|
|
393
|
+
2. Fewer than CALIBRATION_N clean gate runs under the CURRENT configuration -> Blind."""
|
|
394
|
+
h = load_history(_history_path())
|
|
395
|
+
mid = machine_id()
|
|
396
|
+
m = h["machines"].get(mid) or {"survived": {}, "configs": {}}
|
|
397
|
+
if any(m["survived"].values()):
|
|
398
|
+
seen = ", ".join(f"{k} x{v}" for k, v in sorted(m["survived"].items()))
|
|
399
|
+
raise Blind(f"machine {mid[:8]} ({host()}): negative controls have survived here before "
|
|
400
|
+
f"({seen}); chaos stays BLIND on this machine until an operator archives {HISTORY_NAME}")
|
|
401
|
+
c = m["configs"].get(config_key(fingerprint()))
|
|
402
|
+
clean = c["clean_runs"] if c else 0
|
|
403
|
+
if clean < CALIBRATION_N:
|
|
404
|
+
raise Blind(f"machine {mid[:8]} ({host()}): {clean}/{CALIBRATION_N} clean gate runs under this "
|
|
405
|
+
"configuration; chaos stays BLIND until calibrated (forgeproof chaos-calibrate)")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def calibrate(runs: int = CALIBRATION_N) -> dict:
|
|
409
|
+
"""Run the validator's NC gate (no probe) until ``runs`` gate runs are recorded for this
|
|
410
|
+
machine and configuration. Writes ONLY the history file. Stops at the first survival: the
|
|
411
|
+
machine is latched and more runs cannot unlatch it."""
|
|
412
|
+
lib_dir = config.library_dir()
|
|
413
|
+
path = _history_path()
|
|
414
|
+
work = Path(tempfile.mkdtemp(prefix="chaos-cal-", dir=config.scratch_dir()))
|
|
415
|
+
done = 0
|
|
416
|
+
try:
|
|
417
|
+
lib = work / "lib"
|
|
418
|
+
stage_library(lib_dir, lib)
|
|
419
|
+
while done < runs:
|
|
420
|
+
res = _run_recorded(lib, GATE_ONLY, work, path)
|
|
421
|
+
gate = res.get("gate")
|
|
422
|
+
if not _gate_shape(gate):
|
|
423
|
+
raise Blind(f"calibration child failed: {res.get('error', 'no gate')}")
|
|
424
|
+
done += gate["runs"]
|
|
425
|
+
if gate.get("survived"):
|
|
426
|
+
break
|
|
427
|
+
finally:
|
|
428
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
429
|
+
m = load_history(path)["machines"].get(machine_id(), {})
|
|
430
|
+
return {"machine": machine_id(), "hostname": host(), "gate_runs_this_call": done,
|
|
431
|
+
"survived": m.get("survived", {}),
|
|
432
|
+
"config": m.get("configs", {}).get(config_key(fingerprint()), {})}
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
_CACHE: dict = {}
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def result_for(body: bytes, probe: str) -> dict:
|
|
439
|
+
"""One child run per (bytes, probe) per process. learn asks once per function."""
|
|
440
|
+
key = (hashlib.sha256(body).hexdigest(), probe)
|
|
441
|
+
if key not in _CACHE:
|
|
442
|
+
try:
|
|
443
|
+
lib_dir = config.library_dir()
|
|
444
|
+
except config.NotConfigured as e:
|
|
445
|
+
raise Blind(f"not configured: {e}") from None
|
|
446
|
+
path = _history_path()
|
|
447
|
+
work = Path(tempfile.mkdtemp(prefix="chaos-", dir=config.scratch_dir()))
|
|
448
|
+
try:
|
|
449
|
+
lib = work / "lib"
|
|
450
|
+
stage_library(lib_dir, lib)
|
|
451
|
+
_CACHE[key] = _run_recorded(lib, probe, work, path)
|
|
452
|
+
finally:
|
|
453
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
454
|
+
return _CACHE[key]
|