# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-re-admit-poisoned-memory-after-a-provenance-audit-passes-the-quarantine-epoch-aliasing-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-re-admit-poisoned-memory-after-a-provenance-audit-passes-the-quarantine-epoch-aliasing-failure.warrant.json
# Markdown SHA-256:   34e689d70b5e97f89dd5a3286cc2c0f2c8886214e14448d5603bfc3fc555811d
# Code AST SHA-256:   8f3e6c50ef2147c768dc34c2decb0992be55cdd8a870afe444400de95c1c26e2
# Verified Classes:   ProvenanceAliasingError, Provenance, Record
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceAliasingError(RuntimeError):
    """Raised when a re-promotion would admit content whose provenance
    no longer describes the bytes under the record key."""
    pass


@dataclass(frozen=True)
class Provenance:
    content_hash: str
    source: str
    trust: float
    ingested_at: int
    quarantine_epoch: int
    audit_epoch: int
    seq: int  # monotonic append-only sequence; in-place rewrite => seq reuse


@dataclass
class Record:
    mem_id: str
    content: bytes
    provenance: Provenance
    quarantine_log: list = field(default_factory=list)


def _hash(content: bytes) -> str:
    return hashlib.sha256(content).hexdigest()


def re_promote(record: Record, auditor_verdict: bool, current_audit_epoch: int) -> Record:
    """
    Admission gate. The auditor's verdict is a *proposal*; this function is
    the *proof*. All four conjuncts must hold or we refuse and re-quarantine.
    """
    p = record.provenance

    # 1. Content-hash binding: provenance must describe the current bytes.
    if _hash(record.content) != p.content_hash:
        record.quarantine_log.append(
            f"epoch={p.quarantine_epoch + 1} reason=content_provenance_divergence"
        )
        raise ProvenanceAliasingError(
            f"content hash mismatch for {record.mem_id}: "
            f"provenance claims {p.content_hash}, bytes hash {_hash(record.content)}"
        )

    # 2. Epoch monotonicity: audit must postdate the quarantine.
    if p.audit_epoch <= p.quarantine_epoch:
        raise ProvenanceAliasingError(
            f"stale audit for {record.mem_id}: audit_epoch={p.audit_epoch} "
            f"<= quarantine_epoch={p.quarantine_epoch}"
        )

    # 3. Append-only provenance: seq must be strictly greater than any
    #    prior seq recorded for this mem_id in the quarantine log.
    if record.quarantine_log and p.seq <= _last_seq(record.quarantine_log):
        raise ProvenanceAliasingError(
            f"provenance rewrite detected for {record.mem_id}: "
            f"seq={p.seq} not monotonic"
        )

    # 4. Audit epoch must match the epoch the content was ingested under.
    if current_audit_epoch != p.audit_epoch:
        raise ProvenanceAliasingError(
            f"audit epoch drift for {record.mem_id}: "
            f"current={current_audit_epoch} provenance={p.audit_epoch}"
        )

    # Auditor verdict is necessary but never sufficient.
    if not auditor_verdict:
        raise ProvenanceAliasingError(
            f"auditor rejected re-promotion of {record.mem_id}"
        )

    # Append a new provenance entry; never mutate the old one in place.
    new_prov = Provenance(
        content_hash=p.content_hash,
        source=p.source,
        trust=p.trust,
        ingested_at=p.ingested_at,
        quarantine_epoch=p.quarantine_epoch,
        audit_epoch=current_audit_epoch,
        seq=p.seq + 1,
    )
    return Record(
        mem_id=record.mem_id,
        content=record.content,
        provenance=new_prov,
        quarantine_log=record.quarantine_log + [f"promoted seq={new_prov.seq}"],
    )


def _last_seq(log: list) -> int:
    for entry in reversed(log):
        if entry.startswith("seq="):
            return int(entry.split("=")[1])
    return -1
