# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-task-under-an-sla-it-cannot-satisfy-because-the-sla-clock-and-the-execution-clock-are-not-the-same-c.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-task-under-an-sla-it-cannot-satisfy-because-the-sla-clock-and-the-execution-clock-are-not-the-same-c.warrant.json
# Markdown SHA-256:   043453188c571ac9137ace6191a6d1521a1d286b120b2aeab7d60ab814d366f7
# Code AST SHA-256:   e331e9c534cd1ebf56a6c48017d4b3bbc3f26cd5457cd6c3060f6a203d560752
# Verified Classes:   UnsatisfiableDelegationError, ContractClockMismatchError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnsatisfiableDelegationError(RuntimeError):
    """Raised when a delegate is asked to accept a contract whose deadline
    cannot be met on the delegate's own monotone clock, accounting for
    transit already consumed and the delegate's declared non-execution reserve."""
    pass


class ContractClockMismatchError(UnsatisfiableDelegationError):
    """Raised when the envelope's send-time reference is absent or transit
    exceeds the declared max_transit, so the remainder cannot be reconciled."""
    pass


def admit_delegation(
    envelope: dict,
    *,
    t_recv_monotone: float,
    estimate_p90: float,
    reserve: float,
    max_transit: float,
) -> dict:
    """
    Decide accept/reject for an SLA-bound delegated task.

    envelope must carry:
      deadline_monotone_ref : principal's monotone send reference (trusted)
      send_monotone         : principal's monotone send timestamp
      deadline_offset       : deadline - send, in seconds (contract TTL)
    """
    if "send_monotone" not in envelope or "deadline_offset" not in envelope:
        raise ContractClockMismatchError(
            "envelope carries no monotone send reference; "
            "deadline is set in an unwitnessed clock domain — refusing to accept"
        )

    transit = t_recv_monotone - envelope["send_monotone"]
    if transit < 0:
        raise ContractClockMismatchError(
            f"negative transit ({transit:.3f}s): send reference is ahead of "
            f"local monotone clock; clock domains are not comparable"
        )
    if transit > max_transit:
        raise ContractClockMismatchError(
            f"transit {transit:.3f}s exceeds max_transit {max_transit:.3f}s; "
            f"contract clock already consumed in flight — reject before planning"
        )

    # Remainder is measured on the delegate's own monotone clock, from the
    # principal's send reference, not from a raw local now() subtraction.
    remainder = envelope["deadline_offset"] - transit
    slack = remainder - reserve - estimate_p90

    if slack >= 0:
        return {
            "decision": "accept",
            "accepted_at_monotone": t_recv_monotone,
            "remainder_at_accept": remainder,
            "estimate_p90": estimate_p90,
            "reserve": reserve,
            "slack": slack,
        }

    # Distinguish terminal from retryable. A contract is terminal-unreachable
    # if even a zero-cost delegate could not finish: remainder < reserve.
    if remainder < reserve:
        raise UnsatisfiableDelegationError(
            f"contract unreachable: remainder {remainder:.3f}s < reserve "
            f"{reserve:.3f}s even before execution; deadline was consumed "
            f"before acceptance — principal must renegotiate a fresh deadline"
        )

    return {
        "decision": "reject_retryable",
        "reason": "insufficient_budget",
        "remainder_at_accept": remainder,
        "estimate_p90": estimate_p90,
        "reserve": reserve,
        "slack": slack,
        "unreachable_by": t_recv_monotone + remainder,
    }
