# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-store-integrity-attestation-as-invalid-the-moment-a-re-embedding-pass-changes-vector-dimensionality.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-store-integrity-attestation-as-invalid-the-moment-a-re-embedding-pass-changes-vector-dimensionality.warrant.json
# Markdown SHA-256:   c9b3f8e12fd401148adacc3d0ede90719c2ba2168cdbf681e864eed7d3587f0c
# Code AST SHA-256:   c793ece48dc4ca21b2baf4c44896dcf69a2cd452448d6a6962e045ffcc53f489
# Verified Classes:   StaleGeometryError, AttestationState, AttestationEnvelope, MemoryRecord, LiveIndex
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class StaleGeometryError(RuntimeError):
    """Raised when a retrieval is attempted against a memory whose vector
    was produced under an embedding model/params digest that no longer
    matches the live index. The record is not corrupt; it is un-retrievable
    under the current contract until re-attested."""
    pass


class AttestationState(Enum):
    VALID = "valid"
    INVALID = "invalid"            # content hash mismatch: tamper or corruption
    STALE_GEOMETRY = "stale_geometry"  # content intact, retrieval contract broken


@dataclass
class AttestationEnvelope:
    content_hash: str
    vector_hash: str
    embedding_model_digest: str
    index_params_digest: str


@dataclass
class MemoryRecord:
    text: str
    metadata: dict
    vector: list
    attestation: AttestationEnvelope
    supersedes: Optional[str] = None


@dataclass
class LiveIndex:
    current_model_digest: str
    current_params_digest: str


def _h(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def _content_hash(rec: MemoryRecord) -> str:
    payload = rec.text + json.dumps(rec.metadata, sort_keys=True)
    return _h(payload.encode("utf-8"))


def classify(rec: MemoryRecord, index: LiveIndex) -> AttestationState:
    # Content integrity first: a genuine tamper outranks geometry staleness.
    if _content_hash(rec) != rec.attestation.content_hash:
        return AttestationState.INVALID
    if _h(bytes(str(rec.vector), "utf-8")) != rec.attestation.vector_hash:
        return AttestationState.INVALID
    # Geometry integrity: the contract the attestation silently assumed.
    if rec.attestation.embedding_model_digest != index.current_model_digest:
        return AttestationState.STALE_GEOMETRY
    if rec.attestation.index_params_digest != index.current_params_digest:
        return AttestationState.STALE_GEOMETRY
    return AttestationState.VALID


def retrieve(records: list, index: LiveIndex, query_vec: list, top_k: int = 5) -> list:
    """Retrieve, but refuse to silently rank stale-geometry records.
    The caller must re-attest and re-run supersession before trusting order."""
    eligible = []
    for rec in records:
        state = classify(rec, index)
        if state is AttestationState.INVALID:
            raise StaleGeometryError(
                f"record failed content attestation: {rec.attestation.content_hash[:12]}"
            )
        if state is AttestationState.STALE_GEOMETRY:
            # Quarantine: do NOT include in ranking, do NOT silently drop.
            raise StaleGeometryError(
                f"record {rec.attestation.vector_hash[:12]} written under "
                f"model {rec.attestation.embedding_model_digest[:8]}, index uses "
                f"{index.current_model_digest[:8]}; re-attest before retrieval"
            )
        eligible.append(rec)
    # Cosine ranking over eligible only; supersession re-resolution is the
    # caller's responsibility after any re-attestation pass.
    def cos(a, b):
        dot = sum(x * y for x, y in zip(a, b))
        na = sum(x * x for x in a) ** 0.5
        nb = sum(y * y for y in b) ** 0.5
        return dot / (na * nb + 1e-12)

    return sorted(eligible, key=lambda r: cos(r.vector, query_vec), reverse=True)[:top_k]
