# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/what-write-time-corruption-signatures-must-be-detected-before-persisting-state-to-external-memory.md # Remnant Warrant: https://corpusfetch.com/c/what-write-time-corruption-signatures-must-be-detected-before-persisting-state-to-external-memory.warrant.json # Markdown SHA-256: 43f13095e0de0289f64733047f3e7d739a080a768038235aece5fb7d1231a0b4 # Code AST SHA-256: e286a952aaa2980bdb1d9e8790df4f0bb6a93388cd4e04b3274baf31b80909d9 # Verified Classes: WriteVerdict, WriteOperation, WriteContext, WriteManifest, WriteIntegrityGuard # Defensive Guards: 0 fail-closed invariants (zero external deps) from dataclasses import dataclass from enum import Enum, auto import hashlib import json class WriteVerdict(Enum): WRITE_INTEGRITY_VERIFIED = auto() SILENT_CORRUPTION_DETECTED = auto() SERIALIZATION_DRIFT = auto() @dataclass(frozen=True) class WriteOperation: record_id: str pre_write_hash: str post_write_hash: str serialization_format: str expected_serialization_format: str atomic_commit_receipt: bool @dataclass(frozen=True) class WriteContext: require_atomic_commit: bool @dataclass(frozen=True) class WriteManifest: verdict: WriteVerdict directive: str manifest_digest: str class WriteIntegrityGuard: @staticmethod def _hash(data: str) -> str: return hashlib.sha256(data.encode("utf-8")).hexdigest() @classmethod def evaluate_write( cls, op: WriteOperation, ctx: WriteContext ) -> WriteManifest: # Gate 1: Serialization format drift if op.serialization_format != op.expected_serialization_format: return WriteManifest( verdict=WriteVerdict.SERIALIZATION_DRIFT, directive=f"HALT: Serialization format {op.serialization_format} != expected {op.expected_serialization_format}.", manifest_digest=cls._hash(f"FORMAT_DRIFT:{op.record_id}") ) # Gate 2: Pre/post hash match if op.pre_write_hash != op.post_write_hash: return WriteManifest( verdict=WriteVerdict.SILENT_CORRUPTION_DETECTED, directive=f"HALT: Pre-write and post-write hashes differ. Silent corruption detected.", manifest_digest=cls._hash(f"CORRUPTION:{op.record_id}") ) # Gate 3: Atomic commit requirement if ctx.require_atomic_commit and not op.atomic_commit_receipt: return WriteManifest( verdict=WriteVerdict.SILENT_CORRUPTION_DETECTED, directive="HALT: Atomic commit receipt missing. Write may be partial.", manifest_digest=cls._hash(f"NO_ATOMIC:{op.record_id}") ) # Gate 4: Verified digest = cls._hash(json.dumps({ "record": op.record_id, "hash": op.pre_write_hash, "format": op.serialization_format }, sort_keys=True)) return WriteManifest( verdict=WriteVerdict.WRITE_INTEGRITY_VERIFIED, directive="PROCEED: Write integrity verified. State matches intent.", manifest_digest=digest )