"""Finite blind-redo illustration, not Stasis or a crash/durability test. Run: python3 -B stasis_redo.py Check the adjacent published result: python3 -B test_stasis_redo.py No storage I/O, log truncation algorithm, transaction undo or hardware model. """ from dataclasses import dataclass from itertools import product import json @dataclass(frozen=True) class Write: lsn: int offset: int payload: bytes def __post_init__(self): if type(self.lsn) is not int or self.lsn <= 0: raise ValueError("lsn must be a positive integer") if type(self.offset) is not int or self.offset < 0: raise ValueError("offset must be a nonnegative integer") if type(self.payload) is not bytes or not self.payload: raise ValueError("payload must be nonempty bytes") INITIAL = bytes((0, 0, 7)) LOG = (Write(10, 0, bytes((1, 2))), Write(20, 0, bytes((3,)))) EXPECTED = bytes((3, 2, 7)) def replay(state, entries): """Apply entries in supplied order, deliberately without sorting/deduping.""" if type(state) is not bytes: raise ValueError("state must be bytes") result = bytearray(state) for entry in entries: if not isinstance(entry, Write): raise ValueError("entries must be Write instances") end = entry.offset + len(entry.payload) if end > len(result): raise ValueError("write extends beyond the fixed state") result[entry.offset:end] = entry.payload return bytes(result) def start_states(): # Each byte independently takes a value from forward history; byte 2 is untouched. history = [INITIAL] for entry in LOG: history.append(replay(history[-1], (entry,))) values = [sorted({state[i] for state in history}) for i in range(len(INITIAL))] return tuple(bytes(row) for row in product(*values)) def copy_first_to_second(state): """Deliberately state-reading and idempotent, unlike a blind redo write.""" if type(state) is not bytes or len(state) != 3: raise ValueError("copy example requires exactly three bytes") return bytes((state[0], state[0], state[2])) def state_reading_example(): initial = bytes((2, 0, 7)) overwrite = Write(20, 0, bytes((3,))) # Capture the copy's original output, rather than reading its source at redo. blind_log = (Write(10, 1, bytes((2,))), overwrite) copied = copy_first_to_second(initial) forward = replay(copied, (overwrite,)) repeated_copy = copy_first_to_second(forward) repeated = replay(repeated_copy, (overwrite,)) starts = tuple(bytes(row) for row in product((2, 3), (0, 2), (7,))) rows = [] for state in starts: current_read = replay(copy_first_to_second(state), (overwrite,)) logged_value = replay(state, blind_log) rows.append({ "start": list(state), "stateReadingEnd": list(current_read), "blindEnd": list(logged_value), "stateReadingMatches": current_read == EXPECTED, "blindMatches": logged_value == EXPECTED, }) return { "initial": list(initial), "operationsInOrder": ["byte[1] = byte[0]", "byte[0] = 3"], "afterForwardCopy": list(copied), "expected": list(EXPECTED), "afterForwardSequence": list(forward), "afterRepeatedCopy": list(repeated_copy), "afterRepeatedSequence": list(repeated), "loggedAfterImage": [ {"lsn": e.lsn, "offset": e.offset, "bytes": list(e.payload)} for e in blind_log ], "startStateRule": "Independent per-byte choices from this copy example's forward history.", "totalStates": len(starts), "stateReadingMatchingStates": sum(row["stateReadingMatches"] for row in rows), "blindMatchingStates": sum(row["blindMatches"] for row in rows), "rows": rows, "interpretation": ( "Each operation is idempotent on its own. Repeating both in the same " "order still fails after the source byte changes. Logging the original " "copied value removes this state dependency for the selected states." ), } def result(): starts = start_states() schedules = ( ("complete_ordered", LOG), ("complete_ordered_twice", LOG + LOG), ("reversed", tuple(reversed(LOG))), ("stale_first_entry_after_complete", LOG + LOG[:1]), ("missing_first_entry", LOG[1:]), ) scenarios = [] for name, entries in schedules: rows = [{"start": list(state), "end": list(replay(state, entries)), "matchesExpected": replay(state, entries) == EXPECTED} for state in starts] scenarios.append({"name": name, "lsns": [entry.lsn for entry in entries], "matchingStates": sum(row["matchesExpected"] for row in rows), "totalStates": len(starts), "rows": rows}) restart_paths = 0 restored_paths = 0 for start in starts: for cut in range(len(LOG) + 1): partial = replay(start, LOG[:cut]) for mask in product((False, True), repeat=len(start)): persisted = bytes(partial[i] if mask[i] else start[i] for i in range(len(start))) restart_paths += 1 restored_paths += replay(persisted, LOG) == EXPECTED return { "schemaVersion": 1, "evidenceType": "synthetic finite byte-assignment illustration", "initial": list(INITIAL), "log": [{"lsn": e.lsn, "offset": e.offset, "bytes": list(e.payload)} for e in LOG], "expected": list(EXPECTED), "startStateRule": "Independent per-byte choices from forward-history values; untouched byte remains 7.", "scenarios": scenarios, "interruptedReplay": { "rule": "For every start, replay prefix and per-byte persistence mask, restart the complete ordered log.", "pathsChecked": restart_paths, "pathsRestored": restored_paths, "countsAreDistinctStates": False, }, "stateReadingExample": state_reading_example(), "limits": [ "No probability distribution is assigned to states or paths.", "A complete retained log and correct untouched bytes are assumed.", "This is redo only; undo, allocation and page-type changes are excluded.", "This is not execution of Stasis, physical fault injection or a performance measurement.", ], } if __name__ == "__main__": print(json.dumps(result(), indent=2))