# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-brokered-cross-org-delegation-warrant-has-silently-degraded-to-a-transitive-trust-assumption.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-brokered-cross-org-delegation-warrant-has-silently-degraded-to-a-transitive-trust-assumption.warrant.json
# Markdown SHA-256:   877a1a9e309b60ffe19f1911a62cb9f33021ac0c50cf6a60bd0abc2f7cbe7ac4
# Code AST SHA-256:   b78550c0494197ac3268219522f0e81677349c81b114d94b5ee4c151ee8848e9
# Verified Classes:   WarrantProvenanceError, Attenuation, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class WarrantProvenanceError(RuntimeError):
    """Raised when a brokered warrant drops constraints without a matching
    signed attenuation record. This is distinct from a policy violation:
    the request may be in-bounds, but the broker's authority to narrow
    the originator's grant is unproven."""


@dataclass
class Attenuation:
    by: str
    dropped: list[str]
    reason: str  # "intentional_narrowing" | "unevaluable_predicate"


@dataclass
class Warrant:
    issuer: str
    constraints: dict[str, object]
    attenuations: list[Attenuation] = field(default_factory=list)
    signature_valid: bool = True


def verify_brokered_warrant(origin: Warrant, brokered: Warrant) -> None:
    if not brokered.signature_valid:
        raise WarrantProvenanceError(
            f"brokered warrant from {brokered.issuer} has invalid signature"
        )

    origin_keys = set(origin.constraints.keys())
    brokered_keys = set(brokered.constraints.keys())

    # Monotonicity: brokered constraints must be a subset of origin's.
    extra = brokered_keys - origin_keys
    if extra:
        raise WarrantProvenanceError(
            f"brokered warrant widens constraints: {sorted(extra)} not in origin"
        )

    dropped = origin_keys - brokered_keys
    if not dropped:
        return  # no attenuation; nothing to provenance-check

    # Provenance: every dropped constraint needs a signed attenuation record
    # from the broker itself, with a recognized reason.
    recorded: dict[str, Attenuation] = {}
    for att in brokered.attenuations:
        if att.by != brokered.issuer:
            continue
        if att.reason not in ("intentional_narrowing", "unevaluable_predicate"):
            continue
        for c in att.dropped:
            recorded[c] = att

    unrecorded = dropped - recorded.keys()
    if unrecorded:
        raise WarrantProvenanceError(
            f"broker {brokered.issuer} dropped constraints {sorted(unrecorded)} "
            f"without a signed attenuation record; subset-check alone cannot "
            f"distinguish intentional narrowing from silent predicate failure"
        )
