# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-delegated-warrant-attenuation-drift-across-federated-trust-brokers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-delegated-warrant-attenuation-drift-across-federated-trust-brokers.warrant.json
# Markdown SHA-256:   d964c0e3c8a1357843c706fee9086e150975c1b32c4c9980f1c75e5c604cc7e7
# Code AST SHA-256:   1c468ba20589caacb09eae2c25e276b88b7aaed9b5730d9906769c6b14ef4387
# Verified Classes:   AttenuationDriftError, Warrant, Broker
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class AttenuationDriftError(RuntimeError):
    """Raised when a brokered child warrant is not a subset of its parent
    under the parent's pinned policy generation."""


@dataclass(frozen=True)
class Warrant:
    scope: frozenset
    obligations: frozenset
    expires_at: float
    gen: int
    signed_gen: bool = True


@dataclass
class Broker:
    active_gen: int
    # generation -> rule text; only generations we can still reconstruct
    policy_history: dict = field(default_factory=dict)
    clock_skew_margin: float = 5.0

    def _rules_at(self, gen: int) -> dict:
        if gen not in self.policy_history:
            raise AttenuationDriftError(
                f"cannot reconstruct policy generation {gen}; refusing to attenuate"
            )
        return self.policy_history[gen]

    def attenuate(self, parent: Warrant, requested_scope: frozenset,
                  requested_obligations: frozenset, now: float) -> Warrant:
        if not parent.signed_gen:
            raise AttenuationDriftError("parent warrant has unsigned generation claim")

        # Pin: evaluate the child against the PARENT's generation, not active.
        rules = self._rules_at(parent.gen)

        # 1. Scope must be a subset of the parent's scope under parent-gen rules.
        if not requested_scope <= parent.scope:
            raise AttenuationDriftError(
                f"scope {requested_scope} exceeds parent {parent.scope} at gen {parent.gen}"
            )

        # 2. Obligations: cannot drop a non-waivable obligation from parent gen.
        non_waivable = rules.get("non_waivable_obligations", frozenset())
        dropped = (parent.obligations & non_waivable) - requested_obligations
        if dropped:
            raise AttenuationDriftError(
                f"child drops non-waivable obligations {dropped} at gen {parent.gen}"
            )

        # 3. Expiry ceiling: child must not outlive parent minus skew margin.
        ceiling = parent.expires_at - self.clock_skew_margin
        child_expiry = min(now + 3600.0, ceiling)
        if child_expiry > ceiling:
            raise AttenuationDriftError(
                f"child expiry {child_expiry} exceeds parent ceiling {ceiling}"
            )

        # 4. Generation drift: if active != parent.gen, the diff must be disjoint
        #    from what the child touches, or we refuse and force re-brokering.
        if self.active_gen != parent.gen:
            drift = rules.get("drift_dimensions", frozenset())
            touched = requested_scope | requested_obligations
            if drift & touched:
                raise AttenuationDriftError(
                    f"policy drift {drift & touched} intersects child request; "
                    f"re-broker parent at gen {self.active_gen}"
                )

        return Warrant(
            scope=requested_scope,
            obligations=requested_obligations,
            expires_at=child_expiry,
            gen=parent.gen,
        )


def demo_drift_refusal():
    broker = Broker(
        active_gen=2,
        policy_history={
            1: {"non_waivable_obligations": frozenset({"redact_pii"}),
                "drift_dimensions": frozenset()},
            2: {"non_waivable_obligations": frozenset(),
                "drift_dimensions": frozenset({"documents.export", "redact_pii"})},
        },
    )
    parent = Warrant(
        scope=frozenset({"documents.read", "documents.export"}),
        obligations=frozenset({"redact_pii"}),
        expires_at=time.time() + 3600.0,
        gen=1,
    )
    # This is the 14:02:47 request: export without the redact_pii obligation.
    broker.attenuate(
        parent,
        requested_scope=frozenset({"documents.read", "documents.export"}),
        requested_obligations=frozenset(),
        now=time.time(),
    )


if __name__ == "__main__":
    try:
        demo_drift_refusal()
    except AttenuationDriftError as e:
        print(f"REFUSED (correct): {e}")
