# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-lease-against-a-stale-latency-profile-and-the-sla-clock-starts-before-the-handoff-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-lease-against-a-stale-latency-profile-and-the-sla-clock-starts-before-the-handoff-completes.warrant.json
# Markdown SHA-256:   e2cd329a91e8232cd3ed48842e522addb5071b871278899fa83aa2436d9effe4
# Code AST SHA-256:   c6329cdbe90ef461b1f020f71a4a20098b1b0a6a9fe24983d73b067e0012ea0b
# Verified Classes:   StaleLatencyProfileError, CapabilityOffer, Lease
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleLatencyProfileError(RuntimeError):
    """Raised when an SLA lease is bound against a latency profile that
    cannot describe the interval the SLA will be enforced over."""
    pass


@dataclass
class CapabilityOffer:
    peer_id: str
    schema_hash: str
    p95_ms: float
    sampled_at: float
    window_s: float
    inflight: int | None  # None means the peer did not expose load


@dataclass
class Lease:
    peer_id: str
    schema_hash: str
    deadline_ms: float
    bound_at: float
    clock_origin: str  # "bind" or "execution"


SAFETY_FACTOR = 0.6
MAX_CONCURRENT_CALLERS = 4


def bind_lease(
    offer: CapabilityOffer,
    payload_bytes: int,
    deadline_ms: float,
    clock_origin: str,
    now: float,
) -> Lease:
    # Guard 1: profile must not be older than its own window relative to bind.
    if now - offer.sampled_at > offer.window_s:
        raise StaleLatencyProfileError(
            f"peer {offer.peer_id}: profile age {now - offer.sampled_at:.2f}s "
            f"exceeds sampling window {offer.window_s:.2f}s"
        )

    # Guard 2: if the peer exposes inflight, condition the profile on it.
    # If it does not, we must assume worst-case herding across callers.
    if offer.inflight is not None:
        effective_p95 = offer.p95_ms * (1 + offer.inflight) ** 0.5
    else:
        effective_p95 = offer.p95_ms * MAX_CONCURRENT_CALLERS

    # Guard 3: the handoff payload itself contributes queue depth; account
    # for serialization+transport as a fraction of the deadline.
    serialization_ms = payload_bytes / 1_000_000 * 50.0  # ~50ms/MB
    projected_ms = effective_p95 + serialization_ms

    if projected_ms > deadline_ms * SAFETY_FACTOR:
        raise StaleLatencyProfileError(
            f"peer {offer.peer_id}: projected {projected_ms:.1f}ms "
            f"(p95={offer.p95_ms:.1f}ms, inflight={offer.inflight}, "
            f"payload={payload_bytes}B) exceeds "
            f"{SAFETY_FACTOR:.0%} of deadline {deadline_ms:.1f}ms"
        )

    # Guard 4: SLA clock must not include queueing unless the profile
    # explicitly models queueing (i.e. inflight was exposed).
    if clock_origin == "bind" and offer.inflight is None:
        raise StaleLatencyProfileError(
            f"peer {offer.peer_id}: cannot arm SLA at bind without inflight "
            f"visibility; queue time is unbounded and unmeasured"
        )

    return Lease(
        peer_id=offer.peer_id,
        schema_hash=offer.schema_hash,
        deadline_ms=deadline_ms,
        bound_at=now,
        clock_origin=clock_origin,
    )


def verify_lease_at_execution(lease: Lease, execution_schema_hash: str) -> None:
    if execution_schema_hash != lease.schema_hash:
        raise StaleLatencyProfileError(
            f"peer {lease.peer_id}: schema_hash drift at execution "
            f"({lease.schema_hash} -> {execution_schema_hash}); "
            f"lease void, re-negotiate rather than fail on timeout"
        )
