# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-sla-window-closes-before-its-own-projected-verification-replay-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-sla-window-closes-before-its-own-projected-verification-replay-horizon.warrant.json
# Markdown SHA-256:   2450b19a4c560e3e3c88f12fa802d084ee698c700d570517eabdd86f2a116fb3
# Code AST SHA-256:   5493490a0ae310ad6f44e53834511400bfa40c427c30dd17e907742ded380a9c
# Verified Classes:   ReplayHorizonViolation, Contract, HorizonModel
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ReplayHorizonViolation(RuntimeError):
    """Raised when a delegatee would accept an SLA it cannot settle on the replay clock."""


@dataclass
class Contract:
    deadline: float          # absolute wall-clock seconds
    tools: tuple[str, ...]   # tool composition the task will invoke


@dataclass
class HorizonModel:
    exec_p95: float                       # per task class
    replay_p95_by_tool: dict[str, float]  # per tool; worst tool dominates the chain

    def replay_p95(self, tools: tuple[str, ...]) -> float:
        # replay cost is set by the least-deterministic tool in the chain,
        # not the sum: pinning one unstable output gates the whole replay.
        return max((self.replay_p95_by_tool.get(t, 0.0) for t in tools), default=0.0)


def negotiate(contract: Contract, model: HorizonModel, margin: float = 5.0) -> float:
    now = time.time()
    budget = contract.deadline - now
    required = model.exec_p95 + model.replay_p95(contract.tools) + margin

    if budget < required:
        raise ReplayHorizonViolation(
            f"cannot settle: budget={budget:.1f}s < "
            f"exec_p95={model.exec_p95:.1f}s + "
            f"replay_p95={model.replay_p95(contract.tools):.1f}s + "
            f"margin={margin:.1f}s; counter-offer deadline=now+{required:.1f}s"
        )
    return contract.deadline
