# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-brokered-capability-grant-when-the-downstream-peer-re-derives-policy-from-a-stale-trust-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-brokered-capability-grant-when-the-downstream-peer-re-derives-policy-from-a-stale-trust-epoch.warrant.json
# Markdown SHA-256:   97e45186636e675b4abd63a7e9198b4cc09533afd1ed50dd120505a901b96cf7
# Code AST SHA-256:   e385201e363df9f7021b502bba00f686cc44597ceb3da1d16b6b1c488cc8b2ac
# Verified Classes:   EpochJoinViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EpochJoinViolation(RuntimeError):
    """Raised when a data-boundary decision is attempted without three-way
    epoch agreement (grant, peer policy, data classification)."""


def decide_boundary(
    grant_epoch: int,
    policy_epoch: int,
    classification_epoch: int | None,
    broker_current_epoch: int,
) -> str:
    """Return 'allow' or 'deny' only when all three epochs are provably current.

    The two-way short-circuit (grant == policy) is explicitly rejected as
    insufficient; a matching pair with unknown classification epoch is the
    dangerous quadrant and must fail closed.
    """
    if classification_epoch is None:
        # Cannot prove data-classification currency. Never short-circuit here.
        raise EpochJoinViolation(
            f"classification epoch unknown; grant={grant_epoch} "
            f"policy={policy_epoch} broker={broker_current_epoch}"
        )

    if grant_epoch < broker_current_epoch:
        # Grant is stale; re-request rather than decide on a lagging authority.
        raise EpochJoinViolation(
            f"stale grant epoch {grant_epoch} < broker {broker_current_epoch}"
        )

    if grant_epoch == policy_epoch and policy_epoch != classification_epoch:
        # THE TRAP: grant/policy agree, classification disagrees. The peer's
        # cache-hit predicate would have suppressed the refresh. Fail closed.
        raise EpochJoinViolation(
            f"two-way epoch match ({grant_epoch}) but classification "
            f"epoch {classification_epoch} diverges; refusing boundary decision"
        )

    if not (grant_epoch == policy_epoch == classification_epoch):
        raise EpochJoinViolation(
            f"three-way epoch disagreement: grant={grant_epoch} "
            f"policy={policy_epoch} classification={classification_epoch}"
        )

    return "allow"
