Repository navigation
Expand file tree
/
Copy pathtest_validation_heal.py
More file actions
4167 lines (3890 loc) · 284 KB
/
Copy pathtest_validation_heal.py
File metadata and controls
4167 lines (3890 loc) · 284 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Check preservation of Heal branches and prevent evidence from becoming PASS."""
import hashlib
import json
from pathlib import Path
import tempfile
import unittest
import copy
import gzip
from datetime import UTC, datetime, timedelta
import types
from unittest.mock import patch, Mock
from scripts.validation_heal.matrix import STAGES, TOPOLOGIES, audit_evidence, cases, compile_plan, select
from scripts.validation_heal.healthy import validate_healthy, validate_topology, validate_rejection, Fleet, BASE_OPTIONS
from scripts.validation_heal.fleet_node import paths, stopped, inspect_metadata
from scripts.validation_heal.inspector import verify as verify_inspector
from scripts.validation_heal.shards import (BRANCHES, files, map_target, validate_fault, validate_repaired_physical,
validate_repaired_status, peer_status_equal, validate_dry_run_status, validate_coordination_rejection,
validate_coordination_rejection_logs)
from scripts.validation_heal.heal_fault import mutation
from scripts.validation_heal.shards import validate_conditional_response
from scripts.validation_heal.shards import run_task, verify_ranges
from scripts.validation_heal.versions import (BRANCHES as VERSION_BRANCHES, validate_version_receipts,
branch_plan, suspend_fixture, validate_failed_version, validate_unrecoverable_get, verify_quorum_contract,
map_inline_target, verify_proof)
from scripts.validation_heal.versions import seed_semantics, verify_semantics
from scripts.validation_heal.versions import multi_loss_instances, multi_loss_plan, SPECIAL_KEYS, verify_pagination, boundary_plan
from scripts.validation_heal.versions import validate_all_members_online, wait_all_members_online, release_permission_gate_live
from scripts.validation_heal.heal_probe import Probe, validate_s3_request
from scripts.validation_heal.prepare_heal_meta_inspector import quorum_contract, size_contract
from scripts.validation_heal.boundaries import verify_size_contract, boundary_sizes, verify_boundary_ranges
from scripts.validation_heal.node_outage import quorum_plan, put_ack, delete_ack, replica_census, validate_deleted_read
from scripts.validation_heal.fleet_node import runtime_config, BACKGROUND_CONFIG
from scripts.validation_heal.object_lock import (validate_protection, validate_protected_delete, cleanup_locked_fleet,
seed_locked, BRANCHES as LOCK_BRANCHES, KEYS as LOCK_KEYS, CLEANUP_SECONDS)
from scripts.validation_heal.versions import mismatch_plan, seed_mismatch
from scripts.validation_heal import heal_fault
from scripts.validation_heal.read_repair import source_tasks, validate_read, tracked_read_task, ADMISSION_MESSAGE, ADMISSION_TARGET
from scripts.validation_heal.drive_gate import apply_gate, activate_gate, release_gate, checked_gate, start_properties, validate_probe, validate_unwritable
from scripts.validation_heal.scanner_repair import (source_tasks as scanner_sources, cycle_pairs,
observe_task as observe_scanner, JournalWindow)
from scripts.validation_heal.fleet_node import logs as node_logs
from scripts.validation_heal.markers import (INSTANCES as MARKER_INSTANCES, seed_markers, marker_plan,
stale_expected_scene, add_marker, remove_marker, validate_marker_error)
from scripts.validation_heal.drive_gate import probe_gate
from scripts.validation_heal.status import (validate_background, validate_replacement, validate_cli,
reject_unsafe_completion, watch_startup, stable_status, Cli)
from scripts.validation_heal.cursor import (Window, OBJECTS as CURSOR_OBJECTS, SIZE as CURSOR_SIZE,
BRANCHES as CURSOR_BRANCHES, terminal_proof as cursor_terminal, validate_missing_batch, verify_all_parts)
from scripts.validation_heal.fleet_node import resource_limits, verify_parts as node_verify_parts
from scripts.validation_heal.stop import (partial_window, validate_retired_stop, validate_unknown_token, validate_cancelled,
cancelled_physical, idle_fleet as stop_idle_fleet, BRANCHES as STOP_BRANCHES)
from scripts.validation_heal.cancel_restart import validate_journal, BRANCHES as CANCEL_RESTART_BRANCHES
from scripts.validation_heal.fleet_node import task_records as node_task_records
from scripts.validation_heal import overlap
from scripts.validation_heal import rc_binary
from scripts.validation_heal import root_restart, fleet_node
from scripts.validation_heal import quorum_boundary
from scripts.validation_heal import stale_rejoin
from scripts.validation_heal import disk_loss
from scripts.validation_heal import replace_drive, replacement
import errno
import stat
def versioned_scene(keys, sizes=(100, 100, 61)):
base = HealShardOracleTest().snapshot()
bucket = "rv-heal-0123456789abcdef"
expected = []
snapshot = {"node1": {"formats": base["node1"]["formats"], "files": []}}
for key in keys:
for entry in base["node1"]["files"]:
if "/control/" in entry["path"]: continue
cloned = copy.deepcopy(entry)
cloned["path"] = cloned["path"].replace("objects/0008.bin", key)
if "metadata" in cloned:
cloned["metadata"]["key"] = key
versions = []
for nonce, size in enumerate(sizes):
version = copy.deepcopy(cloned["metadata"]["versions"][0])
version.update(versionId=f"v{nonce}", isLatest=nonce == 2, size=size,
dataDir=f"12345678-1234-1234-1234-{nonce:012d}")
version["parts"][0].update(size=size, actualSize=size)
versions.append(version)
cloned["metadata"]["versions"] = versions
snapshot["node1"]["files"].append(cloned)
else:
for nonce, size in enumerate(sizes):
part = copy.deepcopy(cloned)
part["path"] = part["path"].replace("12345678-1234-1234-1234-123456789abc", f"12345678-1234-1234-1234-{nonce:012d}")
part["sha256"] += f"v{nonce}"
part["size"] = (size + 1) // 2 + 32
snapshot["node1"]["files"].append(part)
expected.extend({"key": key, "versionId": f"v{nonce}", "deleteMarker": False, "isLatest": nonce == 2,
"payload": {"size": size}} for nonce, size in enumerate(sizes))
return snapshot, bucket, expected
class HealContractTest(unittest.TestCase):
def test_preserves_all_source_cases_and_applicable_branches(self):
inventory = cases()
plan = compile_plan(inventory, TOPOLOGIES, "manual-heal-unit-test")
self.assertEqual(len(inventory), 84)
self.assertEqual(sum(len(item["variants"]) for item in inventory), 302)
self.assertEqual(plan["branchTemplateCount"], 534)
self.assertEqual(len(plan["nonApplicableCombinations"]), 4)
self.assertFalse(plan["automaticExecution"])
self.assertFalse(plan["livePassClaimed"])
self.assertFalse(plan["environmentBinding"]["verified"])
self.assertTrue(plan["environmentBinding"]["topologies"]["H4"]["requiresExistingAdditionalDrives"])
def test_narrowed_topology_keeps_missing_scope_explicit(self):
plan = compile_plan(select("A01,A03"), {"H1"}, "manual-heal-unit-test")
self.assertEqual(len(plan["instances"]), 2)
self.assertEqual({item["caseId"] for item in plan["scopeExclusions"]},
{"heal.admin-healthy-noop", "heal.admin-token-cross-node-status"})
self.assertFalse(plan["livePassClaimed"])
with self.assertRaisesRegex(ValueError, "same Heal case"):
select("A01,heal.admin-healthy-noop")
def fixture_archive(self, root, plan):
for instance in plan["instances"]:
directory = root / instance["instanceId"]
directory.mkdir()
proof = {"runId": plan["runId"], "instanceId": instance["instanceId"], "evidence": {}}
for stage in STAGES:
value = (stage + " live observation").encode()
(directory / (stage + ".txt")).write_bytes(value)
proof["evidence"][stage] = [{"path": stage + ".txt", "sha256": hashlib.sha256(value).hexdigest()}]
(directory / "evidence.json").write_text(json.dumps(proof))
def test_complete_archive_requires_review_and_never_manufactures_pass(self):
plan = compile_plan(select("A01"), {"H1"}, "manual-heal-unit-test")
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
self.fixture_archive(root, plan)
result = audit_evidence(plan, root)
self.assertEqual(result["state"], "EVIDENCE_COMPLETE_REVIEW_REQUIRED")
self.assertFalse(result["livePassClaimed"])
self.assertIsNone(result["canonicalVerdict"])
first = root / plan["instances"][0]["instanceId"]
(first / "physical.txt").write_text("different evidence")
with self.assertRaisesRegex(ValueError, "digest mismatch"):
audit_evidence(plan, root)
def test_rejects_dropped_branch_and_escaped_evidence(self):
plan = compile_plan(select("A01"), {"H1"}, "manual-heal-unit-test")
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
self.fixture_archive(root, plan)
dropped = {**plan, "instances": plan["instances"][:1]}
with self.assertRaisesRegex(ValueError, "omitted or changed"):
audit_evidence(dropped, root)
first = root / plan["instances"][0]["instanceId"]
index = first / "evidence.json"
proof = json.loads(index.read_text())
proof["evidence"]["physical"][0]["path"] = "../outside.txt"
index.write_text(json.dumps(proof))
with self.assertRaisesRegex(ValueError, "unsafe Heal evidence"):
audit_evidence(plan, root)
class HealHealthyOracleTest(unittest.TestCase):
def test_inspector_rejects_other_candidate_tampered_binary_and_symlinks(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
header = bytearray(20)
header[:6] = b"\x7fELF\x02\x01"
header[18:20] = b"\x3e\x00"
(root / "heal-meta-inspect").write_bytes(header)
(root / "inspector-Cargo.lock").write_text("unit fixture lock")
helper = Path(__file__).parent / "scripts/validation_heal/tools/heal_meta_inspect.rs"
manifest = {"built": True, "candidateCommit": "a" * 40, "candidateLockSha256": "b" * 64,
"role": "read-only decoder; not the RustFS service under test", "target": "x86_64-unknown-linux-gnu",
"binarySha256": hashlib.sha256(header).hexdigest(),
"helperSourceSha256": hashlib.sha256(helper.read_bytes()).hexdigest(),
"inspectorLockSha256": hashlib.sha256((root / "inspector-Cargo.lock").read_bytes()).hexdigest()}
(root / "heal-meta-inspect.json").write_text(json.dumps(manifest))
self.assertEqual(verify_inspector(root, {"source_sha": "a" * 40}), manifest)
with self.assertRaisesRegex(ValueError, "candidate"):
verify_inspector(root, {"source_sha": "c" * 40})
(root / "heal-meta-inspect").write_bytes(header + b"different bytes")
with self.assertRaisesRegex(ValueError, "digest"):
verify_inspector(root, {"source_sha": "a" * 40})
(root / "heal-meta-inspect").unlink()
(root / "heal-meta-inspect").symlink_to(root / "inspector-Cargo.lock")
with self.assertRaisesRegex(ValueError, "artifact file"):
verify_inspector(root, {"source_sha": "a" * 40})
def test_request_rejection_needs_the_exact_server_code(self):
good = {"httpStatus": 400, "response": "<Error><Code>InvalidArgument</Code></Error>"}
validate_rejection(good, "InvalidArgument")
for bad in ({**good, "httpStatus": 200}, {"httpStatus": 400, "response": "<Error><Code>AccessDenied</Code></Error>"},
{"httpStatus": 400, "response": {"Code": "InvalidArgument", "clientToken": "admitted"}}):
with self.assertRaises(ValueError):
validate_rejection(bad, "InvalidArgument")
def receipt(self, disposition="metadata_healthy"):
return {"summary": "finished", "outcome": {"execution": {"state": "completed"},
"coverage": "complete", "objectsTruncated": False,
"counters": {"processed": 1, "healed": 0, "unchanged": 1, "skipped": 0,
"failed": 0, "unknown": 0, "attemptFailures": 0, "overflowed": False},
"objects": [{"identity": {"bucket": "fixture", "object": "object.bin", "poolIndex": 0,
"setIndex": 0, "bucketIncarnationId": "incarnation"},
"disposition": {"state": disposition}}]}}
def test_metadata_is_not_deep_integrity_and_legacy_finish_is_not_success(self):
healthy = self.receipt()
validate_healthy(healthy, "fixture", "object.bin", "metadata_healthy")
with self.assertRaisesRegex(ValueError, "expected verified_healthy"):
validate_healthy(healthy, "fixture", "object.bin", "verified_healthy")
validate_healthy(self.receipt("verified_healthy"), "fixture", "object.bin", "verified_healthy")
for changed in ({"summary": "finished"}, {**healthy, "truncated": True}):
with self.assertRaises(ValueError):
validate_healthy(changed, "fixture", "object.bin", "metadata_healthy")
def test_rejects_wrong_identity_unknown_counters_and_duplicate_receipts(self):
for kind in ("wrong-object", "unknown", "missing-incarnation", "duplicate", "boolean-counter"):
value = copy.deepcopy(self.receipt())
outcome = value["outcome"]
if kind == "wrong-object": outcome["objects"][0]["identity"]["object"] = "other.bin"
elif kind == "unknown": outcome["counters"]["unknown"] = 1
elif kind == "missing-incarnation": outcome["objects"][0]["identity"].pop("bucketIncarnationId")
elif kind == "duplicate": outcome["objects"].append(outcome["objects"][0])
else: outcome["counters"]["processed"] = True
with self.subTest(kind=kind), self.assertRaises(ValueError):
validate_healthy(value, "fixture", "object.bin", "metadata_healthy")
def test_h2_requires_one_set_spanning_all_sixteen_disks(self):
disks = [str(index) for index in range(16)]
snapshot = {f"node{node}": {"formats": [{"value": {"format": "xl", "id": "pool",
"xl": {"sets": [disks], "this": disks[(node - 1) * 4 + disk]}}} for disk in range(4)]}
for node in range(1, 5)}
self.assertEqual(validate_topology(snapshot, "H2")["independentDrives"], 16)
bad = copy.deepcopy(snapshot)
bad["node4"]["formats"][0]["value"]["xl"]["this"] = "0"
with self.assertRaisesRegex(ValueError, "mapping differs"):
validate_topology(bad, "H2")
with self.assertRaisesRegex(ValueError, "node count"):
validate_topology({"node1": snapshot["node1"]}, "H2")
def test_node_paths_cannot_select_shared_roots_or_arbitrary_run(self):
with tempfile.TemporaryDirectory() as directory, patch("scripts.validation_heal.fleet_node.STATE_ROOT", Path(directory).resolve()):
state, roots = paths("gh-12345-1-h1")
self.assertTrue(all(root.parts[-2:] == ("heal-validation", "gh-12345-1-h1") for root in roots))
for value in ("../mnmd", "manual-arbitrary", "gh-12345-1-h4"):
with self.assertRaisesRegex(ValueError, "run ID"):
paths(value)
class HealShardOracleTest(unittest.TestCase):
def test_ranges_at_one_megabyte_boundary_stay_inside_the_real_payload(self):
for size in (1024**2 - 1, 1024**2, 1024**2 + 1):
body = b"x" * size
requested = []
def s3(operation, params):
start, end = map(int, params["Range"].removeprefix("bytes=").split("-"))
self.assertTrue(0 <= start <= end < size)
requested.append((start, end))
value = body[start:end + 1]
return {"acknowledged": True, "response": {"ResponseMetadata": {"HTTPStatusCode": 206},
"ContentRange": f"bytes {start}-{end}/{size}"},
"payload": {"size": len(value), "sha256": hashlib.sha256(value).hexdigest()}}
verify_ranges(types.SimpleNamespace(s3=s3), types.SimpleNamespace(record=lambda label, value: value),
"fixture", "objects/0000.bin", expected_body=body)
self.assertEqual(requested[-1][1], size - 1)
if size > 1024**2:
self.assertTrue(any(start < 1024**2 <= end for start, end in requested))
def test_bucket_and_literal_object_routes_keep_the_original_token_for_status(self):
for key, expected_path in (("", "/rustfs/admin/v3/heal/fixture"),
("literal%2F/key", "/rustfs/admin/v3/heal/fixture/literal%252F/key")):
calls = []
def admin(path, query, body):
calls.append((path, copy.deepcopy(query), body))
if not query:
return {"httpStatus": 200, "response": {"clientToken": "original-token"}}
return {"httpStatus": 200, "response": HealHealthyOracleTest().receipt()}
active, admissions = [], []
run_task(types.SimpleNamespace(admin=admin), types.SimpleNamespace(record=lambda label, value: value),
{"bucket": "fixture", "key": key}, 2, active,
option_overrides={"recursive": True}, admissions=admissions)
self.assertEqual(len(calls), 4)
self.assertTrue(all(path == expected_path for path, _, _ in calls))
self.assertTrue(all(query == [("clientToken", "original-token")] for _, query, _ in calls[1:]))
self.assertTrue(json.loads(calls[0][2])["recursive"])
self.assertEqual(active, [])
self.assertEqual(admissions, [{"path": expected_path, "clientToken": "original-token"}])
def test_exact_coordinator_rejection_is_branch_scoped_and_never_admits_a_task(self):
body = ('<?xml version="1.0" encoding="UTF-8"?><Error><Code>InternalError</Code>'
'<Message>cluster heal coordination unavailable</Message></Error>')
observed = {"method": "POST", "httpStatus": 500, "response": body,
"startedAt": "2026-10-23T06:03:32.490+00:00",
"finishedAt": "2026-10-23T06:03:32.520+00:00", "endpoint": "node1",
"responseHeaders": {"x-request-id": "request-123"}}
calls, records, active, admissions = [], [], [], []
def admin(path, query, request_body):
calls.append((path, query, request_body))
return {**observed, "path": path}
result = run_task(types.SimpleNamespace(admin=admin),
types.SimpleNamespace(record=lambda label, value: records.append((label, value)) or value,
nodes=["vm000"], run_id="gh-39909050467-1-h1"),
{"bucket": "fixture", "key": "objects/0008.bin"}, 2, active,
admissions=admissions, allow_coordination_rejection=True)
self.assertEqual(result["admissionState"], "coordination-rejected")
self.assertEqual(result["httpStatus"], 500)
self.assertFalse(result["taskAdmitted"])
self.assertIsNone(result["clientToken"])
self.assertFalse(result["responsibilityReported"])
self.assertEqual(len(calls), 1)
self.assertEqual(result["requestWindow"]["requestId"], "request-123")
self.assertEqual(result["requestWindow"]["serviceNode"], "vm000")
self.assertEqual(active, [])
self.assertEqual(admissions, [])
with self.assertRaisesRegex(ValueError, "repair admission failed"):
run_task(types.SimpleNamespace(admin=admin),
types.SimpleNamespace(record=lambda _label, value: value),
{"bucket": "fixture", "key": "objects/0008.bin"}, 2, [],
allow_coordination_rejection=False)
def test_coordinator_rejection_requires_exact_status_and_xml(self):
exact = {"httpStatus": 500, "response": ('<?xml version="1.0" encoding="UTF-8"?><Error>'
'<Code>InternalError</Code><Message>cluster heal coordination unavailable</Message></Error>')}
self.assertEqual(validate_coordination_rejection(exact)["errorCode"], "InternalError")
for changed in (
{**exact, "httpStatus": 503},
{**exact, "response": exact["response"].replace("unavailable", "temporarily unavailable")},
{**exact, "response": exact["response"] + " "},
):
with self.subTest(changed=changed):
with self.assertRaisesRegex(ValueError, "reviewed coordinator failure"):
validate_coordination_rejection(changed)
request = {"method": "POST", "httpStatus": 500,
"path": "/rustfs/admin/v3/heal/fixture/objects/0008.bin",
"startedAt": "2026-10-23T06:03:32.490+00:00",
"finishedAt": "2026-10-23T06:03:32.520+00:00", "response": exact["response"],
"requestId": "request-123", "endpoint": "node1", "serviceNode": "vm000",
"unitFragment": "gh-39909050467-1-h1"}
base_event = {"timestamp": "2026-10-23T06:03:32.511021252Z", "level": "WARN",
"message": "cluster heal coordination failed", "event": "admin_request_failed",
"component": "admin_api", "subsystem": "heal_admin", "operation": "heal_control",
"result": "failed", "reason": "local_coordinator_failed",
"error": 'code: \'Internal error\', message: "heal control start admission failed"',
"target": "rustfs::admin::handlers::heal"}
def logs_for(event, *, node="vm000", unit="rustfs-validation-heal-gh-39909050467-1-h1.service"):
return {"request": request, "peers": {node: {"node": node, "unit": unit,
"journal": "Oct 23 06:03:32 rustfs000000 rustfs[874327]: " + json.dumps(event)}}}
proof = validate_coordination_rejection_logs(logs_for(base_event))
self.assertTrue(proof["coordinatorFailureLogged"])
self.assertEqual(proof["preAdmissionFailure"], "heal control start admission failed")
capability = {**base_event, "reason": "cluster_capability_unavailable",
"error": "remote rpc client unavailable: can not get heal control client, err: transport error"}
request["startedAt"] = "2026-10-23T06:30:38.471+00:00"
request["finishedAt"] = "2026-10-23T06:30:38.493+00:00"
request["unitFragment"] = "gh-39911462644-1-h2"
capability["timestamp"] = "2026-10-23T06:30:38.4969218Z"
self.assertEqual(validate_coordination_rejection_logs(logs_for(capability,
unit="rustfs-validation-heal-gh-39911462644-1-h2.service"))["reason"],
"cluster_capability_unavailable")
unrelated = {**capability, "reason": "coordinator_request_failed"}
with self.assertRaisesRegex(ValueError, "exact pre-admission failure"):
validate_coordination_rejection_logs(logs_for(unrelated,
unit="rustfs-validation-heal-gh-39911462644-1-h2.service"))
with self.assertRaisesRegex(ValueError, "request-serving node"):
validate_coordination_rejection_logs(logs_for(capability, node="vm001",
unit="rustfs-validation-heal-gh-39911462644-1-h2.service"))
with self.assertRaisesRegex(ValueError, "active test run"):
validate_coordination_rejection_logs(logs_for(capability,
unit="rustfs-validation-heal-gh-39909050467-1-h1.service"))
late = {**capability, "timestamp": "2026-10-23T06:30:41.000Z"}
with self.assertRaisesRegex(ValueError, "exact pre-admission failure"):
validate_coordination_rejection_logs(logs_for(late,
unit="rustfs-validation-heal-gh-39911462644-1-h2.service"))
def test_condition_denial_is_not_a_transport_failure_or_success_payload(self):
baseline = {"properties": {"ETag": '"etag"'}, "payload": {"size": 3, "sha256": "correct"}}
good = {"response": {"ResponseMetadata": {"HTTPStatusCode": 412}, "Error": {"Code": "PreconditionFailed"}},
"acknowledged": False, "resultUnknown": False}
validate_conditional_response(good, 412, baseline, code="PreconditionFailed")
for changed in ({**good, "payload": {"size": 3}}, {**good, "resultUnknown": True}, {**good, "acknowledged": True}):
with self.assertRaises(ValueError): validate_conditional_response(changed, 412, baseline, code="PreconditionFailed")
success = {"response": {"ResponseMetadata": {"HTTPStatusCode": 200}, "ETag": '"etag"'},
"acknowledged": True, "payload": baseline["payload"]}
validate_conditional_response(success, 200, baseline, full_body=True)
with self.assertRaisesRegex(ValueError, "full content"):
validate_conditional_response({**success, "payload": {"size": 3, "sha256": "wrong"}}, 200, baseline, full_body=True)
def test_ssh_script_compiles_with_fault_module_and_keeps_structured_request(self):
observed = []
def invoke(args, **params):
source = params["input"]
compile(source, "ssh-node-script", "exec")
observed.append(source)
return types.SimpleNamespace(returncode=0, stdout='{"checked":true}', stderr="")
with tempfile.TemporaryDirectory() as directory, patch("scripts.validation_heal.healthy.subprocess.run", side_effect=invoke):
fleet = Fleet(["node1"], Path(directory), "gh-12345-1-h1")
for action in ("preflight", "verify-part", "verify-inline", "apply-fault", "recover-fault", "start", "cleanup", "drive-gate", "drive-gate-probe"):
self.assertTrue(fleet.remote("node1", action, disk=1, relativePath="literal$()'part.1")["checked"])
self.assertEqual(len(observed), 9)
def snapshot(self):
bucket, key, data_dir = "rv-heal-0123456789abcdef", "objects/0008.bin", "12345678-1234-1234-1234-123456789abc"
disks, distribution = [str(index) for index in range(4)], [4, 1, 2, 3]
observation = {"formats": [], "files": []}
for disk, index in enumerate(distribution):
observation["formats"].append({"disk": disk, "value": {"format": "xl", "id": "pool",
"xl": {"sets": [disks], "this": disks[disk]}}})
metadata = {"bucket": bucket, "key": key, "versions": [{"versionId": None, "isLatest": True,
"deleted": False, "dataDir": data_dir, "size": 100, "inline": None, "usesLegacyChecksum": False,
"role": "data" if index <= 2 else "parity", "parts": [{"number": 1, "size": 100, "actualSize": 100}],
"erasure": {"index": index, "data_blocks": 2, "parity_blocks": 2, "block_size": 1048576,
"distribution": distribution, "algorithm": "rs-vandermonde"}}]}
observation["files"].extend([
{"disk": disk, "path": f"{bucket}/{key}/xl.meta", "size": 600, "sha256": "m" + str(disk), "metadata": metadata},
{"disk": disk, "path": f"{bucket}/{key}/{data_dir}/part.1", "size": 82, "sha256": "s" + str(disk)},
{"disk": disk, "path": f"{bucket}/control/xl.meta", "size": 600, "sha256": "c" + str(disk)}])
return {"node1": observation}
def target(self, before, role="data"):
return map_target(before, "rv-heal-0123456789abcdef", "objects/0008.bin", role, 1)
def test_executor_preserves_each_source_branch_and_uses_distinct_objects(self):
inventory = {item["id"]: item for item in cases()}
for case_id, branches in BRANCHES.items():
self.assertEqual([branch[0] for branch in branches], inventory[case_id]["variants"])
self.assertEqual(len({branch[1] for branch in branches}), len(branches))
self.assertEqual(inventory[case_id]["contract"]["probes"]["topology"],
"H2" if case_id == "heal.admin-token-cross-node-status" else "H1,H2")
for case_id, branches in VERSION_BRANCHES.items():
self.assertEqual(list(branches), inventory[case_id]["variants"])
def test_peer_status_cannot_converge_with_wrong_task_unknown_or_incomplete_receipts(self):
coordinator = {**HealHealthyOracleTest().receipt("repaired"), "startTime": "exact-task-start"}
task = ("/rustfs/admin/v3/heal/fixture/object", "original-token")
self.assertTrue(peer_status_equal(coordinator, copy.deepcopy(coordinator), task=task, peer_task=task))
rerendered = {**copy.deepcopy(coordinator), "startTime": "fresh response timestamp"}
self.assertTrue(peer_status_equal(coordinator, rerendered, task=task, peer_task=task))
for invalid in ("task-start", "summary", "coverage", "outcome", "truncated"):
peer = copy.deepcopy(coordinator)
peer_task = task
if invalid == "task-start": peer_task = (task[0], "different-task")
elif invalid == "summary": peer["summary"] = "unknown"
elif invalid == "coverage": peer["outcome"]["coverage"] = "partial"
elif invalid == "outcome": peer["outcome"]["counters"]["unknown"] = 1
else: peer["truncated"] = True
with self.subTest(invalid=invalid): self.assertFalse(peer_status_equal(coordinator, peer, task=task, peer_task=peer_task))
def test_peer_convergence_retains_expected_failures_without_certifying_repair(self):
terminal = HealHealthyOracleTest().receipt("failed")
terminal["summary"] = "stopped"
terminal["outcome"]["execution"]["state"] = "completed_with_errors"
terminal["outcome"]["counters"].update(unchanged=0, failed=1, attemptFailures=1)
terminal["settings"] = {"recursive": False, "pool": 0, "set": 0}
task = ("/rustfs/admin/v3/heal/fixture/object.bin", "original-token")
self.assertTrue(peer_status_equal(terminal, copy.deepcopy(terminal), task=task, peer_task=task))
with self.assertRaises(ValueError): validate_healthy(terminal, "fixture", "object.bin", "verified_healthy")
for mutation in ("aborted", "running", "finished", "zero-failures", "bool-failures", "settings",
"truncated", "partial", "token"):
peer, original = copy.deepcopy(terminal), copy.deepcopy(terminal)
peer_task = task
if mutation == "aborted": original["outcome"]["execution"] = {"state": "aborted", "reason": "untraversable"}
elif mutation == "running": original["outcome"]["execution"]["state"] = "running"
elif mutation == "finished": original["summary"] = "finished"
elif mutation == "zero-failures": original["outcome"]["counters"]["failed"] = 0
elif mutation == "bool-failures": original["outcome"]["counters"]["failed"] = True
elif mutation == "settings": peer["settings"]["set"] = 1
elif mutation == "truncated": original["truncated"] = True
elif mutation == "partial": original["outcome"]["coverage"] = "partial"
else: peer_task = (task[0], "replacement-token")
if mutation not in {"settings", "token"}: peer = copy.deepcopy(original)
with self.subTest(mutation=mutation):
self.assertFalse(peer_status_equal(original, peer, task=task, peer_task=peer_task))
def test_target_role_comes_from_metadata_and_actual_format_slot(self):
before = self.snapshot()
self.assertEqual(self.target(before)["disk"], 1)
self.assertEqual(self.target(before, "parity")["disk"], 0)
for invalid in ("index", "role", "dataDir", "missing-part", "same-shards"):
changed = copy.deepcopy(before)
metadata = changed["node1"]["files"][0]["metadata"]["versions"][0]
if invalid == "index": metadata["erasure"]["index"] = 1
elif invalid == "role": metadata["role"] = "data"
elif invalid == "dataDir": metadata["dataDir"] = "../control"
elif invalid == "missing-part": changed["node1"]["files"].pop(1)
else:
for entry in changed["node1"]["files"]:
if entry["path"].endswith("part.1"): entry["sha256"] = "same"
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
self.target(changed)
def test_fault_requires_exact_target_and_unchanged_controls_and_metadata(self):
before = self.snapshot()
target = self.target(before)
after = copy.deepcopy(before)
after["node1"]["files"] = [entry for entry in after["node1"]["files"]
if not (entry["disk"] == target["disk"] and entry["path"] == target["relativePath"])]
receipt = {"relativePath": target["relativePath"], "before": {"sha256": target["sha256"], "size": 82}, "fault": None}
validate_fault(before, after, target, receipt)
with self.assertRaisesRegex(ValueError, "baseline file"):
validate_repaired_physical(before, after, target)
changed = copy.deepcopy(after)
changed["node1"]["files"][0]["sha256"] = "metadata changed"
with self.assertRaisesRegex(ValueError, "metadata, controls"):
validate_fault(before, changed, target, receipt)
validate_repaired_physical(before, before, target)
rewritten = copy.deepcopy(before)
rewritten["node1"]["files"][0]["sha256"] = "legitimate rewrite"
rewritten["node1"]["files"][0]["metadata"]["versions"][0]["erasure"]["checksums"] = ["new checksum record"]
validate_repaired_physical(before, rewritten, target)
rewritten["node1"]["files"][0]["metadata"]["versions"][0]["dataDir"] = "other generation"
with self.assertRaisesRegex(ValueError, "version/part identity"):
validate_repaired_physical(before, rewritten, target)
changed = copy.deepcopy(before)
changed["node1"]["files"][-1]["sha256"] = "control changed"
with self.assertRaisesRegex(ValueError, "changed a control"):
validate_repaired_physical(before, changed, target)
def test_completed_mpu_sidecar_cleanup_is_bound_to_target_drive_and_manifest(self):
before = self.snapshot()
target = self.target(before)
path = target["relativePath"] + ".meta"
before["node1"]["files"].append({"disk": target["disk"], "path": path, "size": 100, "sha256": "old staging"})
after = copy.deepcopy(before)
after["node1"]["files"].pop()
validate_repaired_physical(before, after, target)
before["node1"]["files"][-1]["disk"] = 0
with self.assertRaisesRegex(ValueError, "lost a baseline file"):
validate_repaired_physical(before, after, target)
def test_repeated_target_backup_requires_exact_current_metadata_and_target_identity(self):
before = self.snapshot()
target = self.target(before)
meta = next(entry for entry in before["node1"]["files"]
if entry["disk"] == target["disk"] and entry["path"] == f"{target['bucket']}/{target['key']}/xl.meta")
backup = {"disk": target["disk"], "path": f"{target['bucket']}/{target['key']}/{target['dataDir']}/xl.meta.bkp",
"size": 599, "sha256": "previous-repair-metadata"}
before["node1"]["files"].append(backup)
after = copy.deepcopy(before)
after["node1"]["files"][-1].update(size=meta["size"], sha256=meta["sha256"])
validate_repaired_physical(before, after, target)
for invalid in ("bytes", "length", "other-drive", "other-generation", "payload"):
changed_before, changed_after = copy.deepcopy(before), copy.deepcopy(after)
if invalid == "bytes": changed_after["node1"]["files"][-1]["sha256"] = "not-authoritative"
elif invalid == "length": changed_after["node1"]["files"][-1]["size"] += 1
elif invalid == "other-drive":
for value in (changed_before, changed_after): value["node1"]["files"][-1]["disk"] = 0
elif invalid == "other-generation":
for value in (changed_before, changed_after): value["node1"]["files"][-1]["path"] = backup["path"].replace(target["dataDir"], "other-generation")
else:
changed_after["node1"]["files"][1]["sha256"] = "changed-payload"
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
validate_repaired_physical(changed_before, changed_after, target)
added_before = self.snapshot()
added_after = copy.deepcopy(added_before)
added_after["node1"]["files"].append(after["node1"]["files"][-1])
validate_repaired_physical(added_before, added_after, target)
added_after["node1"]["files"][-1]["sha256"] = "unexpected"
with self.assertRaisesRegex(ValueError, "unexpected physical file"):
validate_repaired_physical(added_before, added_after, target)
def test_unknown_or_wrong_version_receipt_cannot_certify_physical_repair(self):
target = self.target(self.snapshot())
receipt = HealHealthyOracleTest().receipt("repaired")
receipt["outcome"]["counters"].update(healed=1, unchanged=0)
receipt["outcome"]["objects"][0]["identity"].update(bucket=target["bucket"], object=target["key"], versionId=None)
validate_repaired_status(receipt, target)
for invalid in ("unknown", "wrong-version", "missing-incarnation"):
changed = copy.deepcopy(receipt)
if invalid == "unknown": changed["outcome"]["counters"]["unknown"] = 1
elif invalid == "wrong-version": changed["outcome"]["objects"][0]["identity"]["versionId"] = "another"
else: changed["outcome"]["objects"][0]["identity"].pop("bucketIncarnationId")
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
validate_repaired_status(changed, target)
def test_dry_run_requires_all_version_marker_receipts_and_never_claims_repair(self):
target = self.target(self.snapshot())
expected = [{"key": target["key"], "versionId": version} for version in ("old", "new", "marker")]
receipt = HealHealthyOracleTest().receipt("dry_run_observed")
receipt["outcome"]["counters"].update(processed=3, unchanged=0, skipped=3)
original = receipt["outcome"]["objects"][0]
original["identity"].update(bucket=target["bucket"], object=target["key"], bucketIncarnationId=None)
receipt["outcome"]["objects"] = [copy.deepcopy(original) for _ in expected]
for entry, version in zip(receipt["outcome"]["objects"], expected): entry["identity"]["versionId"] = version["versionId"]
validate_dry_run_status(receipt, target, expected)
for invalid in ("missing-marker", "repaired", "unknown", "healed-counter"):
value = copy.deepcopy(receipt)
if invalid == "missing-marker": value["outcome"]["objects"].pop()
elif invalid == "healed-counter": value["outcome"]["counters"]["healed"] = 1
else: value["outcome"]["objects"][0]["disposition"]["state"] = invalid
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
validate_dry_run_status(value, target, expected)
def test_fault_requires_actual_service_quiescence_and_exact_truncate_length(self):
for value in ("MainPID=99\nActiveState=inactive\nControlGroup=\n", "MainPID=0\nActiveState=active\n", ""):
with patch("scripts.validation_heal.fleet_node.command", return_value=types.SimpleNamespace(stdout=value)):
with self.assertRaisesRegex(ValueError, "service to be stopped"):
stopped({"unit": "owned.service"})
with patch("scripts.validation_heal.fleet_node.command", return_value=types.SimpleNamespace(
stdout="MainPID=0\nActiveState=inactive\nControlGroup=\n")):
stopped({"unit": "owned.service"})
self.assertEqual(mutation(b"abcdef", "truncate", 5), b"abcde")
for length in (-1, 6, True):
with self.assertRaisesRegex(ValueError, "truncate length"):
mutation(b"abcdef", "truncate", length)
class HealVersionOracleTest(unittest.TestCase):
def test_size_contract_derives_distinct_actual_inline_limits_and_rejects_changed_policy(self):
source = {
"crates/ecstore/src/config/storageclass.rs": '''pub static DEFAULT_INLINE_BLOCK: usize = 128 * 1024;
const DEFAULT_INLINE_OBJECT_BUDGET: usize = 2 * DEFAULT_INLINE_BLOCK;
pub fn should_inline(&self, shard_size: i64, data_shards: usize, versioned: bool) -> bool {
if shard_size < 0 || data_shards == 0 { return false; }
let shard_size = shard_size as usize; let inline_block = self.effective_inline_block(data_shards);
if versioned { shard_size <= inline_block / 8 } else { shard_size <= inline_block }
}
pub(crate) fn effective_inline_block(&self, data_shards: usize) -> usize {
if data_shards == 0 { return 0; }
if self.initialized && self.inline_block_explicit { self.inline_block }
else { DEFAULT_INLINE_OBJECT_BUDGET.div_ceil(data_shards).min(DEFAULT_INLINE_BLOCK) }
}''',
"crates/ecstore/src/set_disk/mod.rs": '''fn inline_admission_shard_size(erasure: &coding::Erasure, stored_size: i64, actual_size: i64) -> i64 {
if stored_size >= 0 { return erasure.shard_file_size(stored_size); } actual_size }''',
"crates/ecstore/src/set_disk/ops/object.rs": '''let is_inline_buffer = storage_class_config.should_inline(
inline_admission_shard_size(&erasure, put_object_size, data.actual_size()), erasure.data_shards, opts.versioned,
) && usize::try_from(inline_admission_size).is_ok_and(|size| size <= erasure.block_size);''',
"crates/ecstore/src/erasure/coding/erasure.rs": '''pub fn calc_shard_size(block_size: usize, data_shards: usize) -> usize {
block_size.div_ceil(data_shards) }'''}
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for path, text in source.items():
file = root / path
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(text)
contract = size_contract(root, "a" * 40)
verify_size_contract({"sizeContract": contract}, {"source_sha": "a" * 40})
processes = {"node": {"storageClassEnvironment": {
"RUSTFS_STORAGE_CLASS_INLINE_BLOCK": None, "RUSTFS_STORAGE_CLASS_STANDARD": None}}}
for data, inline in ((2, 262144), (12, 262152)):
target = {"logical": {"usesLegacyChecksum": False, "erasure": {"data_blocks": data, "block_size": 1048576}}}
parameters = boundary_sizes(contract, target, processes)
self.assertEqual(parameters["actualLogicalInlineLimit"], inline)
self.assertEqual(parameters["groups"]["inline-minus-exact-plus"], [inline - 1, inline, inline + 1])
self.assertEqual(parameters["groups"]["stripe-minus-exact-plus"], [1048575, 1048576, 1048577])
with self.assertRaises(ValueError): boundary_sizes(contract, target, {"node": {"storageClassEnvironment": {}}})
for field, value in (("recognized", False), ("extractorSourceSha256", "0" * 64), ("candidateCommit", "b" * 40)):
with self.assertRaises(ValueError):
verify_size_contract({"sizeContract": {**contract, field: value}}, {"source_sha": "a" * 40})
path = root / "crates/ecstore/src/erasure/coding/erasure.rs"
path.write_text(source[str(path.relative_to(root))].replace("div_ceil", "div_floor"))
self.assertFalse(size_contract(root, "a" * 40)["recognized"])
def test_zero_boundary_faults_metadata_and_never_invents_a_part(self):
snapshot = HealShardOracleTest().snapshot()
observation = snapshot["node1"]
observation["files"] = [entry for entry in observation["files"] if "metadata" in entry]
for entry in observation["files"]:
version = entry["metadata"]["versions"][0]
version["size"] = 0
version["parts"][0].update(size=0, actualSize=0)
expected = [{"key": "objects/0008.bin", "versionId": "null", "deleteMarker": False,
"payload": {"size": 0, "sha256": hashlib.sha256(b"").hexdigest()}}]
instance = {"key": expected[0]["key"], "size": 0, "role": "parity", "expectedShape": "zero-metadata", "kind": "bitflip"}
plan = boundary_plan(instance, snapshot, "rv-heal-0123456789abcdef", expected)
self.assertEqual(plan["kind"], "header")
self.assertTrue(plan["proofs"][0]["zeroProof"])
self.assertEqual(plan["faults"][0]["role"], "parity")
self.assertTrue(plan["faults"][0]["relativePath"].endswith("/xl.meta"))
observation["files"].append(next(entry for entry in HealShardOracleTest().snapshot()["node1"]["files"] if "metadata" not in entry))
with self.assertRaisesRegex(ValueError, "zero object"):
boundary_plan(instance, snapshot, "rv-heal-0123456789abcdef", expected)
def test_actual_size_ranges_require_206_bytes_and_empty_range_requires_exact_416(self):
from scripts.validation_heal.heal_probe import payload
bucket, block = "fixture", 4096
expected = [{"key": str(size), "payload": {"size": size}} for size in (0, 1, 4097)]
calls = []
def s3(operation, params):
size = int(params["Key"])
calls.append(params)
if not size:
return {"acknowledged": False, "resultUnknown": False, "response": {
"ResponseMetadata": {"HTTPStatusCode": 416}, "Error": {"Code": "InvalidRange"}}}
start, end = map(int, params["Range"].removeprefix("bytes=").split("-"))
value = payload(f"{bucket}/{params['Key']}/0", size)[start:end + 1]
return {"acknowledged": True, "response": {"ResponseMetadata": {"HTTPStatusCode": 206},
"ContentRange": f"bytes {start}-{end}/{size}"},
"payload": {"size": len(value), "sha256": hashlib.sha256(value).hexdigest()}}
fleet = types.SimpleNamespace(record=lambda label, value: value)
verify_boundary_ranges(types.SimpleNamespace(s3=s3), fleet, bucket, expected, block)
self.assertTrue(any(params["Range"] == "bytes=4079-4096" for params in calls))
for wrong in ({"acknowledged": False, "resultUnknown": True}, {"acknowledged": True, "payload": {"size": 0}}):
with self.assertRaises(ValueError):
verify_boundary_ranges(types.SimpleNamespace(s3=lambda *args: wrong), fleet, bucket, expected[:1], block)
def test_explicit_small_list_pages_preserve_distinct_special_keys(self):
bucket = "rv-heal-pages-unit"
keys = [*SPECIAL_KEYS, *(f"pages/{index:04d}.bin" for index in range(257))]
for failure in (None, "duplicate-version", "omitted-current", "oversized-page"):
calls = []
def paginator(operation):
def paginate(**params):
calls.append((operation, params))
self.assertEqual(params["PaginationConfig"], {"PageSize": 17})
listed = list(keys)
if failure == "duplicate-version" and operation == "list_object_versions": listed[-1] = listed[0]
if failure == "omitted-current" and operation == "list_objects_v2": listed.pop()
width = 18 if failure == "oversized-page" else 17
for start in range(0, len(listed), width):
page = listed[start:start + width]
yield {"Versions": [{"Key": key, "VersionId": "null", "IsLatest": True} for key in page]} \
if operation == "list_object_versions" else {"Contents": [{"Key": key, "Size": 1, "ETag": key} for key in page]}
return types.SimpleNamespace(paginate=paginate)
def s3(operation, params):
if operation == "get_object":
return {"acknowledged": True, "response": {"ETag": params["Key"]}, "payload": {"size": 1, "sha256": "digest"}}
return {"acknowledged": True, "response": {}}
probe = Probe.__new__(Probe)
probe.binding = {"bucketPrefix": bucket, "maxInventoryObjects": 512, "maxInventoryBytes": 512}
probe.s3_client = lambda: types.SimpleNamespace(get_paginator=paginator)
probe.s3 = s3
if failure:
with self.subTest(failure=failure), self.assertRaises(ValueError):
probe.inventory(bucket, unversioned_current_tags=True, page_size=17)
else:
observed = probe.inventory(bucket, unversioned_current_tags=True, page_size=17)
proof = verify_pagination(observed)
self.assertEqual(proof["acknowledgedObjects"], 265)
self.assertEqual(proof["currentPages"], 16)
self.assertEqual(proof["versionPages"], 16)
self.assertEqual({entry["key"] for entry in observed["entries"]}, set(keys))
def test_multi_loss_covers_every_actual_loss_count_and_role_composition(self):
cohort = {"logical": {"erasure": {"data_blocks": 12, "parity_blocks": 4}}, "cohort": list(range(16))}
expected = [{"key": "object", "versionId": "old", "deleteMarker": False}]
with patch("scripts.validation_heal.versions.choose_target", return_value=cohort):
instances = multi_loss_instances({}, "fixture", expected, "DV")
self.assertEqual(len(instances), 14)
self.assertEqual({(item["loss"], item["dataLoss"], item["parityLoss"]) for item in instances},
{(loss, data, loss - data) for loss in range(1, 5) for data in range(loss + 1)})
self.assertEqual(len({item["key"] for item in instances}), 14)
self.assertEqual({item["sourceBranch"] for item in instances}, set(VERSION_BRANCHES["heal.multiple-shard-loss"]))
for item in instances:
self.assertGreaterEqual(item["remainingSameVersionShards"], item["readQuorum"])
before = HealShardOracleTest().snapshot()
entry = {"key": "objects/0008.bin", "versionId": "null", "deleteMarker": False}
instance = {**instances[2], "key": entry["key"], "dataLoss": 1, "parityLoss": 1,
"loss": 2, "readQuorum": 2}
plan = multi_loss_plan(instance, before, "rv-heal-0123456789abcdef", [entry], "DB")
self.assertEqual({item["role"] for item in plan["faults"]}, {"data", "parity"})
self.assertEqual(len({item["disk"] for item in plan["faults"]}), 2)
self.assertEqual(plan["requiredRepairs"], {(entry["key"], "null")})
self.assertTrue(all(item["versionId"] == "null" for item in plan["faults"]))
with self.assertRaisesRegex(ValueError, "quorum"):
multi_loss_plan({**instance, "dataLoss": 3, "loss": 4}, before,
"rv-heal-0123456789abcdef", [entry], "DB")
def test_metadata_fixture_has_real_encoded_content_and_exact_distinct_version_tags(self):
uploaded = []
def call(operation, params, body=None):
if operation == "put_object":
self.assertEqual(params["ContentEncoding"], "gzip")
self.assertTrue(gzip.decompress(body))
self.assertEqual(len(gzip.decompress(body)), 5 * 1024**2 + 123)
self.assertTrue(all(value.isascii() for value in params["Metadata"].values()))
uploaded.append((params["Key"], params["Metadata"]["generation"]))
return {"VersionId": "version-" + str(len(uploaded))}
return {}
expected, public = seed_semantics(types.SimpleNamespace(call=call), "fixture")
self.assertEqual(len(expected), 9)
self.assertEqual(len({entry["versionId"] for entry in expected}), 9)
self.assertEqual(len({key for key, _ in uploaded}), 3)
baseline = {"entries": [{"key": spec["key"], "versionId": spec["versionId"],
"properties": copy.deepcopy(spec["properties"]), "tags": copy.deepcopy(spec["tags"])} for spec in public]}
verify_semantics(public, baseline)
for kind in ("header", "metadata", "versioned-tags"):
changed = copy.deepcopy(baseline)
if kind == "header": changed["entries"][0]["properties"]["ContentEncoding"] = "identity"
elif kind == "metadata": changed["entries"][0]["properties"]["Metadata"]["userkey"] = "another"
else: changed["entries"][0]["tags"] = copy.deepcopy(changed["entries"][1]["tags"])
with self.subTest(kind=kind), self.assertRaises(ValueError): verify_semantics(public, changed)
def test_decoder_failure_is_evidence_only_for_the_exact_witnessed_corruption(self):
entry = {"disk": 0, "path": "fixture/key/xl.meta", "sha256": "changed-sha", "size": 9}
fault = {entry["path"]: {"sha256": "changed-sha", "size": 9}}
rejected = types.SimpleNamespace(returncode=1, stderr="invalid captured metadata", stdout="")
with patch("scripts.validation_heal.fleet_node.command", return_value=rejected):
observed = inspect_metadata("tool", "path", "fixture", "key", entry, fault)
self.assertFalse(observed["metadataError"]["validMetadataClaimed"])
self.assertNotIn("metadata", observed)
for incorrect in ({}, {entry["path"]: {"sha256": "different", "size": 9}},
{entry["path"]: {"sha256": "changed-sha", "size": 10}}):
with self.assertRaises(ValueError): inspect_metadata("tool", "path", "fixture", "key", entry, incorrect)
decoded = {"bucket": "fixture", "key": "another", "physicalBitrotVerified": False}
with patch("scripts.validation_heal.fleet_node.command", return_value=types.SimpleNamespace(
returncode=0, stdout=json.dumps(decoded))):
with self.assertRaises(ValueError): inspect_metadata("tool", "path", "fixture", "key", entry, fault)
def test_inline_fault_uses_unique_candidate_decoded_slice_and_frozen_role_digest(self):
original = HealShardOracleTest().snapshot()
bucket, key = "rv-heal-0123456789abcdef", "objects/0008.bin"
for entry in original["node1"]["files"]:
if "metadata" in entry:
entry["metadata"]["versions"][0]["inline"] = {"length": 82, "rawOffset": 200,
"rawOccurrenceCount": 1, "sha256": str(entry["disk"]) * 64}
expected = {"key": key, "versionId": "null", "payload": {"size": 100}}
target = map_inline_target(original, bucket, expected)
self.assertEqual(target["disk"], 1)
def remote(node, action, **params):
entry = next(entry for entry in target["cohort"] if entry["disk"] == params["disk"])
return {"physicalBitrotVerified": True, "inlineLength": entry["inlineValue"]["length"], "inlineSha256": entry["inlineValue"]["sha256"]}
fleet = types.SimpleNamespace(record=lambda label, value: value, remote=remote)
self.assertTrue(verify_proof(fleet, target, "inline")['originalInlineSha256Restored'])
with patch.object(fleet, "remote", return_value={"inlineLength": 82, "inlineSha256": "wrong"}):
with self.assertRaises(ValueError): verify_proof(fleet, target, "inline")
for kind in ("ambiguous", "outside", "wrong-role", "wrong-digest"):
bad = copy.deepcopy(original)
value = next(entry["metadata"]["versions"][0] for entry in bad["node1"]["files"] if "metadata" in entry)
if kind == "ambiguous": value["inline"]["rawOccurrenceCount"] = 2
elif kind == "outside": value["inline"]["rawOffset"] = 590
elif kind == "wrong-role": value["role"] = "data"
else: value["inline"]["sha256"] = "invalid"
with self.subTest(kind=kind), self.assertRaises(ValueError): map_inline_target(bad, bucket, expected)
def test_below_quorum_needs_exact_failure_and_never_accepts_transport_or_false_repair(self):
status, expected = self.fixture()
status["summary"] = "stopped"
outcome = status["outcome"]
outcome["execution"]["state"] = "completed_with_errors"
outcome["objects"][0]["disposition"] = {"state": "failed", "details": "retry_exhausted"}
outcome["counters"].update(unchanged=3, failed=1, attemptFailures=2)
validate_failed_version(status, "fixture", expected, expected[0])
for kind in ("finished", "running", "completed", "unknown", "repaired", "wrong-version", "hidden-attempts", "wrong-counter"):
value = copy.deepcopy(status)
if kind in {"finished", "running"}: value["summary"] = kind
elif kind == "completed": value["outcome"]["execution"]["state"] = "completed"
elif kind in {"unknown", "repaired"}: value["outcome"]["objects"][0]["disposition"]["state"] = kind
elif kind == "wrong-version": value["outcome"]["objects"][0]["identity"]["versionId"] = "different"
elif kind == "hidden-attempts": value["outcome"]["counters"]["attemptFailures"] = 0
else: value["outcome"]["counters"]["failed"] = True
with self.subTest(kind=kind), self.assertRaises(ValueError):
validate_failed_version(value, "fixture", expected, expected[0])
contract = {"unrecoverableGet": {"httpStatus": 503, "code": "SlowDownRead"}}
observation = {"acknowledged": False, "resultUnknown": False,
"response": {"ResponseMetadata": {"HTTPStatusCode": 503}, "Error": {"Code": "SlowDownRead"}}}
validate_unrecoverable_get(observation, contract)
for changed in ({**observation, "resultUnknown": True}, {**observation, "payload": {"size": 0}},
{**observation, "acknowledged": True}):
with self.assertRaises(ValueError): validate_unrecoverable_get(changed, contract)
def test_tool_freezes_recognized_candidate_quorum_and_rejects_stale_or_changed_contract(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
error = root / "rustfs/src/error.rs"
metadata = root / "crates/ecstore/src/set_disk/metadata.rs"
error.parent.mkdir(parents=True)
metadata.parent.mkdir(parents=True)
error.write_text('const SLOW_DOWN_READ_CODE: &str = "SlowDownRead";\n'
'StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(_, _) => '
'{ S3ErrorCode::Custom(SLOW_DOWN_READ_CODE.into()) }\n'
'S3ErrorCode::Custom(custom) if &**custom == SLOW_DOWN_READ_CODE => Some(StatusCode::SERVICE_UNAVAILABLE)')
metadata.write_text('pub(super) fn object_quorum_from_meta() {\n'
'let data_blocks = parts_metadata.len() as i32 - parity_blocks;\nOk((data_blocks, write_quorum))\n}')
contract = quorum_contract(root, "a" * 40)
self.assertTrue(contract["recognized"])
verify_quorum_contract({"quorumContract": contract}, {"source_sha": "a" * 40})
for changed in ({**contract, "candidateCommit": "b" * 40},
{**contract, "extractorSourceSha256": "0" * 64}, {**contract, "recognized": False}):
with self.assertRaises(ValueError):
verify_quorum_contract({"quorumContract": changed}, {"source_sha": "a" * 40})
metadata.write_text('pub(super) fn object_quorum_from_meta() {\n'
'let data_blocks = parts_metadata.len() as i32 - parity_blocks;\n'
'// Ok((data_blocks, write_quorum))\nOk((data_blocks + 1, write_quorum))\n}')
self.assertFalse(quorum_contract(root, "a" * 40)["recognized"])
def test_suspended_null_fixture_retains_historical_identities_and_requires_real_marker_acks(self):
historical = [{"key": f"objects/{index:04d}.bin", "versionId": f"history-{index}-{version}",
"deleteMarker": False, "isLatest": version == 2}
for index in range(3) for version in range(3)]
calls = []
def invoke(operation, params, body=None):
calls.append((operation, copy.deepcopy(params)))
if operation == "get_bucket_versioning": return {"Status": "Suspended"}
if operation == "put_object": return {"VersionId": "null"}
if operation == "delete_object": return {"VersionId": "null", "DeleteMarker": True}
return {}
recorder = types.SimpleNamespace(call=invoke)
expected = suspend_fixture(recorder, "fixture", historical)
self.assertEqual(len(expected), 12)
self.assertEqual({item["versionId"] for item in expected if item["versionId"] != "null"},
{item["versionId"] for item in historical})
self.assertTrue(all(not item["isLatest"] for item in expected if item["versionId"] != "null"))
markers = [item for item in expected if item["deleteMarker"]]
self.assertEqual(markers, [{"key": "objects/0002.bin", "versionId": "null", "isLatest": True, "deleteMarker": True}])
self.assertEqual(sum(operation == "delete_object" and params.get("VersionId") == "null"
for operation, params in calls), 3)
for kind in ("fake-version", "missing-marker"):
def invalid(operation, params, body=None):
result = invoke(operation, params, body)
if kind == "fake-version" and operation == "put_object": result["VersionId"] = "unexpected-new-version"
elif kind == "missing-marker" and operation == "delete_object": result["DeleteMarker"] = False
return result
with self.subTest(kind=kind), self.assertRaises(ValueError):
suspend_fixture(types.SimpleNamespace(call=invalid), "fixture", historical)
self.assertTrue(all(item["isLatest"] == (index % 3 == 2) for index, item in enumerate(historical)))
def fixture(self):
expected = [{"key": "object", "versionId": version, "deleteMarker": version == "marker"}
for version in ("old", "middle", "current", "marker")]
status = HealHealthyOracleTest().receipt()
original = status["outcome"]["objects"][0]
original["identity"].update(bucket="fixture", object="object")
status["outcome"]["objects"] = [copy.deepcopy(original) for _ in expected]
for receipt, entry in zip(status["outcome"]["objects"], expected):
receipt["identity"]["versionId"] = entry["versionId"]
receipt["disposition"]["state"] = "metadata_healthy" if entry["deleteMarker"] else "verified_healthy"
status["outcome"]["counters"].update(processed=4, unchanged=4)
return status, expected
def test_all_version_receipts_and_counters_are_required(self):
status, expected = self.fixture()
status["outcome"]["objects"][0]["disposition"]["state"] = "repaired"
status["outcome"]["counters"].update(healed=1, unchanged=3)
validate_version_receipts(status, "fixture", expected, 2, required_repairs={("object", "old")})
for kind in ("missing-marker", "duplicate", "wrong-version", "unknown", "incarnation", "boolean-counter", "healthy-fault"):
bad = copy.deepcopy(status)
objects = bad["outcome"]["objects"]
if kind == "missing-marker": objects.pop()
elif kind == "duplicate": objects[-1] = copy.deepcopy(objects[0])
elif kind == "wrong-version": objects[0]["identity"]["versionId"] = "another"
elif kind == "unknown": objects[0]["disposition"]["state"] = "unknown"
elif kind == "incarnation": objects[0]["identity"]["bucketIncarnationId"] = "other"
elif kind == "boolean-counter": bad["outcome"]["counters"]["healed"] = True
else: objects[0]["disposition"]["state"] = "verified_healthy"
with self.subTest(kind=kind), self.assertRaises(ValueError):
validate_version_receipts(bad, "fixture", expected, 2, required_repairs={("object", "old")})
def test_repeat_requires_mode_specific_health_and_zero_repairs(self):
status, expected = self.fixture()
validate_version_receipts(status, "fixture", expected, 2)
with self.assertRaises(ValueError): validate_version_receipts(status, "fixture", expected, 1)
for entry in status["outcome"]["objects"]: entry["disposition"]["state"] = "metadata_healthy"
validate_version_receipts(status, "fixture", expected, 1)
with self.assertRaises(ValueError): validate_version_receipts(status, "fixture", expected, 2)
status["outcome"]["objects"][0]["disposition"]["state"] = "repaired"
status["outcome"]["counters"].update(healed=1, unchanged=3)
with self.assertRaises(ValueError): validate_version_receipts(status, "fixture", expected, 1)
def test_admin_nil_uuid_maps_only_to_the_acknowledged_s3_null_version(self):
status, expected = self.fixture()
expected[0]["versionId"] = "null"
status["outcome"]["objects"][0]["identity"]["versionId"] = "00000000-0000-0000-0000-000000000000"
validate_version_receipts(status, "fixture", expected, 2)
wrong = copy.deepcopy(status)
wrong["outcome"]["objects"][0]["identity"]["versionId"] = "00000000-0000-0000-0000-000000000001"
with self.assertRaises(ValueError):
validate_version_receipts(wrong, "fixture", expected, 2)
expected[0]["versionId"] = "old"
with self.assertRaises(ValueError):
validate_version_receipts(status, "fixture", expected, 2)
def test_metadata_repair_may_repair_all_receipts_but_marker_cannot_claim_deep_payload(self):
status, expected = self.fixture()
with self.assertRaisesRegex(ValueError, "never attributed"):
validate_version_receipts(status, "fixture", expected, 2, metadata_repairs={"object"})
for entry in status["outcome"]["objects"]: entry["disposition"]["state"] = "repaired"
status["outcome"]["counters"].update(healed=4, unchanged=0)
validate_version_receipts(status, "fixture", expected, 2, metadata_repairs={"object"})
status["outcome"]["objects"][-1]["disposition"]["state"] = "verified_healthy"
status["outcome"]["counters"].update(healed=3, unchanged=1)
with self.assertRaises(ValueError):
validate_version_receipts(status, "fixture", expected, 2, metadata_repairs={"object"})
def test_version_fault_plan_uses_ack_versions_distinct_disks_and_exact_recursive_scope(self):
original = HealShardOracleTest().snapshot()
observation = original["node1"]
templates = {entry["disk"]: entry for entry in observation["files"] if "metadata" in entry}
shards = {entry["disk"]: entry for entry in observation["files"] if entry["path"].endswith("part.1")}
snapshot = {"node1": {"formats": observation["formats"], "files": []}}
bucket, expected = "rv-heal-0123456789abcdef", []
for key_index in range(4):
key = f"objects/{key_index:04d}.bin"
version_ids = [f"00000000-0000-0000-0000-{key_index * 3 + index + 1:012d}" for index in range(3)]
for index, version in enumerate(version_ids):
expected.append({"key": key, "versionId": version, "deleteMarker": False,
"isLatest": index == 2 and key_index % 2 == 1})
if key_index % 2 == 0:
expected.append({"key": key, "versionId": "marker-" + str(key_index), "deleteMarker": True, "isLatest": True})
for disk in range(4):
meta = copy.deepcopy(templates[disk])
meta["path"] = f"{bucket}/{key}/xl.meta"
meta["metadata"]["key"] = key
version_template = meta["metadata"]["versions"][0]
meta["metadata"]["versions"] = []