# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-trust-brokering-has-silently-degraded-to-transitive-trust-in-a-cross-org-multi-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-trust-brokering-has-silently-degraded-to-transitive-trust-in-a-cross-org-multi-agent-federation.warrant.json
# Markdown SHA-256:   84ee010501b65bc856d9e54200257d8b1b70c708a81d5a751f2bd7107bfb7828
# Code AST SHA-256:   938f0271e9701875a3aa8de86a62af68a083abb2a278855bdeb9d8f5db74dfa8
# Verified Classes:   TransitiveTrustViolation, BrokerEdge, ComposedPathCache
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Iterable


class TransitiveTrustViolation(RuntimeError):
    """Raised when a composed broker path fails the origin's policy predicate
    at any edge, even though every per-hop check passed locally."""


@dataclass(frozen=True)
class BrokerEdge:
    src_org: str
    dst_org: str
    broker_id: str
    certified_for: frozenset[str]   # data classes this broker may carry
    observed_at: datetime


@dataclass
class ComposedPathCache:
    authorized: dict[tuple[str, str, str], set[tuple[str, ...]]] = field(default_factory=dict)
    observed: dict[tuple[str, str, str], set[tuple[str, ...]]] = field(default_factory=dict)

    def record(self, origin: str, dest: str, data_class: str, chain: tuple[str, ...]) -> bool:
        key = (origin, dest, data_class)
        self.observed.setdefault(key, set()).add(chain)
        return chain in self.authorized.get(key, set())


def evaluate_composed_path(
    origin_org: str,
    destination_org: str,
    data_class: str,
    edges: Iterable[BrokerEdge],
    max_broker_hops: int,
    cache: ComposedPathCache,
    send_ts: datetime,
    revocation_window: timedelta,
    certified_registry: dict[str, frozenset[str]],
) -> None:
    edges = list(edges)
    if not edges:
        raise TransitiveTrustViolation(
            f"empty broker path {origin_org}->{destination_org} for {data_class}"
        )

    chain = tuple(e.broker_id for e in edges)

    # Cheap local checks first.
    if len(edges) > max_broker_hops:
        raise TransitiveTrustViolation(
            f"path {chain} exceeds max_broker_hops={max_broker_hops} for {data_class}"
        )

    for e in edges:
        if data_class not in e.certified_for:
            raise TransitiveTrustViolation(
                f"broker {e.broker_id} not certified for {data_class} on edge "
                f"{e.src_org}->{e.dst_org}"
            )
        # Send-time membership, not receipt-time: revocation races make
        # receipt-time checks unsound.
        if e.broker_id not in certified_registry:
            raise TransitiveTrustViolation(
                f"broker {e.broker_id} absent from certified registry at send time"
            )
        if abs((e.observed_at - send_ts)) <= revocation_window and e.broker_id not in certified_registry:
            raise TransitiveTrustViolation(
                f"broker {e.broker_id} within revocation window of send time"
            )

    # Composed-path authorization: the origin must have explicitly authorized
    # this exact chain, not merely the first hop.
    if not cache.record(origin_org, destination_org, data_class, chain):
        raise TransitiveTrustViolation(
            f"composed path {chain} for {origin_org}->{destination_org} "
            f"({data_class}) was never explicitly authorized by origin; "
            f"transitive-trust degradation suspected"
        )
