# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/by-what-semantic-preservation-gates-must-an-instance-govern-cross-version-code-and-api-migrations-to-prevent-silent-behavioral-drift.md # Remnant Warrant: https://corpusfetch.com/c/by-what-semantic-preservation-gates-must-an-instance-govern-cross-version-code-and-api-migrations-to-prevent-silent-behavioral-drift.warrant.json # Markdown SHA-256: 64db70b92e98a411d5dc97fc55c42de953399afa4f3072b4d8766aa87a0d542e # Code AST SHA-256: 65892fd74d5174c69b3cee76f79ff972edf394f77f61458896ab119b2b5ddf57 # Verified Classes: MigrationBehavioralDriftError, GoldenMasterVector, DifferentialMigrationReport, CrossVersionEquivalenceGate # Defensive Guards: 7 fail-closed invariants (zero external deps) from dataclasses import dataclass from typing import Any, Callable class MigrationBehavioralDriftError(AssertionError): '''Raised when a migrated function diverges from the legacy golden-master output, type, or exception contract.''' pass @dataclass(frozen=True) class GoldenMasterVector: vector_id: str args: tuple[Any, ...] kwargs: dict[str, Any] @dataclass(frozen=True) class DifferentialMigrationReport: total_vectors_tested: int nominal_matches: int exception_contract_matches: int zero_behavioral_drift: bool class CrossVersionEquivalenceGate: ''' Enforces strict runtime semantic preservation across code and API migrations: 1. Executes both `legacy_fn` and `migrated_fn` across a Golden-Master edge-case corpus. 2. Verifies exact return-type identity (`type(new) is type(old)`) and value equality (`new == old`), catching list-to-generator drift, float rounding shifts, and None-vs-empty changes. 3. Verifies exception-hierarchy compatibility (`issubclass(type(new_exc), type(old_exc))`) on error inputs. ''' @classmethod def verify_semantic_equivalence( cls, *, legacy_fn: Callable[..., Any], migrated_fn: Callable[..., Any], corpus: list[GoldenMasterVector], ) -> DifferentialMigrationReport: if not corpus: raise ValueError("Golden-Master corpus cannot be empty.") nominal_ok = 0 exc_ok = 0 for vec in corpus: old_exc: Exception | None = None new_exc: Exception | None = None old_val: Any = None new_val: Any = None try: old_val = legacy_fn(*vec.args, **vec.kwargs) except Exception as e: old_exc = e try: new_val = migrated_fn(*vec.args, **vec.kwargs) except Exception as e: new_exc = e # Gate 3: Exception-contract parity check if old_exc is not None or new_exc is not None: if old_exc is None and new_exc is not None: raise MigrationBehavioralDriftError( f"Vector '{vec.vector_id}' raised unexpected {type(new_exc).__name__}({new_exc}) " f"in migrated_fn, whereas legacy_fn returned {old_val!r}." ) if old_exc is not None and new_exc is None: raise MigrationBehavioralDriftError( f"Vector '{vec.vector_id}' swallowed expected {type(old_exc).__name__} " f"and returned {new_val!r} in migrated_fn." ) assert old_exc is not None and new_exc is not None if not issubclass(type(new_exc), type(old_exc)): raise MigrationBehavioralDriftError( f"Exception Contract Drift on '{vec.vector_id}': migrated_fn raised " f"'{type(new_exc).__name__}', which is not a subclass of legacy '{type(old_exc).__name__}'." ) exc_ok += 1 continue # Gate 2: Exact return type and value equivalence check if type(new_val) is not type(old_val): raise MigrationBehavioralDriftError( f"Return-Type Drift on '{vec.vector_id}': legacy returned '{type(old_val).__name__}', " f"migrated returned '{type(new_val).__name__}'." ) if new_val != old_val: raise MigrationBehavioralDriftError( f"Semantic Value Drift on '{vec.vector_id}': legacy={old_val!r} != migrated={new_val!r}." ) nominal_ok += 1 return DifferentialMigrationReport( total_vectors_tested=len(corpus), nominal_matches=nominal_ok, exception_contract_matches=exc_ok, zero_behavioral_drift=True, )