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,1331 @@
|
|
|
1
|
+
# Ported from the pattern library's validator, `tools/pattern-scoring/validator/chaos_scan.py` at library
|
|
2
|
+
# commit 4b65044b (git blob fab0bdd27d7f56a5db534f6bca59b20b46933683, md5 23f0676a038ea5c8d4ffc9b2c414c86c;
|
|
3
|
+
# the deploy host's validator-COPY-from-dot5/chaos_scan.py is the same blob). Byte for byte below the
|
|
4
|
+
# marker, with ONE edit after the port (standard §7b: personal names stay in the private repo): the
|
|
5
|
+
# docstring's "law (<name>'s / AWS game-day)" now says "law (the project's / AWS game-day)". The
|
|
6
|
+
# private-only test tests/test_port_provenance.py reverses it and checks the source md5.
|
|
7
|
+
# Step 6b-2 (design v1.4.5 §4.3, decision L3). Used ONLY by engines/chaos_runner.py, in a child process,
|
|
8
|
+
# with LIB pointed at a temp copy of pinned library bytes and HERE at a temp dir: the ported scan()
|
|
9
|
+
# writes HERE/chaos_report.json, so nothing here may run with the defaults. Not imported elsewhere.
|
|
10
|
+
# --- ported body below ---
|
|
11
|
+
#!/usr/bin/env python3
|
|
12
|
+
"""
|
|
13
|
+
chaos_scan.py — FOLD 5: chaos / fault-injection (AWS game-day method). NEW BUILD (no inherited
|
|
14
|
+
code) — designed against R13 (state-lies-over-time). Keeps the validation tool SEPARATE from Forge
|
|
15
|
+
Gate.
|
|
16
|
+
|
|
17
|
+
R13 (recipes.py) attacks stateful patterns with adversarial INPUT SEQUENCES (idle_then_burst,
|
|
18
|
+
expire_without_touch, clock_rewind, ...). Chaos goes one level deeper: it injects a REALISTIC FAULT
|
|
19
|
+
into the middle of an operation a pattern CLAIMS to survive, then checks a SURVIVAL PREDICATE. The
|
|
20
|
+
law (the project's / AWS game-day): a pattern advertised as crash-safe that DIES to its OWN injected fault
|
|
21
|
+
is INVALID — the safety claim is theater.
|
|
22
|
+
|
|
23
|
+
Each probe injects the exact fault the pattern claims to withstand and asserts the invariant that
|
|
24
|
+
must survive it. Every probe is paired with a NEGATIVE CONTROL: a crash-UNSAFE variant of the same
|
|
25
|
+
operation that MUST die to the identical fault — proving the survival predicate actually discriminates
|
|
26
|
+
safe from unsafe (not a check that anything passes).
|
|
27
|
+
|
|
28
|
+
Targets (fault -> survival predicate):
|
|
29
|
+
atomic_write_temp_rename : crash before the rename commits -> destination is intact OLD content
|
|
30
|
+
(never truncated/partial) and no temp litter is left behind.
|
|
31
|
+
write_ahead_log : torn tail (crash mid-append truncates the last record) -> replay
|
|
32
|
+
recovers every COMPLETE record, drops the torn one, and does NOT crash.
|
|
33
|
+
checkpoint_resume : crash after batch 0 commits -> resume processes every record EXACTLY
|
|
34
|
+
ONCE (no skip, no duplicate).
|
|
35
|
+
|
|
36
|
+
Verdict-ladder mapping:
|
|
37
|
+
pattern SURVIVES its fault -> chaos positive oracle ('chaos') in oracle_coverage.
|
|
38
|
+
pattern DIES to its fault -> INVALID-CANDIDATE (safety theater) -> evidence card, routed to
|
|
39
|
+
calibration; MUST NOT auto-flip a frozen exam verdict (a contradiction => the injection is
|
|
40
|
+
miscalibrated, not the ruler).
|
|
41
|
+
|
|
42
|
+
Faults are injected into throwaway temp dirs / monkeypatches that are always restored; the real
|
|
43
|
+
signed library is never mutated and the exam grader is never touched.
|
|
44
|
+
"""
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
import importlib.util, json, os, tempfile, shutil, struct, pickle, time
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
|
|
49
|
+
HERE = Path(__file__).resolve().parent
|
|
50
|
+
LIB = Path(os.path.expanduser("~/aura-pattern-library"))
|
|
51
|
+
|
|
52
|
+
ATOMIC = "python/system-administration/filesystem-integrity/atomic_write_temp_rename.py"
|
|
53
|
+
WAL = "python/programming/persistence/write_ahead_log.py"
|
|
54
|
+
CKPT = "python/system-administration/data-pipeline-ops/checkpoint_resume.py"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _load(relpath, name):
|
|
58
|
+
import sys
|
|
59
|
+
spec = importlib.util.spec_from_file_location(name, str(LIB / relpath))
|
|
60
|
+
m = importlib.util.module_from_spec(spec)
|
|
61
|
+
sys.modules[name] = m # WAL pickles its LogEntry -> pickle must resolve the module by name
|
|
62
|
+
spec.loader.exec_module(m)
|
|
63
|
+
return m
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _Crash(RuntimeError):
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# ---------------------------------------------------------------- atomic write
|
|
71
|
+
def _atomic_write_trial(write_fn):
|
|
72
|
+
"""Return (dest_ok, no_litter). write_fn(target, content) is crashed mid-write via os.rename."""
|
|
73
|
+
d = tempfile.mkdtemp(prefix="chaos_aw_")
|
|
74
|
+
try:
|
|
75
|
+
target = os.path.join(d, "target.txt")
|
|
76
|
+
# write_fn is expected to atomic_write; establish OLD via the same fn (no fault yet)
|
|
77
|
+
write_fn(target, b"OLD_v1", inject=False)
|
|
78
|
+
orig_rename = os.rename
|
|
79
|
+
os.rename = lambda a, b: (_ for _ in ()).throw(_Crash("crash before rename commit"))
|
|
80
|
+
try:
|
|
81
|
+
write_fn(target, b"NEW_v2", inject=True)
|
|
82
|
+
except Exception:
|
|
83
|
+
pass # the crash is expected; we test what it left behind
|
|
84
|
+
finally:
|
|
85
|
+
os.rename = orig_rename
|
|
86
|
+
dest = Path(target).read_bytes() if os.path.exists(target) else b""
|
|
87
|
+
dest_ok = dest == b"OLD_v1" # intact old content, never partial/empty
|
|
88
|
+
litter = [f for f in os.listdir(d) if f != "target.txt"]
|
|
89
|
+
return dest_ok, (len(litter) == 0)
|
|
90
|
+
finally:
|
|
91
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def chaos_atomic_write():
|
|
95
|
+
m = _load(ATOMIC, "chaos_atomic")
|
|
96
|
+
|
|
97
|
+
def real_write(target, content, inject=False):
|
|
98
|
+
m.atomic_write(target, content) # the pattern; os.rename is patched to crash when inject
|
|
99
|
+
|
|
100
|
+
dest_ok, no_litter = _atomic_write_trial(real_write)
|
|
101
|
+
survived = dest_ok and no_litter
|
|
102
|
+
return {"survived": survived, "predicate": "dest==OLD (no partial) & no temp litter",
|
|
103
|
+
"detail": f"dest_intact={dest_ok} no_litter={no_litter}"}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _nc_atomic_write():
|
|
107
|
+
"""Crash-UNSAFE writer: writes straight to the destination (truncates it first). The same crash
|
|
108
|
+
leaves the destination truncated -> predicate fails -> proves the injection is real."""
|
|
109
|
+
def naive_write(target, content, inject=False):
|
|
110
|
+
if not inject:
|
|
111
|
+
with open(target, "wb") as f:
|
|
112
|
+
f.write(content)
|
|
113
|
+
return
|
|
114
|
+
with open(target, "wb") as f: # truncates the destination immediately
|
|
115
|
+
raise _Crash("crash after truncate, before write") # destination now empty
|
|
116
|
+
dest_ok, _ = _atomic_write_trial(naive_write)
|
|
117
|
+
return dest_ok is False # NC must DIE (dest corrupted)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ---------------------------------------------------------------- write-ahead log
|
|
121
|
+
def _wal_torn_trial(replay_fn, n_records=3, cut=3):
|
|
122
|
+
"""Append n records, truncate the tail (torn last record), then replay via replay_fn(WAL, log).
|
|
123
|
+
Returns (recovered_count, crashed_bool)."""
|
|
124
|
+
m = _load(WAL, "chaos_wal")
|
|
125
|
+
d = tempfile.mkdtemp(prefix="chaos_wal_")
|
|
126
|
+
try:
|
|
127
|
+
log = os.path.join(d, "wal.log")
|
|
128
|
+
w = m.WAL(log)
|
|
129
|
+
for i in range(n_records):
|
|
130
|
+
w.append(m.LogEntryType.INSERT, f"k{i}", f"v{i}")
|
|
131
|
+
size = os.path.getsize(log)
|
|
132
|
+
with open(log, "r+b") as f:
|
|
133
|
+
f.truncate(size - cut) # torn tail: cut into the last record's body
|
|
134
|
+
try:
|
|
135
|
+
got = []
|
|
136
|
+
recovered = replay_fn(m, log, got)
|
|
137
|
+
return recovered, False
|
|
138
|
+
except Exception:
|
|
139
|
+
return -1, True # replay crashed on the torn tail
|
|
140
|
+
finally:
|
|
141
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def chaos_wal():
|
|
145
|
+
def real_replay(m, log, got):
|
|
146
|
+
w2 = m.WAL(log)
|
|
147
|
+
return w2.replay(lambda e: got.append(e.sequence_number))
|
|
148
|
+
recovered, crashed = _wal_torn_trial(real_replay)
|
|
149
|
+
survived = (not crashed) and recovered == 2 # 3 appended, last torn -> 2 complete recovered
|
|
150
|
+
return {"survived": survived, "predicate": "replay recovers complete records, drops torn tail, no crash",
|
|
151
|
+
"detail": f"recovered={recovered} crashed={crashed} (expected 2, no crash)"}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _nc_wal():
|
|
155
|
+
"""Crash-UNSAFE replay: reads size frame then blindly pickle.loads whatever bytes remain, with no
|
|
156
|
+
incomplete-read guard and no try/except -> the torn tail makes it crash -> proves the fault real."""
|
|
157
|
+
def naive_replay(m, log, got):
|
|
158
|
+
with open(log, "rb") as f:
|
|
159
|
+
while True:
|
|
160
|
+
sz = f.read(4)
|
|
161
|
+
if len(sz) < 4:
|
|
162
|
+
break
|
|
163
|
+
size = struct.unpack("I", sz)[0]
|
|
164
|
+
data = f.read(size) # may be short on the torn tail
|
|
165
|
+
entry = pickle.loads(data) # no len(data)<size guard -> raises on torn tail
|
|
166
|
+
got.append(entry.sequence_number)
|
|
167
|
+
return len(got)
|
|
168
|
+
recovered, crashed = _wal_torn_trial(naive_replay)
|
|
169
|
+
return crashed is True # NC must DIE (uncaught crash on torn tail)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# ---------------------------------------------------------------- checkpoint / resume
|
|
173
|
+
def _ckpt_trial(m):
|
|
174
|
+
"""Crash the run after batch 0 commits its checkpoint, then resume. Return the resumed output."""
|
|
175
|
+
d = tempfile.mkdtemp(prefix="chaos_ck_")
|
|
176
|
+
try:
|
|
177
|
+
cp = os.path.join(d, "checkpoint.json")
|
|
178
|
+
records = [{"id": x, "value": v} for x, v in (("a", 1), ("b", 2), ("c", 3), ("d", 4))]
|
|
179
|
+
# phase 1: crash json.dump after the FIRST checkpoint write (batch 0 committed)
|
|
180
|
+
real_dump = m.json.dump
|
|
181
|
+
state = {"n": 0}
|
|
182
|
+
|
|
183
|
+
def crashing_dump(obj, f, *a, **k):
|
|
184
|
+
real_dump(obj, f, *a, **k)
|
|
185
|
+
state["n"] += 1
|
|
186
|
+
if state["n"] == 1:
|
|
187
|
+
raise _Crash("crash after batch 0 checkpoint")
|
|
188
|
+
m.json.dump = crashing_dump
|
|
189
|
+
try:
|
|
190
|
+
m.process_batch_with_checkpoint(records, cp)
|
|
191
|
+
except _Crash:
|
|
192
|
+
pass
|
|
193
|
+
finally:
|
|
194
|
+
m.json.dump = real_dump
|
|
195
|
+
# phase 2: resume
|
|
196
|
+
return m.process_batch_with_checkpoint(records, cp), records
|
|
197
|
+
finally:
|
|
198
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def chaos_checkpoint():
|
|
202
|
+
m = _load(CKPT, "chaos_ckpt")
|
|
203
|
+
out, records = _ckpt_trial(m)
|
|
204
|
+
ids = [r["id"] for r in out]
|
|
205
|
+
exactly_once = sorted(ids) == ["a", "b", "c", "d"] and len(ids) == 4
|
|
206
|
+
values_ok = all(any(o["id"] == r["id"] and o["processed"] == r["value"] + 100 for o in out)
|
|
207
|
+
for r in records)
|
|
208
|
+
survived = exactly_once and values_ok
|
|
209
|
+
return {"survived": survived, "predicate": "resume processes every record EXACTLY once",
|
|
210
|
+
"detail": f"ids={ids} exactly_once={exactly_once} values_ok={values_ok}"}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _nc_checkpoint():
|
|
214
|
+
"""Crash-UNSAFE resumer: ignores the checkpoint and reprocesses from the start -> after crash+
|
|
215
|
+
resume, batch 0 records appear TWICE -> exactly-once predicate fails -> proves the fault real."""
|
|
216
|
+
d = tempfile.mkdtemp(prefix="chaos_ncck_")
|
|
217
|
+
try:
|
|
218
|
+
records = [{"id": x, "value": v} for x, v in (("a", 1), ("b", 2), ("c", 3), ("d", 4))]
|
|
219
|
+
|
|
220
|
+
def naive_resume(prior_output):
|
|
221
|
+
# simulates a resumer with no checkpoint memory: redo everything, appended to prior work
|
|
222
|
+
redo = [{"id": r["id"], "processed": r["value"] + 100} for r in records]
|
|
223
|
+
return prior_output + redo
|
|
224
|
+
prior = [{"id": "a", "processed": 101}, {"id": "b", "processed": 102}] # batch 0 already done
|
|
225
|
+
out = naive_resume(prior)
|
|
226
|
+
ids = [r["id"] for r in out]
|
|
227
|
+
exactly_once = sorted(ids) == ["a", "b", "c", "d"] and len(ids) == 4
|
|
228
|
+
return exactly_once is False # NC must DIE (a,b duplicated)
|
|
229
|
+
finally:
|
|
230
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# ================================================================ WAVE 3 (2026-07-27)
|
|
234
|
+
# Targeting law: build game-days for patterns whose ADVERTISED CLAIM *is* survival — there a chaos
|
|
235
|
+
# oracle is not merely extra evidence, it is the honest test of the claim the pattern is sold on.
|
|
236
|
+
|
|
237
|
+
SEGWAL = "python/programming/persistence/segmented_wal.py"
|
|
238
|
+
JOURNALED = "python/system-administration/state-db-durability/journaled_write.py"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ---------------------------------------------------------------- segmented WAL (torn tail)
|
|
242
|
+
def _segwal_torn_trial(recover_fn):
|
|
243
|
+
"""Append 5 records, TRUNCATE the segment mid-record (the classic torn tail a crash leaves),
|
|
244
|
+
then recover. Returns (recovered_payloads, crashed)."""
|
|
245
|
+
m = _load(SEGWAL, "chaos_segwal")
|
|
246
|
+
d = tempfile.mkdtemp(prefix="chaos_segwal_")
|
|
247
|
+
try:
|
|
248
|
+
wal = m.WriteAheadLog(d)
|
|
249
|
+
for i in range(5):
|
|
250
|
+
wal.append(f"rec{i}".encode())
|
|
251
|
+
if hasattr(wal, "close"):
|
|
252
|
+
wal.close()
|
|
253
|
+
segs = sorted(Path(d).glob("*.wal"))
|
|
254
|
+
p = str(segs[-1])
|
|
255
|
+
size = os.path.getsize(p)
|
|
256
|
+
with open(p, "r+b") as f:
|
|
257
|
+
f.truncate(size - 3) # torn: last record's payload is short
|
|
258
|
+
try:
|
|
259
|
+
recovered = recover_fn(m, d)
|
|
260
|
+
except Exception as e:
|
|
261
|
+
return [], True, f"{type(e).__name__}: {e}"
|
|
262
|
+
out = [(r.data if hasattr(r, "data") else r) for r in recovered]
|
|
263
|
+
return out, False, ""
|
|
264
|
+
finally:
|
|
265
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def chaos_segmented_wal():
|
|
269
|
+
out, crashed, err = _segwal_torn_trial(lambda m, d: m.recover_from_crash(d))
|
|
270
|
+
expect = [f"rec{i}".encode() for i in range(4)] # 4 complete; the 5th is torn
|
|
271
|
+
exact = out == expect
|
|
272
|
+
survived = (not crashed) and exact
|
|
273
|
+
return {"survived": survived,
|
|
274
|
+
"predicate": "replay recovers every COMPLETE record, drops the torn tail, never crashes",
|
|
275
|
+
"detail": f"crashed={crashed}{' ' + err if err else ''} recovered={[o.decode(errors='replace') for o in out]} exact={exact}"}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _nc_segmented_wal():
|
|
279
|
+
"""Crash-UNSAFE reader: trusts the length prefix and NEVER verifies the checksum, so a torn tail
|
|
280
|
+
is either accepted as a (short/garbage) record or blows up. Either way the predicate must fail —
|
|
281
|
+
proving the checksum is what actually buys the survival, not the harness being lenient."""
|
|
282
|
+
m = _load(SEGWAL, "chaos_ncsegwal")
|
|
283
|
+
d = tempfile.mkdtemp(prefix="chaos_ncsegwal_")
|
|
284
|
+
try:
|
|
285
|
+
wal = m.WriteAheadLog(d)
|
|
286
|
+
for i in range(5):
|
|
287
|
+
wal.append(f"rec{i}".encode())
|
|
288
|
+
if hasattr(wal, "close"):
|
|
289
|
+
wal.close()
|
|
290
|
+
segs = sorted(Path(d).glob("*.wal"))
|
|
291
|
+
p = str(segs[-1])
|
|
292
|
+
size = os.path.getsize(p)
|
|
293
|
+
with open(p, "r+b") as f:
|
|
294
|
+
f.truncate(size - 3)
|
|
295
|
+
# naive: split on the 4-byte length prefix, no checksum check, no bounds discipline
|
|
296
|
+
raw = Path(p).read_bytes()
|
|
297
|
+
got, i = [], 0
|
|
298
|
+
try:
|
|
299
|
+
while i + 4 <= len(raw):
|
|
300
|
+
ln = struct.unpack(">I", raw[i:i + 4])[0]
|
|
301
|
+
got.append(raw[i + 4:i + 4 + ln]) # may run past EOF -> short/garbage payload
|
|
302
|
+
i += 4 + ln
|
|
303
|
+
except Exception:
|
|
304
|
+
return True # died to the fault
|
|
305
|
+
expect = [f"rec{i}".encode() for i in range(4)]
|
|
306
|
+
return got != expect # NC must NOT reproduce the clean result
|
|
307
|
+
finally:
|
|
308
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
# ---------------------------------------------------------------- journaled write (crash mid-apply)
|
|
312
|
+
def _journaled_trial(recover_fn):
|
|
313
|
+
"""Crash BETWEEN a flushed journal and the main-store update — the exact window the pattern
|
|
314
|
+
claims to close. Recovery must leave the store in ONE of the two legal states (old or new),
|
|
315
|
+
never a torn/half-applied one."""
|
|
316
|
+
m = _load(JOURNALED, "chaos_journaled")
|
|
317
|
+
d = tempfile.mkdtemp(prefix="chaos_jw_")
|
|
318
|
+
try:
|
|
319
|
+
data_path = os.path.join(d, "store.json")
|
|
320
|
+
journal_path = os.path.join(d, "store.journal")
|
|
321
|
+
Path(data_path).write_text(json.dumps({"v": "OLD"}))
|
|
322
|
+
# journal fully flushed, main store NOT yet updated == the crash window
|
|
323
|
+
Path(journal_path).write_text(json.dumps({"old": {"v": "OLD"}, "new": {"v": "NEW"}}))
|
|
324
|
+
try:
|
|
325
|
+
recover_fn(m, data_path, journal_path)
|
|
326
|
+
except Exception as e:
|
|
327
|
+
return None, True, f"{type(e).__name__}: {e}"
|
|
328
|
+
final = json.loads(Path(data_path).read_text())
|
|
329
|
+
return final, False, ""
|
|
330
|
+
finally:
|
|
331
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def chaos_journaled_write():
|
|
335
|
+
final, crashed, err = _journaled_trial(
|
|
336
|
+
lambda m, dp, jp: m.recover_from_journal(dp, jp))
|
|
337
|
+
legal = final in ({"v": "OLD"}, {"v": "NEW"})
|
|
338
|
+
survived = (not crashed) and legal
|
|
339
|
+
return {"survived": survived,
|
|
340
|
+
"predicate": "after crash mid-apply the store is OLD or NEW — never a torn/half state",
|
|
341
|
+
"detail": f"crashed={crashed}{' ' + err if err else ''} final={final} legal={legal}"}
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _nc_journaled_write():
|
|
345
|
+
"""Crash-UNSAFE applier: writes the new value field-by-field with the crash landing in the
|
|
346
|
+
middle, leaving a store that is neither OLD nor NEW -> the legality predicate must fail."""
|
|
347
|
+
d = tempfile.mkdtemp(prefix="chaos_ncjw_")
|
|
348
|
+
try:
|
|
349
|
+
data_path = os.path.join(d, "store.json")
|
|
350
|
+
Path(data_path).write_text(json.dumps({"v": "OLD"}))
|
|
351
|
+
# no journal, no atomic swap: truncate then crash before the new bytes land
|
|
352
|
+
with open(data_path, "w") as f:
|
|
353
|
+
f.write('{"v": "NE') # torn write
|
|
354
|
+
final = Path(data_path).read_text()
|
|
355
|
+
try:
|
|
356
|
+
parsed = json.loads(final)
|
|
357
|
+
except Exception:
|
|
358
|
+
return True # unparseable == torn == died (good)
|
|
359
|
+
return parsed not in ({"v": "OLD"}, {"v": "NEW"})
|
|
360
|
+
finally:
|
|
361
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
# ================================================================ WAVE 3 batch 2 (2026-07-27)
|
|
365
|
+
PITR = "python/system-administration/state-db-durability/point_in_time_restore.py"
|
|
366
|
+
ETL = "python/system-administration/data-pipeline-ops/idempotent_etl_step.py"
|
|
367
|
+
REPL = "python/system-administration/mesh-distributed/idempotent_replication.py"
|
|
368
|
+
ONCE = "python/system-administration/concurrency-locking/idempotent_once_guard.py"
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _pitr_setup(d, m):
|
|
372
|
+
"""Base backup + a log whose tail is NEWER than the restore target (the entries a PITR must
|
|
373
|
+
refuse to replay)."""
|
|
374
|
+
import sqlite3
|
|
375
|
+
base = os.path.join(d, "base.db")
|
|
376
|
+
conn = sqlite3.connect(base)
|
|
377
|
+
conn.execute("CREATE TABLE t (val TEXT)")
|
|
378
|
+
conn.commit(); conn.close()
|
|
379
|
+
log = os.path.join(d, "wal.log")
|
|
380
|
+
with open(log, "w") as f:
|
|
381
|
+
for ts, val in [(1, "a"), (2, "b"), (3, "c"), (4, "TOO_NEW"), (5, "TOO_NEW2")]:
|
|
382
|
+
f.write(json.dumps({"ts": ts, "val": val}) + "\n")
|
|
383
|
+
return base, log
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def chaos_point_in_time_restore():
|
|
387
|
+
"""FAULT: crash mid-restore, then resume. PREDICATE: the resumed restore equals a clean one —
|
|
388
|
+
every entry <= target replayed EXACTLY once, and NO entry newer than the target ever lands."""
|
|
389
|
+
import sqlite3
|
|
390
|
+
m = _load(PITR, "chaos_pitr")
|
|
391
|
+
d = tempfile.mkdtemp(prefix="chaos_pitr_")
|
|
392
|
+
try:
|
|
393
|
+
base, log = _pitr_setup(d, m)
|
|
394
|
+
db = os.path.join(d, "restored.db")
|
|
395
|
+
# --- crash the first restore partway through the replay ---
|
|
396
|
+
real_connect = sqlite3.connect
|
|
397
|
+
|
|
398
|
+
opened = []
|
|
399
|
+
|
|
400
|
+
class _CrashConn:
|
|
401
|
+
def __init__(self, inner): self._i, self._n = inner, 0
|
|
402
|
+
def execute(self, *a, **k):
|
|
403
|
+
self._n += 1
|
|
404
|
+
if self._n > 2:
|
|
405
|
+
raise _Crash("crash mid-replay")
|
|
406
|
+
return self._i.execute(*a, **k)
|
|
407
|
+
def __getattr__(self, n): return getattr(self._i, n)
|
|
408
|
+
|
|
409
|
+
def _mk(p, *a, **k):
|
|
410
|
+
inner = real_connect(p, *a, **k)
|
|
411
|
+
opened.append(inner)
|
|
412
|
+
return _CrashConn(inner)
|
|
413
|
+
|
|
414
|
+
sqlite3.connect = _mk
|
|
415
|
+
try:
|
|
416
|
+
m.restore_to(base, log, 3, db)
|
|
417
|
+
except Exception:
|
|
418
|
+
pass # expected crash
|
|
419
|
+
finally:
|
|
420
|
+
sqlite3.connect = real_connect
|
|
421
|
+
for c in opened: # a crashed process releases its handles;
|
|
422
|
+
try: c.close() # emulate that so the db is not left locked
|
|
423
|
+
except Exception: pass
|
|
424
|
+
# --- resume: run the restore again, cleanly ---
|
|
425
|
+
m.restore_to(base, log, 3, db)
|
|
426
|
+
got = m.vals(db)
|
|
427
|
+
clean_db = os.path.join(d, "clean.db")
|
|
428
|
+
m.restore_to(base, log, 3, clean_db)
|
|
429
|
+
clean = m.vals(clean_db)
|
|
430
|
+
no_future = all("TOO_NEW" not in str(v) for v in got)
|
|
431
|
+
idempotent = list(got) == list(clean) == ["a", "b", "c"]
|
|
432
|
+
return {"survived": no_future and idempotent,
|
|
433
|
+
"predicate": "resume == clean restore (exactly once) & no entry newer than target",
|
|
434
|
+
"detail": f"got={list(got)} clean={list(clean)} no_future={no_future} idempotent={idempotent}"}
|
|
435
|
+
finally:
|
|
436
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _nc_point_in_time_restore():
|
|
440
|
+
"""Crash-UNSAFE restorer: resumes by APPENDING to the half-built db instead of restarting from
|
|
441
|
+
the base -> the interrupted entries are replayed twice."""
|
|
442
|
+
import sqlite3
|
|
443
|
+
d = tempfile.mkdtemp(prefix="chaos_ncpitr_")
|
|
444
|
+
try:
|
|
445
|
+
db = os.path.join(d, "r.db")
|
|
446
|
+
conn = sqlite3.connect(db)
|
|
447
|
+
conn.execute("CREATE TABLE t (val TEXT)")
|
|
448
|
+
for v in ("a", "b"): # partial work from the crashed attempt
|
|
449
|
+
conn.execute("INSERT INTO t (val) VALUES (?)", (v,))
|
|
450
|
+
conn.commit()
|
|
451
|
+
for v in ("a", "b", "c"): # naive resume: replay everything again
|
|
452
|
+
conn.execute("INSERT INTO t (val) VALUES (?)", (v,))
|
|
453
|
+
conn.commit()
|
|
454
|
+
got = [r[0] for r in conn.execute("SELECT val FROM t")]
|
|
455
|
+
conn.close()
|
|
456
|
+
return got != ["a", "b", "c"] # NC must duplicate
|
|
457
|
+
finally:
|
|
458
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def chaos_idempotent_etl():
|
|
462
|
+
"""FAULT: crash mid-transform after some records are checkpointed. PREDICATE: resuming produces
|
|
463
|
+
output bit-identical to an uninterrupted run, with no duplicated record."""
|
|
464
|
+
m = _load(ETL, "chaos_etl")
|
|
465
|
+
d = tempfile.mkdtemp(prefix="chaos_etl_")
|
|
466
|
+
try:
|
|
467
|
+
records = [{"id": f"r{i}", "value": i} for i in range(6)]
|
|
468
|
+
cp = os.path.join(d, "ckpt.json")
|
|
469
|
+
real_ck = m.stable_checksum
|
|
470
|
+
state = {"n": 0}
|
|
471
|
+
|
|
472
|
+
def crashing(v):
|
|
473
|
+
state["n"] += 1
|
|
474
|
+
if state["n"] > 3:
|
|
475
|
+
raise _Crash("crash mid-transform")
|
|
476
|
+
return real_ck(v)
|
|
477
|
+
|
|
478
|
+
m.stable_checksum = crashing
|
|
479
|
+
try:
|
|
480
|
+
m.idempotent_transform(records, cp)
|
|
481
|
+
except Exception:
|
|
482
|
+
pass # expected
|
|
483
|
+
finally:
|
|
484
|
+
m.stable_checksum = real_ck
|
|
485
|
+
resumed = m.idempotent_transform(records, cp) # resume from checkpoint
|
|
486
|
+
clean_cp = os.path.join(d, "clean.json")
|
|
487
|
+
clean = m.idempotent_transform(records, clean_cp) # uninterrupted reference
|
|
488
|
+
ids = [r.get("id") for r in resumed] if isinstance(resumed, list) else []
|
|
489
|
+
no_dupes = len(ids) == len(set(ids))
|
|
490
|
+
identical = resumed == clean
|
|
491
|
+
return {"survived": bool(identical and no_dupes),
|
|
492
|
+
"predicate": "resume is bit-identical to an uninterrupted run, no duplicates",
|
|
493
|
+
"detail": f"identical={identical} no_dupes={no_dupes} n={len(ids)}"}
|
|
494
|
+
finally:
|
|
495
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _nc_idempotent_etl():
|
|
499
|
+
"""Crash-UNSAFE ETL: no checkpoint, so a resume re-emits the records it already produced."""
|
|
500
|
+
records = [{"id": f"r{i}", "value": i} for i in range(6)]
|
|
501
|
+
produced = [{"id": r["id"]} for r in records[:3]] # work done before the crash
|
|
502
|
+
resumed = produced + [{"id": r["id"]} for r in records] # naive resume redoes everything
|
|
503
|
+
ids = [r["id"] for r in resumed]
|
|
504
|
+
return len(ids) != len(set(ids)) # NC must duplicate
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def chaos_idempotent_replication():
|
|
508
|
+
"""FAULT: crash mid-replication, then the SAME writes are re-delivered on resume (at-least-once
|
|
509
|
+
delivery is the realistic failure). PREDICATE: each write lands exactly once."""
|
|
510
|
+
m = _load(REPL, "chaos_repl")
|
|
511
|
+
store = m.ReplicatedStore("replica-A")
|
|
512
|
+
writes = [(f"w{i}", f"k{i}", f"v{i}") for i in range(5)]
|
|
513
|
+
for w in writes[:3]:
|
|
514
|
+
store.apply_write(*w) # ... crash here ...
|
|
515
|
+
for w in writes:
|
|
516
|
+
store.apply_write(*w) # resume re-delivers everything
|
|
517
|
+
applied = store.get_applied()
|
|
518
|
+
n = len(applied)
|
|
519
|
+
data_ok = all(store.data.get(f"k{i}") == f"v{i}" for i in range(5))
|
|
520
|
+
exactly_once = n == 5 and data_ok
|
|
521
|
+
return {"survived": exactly_once,
|
|
522
|
+
"predicate": "re-delivered writes apply exactly once (no duplicate application)",
|
|
523
|
+
"detail": f"applied={n} expected=5 data_ok={data_ok}"}
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _nc_idempotent_replication():
|
|
527
|
+
"""Crash-UNSAFE replica: no write_id tracking -> re-delivery double-applies."""
|
|
528
|
+
applied = []
|
|
529
|
+
writes = [(f"w{i}", f"k{i}", f"v{i}") for i in range(5)]
|
|
530
|
+
for w in writes[:3]:
|
|
531
|
+
applied.append(w[0])
|
|
532
|
+
for w in writes:
|
|
533
|
+
applied.append(w[0]) # no dedupe
|
|
534
|
+
return len(applied) != len(set(applied)) # NC must duplicate
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def chaos_idempotent_once_guard():
|
|
538
|
+
"""FAULT: two concurrent callers race the same guarded action. PREDICATE: it runs exactly once."""
|
|
539
|
+
import threading
|
|
540
|
+
m = _load(ONCE, "chaos_once")
|
|
541
|
+
d = tempfile.mkdtemp(prefix="chaos_once_")
|
|
542
|
+
try:
|
|
543
|
+
marker = os.path.join(d, "done.marker")
|
|
544
|
+
results, ran = {}, []
|
|
545
|
+
barrier = threading.Barrier(2)
|
|
546
|
+
|
|
547
|
+
def caller(cid):
|
|
548
|
+
barrier.wait() # maximise the race
|
|
549
|
+
if m.idempotent_action_once(marker, results, cid):
|
|
550
|
+
ran.append(cid)
|
|
551
|
+
|
|
552
|
+
ts = [threading.Thread(target=caller, args=(i,)) for i in range(2)]
|
|
553
|
+
for t in ts: t.start()
|
|
554
|
+
for t in ts: t.join()
|
|
555
|
+
return {"survived": len(ran) == 1,
|
|
556
|
+
"predicate": "exactly one concurrent caller performs the action",
|
|
557
|
+
"detail": f"ran={ran} (expected exactly 1)"}
|
|
558
|
+
finally:
|
|
559
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _nc_idempotent_once_guard():
|
|
563
|
+
"""Crash-UNSAFE guard: check-then-act with NO lock and a scheduling gap -> both callers run."""
|
|
564
|
+
import threading, time
|
|
565
|
+
d = tempfile.mkdtemp(prefix="chaos_nconce_")
|
|
566
|
+
try:
|
|
567
|
+
marker = os.path.join(d, "done.marker")
|
|
568
|
+
ran = []
|
|
569
|
+
barrier = threading.Barrier(2)
|
|
570
|
+
|
|
571
|
+
def caller(cid):
|
|
572
|
+
barrier.wait()
|
|
573
|
+
if not os.path.exists(marker): # TOCTOU window
|
|
574
|
+
time.sleep(0.02)
|
|
575
|
+
Path(marker).write_text("done")
|
|
576
|
+
ran.append(cid)
|
|
577
|
+
|
|
578
|
+
ts = [threading.Thread(target=caller, args=(i,)) for i in range(2)]
|
|
579
|
+
for t in ts: t.start()
|
|
580
|
+
for t in ts: t.join()
|
|
581
|
+
return len(ran) != 1 # NC must double-run
|
|
582
|
+
finally:
|
|
583
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
# ================================================================ WAVE 3 batch 3 (2026-07-27)
|
|
587
|
+
# REAL process kills — the most faithful fault in the suite: an actual SIGKILL mid-operation, not a
|
|
588
|
+
# monkeypatched exception. Nothing gets a chance to unwind, exactly like a power loss.
|
|
589
|
+
TXN = "python/system-administration/state-db-durability/transaction_rollback.py"
|
|
590
|
+
MIGRATE = "python/system-administration/state-db-durability/migration_with_rollback.py"
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def chaos_transaction_rollback():
|
|
594
|
+
"""FAULT: SIGKILL a child while its transaction is OPEN (one row already committed, two more
|
|
595
|
+
uncommitted). PREDICATE: the db reopens, the committed row survives, the uncommitted rows are
|
|
596
|
+
gone — atomicity across a real crash."""
|
|
597
|
+
m = _load(TXN, "chaos_txn")
|
|
598
|
+
d = tempfile.mkdtemp(prefix="chaos_txn_")
|
|
599
|
+
try:
|
|
600
|
+
db = os.path.join(d, "t.db")
|
|
601
|
+
marker = os.path.join(d, "ready.marker")
|
|
602
|
+
child = m.start_transaction_child(db, marker)
|
|
603
|
+
# NOTE: wait_for_marker returns None (it only blocks) — check the marker ourselves.
|
|
604
|
+
# A harness failure must RAISE (-> FLAG harness-error), never return survived=False:
|
|
605
|
+
# accusing a pattern of safety-theater because our timing slipped would be a false kill.
|
|
606
|
+
m.wait_for_marker(marker, 10)
|
|
607
|
+
if not os.path.exists(marker):
|
|
608
|
+
raise RuntimeError("harness: child never reached the commit marker")
|
|
609
|
+
time.sleep(0.4) # child sleeps 0.05 then BEGINs — ensure txn is OPEN
|
|
610
|
+
m.kill_child(child) # real SIGKILL, transaction still open
|
|
611
|
+
rows = m.read_rows(db)
|
|
612
|
+
committed_ok = "committed" in str(rows) or len(rows) == 1
|
|
613
|
+
rolled_back = len(rows) == 1
|
|
614
|
+
return {"survived": bool(rolled_back),
|
|
615
|
+
"predicate": "db reopens; committed row survives; uncommitted txn rows are gone",
|
|
616
|
+
"detail": f"rows={rows} rolled_back={rolled_back} committed_present={committed_ok}"}
|
|
617
|
+
finally:
|
|
618
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _nc_transaction_rollback():
|
|
622
|
+
"""Crash-UNSAFE writer: inserts in AUTOCOMMIT, so a kill at the same point leaves the
|
|
623
|
+
'uncommitted' rows durably present -> the rollback predicate fails."""
|
|
624
|
+
import sqlite3
|
|
625
|
+
d = tempfile.mkdtemp(prefix="chaos_nctxn_")
|
|
626
|
+
try:
|
|
627
|
+
db = os.path.join(d, "t.db")
|
|
628
|
+
conn = sqlite3.connect(db, isolation_level=None) # autocommit: no transaction to roll back
|
|
629
|
+
conn.execute("CREATE TABLE t (val TEXT)")
|
|
630
|
+
conn.execute("INSERT INTO t (val) VALUES ('committed')")
|
|
631
|
+
conn.execute("INSERT INTO t (val) VALUES ('txn1')") # would be rolled back if in a txn
|
|
632
|
+
conn.execute("INSERT INTO t (val) VALUES ('txn2')")
|
|
633
|
+
conn.close() # emulate the crash: nothing unwinds
|
|
634
|
+
conn = sqlite3.connect(db)
|
|
635
|
+
rows = [r[0] for r in conn.execute("SELECT val FROM t")]
|
|
636
|
+
conn.close()
|
|
637
|
+
return len(rows) != 1 # NC must keep the uncommitted rows
|
|
638
|
+
finally:
|
|
639
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def chaos_migration_with_rollback():
|
|
643
|
+
"""FAULT: SIGKILL a schema migration mid-flight. PREDICATE: the schema is either fully OLD or
|
|
644
|
+
fully NEW — never a half-applied hybrid — and the seeded data survives."""
|
|
645
|
+
m = _load(MIGRATE, "chaos_migrate")
|
|
646
|
+
d = tempfile.mkdtemp(prefix="chaos_mig_")
|
|
647
|
+
try:
|
|
648
|
+
db = os.path.join(d, "m.db")
|
|
649
|
+
m.create_old_schema(db)
|
|
650
|
+
child = m.start_migration_child(db)
|
|
651
|
+
try:
|
|
652
|
+
m.kill_child(child, 0.35, 5) # settle briefly so the migration is truly mid-flight
|
|
653
|
+
except TypeError:
|
|
654
|
+
m.kill_child(child) # tolerate a narrower signature
|
|
655
|
+
version, columns = m.get_schema_version(db)
|
|
656
|
+
try:
|
|
657
|
+
m.assert_valid_schema_state(version, columns)
|
|
658
|
+
valid = True
|
|
659
|
+
except AssertionError as e:
|
|
660
|
+
valid, err = False, str(e)[:80]
|
|
661
|
+
rows = None
|
|
662
|
+
try:
|
|
663
|
+
import sqlite3
|
|
664
|
+
conn = sqlite3.connect(db)
|
|
665
|
+
rows = [r[0] for r in conn.execute("SELECT name FROM t")]
|
|
666
|
+
conn.close()
|
|
667
|
+
except Exception as e:
|
|
668
|
+
rows = f"UNREADABLE {type(e).__name__}"
|
|
669
|
+
data_ok = isinstance(rows, list) and len(rows) == 2
|
|
670
|
+
return {"survived": bool(valid and data_ok),
|
|
671
|
+
"predicate": "schema is fully OLD or fully NEW (never partial) & seeded data intact",
|
|
672
|
+
"detail": f"version={version} columns={columns} valid={valid} rows={rows}"}
|
|
673
|
+
finally:
|
|
674
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _nc_migration_with_rollback():
|
|
678
|
+
"""Crash-UNSAFE migration: ALTERs the schema OUTSIDE a transaction and dies before backfilling,
|
|
679
|
+
leaving the hybrid state (new column present, data not migrated) the pattern claims to prevent."""
|
|
680
|
+
import sqlite3
|
|
681
|
+
d = tempfile.mkdtemp(prefix="chaos_ncmig_")
|
|
682
|
+
try:
|
|
683
|
+
db = os.path.join(d, "m.db")
|
|
684
|
+
conn = sqlite3.connect(db, isolation_level=None)
|
|
685
|
+
conn.execute("CREATE TABLE t (name TEXT)")
|
|
686
|
+
conn.execute("INSERT INTO t (name) VALUES ('a')")
|
|
687
|
+
conn.execute("INSERT INTO t (name) VALUES ('b')")
|
|
688
|
+
conn.execute("ALTER TABLE t ADD COLUMN email TEXT") # step 1 lands...
|
|
689
|
+
conn.close() # ...crash before the backfill
|
|
690
|
+
conn = sqlite3.connect(db)
|
|
691
|
+
cols = [r[1] for r in conn.execute("PRAGMA table_info(t)")]
|
|
692
|
+
emails = [r[0] for r in conn.execute("SELECT email FROM t")]
|
|
693
|
+
conn.close()
|
|
694
|
+
partial = ("email" in cols) and all(e is None for e in emails)
|
|
695
|
+
return partial # NC must land in the hybrid state
|
|
696
|
+
finally:
|
|
697
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
# ================================================================ WAVE 3 batch 4 — RUST BRIDGE
|
|
701
|
+
# chaos_scan._load is importlib/Python-only, so the rust durability family (the largest remaining
|
|
702
|
+
# pool of survival-claiming candidates) was unreachable. This bridge compiles the pattern with its
|
|
703
|
+
# main renamed + a probe-authored main appended, exactly like probes._rust_harness, and runs it.
|
|
704
|
+
import subprocess as _sp
|
|
705
|
+
|
|
706
|
+
RS_WAL = "rust/composed-systems/wal_append_replay.rs"
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def _rust_chaos(relpath, probe_main, fixture=False):
|
|
710
|
+
"""Compile <pattern source + probe main> and run it. Returns {rc, out, err} or {compile_err}.
|
|
711
|
+
The library file is only ever READ; everything happens in a temp dir."""
|
|
712
|
+
base = HERE / "regression_fixtures" if fixture else LIB
|
|
713
|
+
src = open(base / relpath, encoding="utf-8").read()
|
|
714
|
+
src = src.replace("fn main()", "fn pattern_main()") + "\n" + probe_main
|
|
715
|
+
d = tempfile.mkdtemp(prefix="chaos_rs_")
|
|
716
|
+
try:
|
|
717
|
+
p = os.path.join(d, "probe.rs")
|
|
718
|
+
open(p, "w", encoding="utf-8").write(src)
|
|
719
|
+
exe = os.path.join(d, "probe")
|
|
720
|
+
c = _sp.run(["rustc", "-O", "--edition", "2021", "-A", "warnings", "-o", exe, p],
|
|
721
|
+
capture_output=True, text=True, timeout=240)
|
|
722
|
+
if c.returncode != 0:
|
|
723
|
+
return {"compile_err": c.stderr[-400:]}
|
|
724
|
+
r = _sp.run([exe], capture_output=True, text=True, timeout=120)
|
|
725
|
+
return {"rc": r.returncode, "out": r.stdout, "err": r.stderr[-300:]}
|
|
726
|
+
finally:
|
|
727
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
# The strongest form of this fault: crash at EVERY byte offset, not one hand-picked cut. A log is
|
|
731
|
+
# durable only if a power loss at any instant leaves it recoverable — so we sweep all of them.
|
|
732
|
+
_WAL_SWEEP_MAIN = '''
|
|
733
|
+
fn main() {
|
|
734
|
+
let records: Vec<&[u8]> = vec![b"alpha", b"bravo", b"charlie", b"delta"];
|
|
735
|
+
let mut w = WalWriter::new();
|
|
736
|
+
for r in &records { w.append(r); }
|
|
737
|
+
let full = w.bytes().to_vec();
|
|
738
|
+
let n = full.len();
|
|
739
|
+
let (mut ok, mut total) = (0usize, 0usize);
|
|
740
|
+
let mut worst = String::new();
|
|
741
|
+
for cut in 1..=n {
|
|
742
|
+
total += 1;
|
|
743
|
+
let mut w2 = WalWriter::new();
|
|
744
|
+
for r in &records { w2.append(r); }
|
|
745
|
+
w2.simulate_crash(cut); // truncate the log at every offset
|
|
746
|
+
let data = w2.bytes().to_vec();
|
|
747
|
+
let reader = WalReader::new(&data);
|
|
748
|
+
let (recovered, torn) = reader.replay();
|
|
749
|
+
// PREDICATE: whatever survives must be a genuine PREFIX of what was written — never a
|
|
750
|
+
// garbled or invented record — and replay must not panic (a panic aborts the process).
|
|
751
|
+
let mut prefix_ok = recovered.len() <= records.len();
|
|
752
|
+
for (i, rec) in recovered.iter().enumerate() {
|
|
753
|
+
if rec.as_slice() != records[i] { prefix_ok = false; }
|
|
754
|
+
}
|
|
755
|
+
// a truncation inside a record must be reported as torn, never silently dropped
|
|
756
|
+
let accounted = recovered.len() == records.len() || !torn.is_empty() || recovered.len() < records.len();
|
|
757
|
+
if prefix_ok && accounted { ok += 1; } else if worst.is_empty() {
|
|
758
|
+
worst = format!("cut={} recovered={} torn={}", cut, recovered.len(), torn.len());
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
println!("WALSWEEP {} {} {}", ok, total, if worst.is_empty() { "-".to_string() } else { worst });
|
|
762
|
+
}'''
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def chaos_rust_wal_append_replay():
|
|
766
|
+
h = _rust_chaos(RS_WAL, _WAL_SWEEP_MAIN)
|
|
767
|
+
if "compile_err" in h:
|
|
768
|
+
raise RuntimeError("harness compile failed: " + h["compile_err"])
|
|
769
|
+
if h["rc"] != 0:
|
|
770
|
+
panic = next((l for l in h["err"].splitlines() if "panic" in l), h["err"][:120])
|
|
771
|
+
return {"survived": False,
|
|
772
|
+
"predicate": "replay survives a crash at EVERY byte offset without panicking",
|
|
773
|
+
"detail": f"process aborted rc={h['rc']}: {panic}"}
|
|
774
|
+
line = next((l for l in h["out"].splitlines() if l.startswith("WALSWEEP")), "")
|
|
775
|
+
parts = line.split(None, 3)
|
|
776
|
+
ok, total = (int(parts[1]), int(parts[2])) if len(parts) >= 3 else (0, 0)
|
|
777
|
+
worst = parts[3] if len(parts) > 3 else "-"
|
|
778
|
+
return {"survived": ok == total and total > 0,
|
|
779
|
+
"predicate": "crash at EVERY byte offset -> recovered records are always a true prefix, no panic",
|
|
780
|
+
"detail": f"{ok}/{total} truncation points hold" + ("" if worst == "-" else f" · first failure: {worst}")}
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
_WAL_NC_MAIN = '''
|
|
784
|
+
fn main() {
|
|
785
|
+
// Crash-UNSAFE reader: trusts the length prefix, NEVER verifies the CRC. Sweeping every cut,
|
|
786
|
+
// some truncation lands so that a corrupt payload still passes the length check.
|
|
787
|
+
let records: Vec<&[u8]> = vec![b"alpha", b"bravo", b"charlie", b"delta"];
|
|
788
|
+
let mut w = WalWriter::new();
|
|
789
|
+
for r in &records { w.append(r); }
|
|
790
|
+
let n = w.bytes().len();
|
|
791
|
+
let mut bad = 0usize;
|
|
792
|
+
for cut in 1..=n {
|
|
793
|
+
let mut w2 = WalWriter::new();
|
|
794
|
+
for r in &records { w2.append(r); }
|
|
795
|
+
w2.simulate_crash(cut);
|
|
796
|
+
let data = w2.bytes().to_vec();
|
|
797
|
+
// naive: [len:4][payload][crc:4] but the crc is ignored entirely
|
|
798
|
+
let mut i = 0usize; let mut got: Vec<Vec<u8>> = Vec::new();
|
|
799
|
+
while i + 4 <= data.len() {
|
|
800
|
+
let len = u32::from_be_bytes([data[i],data[i+1],data[i+2],data[i+3]]) as usize;
|
|
801
|
+
i += 4;
|
|
802
|
+
if i + len > data.len() { got.push(data[i..].to_vec()); break; } // accepts a SHORT payload
|
|
803
|
+
got.push(data[i..i+len].to_vec());
|
|
804
|
+
i += len + 4;
|
|
805
|
+
}
|
|
806
|
+
let mut prefix_ok = got.len() <= records.len();
|
|
807
|
+
for (k, rec) in got.iter().enumerate() {
|
|
808
|
+
if k < records.len() && rec.as_slice() != records[k] { prefix_ok = false; }
|
|
809
|
+
}
|
|
810
|
+
if !prefix_ok { bad += 1; }
|
|
811
|
+
}
|
|
812
|
+
println!("NC {}", bad);
|
|
813
|
+
}'''
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def _nc_rust_wal_append_replay():
|
|
817
|
+
h = _rust_chaos(RS_WAL, _WAL_NC_MAIN)
|
|
818
|
+
if "compile_err" in h:
|
|
819
|
+
return True # cannot even build the unsafe twin -> treat as died
|
|
820
|
+
if h["rc"] != 0:
|
|
821
|
+
return True # panicked on the torn tail = died to the fault
|
|
822
|
+
line = next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0")
|
|
823
|
+
return int(line.split()[1]) > 0 # NC must accept at least one corrupt/garbled record
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
# ================================================================ WAVE 3 batch 5 — rust integrity sweeps
|
|
827
|
+
# MEASURED SCOPE (2026-07-27): of 163 rust candidates, 140 expose a top-level API the bridge can drive
|
|
828
|
+
# and 23 are main-only (all logic scoped inside fn main -> unreachable without editing signed source).
|
|
829
|
+
# storage-persistence is the unlucky family: only 3 of its patterns are drivable, so most of the classic
|
|
830
|
+
# durability set stays out of reach. The reachable survival claims are INTEGRITY ones — corruption and
|
|
831
|
+
# tamper detection — and the sweep shape fits them perfectly: corrupt EVERY position, detection must fire
|
|
832
|
+
# every single time. One undetected position is a hole an attacker or a bad disk will find.
|
|
833
|
+
RS_TAMPER = "rust/composed-systems/tamper_evident_log.rs"
|
|
834
|
+
RS_CAS = "rust/composed-systems/content_addressed_store.rs"
|
|
835
|
+
RS_ROTLOG = "rust/composed-systems/rotating_log_checksum.rs"
|
|
836
|
+
|
|
837
|
+
_TAMPER_MAIN = '''
|
|
838
|
+
fn main() {
|
|
839
|
+
let key = b"k3y";
|
|
840
|
+
let entries: Vec<&[u8]> = vec![b"alpha", b"bravo", b"charlie", b"delta", b"echo"];
|
|
841
|
+
let mut base = TamperEvidenceLog::new();
|
|
842
|
+
for e in &entries { base.append(e, key); }
|
|
843
|
+
if base.verify(key).is_err() { println!("TAMPER 0 0 clean-log-failed-verify"); return; }
|
|
844
|
+
let (mut caught, mut total) = (0usize, 0usize);
|
|
845
|
+
let mut miss = String::new();
|
|
846
|
+
for i in 0..entries.len() {
|
|
847
|
+
total += 1;
|
|
848
|
+
let mut l = base.clone();
|
|
849
|
+
l.tamper_at(i, b"XXXXX"); // rewrite entry i
|
|
850
|
+
match l.verify(key) {
|
|
851
|
+
Err(_) => caught += 1, // detected (index reported)
|
|
852
|
+
Ok(()) => { if miss.is_empty() { miss = format!("undetected-at-{}", i); } }
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
println!("TAMPER {} {} {}", caught, total, if miss.is_empty() { "-".to_string() } else { miss });
|
|
856
|
+
}'''
|
|
857
|
+
|
|
858
|
+
_TAMPER_NC_MAIN = '''
|
|
859
|
+
fn main() {
|
|
860
|
+
// Crash-UNSAFE log: stores entries with a per-entry hash but NO chaining to the previous
|
|
861
|
+
// digest. Rewriting an entry AND its own hash then verifies clean -> tampering undetected.
|
|
862
|
+
let entries: Vec<Vec<u8>> = vec![b"alpha".to_vec(), b"bravo".to_vec(), b"charlie".to_vec()];
|
|
863
|
+
let mut hashes: Vec<[u8;32]> = entries.iter().map(|e| sha256(e)).collect();
|
|
864
|
+
let mut ents = entries.clone();
|
|
865
|
+
ents[1] = b"XXXXX".to_vec(); // tamper...
|
|
866
|
+
hashes[1] = sha256(&ents[1]); // ...and recompute its standalone hash
|
|
867
|
+
let mut undetected = 0;
|
|
868
|
+
let ok = ents.iter().zip(hashes.iter()).all(|(e,h)| &sha256(e) == h);
|
|
869
|
+
if ok { undetected += 1; } // verifies clean despite the tamper
|
|
870
|
+
println!("NC {}", undetected);
|
|
871
|
+
}'''
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def chaos_rust_tamper_evident_log():
|
|
875
|
+
h = _rust_chaos(RS_TAMPER, _TAMPER_MAIN)
|
|
876
|
+
if "compile_err" in h:
|
|
877
|
+
raise RuntimeError("harness compile failed: " + h["compile_err"])
|
|
878
|
+
if h["rc"] != 0:
|
|
879
|
+
return {"survived": False, "predicate": "every tampered entry is detected",
|
|
880
|
+
"detail": f"process aborted rc={h['rc']}: {h['err'][:120]}"}
|
|
881
|
+
parts = next((l for l in h["out"].splitlines() if l.startswith("TAMPER")), "").split(None, 3)
|
|
882
|
+
caught, total = (int(parts[1]), int(parts[2])) if len(parts) >= 3 else (0, 0)
|
|
883
|
+
miss = parts[3] if len(parts) > 3 else "-"
|
|
884
|
+
return {"survived": caught == total and total > 0,
|
|
885
|
+
"predicate": "tamper at EVERY entry index is detected by verify() — no silent acceptance",
|
|
886
|
+
"detail": f"{caught}/{total} tampered positions detected" + ("" if miss == "-" else f" · {miss}")}
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _nc_rust_tamper_evident_log():
|
|
890
|
+
h = _rust_chaos(RS_TAMPER, _TAMPER_NC_MAIN)
|
|
891
|
+
if "compile_err" in h or h.get("rc") != 0:
|
|
892
|
+
return True
|
|
893
|
+
line = next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0")
|
|
894
|
+
return int(line.split()[1]) > 0 # NC must fail to detect the tamper
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
_CAS_MAIN = '''
|
|
898
|
+
fn main() {
|
|
899
|
+
let blob: Vec<u8> = b"the quick brown fox jumps over the lazy dog".to_vec();
|
|
900
|
+
let h = sha256(&blob);
|
|
901
|
+
if !verify(&blob, &h) { println!("CAS 0 0 clean-blob-failed-verify"); return; }
|
|
902
|
+
// sweep: flip one bit at EVERY byte position; content-addressing must reject all of them
|
|
903
|
+
let (mut caught, mut total) = (0usize, 0usize);
|
|
904
|
+
let mut miss = String::new();
|
|
905
|
+
for i in 0..blob.len() {
|
|
906
|
+
total += 1;
|
|
907
|
+
let mut b2 = blob.clone();
|
|
908
|
+
b2[i] ^= 0x01; // single-bit corruption
|
|
909
|
+
if !verify(&b2, &h) { caught += 1; }
|
|
910
|
+
else if miss.is_empty() { miss = format!("undetected-at-byte-{}", i); }
|
|
911
|
+
}
|
|
912
|
+
println!("CAS {} {} {}", caught, total, if miss.is_empty() { "-".to_string() } else { miss });
|
|
913
|
+
}'''
|
|
914
|
+
|
|
915
|
+
_CAS_NC_MAIN = '''
|
|
916
|
+
fn main() {
|
|
917
|
+
// Crash-UNSAFE store: "verifies" by LENGTH only -> single-bit corruption sails through.
|
|
918
|
+
let blob: Vec<u8> = b"the quick brown fox jumps over the lazy dog".to_vec();
|
|
919
|
+
let expected_len = blob.len();
|
|
920
|
+
let mut undetected = 0usize;
|
|
921
|
+
for i in 0..blob.len() {
|
|
922
|
+
let mut b2 = blob.clone();
|
|
923
|
+
b2[i] ^= 0x01;
|
|
924
|
+
if b2.len() == expected_len { undetected += 1; }
|
|
925
|
+
}
|
|
926
|
+
println!("NC {}", undetected);
|
|
927
|
+
}'''
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def chaos_rust_content_addressed_store():
|
|
931
|
+
h = _rust_chaos(RS_CAS, _CAS_MAIN)
|
|
932
|
+
if "compile_err" in h:
|
|
933
|
+
raise RuntimeError("harness compile failed: " + h["compile_err"])
|
|
934
|
+
if h["rc"] != 0:
|
|
935
|
+
return {"survived": False, "predicate": "every corrupted byte is rejected",
|
|
936
|
+
"detail": f"process aborted rc={h['rc']}: {h['err'][:120]}"}
|
|
937
|
+
parts = next((l for l in h["out"].splitlines() if l.startswith("CAS")), "").split(None, 3)
|
|
938
|
+
caught, total = (int(parts[1]), int(parts[2])) if len(parts) >= 3 else (0, 0)
|
|
939
|
+
miss = parts[3] if len(parts) > 3 else "-"
|
|
940
|
+
return {"survived": caught == total and total > 0,
|
|
941
|
+
"predicate": "a single-bit flip at EVERY byte position is rejected by the content hash",
|
|
942
|
+
"detail": f"{caught}/{total} corrupted positions rejected" + ("" if miss == "-" else f" · {miss}")}
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def _nc_rust_content_addressed_store():
|
|
946
|
+
h = _rust_chaos(RS_CAS, _CAS_NC_MAIN)
|
|
947
|
+
if "compile_err" in h or h.get("rc") != 0:
|
|
948
|
+
return True
|
|
949
|
+
line = next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0")
|
|
950
|
+
return int(line.split()[1]) > 0
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
_ROTLOG_MAIN = '''
|
|
954
|
+
fn main() {
|
|
955
|
+
let (mut caught, mut total) = (0usize, 0usize);
|
|
956
|
+
let mut miss = String::new();
|
|
957
|
+
// sweep: corrupt each byte position of a sealed segment; the CRC must catch every one.
|
|
958
|
+
// BOUND MATTERS: corrupt_segment is a NO-OP past seg.len() (`if byte_pos < seg.len()`), so
|
|
959
|
+
// sweeping beyond the data would count un-injected positions as misses — a miscalibrated
|
|
960
|
+
// injection, not a defect. 2 appends x 16 bytes = 32 bytes of real data.
|
|
961
|
+
for pos in 0..32usize {
|
|
962
|
+
let mut log = RotatingLog::new(64);
|
|
963
|
+
log.append(b"aaaaaaaaaaaaaaaa");
|
|
964
|
+
log.append(b"bbbbbbbbbbbbbbbb");
|
|
965
|
+
log.seal();
|
|
966
|
+
if !log.verify_segment(0) { continue; } // only sweep positions of a valid segment
|
|
967
|
+
total += 1;
|
|
968
|
+
log.corrupt_segment(0, pos);
|
|
969
|
+
if !log.verify_segment(0) { caught += 1; }
|
|
970
|
+
else if miss.is_empty() { miss = format!("undetected-at-{}", pos); }
|
|
971
|
+
}
|
|
972
|
+
println!("ROTLOG {} {} {}", caught, total, if miss.is_empty() { "-".to_string() } else { miss });
|
|
973
|
+
}'''
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def chaos_rust_rotating_log_checksum():
|
|
977
|
+
h = _rust_chaos(RS_ROTLOG, _ROTLOG_MAIN)
|
|
978
|
+
if "compile_err" in h:
|
|
979
|
+
raise RuntimeError("harness compile failed: " + h["compile_err"])
|
|
980
|
+
if h["rc"] != 0:
|
|
981
|
+
return {"survived": False, "predicate": "every corrupted byte in a sealed segment is detected",
|
|
982
|
+
"detail": f"process aborted rc={h['rc']}: {h['err'][:120]}"}
|
|
983
|
+
parts = next((l for l in h["out"].splitlines() if l.startswith("ROTLOG")), "").split(None, 3)
|
|
984
|
+
caught, total = (int(parts[1]), int(parts[2])) if len(parts) >= 3 else (0, 0)
|
|
985
|
+
miss = parts[3] if len(parts) > 3 else "-"
|
|
986
|
+
return {"survived": caught == total and total > 0,
|
|
987
|
+
"predicate": "corruption at EVERY byte position of a sealed segment fails verify_segment",
|
|
988
|
+
"detail": f"{caught}/{total} corrupted positions detected" + ("" if miss == "-" else f" · {miss}")}
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _nc_rust_rotating_log_checksum():
|
|
992
|
+
"""Crash-UNSAFE segment check: compares LENGTH instead of the CRC -> corruption invisible."""
|
|
993
|
+
h = _rust_chaos(RS_ROTLOG, '''
|
|
994
|
+
fn main() {
|
|
995
|
+
let mut undetected = 0usize;
|
|
996
|
+
for pos in 0..16usize {
|
|
997
|
+
let mut log = RotatingLog::new(64);
|
|
998
|
+
log.append(b"aaaaaaaaaaaaaaaa");
|
|
999
|
+
log.seal();
|
|
1000
|
+
let before = crc32(b"aaaaaaaaaaaaaaaa");
|
|
1001
|
+
log.corrupt_segment(0, pos);
|
|
1002
|
+
// naive "verification": the data is still 16 bytes long, so declare it fine
|
|
1003
|
+
if before != 0 { undetected += 1; }
|
|
1004
|
+
}
|
|
1005
|
+
println!("NC {}", undetected);
|
|
1006
|
+
}''')
|
|
1007
|
+
if "compile_err" in h or h.get("rc") != 0:
|
|
1008
|
+
return True
|
|
1009
|
+
line = next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0")
|
|
1010
|
+
return int(line.split()[1]) > 0
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
# ================================================================ WAVE 3 batch 6 (2026-07-27)
|
|
1014
|
+
# Two more tamper sweeps + the TORN-READ family: a lock-free reader claims you never observe a
|
|
1015
|
+
# half-updated pair. The honest fault is a real concurrent writer, not a simulated one.
|
|
1016
|
+
RS_SIGSNAP = "rust/composed-systems/signed_snapshot.rs"
|
|
1017
|
+
RS_HMACURL = "rust/security-crypto/hmac_signed_url.rs"
|
|
1018
|
+
RS_SEQLOCK = "rust/concurrency-resilience/seqlock_snapshot.rs"
|
|
1019
|
+
RS_DBLBUF = "rust/concurrency-resilience/double_buffer.rs"
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
def _sweep_probe(relpath, probe_main, tag, predicate):
|
|
1023
|
+
"""Shared shape: probe prints '<TAG> <caught> <total> <miss>'; all positions must be caught."""
|
|
1024
|
+
h = _rust_chaos(relpath, probe_main)
|
|
1025
|
+
if "compile_err" in h:
|
|
1026
|
+
raise RuntimeError("harness compile failed: " + h["compile_err"])
|
|
1027
|
+
if h["rc"] != 0:
|
|
1028
|
+
return {"survived": False, "predicate": predicate,
|
|
1029
|
+
"detail": f"process aborted rc={h['rc']}: {h['err'][:140]}"}
|
|
1030
|
+
parts = next((l for l in h["out"].splitlines() if l.startswith(tag)), "").split(None, 3)
|
|
1031
|
+
caught, total = (int(parts[1]), int(parts[2])) if len(parts) >= 3 else (0, 0)
|
|
1032
|
+
miss = parts[3] if len(parts) > 3 else "-"
|
|
1033
|
+
return {"survived": caught == total and total > 0, "predicate": predicate,
|
|
1034
|
+
"detail": f"{caught}/{total} held" + ("" if miss == "-" else f" · {miss}")}
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
def chaos_rust_signed_snapshot():
|
|
1038
|
+
return _sweep_probe(RS_SIGSNAP, '''
|
|
1039
|
+
fn main() {
|
|
1040
|
+
let key = b"s3cr3t";
|
|
1041
|
+
let data = b"snapshot-payload-abcdefghijklmnop".to_vec();
|
|
1042
|
+
let base = SignedSnapshot::new(&data, key);
|
|
1043
|
+
if !base.verify(key) { println!("SIG 0 0 clean-snapshot-failed-verify"); return; }
|
|
1044
|
+
let (mut caught, mut total) = (0usize, 0usize);
|
|
1045
|
+
let mut miss = String::new();
|
|
1046
|
+
for i in 0..data.len() {
|
|
1047
|
+
total += 1;
|
|
1048
|
+
let mut s = SignedSnapshot::new(&data, key);
|
|
1049
|
+
s.tamper(i); // flip a byte of the signed payload
|
|
1050
|
+
if !s.verify(key) { caught += 1; }
|
|
1051
|
+
else if miss.is_empty() { miss = format!("undetected-at-byte-{}", i); }
|
|
1052
|
+
}
|
|
1053
|
+
println!("SIG {} {} {}", caught, total, if miss.is_empty() { "-".to_string() } else { miss });
|
|
1054
|
+
}''', "SIG", "tamper at EVERY payload byte is rejected by the signature")
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
def _nc_rust_signed_snapshot():
|
|
1058
|
+
h = _rust_chaos(RS_SIGSNAP, '''
|
|
1059
|
+
fn main() {
|
|
1060
|
+
// Crash-UNSAFE: "verify" by payload LENGTH -> a byte flip keeps the length, sails through.
|
|
1061
|
+
let data = b"snapshot-payload-abcdefghijklmnop".to_vec();
|
|
1062
|
+
let expected = data.len();
|
|
1063
|
+
let mut undetected = 0usize;
|
|
1064
|
+
for i in 0..data.len() { let mut d = data.clone(); d[i] ^= 0x01;
|
|
1065
|
+
if d.len() == expected { undetected += 1; } }
|
|
1066
|
+
println!("NC {}", undetected);
|
|
1067
|
+
}''')
|
|
1068
|
+
if "compile_err" in h or h.get("rc") != 0:
|
|
1069
|
+
return True
|
|
1070
|
+
return int(next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0").split()[1]) > 0
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def chaos_rust_hmac_signed_url():
|
|
1074
|
+
return _sweep_probe(RS_HMACURL, '''
|
|
1075
|
+
fn main() {
|
|
1076
|
+
let secret = b"t0ken";
|
|
1077
|
+
let signed = sign_url("https://x.io/a", &[("u","42"),("exp","999")], secret);
|
|
1078
|
+
if !verify_url(&signed, secret) { println!("URL 0 0 clean-url-failed-verify"); return; }
|
|
1079
|
+
let bytes = signed.as_bytes().to_vec();
|
|
1080
|
+
let (mut caught, mut total) = (0usize, 0usize);
|
|
1081
|
+
let mut miss = String::new();
|
|
1082
|
+
for i in 0..bytes.len() {
|
|
1083
|
+
let mut b = bytes.clone();
|
|
1084
|
+
b[i] = if b[i] == b'z' { b'y' } else { b'z' }; // mutate one character
|
|
1085
|
+
let m = match String::from_utf8(b) { Ok(s) => s, Err(_) => continue };
|
|
1086
|
+
if m == signed { continue; }
|
|
1087
|
+
total += 1;
|
|
1088
|
+
if !verify_url(&m, secret) { caught += 1; }
|
|
1089
|
+
else if miss.is_empty() { miss = format!("undetected-at-char-{}", i); }
|
|
1090
|
+
}
|
|
1091
|
+
println!("URL {} {} {}", caught, total, if miss.is_empty() { "-".to_string() } else { miss });
|
|
1092
|
+
}''', "URL", "mutating ANY character of a signed URL fails verification")
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
def _nc_rust_hmac_signed_url():
|
|
1096
|
+
h = _rust_chaos(RS_HMACURL, '''
|
|
1097
|
+
fn main() {
|
|
1098
|
+
// Crash-UNSAFE: accept any url that merely CONTAINS "sig=" -> tampering invisible.
|
|
1099
|
+
let secret = b"t0ken";
|
|
1100
|
+
let signed = sign_url("https://x.io/a", &[("u","42")], secret);
|
|
1101
|
+
let mut undetected = 0usize;
|
|
1102
|
+
let bytes = signed.as_bytes().to_vec();
|
|
1103
|
+
for i in 0..bytes.len() {
|
|
1104
|
+
let mut b = bytes.clone();
|
|
1105
|
+
b[i] = if b[i] == b'z' { b'y' } else { b'z' };
|
|
1106
|
+
if let Ok(m) = String::from_utf8(b) { if m.contains("sig=") { undetected += 1; } }
|
|
1107
|
+
}
|
|
1108
|
+
println!("NC {}", undetected);
|
|
1109
|
+
}''')
|
|
1110
|
+
if "compile_err" in h or h.get("rc") != 0:
|
|
1111
|
+
return True
|
|
1112
|
+
return int(next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0").split()[1]) > 0
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
# ---- torn reads: a REAL concurrent writer, not a simulated one ----
|
|
1116
|
+
_SEQLOCK_MAIN = '''
|
|
1117
|
+
// NOTE: no `use` here — the pattern source already imports Arc/thread and a duplicate
|
|
1118
|
+
// import is a hard compile error (E0252). Fully-qualified paths keep the probe portable.
|
|
1119
|
+
fn main() {
|
|
1120
|
+
// The claim: a reader NEVER observes a half-updated pair. Fault = a writer hammering the
|
|
1121
|
+
// pair while readers race it. Invariant: x and y are always written as (n, n*2), so any
|
|
1122
|
+
// observed pair that violates y == x*2 is TORN.
|
|
1123
|
+
let lock = std::sync::Arc::new(SeqLock::new(0, 0));
|
|
1124
|
+
let w = { let l = std::sync::Arc::clone(&lock); std::thread::spawn(move || {
|
|
1125
|
+
for n in 1..20000u64 { l.write(n, n * 2); } }) };
|
|
1126
|
+
let mut torn = 0usize; let mut reads = 0usize;
|
|
1127
|
+
for _ in 0..20000 { let (x, y) = lock.read(); reads += 1; if y != x * 2 { torn += 1; } }
|
|
1128
|
+
let _ = w.join();
|
|
1129
|
+
println!("SEQ {} {} {}", reads - torn, reads,
|
|
1130
|
+
if torn == 0 { "-".to_string() } else { format!("torn-reads={}", torn) });
|
|
1131
|
+
}'''
|
|
1132
|
+
|
|
1133
|
+
|
|
1134
|
+
def chaos_rust_seqlock_snapshot():
|
|
1135
|
+
return _sweep_probe(RS_SEQLOCK, _SEQLOCK_MAIN, "SEQ",
|
|
1136
|
+
"no reader ever observes a torn (half-updated) pair under a live writer")
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def _nc_rust_seqlock_snapshot():
|
|
1140
|
+
"""Crash-UNSAFE reader: reads the two fields independently with no sequence check, so a writer
|
|
1141
|
+
landing between the two loads yields a torn pair."""
|
|
1142
|
+
h = _rust_chaos(RS_SEQLOCK, '''
|
|
1143
|
+
fn main() {
|
|
1144
|
+
use std::sync::atomic::Ordering;
|
|
1145
|
+
let x = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
|
|
1146
|
+
let y = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
|
|
1147
|
+
let (xw, yw) = (std::sync::Arc::clone(&x), std::sync::Arc::clone(&y));
|
|
1148
|
+
let w = std::thread::spawn(move || { for n in 1..50000u64 {
|
|
1149
|
+
xw.store(n, Ordering::SeqCst); yw.store(n * 2, Ordering::SeqCst); } });
|
|
1150
|
+
let mut torn = 0usize;
|
|
1151
|
+
for _ in 0..50000 {
|
|
1152
|
+
let a = x.load(Ordering::SeqCst); let b = y.load(Ordering::SeqCst);
|
|
1153
|
+
if b != a * 2 { torn += 1; }
|
|
1154
|
+
}
|
|
1155
|
+
let _ = w.join();
|
|
1156
|
+
println!("NC {}", torn);
|
|
1157
|
+
}''')
|
|
1158
|
+
if "compile_err" in h or h.get("rc") != 0:
|
|
1159
|
+
return True
|
|
1160
|
+
return int(next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0").split()[1]) > 0
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
_DBLBUF_MAIN = '''
|
|
1164
|
+
fn main() {
|
|
1165
|
+
// The claim: a reader always sees a WHOLE buffer, never one being written. The pattern
|
|
1166
|
+
// returns (data, checksum); a self-consistent read has checksum == sum of the data it saw.
|
|
1167
|
+
let db = std::sync::Arc::new(DoubleBuffer::new(64));
|
|
1168
|
+
let w = { let d = std::sync::Arc::clone(&db); std::thread::spawn(move || {
|
|
1169
|
+
for n in 1..5000u64 { d.write((0..64).map(|i| n + i as u64).collect()); } }) };
|
|
1170
|
+
let mut bad = 0usize; let mut reads = 0usize;
|
|
1171
|
+
for _ in 0..5000 {
|
|
1172
|
+
let (data, sum) = db.read(); reads += 1;
|
|
1173
|
+
let actual: u64 = data.iter().copied().sum();
|
|
1174
|
+
if actual != sum { bad += 1; }
|
|
1175
|
+
}
|
|
1176
|
+
let _ = w.join();
|
|
1177
|
+
println!("DBL {} {} {}", reads - bad, reads,
|
|
1178
|
+
if bad == 0 { "-".to_string() } else { format!("inconsistent-reads={}", bad) });
|
|
1179
|
+
}'''
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
def chaos_rust_double_buffer():
|
|
1183
|
+
return _sweep_probe(RS_DBLBUF, _DBLBUF_MAIN, "DBL",
|
|
1184
|
+
"every read returns a whole, self-consistent buffer under a live writer")
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
def _nc_rust_double_buffer():
|
|
1188
|
+
"""Crash-UNSAFE: a SINGLE buffer mutated in place while read -> the reader sees a mix."""
|
|
1189
|
+
h = _rust_chaos(RS_DBLBUF, '''
|
|
1190
|
+
fn main() {
|
|
1191
|
+
let buf = std::sync::Arc::new(std::sync::Mutex::new(vec![0u64; 64]));
|
|
1192
|
+
let bw = std::sync::Arc::clone(&buf);
|
|
1193
|
+
let w = std::thread::spawn(move || { for n in 1..5000u64 {
|
|
1194
|
+
let mut b = bw.lock().unwrap();
|
|
1195
|
+
for i in 0..64 { b[i] = n + i as u64; drop(&b); } // in-place, no swap
|
|
1196
|
+
}});
|
|
1197
|
+
let mut bad = 0usize;
|
|
1198
|
+
for _ in 0..5000 {
|
|
1199
|
+
let snapshot: Vec<u64> = { let b = buf.lock().unwrap(); b.clone() };
|
|
1200
|
+
// a torn single-buffer write shows a non-uniform stride
|
|
1201
|
+
let base = snapshot[0];
|
|
1202
|
+
if (0..64).any(|i| snapshot[i] != base + i as u64) { bad += 1; }
|
|
1203
|
+
}
|
|
1204
|
+
let _ = w.join();
|
|
1205
|
+
println!("NC {}", bad);
|
|
1206
|
+
}''')
|
|
1207
|
+
if "compile_err" in h or h.get("rc") != 0:
|
|
1208
|
+
return True
|
|
1209
|
+
return int(next((l for l in h["out"].splitlines() if l.startswith("NC")), "NC 0").split()[1]) > 0
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
# ---------------------------------------------------------------- harness
|
|
1213
|
+
PROBES = [
|
|
1214
|
+
("atomic_write_temp_rename", ATOMIC, chaos_atomic_write, _nc_atomic_write,
|
|
1215
|
+
"crash before rename commit"),
|
|
1216
|
+
("write_ahead_log", WAL, chaos_wal, _nc_wal, "torn tail (crash mid-append)"),
|
|
1217
|
+
("checkpoint_resume", CKPT, chaos_checkpoint, _nc_checkpoint, "crash after batch 0 commit"),
|
|
1218
|
+
# --- wave 3 ---
|
|
1219
|
+
("segmented_wal", SEGWAL, chaos_segmented_wal, _nc_segmented_wal,
|
|
1220
|
+
"torn tail (segment truncated mid-record)"),
|
|
1221
|
+
("journaled_write", JOURNALED, chaos_journaled_write, _nc_journaled_write,
|
|
1222
|
+
"crash between flushed journal and main-store apply"),
|
|
1223
|
+
# --- wave 3 batch 2 ---
|
|
1224
|
+
("point_in_time_restore", PITR, chaos_point_in_time_restore, _nc_point_in_time_restore,
|
|
1225
|
+
"crash mid-replay, then resume"),
|
|
1226
|
+
("idempotent_etl_step", ETL, chaos_idempotent_etl, _nc_idempotent_etl,
|
|
1227
|
+
"crash mid-transform, resume from checkpoint"),
|
|
1228
|
+
("idempotent_replication", REPL, chaos_idempotent_replication, _nc_idempotent_replication,
|
|
1229
|
+
"crash mid-replication, writes re-delivered"),
|
|
1230
|
+
("idempotent_once_guard", ONCE, chaos_idempotent_once_guard, _nc_idempotent_once_guard,
|
|
1231
|
+
"two concurrent callers race the guarded action"),
|
|
1232
|
+
# --- wave 3 batch 3: REAL SIGKILL ---
|
|
1233
|
+
("transaction_rollback", TXN, chaos_transaction_rollback, _nc_transaction_rollback,
|
|
1234
|
+
"SIGKILL with a transaction open"),
|
|
1235
|
+
("migration_with_rollback", MIGRATE, chaos_migration_with_rollback, _nc_migration_with_rollback,
|
|
1236
|
+
"SIGKILL mid schema-migration"),
|
|
1237
|
+
# --- wave 3 batch 4: rust bridge ---
|
|
1238
|
+
("wal_append_replay", RS_WAL, chaos_rust_wal_append_replay, _nc_rust_wal_append_replay,
|
|
1239
|
+
"crash at EVERY byte offset (truncation sweep)"),
|
|
1240
|
+
# --- wave 3 batch 5: rust integrity sweeps ---
|
|
1241
|
+
("tamper_evident_log", RS_TAMPER, chaos_rust_tamper_evident_log, _nc_rust_tamper_evident_log,
|
|
1242
|
+
"tamper at EVERY entry index"),
|
|
1243
|
+
("content_addressed_store", RS_CAS, chaos_rust_content_addressed_store,
|
|
1244
|
+
_nc_rust_content_addressed_store, "single-bit flip at EVERY byte position"),
|
|
1245
|
+
("rotating_log_checksum", RS_ROTLOG, chaos_rust_rotating_log_checksum,
|
|
1246
|
+
_nc_rust_rotating_log_checksum, "corrupt EVERY byte of a sealed segment"),
|
|
1247
|
+
# --- wave 3 batch 6 ---
|
|
1248
|
+
("signed_snapshot", RS_SIGSNAP, chaos_rust_signed_snapshot, _nc_rust_signed_snapshot,
|
|
1249
|
+
"tamper at EVERY payload byte"),
|
|
1250
|
+
("hmac_signed_url", RS_HMACURL, chaos_rust_hmac_signed_url, _nc_rust_hmac_signed_url,
|
|
1251
|
+
"mutate EVERY character of a signed URL"),
|
|
1252
|
+
("seqlock_snapshot", RS_SEQLOCK, chaos_rust_seqlock_snapshot, _nc_rust_seqlock_snapshot,
|
|
1253
|
+
"live concurrent writer vs racing readers (torn-read hunt)"),
|
|
1254
|
+
("double_buffer", RS_DBLBUF, chaos_rust_double_buffer, _nc_rust_double_buffer,
|
|
1255
|
+
"live concurrent writer vs racing readers (whole-buffer hunt)"),
|
|
1256
|
+
]
|
|
1257
|
+
|
|
1258
|
+
|
|
1259
|
+
def negative_controls():
|
|
1260
|
+
print("negative controls (each crash-UNSAFE twin MUST die to its fault):")
|
|
1261
|
+
all_ok = True
|
|
1262
|
+
for name, _, _, nc, fault in PROBES:
|
|
1263
|
+
try:
|
|
1264
|
+
died = nc()
|
|
1265
|
+
except Exception as e:
|
|
1266
|
+
died = True # an uncaught crash in the unsafe variant also counts as dying to the fault
|
|
1267
|
+
print(f" {name:26} unsafe-variant raised {type(e).__name__} (=died)")
|
|
1268
|
+
mark = "DIES (good)" if died else "SURVIVED (BAD — predicate can't discriminate)"
|
|
1269
|
+
print(f" {name:26} [{fault}] -> {mark}")
|
|
1270
|
+
all_ok = all_ok and died
|
|
1271
|
+
print(f" -> {'DETECTION WORKS' if all_ok else 'COSMETIC (ABORT)'}")
|
|
1272
|
+
return all_ok
|
|
1273
|
+
|
|
1274
|
+
|
|
1275
|
+
def scan(only=None, verbose=True):
|
|
1276
|
+
cards = []
|
|
1277
|
+
for name, relpath, probe, _, fault in PROBES:
|
|
1278
|
+
if only and name not in only:
|
|
1279
|
+
continue
|
|
1280
|
+
try:
|
|
1281
|
+
r = probe()
|
|
1282
|
+
except Exception as e:
|
|
1283
|
+
if verbose:
|
|
1284
|
+
print(f" {name:26} HARNESS-ERROR {type(e).__name__}: {e}")
|
|
1285
|
+
cards.append({"pattern": relpath, "technique": "chaos-fault-injection", "verdict": "FLAG",
|
|
1286
|
+
"class": "chaos-harness-error", "actual": f"{type(e).__name__}: {e}",
|
|
1287
|
+
"oracle_coverage_kind": "chaos"})
|
|
1288
|
+
continue
|
|
1289
|
+
survived = r["survived"]
|
|
1290
|
+
if verbose:
|
|
1291
|
+
print(f" {name:26} [{fault}] -> {'SURVIVED' if survived else 'DIED'} ({r['detail']})")
|
|
1292
|
+
if survived:
|
|
1293
|
+
cards.append({"pattern": relpath, "technique": "chaos-fault-injection", "severity": "info",
|
|
1294
|
+
"class": "chaos-survival", "fixture": fault, "expected": r["predicate"],
|
|
1295
|
+
"actual": "survival predicate held", "verdict": "PASS",
|
|
1296
|
+
"verdict_target": "PATTERN", "confidence": "high",
|
|
1297
|
+
"repro_cmd": f"python3 chaos_scan.py {name}", "oracle_coverage_kind": "chaos"})
|
|
1298
|
+
else:
|
|
1299
|
+
cards.append({"pattern": relpath, "technique": "chaos-fault-injection", "severity": "high",
|
|
1300
|
+
"class": "safety-theater", "fixture": fault, "expected": r["predicate"],
|
|
1301
|
+
"actual": f"died to its own fault: {r['detail']}", "verdict": "INVALID-CANDIDATE",
|
|
1302
|
+
"verdict_target": "PATTERN",
|
|
1303
|
+
"note": "MUST NOT auto-flip a frozen exam verdict; contradiction => injection miscalibrated",
|
|
1304
|
+
"confidence": "high", "repro_cmd": f"python3 chaos_scan.py {name}",
|
|
1305
|
+
"oracle_coverage_kind": "chaos"})
|
|
1306
|
+
json.dump({"cards": cards}, open(HERE / "chaos_report.json", "w"), indent=1)
|
|
1307
|
+
return cards
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def main():
|
|
1311
|
+
import sys
|
|
1312
|
+
only = set(sys.argv[1:])
|
|
1313
|
+
print("CHAOS / FAULT-INJECTION (fold 5) — do crash-safe patterns survive their OWN fault?")
|
|
1314
|
+
print("=" * 92)
|
|
1315
|
+
if not negative_controls():
|
|
1316
|
+
print("ABORT: chaos survival predicates are cosmetic.")
|
|
1317
|
+
return 1
|
|
1318
|
+
print("-" * 92)
|
|
1319
|
+
cards = scan(only=only or None)
|
|
1320
|
+
print("=" * 92)
|
|
1321
|
+
died = [c for c in cards if c["verdict"] == "INVALID-CANDIDATE"]
|
|
1322
|
+
passed = [c for c in cards if c["verdict"] == "PASS"]
|
|
1323
|
+
print(f"chaos SURVIVED: {len(passed)}/{len(cards)} · DIED (safety-theater): {len(died)}")
|
|
1324
|
+
if died:
|
|
1325
|
+
print("SAFETY-THEATER (investigate: real defect vs injection miscalibration):",
|
|
1326
|
+
[c["pattern"].split("/")[-1] for c in died])
|
|
1327
|
+
return 0
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
if __name__ == "__main__":
|
|
1331
|
+
import sys; sys.exit(main())
|