# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-sla-bound-delegation-contract-has-silently-degraded-into-an-unbounded-obligation-across-an-organizational-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-sla-bound-delegation-contract-has-silently-degraded-into-an-unbounded-obligation-across-an-organizational-boundary.warrant.json
# Markdown SHA-256:   2bd75ffec9fe720a216efa21480a838990fa1e994f588e8087c5f2c06d58a364
# Code AST SHA-256:   39b47b55e54be17634b7c956b870aba35a8ebedc9b96dc0ced557fb70dae3e67
# Verified Classes:   UnboundedDelegationError, Contract, ExecutionReceipt
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnboundedDelegationError(RuntimeError):
    """Raised when an SLA-bound delegation's obligation cannot be computed
    from the signed contract alone — i.e., the counterparty's execution
    tree is not contract-visible and the SLA field is a claim, not a bound."""


@dataclass
class Contract:
    max_latency_ms: int
    max_cost_units: int
    max_retries: int
    max_fanout: Optional[int]          # None => counterparty will not declare
    latency_clock: Optional[str]       # "principal_boundary" | "counterparty_internal" | None
    scope_enforcement: Optional[str]   # "boundary" | "response_filter" | None
    scope: list = field(default_factory=list)


@dataclass
class ExecutionReceipt:
    sub_call_count: int
    internal_retry_count: int
    counterparty_reported_latency_ms: int
    principal_boundary_latency_ms: int
    scope_check_log_present: bool


def assert_delegation_bounded(contract: Contract, receipt: ExecutionReceipt,
                              latency_tolerance_ms: int = 250) -> None:
    """Verify a completed delegation stayed within the contract's *structural*
    bounds. Raises on any signal that the bound has degraded to a claim."""

    # 1. Tree must be contract-visible: fan-out cap declared and respected.
    if contract.max_fanout is None:
        raise UnboundedDelegationError(
            "counterparty did not declare max_fanout; obligation is not "
            "computable from contract alone"
        )
    if receipt.sub_call_count > contract.max_fanout:
        raise UnboundedDelegationError(
            f"execution tree fanned out to {receipt.sub_call_count} sub-calls, "
            f"exceeding declared max_fanout={contract.max_fanout}"
        )

    # 2. Single clock: principal-boundary latency must be the measured one,
    #    and must not diverge from the counterparty's claim beyond tolerance.
    if contract.latency_clock != "principal_boundary":
        raise UnboundedDelegationError(
            f"latency_clock={contract.latency_clock!r}; SLA field is a "
            "counterparty claim, not a principal-observable bound"
        )
    divergence = abs(receipt.principal_boundary_latency_ms
                     - receipt.counterparty_reported_latency_ms)
    if divergence > latency_tolerance_ms:
        raise UnboundedDelegationError(
            f"boundary-clock divergence {divergence}ms exceeds tolerance "
            f"{latency_tolerance_ms}ms; two clocks, one field"
        )
    if receipt.principal_boundary_latency_ms > contract.max_latency_ms:
        raise UnboundedDelegationError(
            f"principal-boundary latency {receipt.principal_boundary_latency_ms}ms "
            f"exceeds max_latency_ms={contract.max_latency_ms}"
        )

    # 3. Retry budget must be tree-wide, not per-hop.
    if receipt.internal_retry_count > contract.max_retries:
        raise UnboundedDelegationError(
            f"internal retry count {receipt.internal_retry_count} exceeds "
            f"tree-wide max_retries={contract.max_retries}; amplification "
            f"is {contract.max_retries} x {receipt.internal_retry_count}"
        )

    # 4. Scope must be enforced at the boundary, with a check log.
    if contract.scope_enforcement != "boundary":
        raise UnboundedDelegationError(
            f"scope_enforcement={contract.scope_enforcement!r}; scope is "
            "filtered at response, not enforced at boundary — outputs may "
            "derive from unauthorized internal reads"
        )
    if not receipt.scope_check_log_present:
        raise UnboundedDelegationError(
            "scope-check log absent; cannot verify boundary enforcement"
        )
