# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-whose-receipt-chain-is-valid-but-whose-sla-clock-was-started-by-the-delegator.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-whose-receipt-chain-is-valid-but-whose-sla-clock-was-started-by-the-delegator.warrant.json
# Markdown SHA-256:   1586768beec332575ddcb26548aacbf26f0c0bb95083dc49baf0cda23c56f610
# Code AST SHA-256:   dcf87c644365dcff387aa8f63e6b104d75b2ce94a0b20ce5863496e3d5a6b32f
# Verified Classes:   BudgetInflationError, Receipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BudgetInflationError(RuntimeError):
    """Raised when a child warrant's SLA budget exceeds what the parent had remaining.

    The receipt chain may be cryptographically valid; this error means it is
    temporally forged (typically by a delegator computing the child deadline
    from a stale cached budget rather than from the parent deadline at sign time).
    """


@dataclass(frozen=True)
class Receipt:
    hop_id: str
    issued_at_ms: int
    deadline_ms: int
    parent_hash: str
    signature: str  # assumed pre-verified upstream

    def digest(self) -> str:
        body = f"{self.hop_id}|{self.issued_at_ms}|{self.deadline_ms}|{self.parent_hash}"
        return hashlib.sha256(body.encode()).hexdigest()


def assert_temporal_conservation(parent: Receipt, child: Receipt,
                                 min_viable_ms: int) -> None:
    """Enforce budget conservation across one delegation hop.

    Call this AFTER signature verification and BEFORE executing the child warrant.
    Signature validity is necessary but not sufficient; this is the sufficiency check.
    """
    if child.issued_at_ms < parent.issued_at_ms:
        raise BudgetInflationError(
            f"causality inversion at hop {child.hop_id}: "
            f"child issued {child.issued_at_ms} < parent {parent.issued_at_ms}"
        )

    if child.deadline_ms > parent.deadline_ms:
        raise BudgetInflationError(
            f"absolute deadline exceeded at hop {child.hop_id}: "
            f"child deadline {child.deadline_ms} > parent deadline {parent.deadline_ms} "
            f"(overrun {child.deadline_ms - parent.deadline_ms}ms)"
        )

    parent_remaining = parent.deadline_ms - parent.issued_at_ms
    child_budget = child.deadline_ms - child.issued_at_ms
    if child_budget > parent_remaining:
        raise BudgetInflationError(
            f"budget inflation at hop {child.hop_id}: "
            f"child granted {child_budget}ms but parent had only {parent_remaining}ms "
            f"at issue (inflation {child_budget - parent_remaining}ms); "
            f"parent_hash={parent.digest()}"
        )

    effective_remaining = child.deadline_ms - child.issued_at_ms
    if effective_remaining < min_viable_ms:
        raise BudgetInflationError(
            f"unsatisfiable warrant at hop {child.hop_id}: "
            f"{effective_remaining}ms remaining < min viable {min_viable_ms}ms; "
            f"refusing before side effects are applied"
        )


def delegate(parent: Receipt, now_ms: int, allocated_slice_ms: int,
             hop_id: str, sign) -> Receipt:
    """Correct delegation: read the clock now, under the lock, then sign immediately."""
    child_deadline = min(parent.deadline_ms, now_ms + allocated_slice_ms)
    child = Receipt(
        hop_id=hop_id,
        issued_at_ms=now_ms,
        deadline_ms=child_deadline,
        parent_hash=parent.digest(),
        signature="",
    )
    child = Receipt(hop_id, now_ms, child_deadline, child.parent_hash,
                    sign(child.digest()))
    assert_temporal_conservation(parent, child, min_viable_ms=50)
    return child
