# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-poisoned-episodic-memory-after-a-semantic-re-distillation-pass-that-re-derives-embeddings-from-tampered-text.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-poisoned-episodic-memory-after-a-semantic-re-distillation-pass-that-re-derives-embeddings-from-tampered-text.warrant.json
# Markdown SHA-256:   d7bb40313b01bcccd16804b0dcfc391ede60028cba95889a38d9899049d9b24a
# Code AST SHA-256:   686a0db30b6ecd787240b84ad58c70ae3d2a972202319c5eb17dc0bc19c37c7b
# Verified Classes:   IntegrityLaunderingError, EpisodicRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class IntegrityLaunderingError(RuntimeError):
    """Raised when a maintenance pass attempts to re-derive an integrity
    anchor from mutable state instead of validating against the admission anchor."""


@dataclass(frozen=True)
class EpisodicRecord:
    record_id: str
    text: str
    admission_hash: str          # written once at admission, never rewritten
    embedding: tuple[float, ...]


def redistill(record: EpisodicRecord, embed_fn) -> EpisodicRecord:
    """Re-embed a record for a model upgrade WITHOUT laundering integrity.

    Invariant: the vector we serve for retrieval must be derived from the bytes
    that were signed at admission. If current text no longer matches the
    admission anchor, we refuse to re-derive and refuse to rebase the anchor.
    """
    current = hashlib.sha256(record.text.encode("utf-8")).hexdigest()

    if current != record.admission_hash:
        # Do NOT recompute the hash over current text. The admission anchor is
        # the only witness; overwriting it converts tampering into a clean pass.
        raise IntegrityLaunderingError(
            f"record {record.record_id}: text hash {current[:12]} != admission "
            f"anchor {record.admission_hash[:12]}; quarantining, not re-embedding"
        )

    new_vec = tuple(embed_fn(record.text))
    # Anchor is preserved verbatim; only the vector is upgraded.
    return EpisodicRecord(
        record_id=record.record_id,
        text=record.text,
        admission_hash=record.admission_hash,
        embedding=new_vec,
    )


def run_maintenance(records, embed_fn, quarantine):
    for rec in records:
        try:
            yield redistill(rec, embed_fn)
        except IntegrityLaunderingError as exc:
            quarantine.append((rec.record_id, str(exc)))
