"""Independent rank and finite-state checks for the placement teaching model.""" from collections import Counter from fractions import Fraction from itertools import combinations, product import json from pathlib import Path import unittest from model import failure_stripes, laws, results, stripe_erasures, summarize # A separate (4,2) MDS code over GF(5), used only as a rank oracle. # This is not the byte field or on-disk format of a production RAID6 driver. ROWS = ((1, 0), (0, 1), (1, 1), (1, 2)) def rank_mod5(rows): matrix = [list(row) for row in rows] rank = 0 for col in range(2): pivot = next((r for r in range(rank, len(matrix)) if matrix[r][col] % 5), None) if pivot is None: continue matrix[rank], matrix[pivot] = matrix[pivot], matrix[rank] inv = pow(matrix[rank][col], -1, 5) matrix[rank] = [(x * inv) % 5 for x in matrix[rank]] for r in range(len(matrix)): if r != rank: factor = matrix[r][col] matrix[r] = [(x - factor * y) % 5 for x, y in zip(matrix[r], matrix[rank])] rank += 1 return rank def rank_failure(positions, offsets): return tuple( stripe for stripe in range(4) if rank_mod5([ ROWS[disk + 1] for disk in range(3) if positions[disk] != (stripe + offsets[disk]) % 4 ]) < 2 ) class PlacementTests(unittest.TestCase): def test_all_two_rows_are_independent(self): for pair in combinations(ROWS, 2): self.assertEqual(rank_mod5(pair), 2) def test_all_masks_match_erasure_bound(self): for mask in range(16): survivors = [row for i, row in enumerate(ROWS) if not mask & (1 << i)] self.assertEqual(rank_mod5(survivors) == 2, mask.bit_count() <= 2) def test_all_positions_and_offsets_match_rank(self): checked = 0 for positions in product(range(4), repeat=3): for offsets in product(range(4), repeat=3): self.assertEqual(failure_stripes(positions, offsets), rank_failure(positions, offsets)) checked += 1 self.assertEqual(checked, 4096) def test_every_law_has_identical_uniform_marginals(self): for rows in laws().values(): for disk in range(3): counts = Counter(row[disk] for row in rows) self.assertEqual(set(counts), {0, 1, 2, 3}) self.assertEqual(set(counts.values()), {len(rows) // 4}) def test_every_state_has_exactly_three_additional_erasures(self): for rows in laws().values(): for row in rows: self.assertEqual(sum(stripe_erasures(row)) - 4, 3) def test_main_exact_results(self): summary = {case["id"]: case for case in results()["cases"]} for name, states, failures in ( ("aligned_standard", 4, 4), ("independent_standard", 64, 40), ("separated_standard", 24, 0), ): self.assertEqual(summary[name]["equally_weighted_states"], states) self.assertEqual(summary[name]["states_with_unrecoverable_stripe"], failures) def test_independent_collision_probability_without_enumeration(self): # Three distinct positions can be chosen in 4 * 3 * 2 ways. expected = 1 - Fraction(4 * 3 * 2, 4 ** 3) row = summarize("independent", "independent", (0, 0, 0)) fraction = row["probability_any_unrecoverable_stripe"] self.assertEqual(Fraction(fraction["numerator"], fraction["denominator"]), expected) self.assertEqual(expected, Fraction(5, 8)) def test_offsets_do_not_change_independent_law(self): for offset in product(range(4), repeat=3): self.assertEqual(summarize("x", "independent", offset)[ "states_with_unrecoverable_stripe"], 40) def test_offsets_help_only_the_specified_alignment(self): self.assertEqual(summarize("x", "aligned", (0, 1, 2))[ "states_with_unrecoverable_stripe"], 0) self.assertEqual(summarize("x", "offset_aligned", (0, 1, 2))[ "states_with_unrecoverable_stripe"], 4) self.assertEqual(summarize("x", "offset_aligned", (0, 0, 0))[ "states_with_unrecoverable_stripe"], 0) def test_ambiguity_is_real_not_a_decoder_choice(self): # Missing member 0 and erasures on members 1 and 2 leave Q only. first = (0, 0) second = (3, 1) encode = lambda value: tuple((a * value[0] + b * value[1]) % 5 for a, b in ROWS) self.assertNotEqual(first, second) self.assertEqual(encode(first)[3], encode(second)[3]) def test_two_survivors_recover_all_small_field_messages(self): for pair in combinations(range(4), 2): signatures = { tuple((ROWS[d][0] * a + ROWS[d][1] * b) % 5 for d in pair) for a, b in product(range(5), repeat=2) } self.assertEqual(len(signatures), 25) def test_per_stripe_and_any_stripe_denominators_differ(self): row = summarize("x", "independent", (0, 0, 0)) self.assertEqual(row["probability_any_unrecoverable_stripe"], {"numerator": 5, "denominator": 8}) self.assertEqual(row["expected_unrecoverable_stripe_fraction"], {"numerator": 5, "denominator": 32}) def test_inputs_reject_invalid_positions_and_offsets(self): for bad in (None, "012", (), (0, 1), (0, 1, 2, 3), (0, 1, -1), (0, 1, 4), (0, 1, 1.0), (0, 1, True)): with self.assertRaises(ValueError): stripe_erasures(bad) with self.assertRaises(ValueError): stripe_erasures((0, 1, 2), bad) def test_generated_evidence_matches(self): actual = Path(__file__).with_name("results.json").read_text(encoding="utf-8") expected = json.dumps(results(), indent=2, sort_keys=True) + "\n" self.assertEqual(actual, expected) def test_results_are_deterministic(self): self.assertEqual(results(), results()) if __name__ == "__main__": unittest.main()