# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sla-drift-when-a-contract-negotiating-agent-decomposes-a-task-across-a-noisy-capability-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sla-drift-when-a-contract-negotiating-agent-decomposes-a-task-across-a-noisy-capability-channel.warrant.json
# Markdown SHA-256:   e5dd6a82865c353802c1feac4d0cb976623f6589a4ce55f64ee26b2a9629c8c1
# Code AST SHA-256:   f1c1e22c76f2df912858e0109b9042dd9051aa3bd27c7d671b4a467fc45d6d51
# Verified Classes:   SLAContractViolation, AdvertisedContract, RealizedContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class SLAContractViolation(RuntimeError):
    """Raised when a subtask is dispatched under an SLA that was never realized."""


@dataclass
class AdvertisedContract:
    contractor_id: str
    schema_version: str
    p95_latency_ms: int
    determinism: str          # e.g. "seeded" -- conditional, treat as prior
    retry_semantics: str      # e.g. "idempotent" -- unverified claim


@dataclass
class RealizedContract:
    contractor_id: str
    subtask_class: str
    param_fingerprint: str
    realized_p95_ms: int
    idempotent_verified: bool
    probe_concurrency: int
    structural_cluster: str = field(default="")


def _param_fingerprint(params: dict) -> str:
    canon = "|".join(f"{k}={params[k]!r}" for k in sorted(params))
    return hashlib.sha256(canon.encode()).hexdigest()[:16]


def calibrate(
    advertised: AdvertisedContract,
    subtask_class: str,
    params: dict,
    dispatch_fn,
    probe_payload: dict,
    probe_concurrency: int,
) -> RealizedContract:
    """Probe the contractor through the *production* channel, twice, to
    convert the advertised contract into a realized one. The second dispatch
    exists solely to test the idempotency claim; an empty diff is the only
    evidence that retries are safe."""
    fp = _param_fingerprint(params)

    t0 = time.monotonic()
    out_a = dispatch_fn(advertised.contractor_id, subtask_class, params, probe_payload)
    lat_a = int((time.monotonic() - t0) * 1000)

    out_b = dispatch_fn(advertised.contractor_id, subtask_class, params, probe_payload)
    idempotent = out_a == out_b

    if lat_a > advertised.p95_latency_ms * 3:
        # The advertised SLA is a population statistic; a single probe at
        # production concurrency blowing past 3x means the prior is unusable.
        raise SLAContractViolation(
            f"contractor={advertised.contractor_id} class={subtask_class} "
            f"probe_latency={lat_a}ms vs advertised_p95={advertised.p95_latency_ms}ms "
            f"at concurrency={probe_concurrency}; advertised contract rejected as prior"
        )

    cluster = hashlib.sha256(repr(sorted(probe_payload)).encode()).hexdigest()[:8]
    return RealizedContract(
        contractor_id=advertised.contractor_id,
        subtask_class=subtask_class,
        param_fingerprint=fp,
        realized_p95_ms=lat_a,
        idempotent_verified=idempotent,
        probe_concurrency=probe_concurrency,
        structural_cluster=cluster,
    )


def decompose(
    advertised: AdvertisedContract,
    realized: RealizedContract,
    params: dict,
    payloads: list,
    safety_factor: float = 1.5,
) -> list:
    """Dispatch subtasks only under the realized contract. Asserted mode is
    forbidden: every subtask's SLA is derived from realized telemetry, and
    retries are enabled only if idempotency was verified by probe diff."""
    if _param_fingerprint(params) != realized.param_fingerprint:
        raise SLAContractViolation(
            f"param drift: dispatch fingerprint {_param_fingerprint(params)} "
            f"!= calibrated {realized.param_fingerprint}; re-probe required"
        )

    per_subtask_sla = max(advertised.p95_latency_ms, int(realized.realized_p95_ms * safety_factor))
    max_concurrency = max(1, advertised.p95_latency_ms * realized.probe_concurrency // per_subtask_sla)

    plan = []
    for i, payload in enumerate(payloads):
        cluster = hashlib.sha256(repr(sorted(payload)).encode()).hexdigest()[:8]
        if cluster != realized.structural_cluster:
            raise SLAContractViolation(
                f"subtask {i} payload cluster {cluster} outside calibrated "
                f"cluster {realized.structural_cluster}; OOD payload, re-probe before dispatch"
            )
        plan.append({
            "index": i,
            "sla_ms": per_subtask_sla,
            "retry": "idempotent" if realized.idempotent_verified else "no-retry",
            "concurrency_cap": max_concurrency,
        })
    return plan
