# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/what-invariants-must-survive-when-an-agents-local-state-is-partially-corrupted-by-memory-bit-flips.md # Remnant Warrant: https://corpusfetch.com/c/what-invariants-must-survive-when-an-agents-local-state-is-partially-corrupted-by-memory-bit-flips.warrant.json # Markdown SHA-256: 1a96c8694d42cf6b8484d7967e318e985c4b490f84b3508c1e90b8a213d95c89 # Code AST SHA-256: 5cea373141b1bdaa72a77018c646ea5f151e5039a94a56750b630362a91d971a # Verified Classes: IntegrityVerdict, StateRecord, IntegrityPolicy, IntegrityManifest, BitFlipGuard # Defensive Guards: 0 fail-closed invariants (zero external deps) from dataclasses import dataclass from enum import Enum, auto import hashlib import json class IntegrityVerdict(Enum): INTEGRITY_VERIFIED = auto() BIT_FLIP_DETECTED = auto() HARDWARE_ECC_TRUSTED = auto() @dataclass(frozen=True) class StateRecord: record_id: str stored_checksum: str current_readback_hash: str is_regenerable: bool is_ecc_protected: bool @dataclass(frozen=True) class IntegrityPolicy: require_checksum_on_critical: bool @dataclass(frozen=True) class IntegrityManifest: verdict: IntegrityVerdict directive: str manifest_digest: str class BitFlipGuard: @staticmethod def _hash(data: str) -> str: return hashlib.sha256(data.encode("utf-8")).hexdigest() @classmethod def evaluate_record( cls, record: StateRecord, policy: IntegrityPolicy ) -> IntegrityManifest: # Gate 1: Hardware ECC if record.is_ecc_protected: digest = cls._hash(json.dumps({ "record": record.record_id, "protection": "ECC" }, sort_keys=True)) return IntegrityManifest( verdict=IntegrityVerdict.HARDWARE_ECC_TRUSTED, directive="PROCEED: Hardware ECC protects this record.", manifest_digest=digest ) # Gate 2: Checksum presence if policy.require_checksum_on_critical and not record.stored_checksum: return IntegrityManifest( verdict=IntegrityVerdict.BIT_FLIP_DETECTED, directive=f"HALT: No checksum for critical record {record.record_id}. Cannot verify.", manifest_digest=cls._hash(f"NO_CHECKSUM:{record.record_id}") ) # Gate 3: Checksum match if record.stored_checksum != record.current_readback_hash: if record.is_regenerable: return IntegrityManifest( verdict=IntegrityVerdict.BIT_FLIP_DETECTED, directive=f"ACTION: Bit flip detected on regenerable {record.record_id}. Re-derive from source.", manifest_digest=cls._hash(f"FLIP_REGENERABLE:{record.record_id}") ) return IntegrityManifest( verdict=IntegrityVerdict.BIT_FLIP_DETECTED, directive=f"HALT: Bit flip on critical {record.record_id}. Quarantine and halt.", manifest_digest=cls._hash(f"FLIP_CRITICAL:{record.record_id}") ) # Gate 4: Verified digest = cls._hash(json.dumps({ "record": record.record_id, "checksum": record.stored_checksum }, sort_keys=True)) return IntegrityManifest( verdict=IntegrityVerdict.INTEGRITY_VERIFIED, directive="PROCEED: Bit-level integrity verified.", manifest_digest=digest )