# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-memory-poisoning-detector-silently-stop-detecting-after-a-store-compaction-the-attestation-window-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-memory-poisoning-detector-silently-stop-detecting-after-a-store-compaction-the-attestation-window-invariant.warrant.json
# Markdown SHA-256:   e94eeb355355b9df3aee92ec03023ebf7ae199e700a98ebdd4819edb677a00e8
# Code AST SHA-256:   087fc76992674a6cd5279695a821fad4df88f8fccdc64be271076438152187af
# Verified Classes:   AttestationWindowViolation, ProvenanceChain
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttestationWindowViolation(RuntimeError):
    """Raised when a baseline advance is not backed by an append-only provenance event."""
    pass


class ProvenanceChain:
    def __init__(self, external_root: bytes):
        # external_root is provisioned once, signed outside the store writer's trust domain
        self._head = external_root
        self._events = []

    @property
    def head(self) -> bytes:
        return self._head

    def append_rewrite_event(self, old_segments: dict, new_segments: dict, signer) -> bytes:
        if not signer.is_external():
            raise AttestationWindowViolation(
                "rewrite event signed by in-domain key; baseline would be self-attesting"
            )
        event = {
            "type": "rewrite",
            "old": old_segments,
            "new": new_segments,
            "prev": self._head,
        }
        self._events.append(event)
        self._head = signer.sign(event, prev=self._head)
        return self._head


def advance_baseline(chain: ProvenanceChain, new_manifest_root: bytes, signer) -> bytes:
    """Advance the attested baseline. Refuses any advance not covered by a rewrite event."""
    covered = any(
        e["type"] == "rewrite" and e["new"].get("manifest") == new_manifest_root
        for e in chain._events
    )
    if not covered:
        raise AttestationWindowViolation(
            f"baseline advance to {new_manifest_root.hex()[:12]} has no covering rewrite event; "
            "compaction likely regenerated the baseline from store content"
        )
    return chain.head


def detect_poison(candidate: bytes, chain: ProvenanceChain, expected_root: bytes) -> bool:
    if chain.head != expected_root:
        raise AttestationWindowViolation(
            "provenance head diverged from externally held root; detector is unsound"
        )
    return candidate not in chain._events  # placeholder for real membership check
