# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-token-as-invalid-when-the-delegation-chain-s-issuer-set-is-transitively-trusted-bu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-token-as-invalid-when-the-delegation-chain-s-issuer-set-is-transitively-trusted-bu.warrant.json
# Markdown SHA-256:   999b838d298fd3d77f60f831747de71051fc7f8748fbe8addbb30ed8a2a246e2
# Code AST SHA-256:   ba5bd409ff4fa94026341bdd8a7dcb6ec536dde5eb5b74a52e35b88babbd4e57
# Verified Classes:   NonMonotonicAttenuationError, EffectiveScope, Hop
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class NonMonotonicAttenuationError(RuntimeError):
    """Raised when a delegation hop's attenuation witness does not preserve
    the parent's effective scope (positive minus negative) under set difference."""


@dataclass(frozen=True)
class EffectiveScope:
    positive: FrozenSet[str]
    negative: FrozenSet[str] = field(default_factory=frozenset)

    def effective(self) -> FrozenSet[str]:
        return self.positive - self.negative

    def is_subset_of(self, other: "EffectiveScope") -> bool:
        # Subset must hold on the effective set, and every negative constraint
        # live in the parent must be carried (or strengthened) in the child.
        if not self.effective().issubset(other.effective()):
            return False
        return other.negative.issubset(self.negative)


@dataclass(frozen=True)
class Hop:
    issuer: str
    child_scope: EffectiveScope
    witness_signed_by: str


def verify_chain(root: EffectiveScope, root_issuer: str, hops: list[Hop]) -> EffectiveScope:
    current = root
    current_issuer = root_issuer
    for hop in hops:
        if hop.witness_signed_by != current_issuer:
            raise NonMonotonicAttenuationError(
                f"hop issued by {hop.issuer} has witness signed by "
                f"{hop.witness_signed_by}, not parent issuer {current_issuer}"
            )
        if not hop.child_scope.is_subset_of(current):
            missing_negatives = current.negative - hop.child_scope.negative
            raise NonMonotonicAttenuationError(
                f"hop {current_issuer}->{hop.issuer} is non-monotonic: "
                f"child effective={sorted(hop.child_scope.effective())} "
                f"not subset of parent effective={sorted(current.effective())}; "
                f"dropped negative constraints={sorted(missing_negatives)}"
            )
        current = hop.child_scope
        current_issuer = hop.issuer
    return current


# Reproduces the observed failure: root grants write minus write-on-billing,
# hop B->C invents write-on-subresource without carrying the exclusion.
root = EffectiveScope(positive=frozenset({"read", "write"}), negative=frozenset({"write-on-billing"}))
chain = [
    Hop(issuer="B", child_scope=EffectiveScope(positive=frozenset({"read"})), witness_signed_by="A"),
    Hop(
        issuer="C",
        child_scope=EffectiveScope(positive=frozenset({"read", "write-on-subresource"})),
        witness_signed_by="B",
    ),
]
verify_chain(root, "A", chain)  # raises NonMonotonicAttenuationError
