# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-macaroon-attenuation-chain-has-crossed-a-federation-boundary-it-cannot-legally-discharge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-macaroon-attenuation-chain-has-crossed-a-federation-boundary-it-cannot-legally-discharge.warrant.json
# Markdown SHA-256:   c31539031b4452c17e57bb706cd80f7f245996b8abb4db5aca17367c7d5c19b7
# Code AST SHA-256:   fd90ff3f0ff410cbe96b25d27049a6d367272e052b0b507736d2ed07ed4b2b1e
# Verified Classes:   UndischargeableCaveatError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UndischargeableCaveatError(RuntimeError):
    """Raised when a macaroon caveat cannot be discharged at the terminal verifier.

    Distinct from a signature failure (which is caught earlier) and from a
    transient network failure (which is retryable). This error means the
    caveat is structurally valid but binding-invalid at the terminal verifier,
    and no amount of re-attenuation will fix it.
    """

    def __init__(self, caveat_index: int, author_domain: str, reason: str):
        self.caveat_index = caveat_index
        self.author_domain = author_domain
        self.reason = reason
        super().__init__(
            f"caveat[{caveat_index}] authored by {author_domain} "
            f"cannot be discharged at terminal verifier: {reason}"
        )


def verify_before_side_effect(
    macaroon,
    terminal_verifier,
    federation_allow_list: set[str],
) -> None:
    """Enforce the discharge-asymmetry invariant before committing side effects.

    Walks the caveat chain. For each third-party caveat whose author domain is
    outside the allow-list, performs a dry-run discharge against the terminal
    verifier. Raises UndischargeableCaveatError on binding mismatch.

    Must be called before any non-idempotent action (transfer, write, emit).
    """
    for idx, caveat in enumerate(macaroon.third_party_caveats):
        if caveat.author_domain in federation_allow_list:
            # Reachable discharger; local discharge is sufficient.
            continue

        # Unreachable-by-standing: must discharge at the terminal verifier.
        result = terminal_verifier.dry_run_discharge(macaroon, caveat)

        if result.status == "audience_binding_mismatch":
            # Do NOT re-attenuate. Escalate to root issuer.
            raise UndischargeableCaveatError(
                caveat_index=idx,
                author_domain=caveat.author_domain,
                reason=result.status,
            )
        if result.status != "ok":
            raise UndischargeableCaveatError(
                caveat_index=idx,
                author_domain=caveat.author_domain,
                reason=f"unexpected_discharge_status:{result.status}",
            )

    # All third-party caveats discharged at terminal; side effects are safe.
