# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-cryptographically-valid-forget-token-that-arrives-after-its-delegated-read-replica-has-already-served-the-con.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-cryptographically-valid-forget-token-that-arrives-after-its-delegated-read-replica-has-already-served-the-con.warrant.json
# Markdown SHA-256:   813ca8d5cbf99017e0efdd71acc1fb1a5147bc6b93e030a28cf21317f3fe610e
# Code AST SHA-256:   b4974a8eff92d81f2c931247e7a96f80b4b9bac1905800e7b244bf78fada4537
# Verified Classes:   ErasureCertificationError, ForgetToken, LedgerEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ErasureCertificationError(RuntimeError):
    """Raised when an instance is asked to certify erasure it cannot causally justify."""
    pass


@dataclass(frozen=True)
class ForgetToken:
    object_hash: str
    issuer: str
    signature_valid: bool
    causal_ref_seq: Optional[int]   # seq of the ack_read this token intends to dominate
    wall_clock: float


@dataclass(frozen=True)
class LedgerEntry:
    kind: str          # "ack_read" | "dispatch" | "terminate"
    object_hash: str
    seq: int
    dispatch_id: Optional[str] = None


def certify_erasure(token: ForgetToken, ledger: list[LedgerEntry]) -> str:
    if not token.signature_valid:
        raise ErasureCertificationError(
            f"token for {token.object_hash} failed signature verification"
        )

    acks = [e for e in ledger
            if e.kind == "ack_read" and e.object_hash == token.object_hash]
    if not acks:
        # nothing was ever served; erasure is trivially certifiable
        return "certified_no_prior_read"

    latest_ack = max(a.seq for a in acks)

    # The boundary: signature validity is NOT causal dominance.
    if token.causal_ref_seq is None:
        raise ErasureCertificationError(
            f"token for {token.object_hash} carries no causal_ref; "
            f"cannot prove dominance over ack_read seq={latest_ack}"
        )
    if token.causal_ref_seq < latest_ack:
        raise ErasureCertificationError(
            f"token seq={token.causal_ref_seq} is causally prior to "
            f"served read seq={latest_ack}; refusing to certify erasure"
        )

    # Live-dispatch check: a downstream agent may still hold the object in context.
    live = {}
    for e in ledger:
        if e.object_hash != token.object_hash or e.dispatch_id is None:
            continue
        if e.kind == "dispatch":
            live[e.dispatch_id] = True
        elif e.kind == "terminate":
            live[e.dispatch_id] = False
    still_running = [d for d, running in live.items() if running]
    if still_running:
        raise ErasureCertificationError(
            f"object {token.object_hash} still held by live dispatches "
            f"{still_running}; withhold certificate, emit pending_revocation"
        )

    return "certified"
