# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-that-its-own-policy-engine-has-already-approved.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-that-its-own-policy-engine-has-already-approved.warrant.json
# Markdown SHA-256:   cb9f345016f9e99e885c61e5ab49f3b9815c95f0419757e1a06bbdbab41cfd73
# Code AST SHA-256:   6c5afed03eea02a3652342223bd957c36511d6a6f3a1f0d3a5d127582e2b0c62
# Verified Classes:   SplitBrainAuthorizationError, ConstraintDelta, PolicyLineage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SplitBrainAuthorizationError(RuntimeError):
    """Raised when a warrant's policy lineage and the enforced lineage are
    jointly incoherent: the grant was approved against a policy state that
    the enforcement path no longer (or never) occupied."""
    pass


@dataclass(frozen=True)
class ConstraintDelta:
    dimension: str
    direction: str  # "tighten" | "loosen" | "unchanged"


@dataclass
class PolicyLineage:
    version: int
    digest: str
    # per-dimension constraint records; higher = stricter for "tighten" dims
    constraints: dict = field(default_factory=dict)

    @staticmethod
    def from_version(version: int, constraints: dict) -> "PolicyLineage":
        blob = repr(sorted(constraints.items())).encode()
        return PolicyLineage(version, hashlib.sha256(blob).hexdigest(), dict(constraints))


def _is_ancestor(older: PolicyLineage, newer: PolicyLineage) -> bool:
    # Total order assumption: version integers are monotone within a branch.
    return older.version < newer.version


def _tightening_deltas(warrant: PolicyLineage, enforced: PolicyLineage) -> list[ConstraintDelta]:
    out = []
    for dim, enforced_val in enforced.constraints.items():
        warrant_val = warrant.constraints.get(dim)
        if warrant_val is None:
            out.append(ConstraintDelta(dim, "tighten"))  # newly constrained
        elif enforced_val != warrant_val:
            # Convention: larger value = tighter for limit dims, set membership
            # for categorical dims; caller supplies the comparator semantics.
            direction = "tighten" if enforced_val < warrant_val else "loosen"
            out.append(ConstraintDelta(dim, direction))
    return out


def admit_federated_call(
    warrant_lineage: PolicyLineage,
    enforced_lineage: PolicyLineage,
    exercised_dimensions: set[str],
) -> None:
    if warrant_lineage.digest == enforced_lineage.digest:
        return  # exact match, always sound

    if not _is_ancestor(warrant_lineage, enforced_lineage):
        raise SplitBrainAuthorizationError(
            f"lineage divergence: warrant v{warrant_lineage.version} and "
            f"enforced v{enforced_lineage.version} share no ancestry; broker "
            f"attestation is against a branch the enforcement path abandoned"
        )

    deltas = _tightening_deltas(warrant_lineage, enforced_lineage)
    exercised_tightenings = [
        d for d in deltas
        if d.direction == "tighten" and d.dimension in exercised_dimensions
    ]
    if exercised_tightenings:
        raise SplitBrainAuthorizationError(
            f"warrant v{warrant_lineage.version} admits excess privilege under "
            f"enforced v{enforced_lineage.version}: tightening on exercised "
            f"dimensions {[d.dimension for d in exercised_tightenings]}; "
            f"re-negotiate through broker against enforced lineage"
        )
    # tightening exists but is not exercised, or delta is loosening-only: admit.
    return


def handle_inbound_federated_call(warrant, enforced, request) -> None:
    try:
        admit_federated_call(warrant.lineage, enforced.lineage, request.dimensions)
    except SplitBrainAuthorizationError as e:
        # Surface the delta to the broker so it can re-mint against `enforced`.
        warrant.broker.renegotiate(capability=request.capability,
                                   target_lineage=enforced.lineage,
                                   reason=str(e))
        raise
    request.execute()
