# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-audit-witness-whose-policy-epoch-precedes-the-task-space-grant-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-audit-witness-whose-policy-epoch-precedes-the-task-space-grant-epoch.warrant.json
# Markdown SHA-256:   40a1e920a5c7266c4547f05a96f7f466682d1c0a1f96b85aa1b6131b971370aa
# Code AST SHA-256:   0879b7f27b12cbbb6f5dfe82e6a649b2d4f1fbfd4f9cc15ed47f5b215e87b277
# Verified Classes:   EpochInversionError, LineageForkError, Grant, Witness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class EpochInversionError(RuntimeError):
    """Raised when a witness's policy epoch precedes its grant's admission epoch."""


class LineageForkError(RuntimeError):
    """Raised when a witness epoch is not reachable from the grant epoch's lineage."""


@dataclass(frozen=True)
class Grant:
    agent_id: str
    task_space: str
    admission_epoch: int


@dataclass(frozen=True)
class Witness:
    agent_id: str
    task_space: str
    policy_epoch: int
    action_hash: str


def _lineage_contains(grant_epoch: int, witness_epoch: int, lineage: dict[int, set[int]]) -> bool:
    # lineage maps epoch -> set of ancestor epochs (inclusive of self)
    return witness_epoch in lineage.get(grant_epoch, {grant_epoch})


def ingest_witness(w: Witness, g: Grant, lineage: dict[int, set[int]]) -> str:
    if w.agent_id != g.agent_id or w.task_space != g.task_space:
        raise ValueError("witness/grant pair mismatch on agent or task space")

    if w.policy_epoch < g.admission_epoch:
        # The witness describes a policy regime that predates admission.
        # The action may be physically valid but the attestation is epoch-inverted.
        raise EpochInversionError(
            f"witness epoch {w.policy_epoch} precedes grant admission epoch "
            f"{g.admission_epoch} for agent {w.agent_id} in {w.task_space}; "
            f"quarantine action_hash={w.action_hash}"
        )

    if w.policy_epoch > g.admission_epoch and not _lineage_contains(
        g.admission_epoch, w.policy_epoch, lineage
    ):
        # Higher epoch but not on the grant's policy branch: a fork.
        raise LineageForkError(
            f"witness epoch {w.policy_epoch} is not in lineage of grant epoch "
            f"{g.admission_epoch} for agent {w.agent_id}; halt ingestion"
        )

    return "accepted"


def ingest_batch(witnesses: list[Witness], g: Grant, lineage: dict[int, set[int]]) -> dict[str, int]:
    counts = {"accepted": 0, "quarantined": 0, "halted": 0}
    for w in witnesses:
        try:
            ingest_witness(w, g, lineage)
            counts["accepted"] += 1
        except EpochInversionError:
            counts["quarantined"] += 1
        except LineageForkError:
            counts["halted"] += 1
            break
    return counts
