# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-sla-bound-delegation-has-silently-widened-its-own-execution-budget-through-receipt-chain-compounding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-sla-bound-delegation-has-silently-widened-its-own-execution-budget-through-receipt-chain-compounding.warrant.json
# Markdown SHA-256:   44872a0245b1d8c6949965a94f1619ef463a128c7a861d0f6d65f2b5878eecbe
# Code AST SHA-256:   abaa5e194d7b406f5acba28f7285aa02e084a2d3ad37a003ec7ca410cf13c054
# Verified Classes:   BudgetWideningError, Receipt
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class BudgetWideningError(RuntimeError):
    """Raised when a receipt in a delegation chain declares a remaining budget
    larger than the root-anchored remaining budget at its timestamp.

    This is the structural signal that a hop re-instantiated an SLA template
    with fresh absolutes instead of inheriting the root contract's remaining
    delta. It is a chain-level violation: every individual receipt may be
    internally consistent, yet the chain has inflated the root budget.
    """


@dataclass(frozen=True)
class Receipt:
    hop_id: str
    parent_receipt_hash: str | None
    root_contract_hash: str
    root_issued_at: float          # epoch seconds, set once at the root
    timestamp: float               # epoch seconds at receipt emission
    calls_used: int                # calls consumed by THIS hop only
    declared_deadline_remaining: float  # hop's self-reported remaining time
    declared_budget_remaining: int      # hop's self-reported remaining calls


def verify_chain(
    root: Receipt,
    chain: Iterable[Receipt],
    root_deadline_s: float,
    root_budget_calls: int,
    clock_skew_tolerance_s: float = 0.050,
) -> None:
    """Replay a receipt chain against the root contract.

    Raises BudgetWideningError on the first receipt whose declared remaining
    budget exceeds the root-anchored remaining budget. Also raises on
    structural breaks (missing parent link, root hash mismatch) because those
    make the replay unsound rather than merely failing.
    """
    seen: dict[str, Receipt] = {root.hop_id: root}
    cumulative_calls = root.calls_used

    for r in chain:
        if r.root_contract_hash != root.root_contract_hash:
            raise BudgetWideningError(
                f"hop {r.hop_id}: root_contract_hash mismatch "
                f"({r.root_contract_hash!r} != {root.root_contract_hash!r}); "
                f"receipt cannot be replayed against this root"
            )
        if r.parent_receipt_hash is None or r.parent_receipt_hash not in seen:
            raise BudgetWideningError(
                f"hop {r.hop_id}: parent_receipt_hash "
                f"{r.parent_receipt_hash!r} not present in chain; "
                f"delegation DAG is disconnected"
            )

        root_elapsed = r.timestamp - root.root_issued_at
        root_remaining_time = root_deadline_s - root_elapsed
        cumulative_calls += r.calls_used
        root_remaining_calls = root_budget_calls - cumulative_calls

        # Core invariant: a hop may not claim more remaining budget than the
        # root actually has left at this hop's timestamp.
        if r.declared_deadline_remaining > root_remaining_time + clock_skew_tolerance_s:
            raise BudgetWideningError(
                f"hop {r.hop_id}: declared_deadline_remaining="
                f"{r.declared_deadline_remaining:.3f}s exceeds root-anchored "
                f"remaining={root_remaining_time:.3f}s at t={r.timestamp:.3f}; "
                f"hop re-derived its SLA from local start time"
            )
        if r.declared_budget_remaining > root_remaining_calls:
            raise BudgetWideningError(
                f"hop {r.hop_id}: declared_budget_remaining="
                f"{r.declared_budget_remaining} exceeds root-anchored "
                f"remaining={root_remaining_calls} after cumulative "
                f"calls_used={cumulative_calls}; hop re-instantiated the "
                f"budget template instead of inheriting the remaining delta"
            )

        seen[r.hop_id] = r


def accept_subcontract(
    parent: Receipt,
    root: Receipt,
    root_deadline_s: float,
    root_budget_calls: int,
    requested_deadline_s: float,
    requested_calls: int,
    handoff_latency_estimate_s: float = 0.100,
) -> None:
    """Child-side pre-acceptance check. Must be run BEFORE the child begins
    work, so that a budget-widening delegation is refused rather than
    discovered at verification time.
    """
    root_elapsed = parent.timestamp - root.root_issued_at
    root_remaining_time = root_deadline_s - root_elapsed - handoff_latency_estimate_s
    root_remaining_calls = root_budget_calls - parent.calls_used

    if requested_deadline_s > root_remaining_time:
        raise BudgetWideningError(
            f"subcontract from {parent.hop_id} requests deadline="
            f"{requested_deadline_s:.3f}s but root-anchored remaining is "
            f"{root_remaining_time:.3f}s; refuse and escalate to root"
        )
    if requested_calls > root_remaining_calls:
        raise BudgetWideningError(
            f"subcontract from {parent.hop_id} requests calls={requested_calls} "
            f"but root-anchored remaining is {root_remaining_calls}; "
            f"refuse and escalate to root"
        )
