# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-task-whose-sla-contract-was-negotiated-against-a-stale-capability-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-task-whose-sla-contract-was-negotiated-against-a-stale-capability-manifest.warrant.json
# Markdown SHA-256:   eac957392e1b5f5266ec3e7993095054b54e148d7bd28decc30020fc1f659a28
# Code AST SHA-256:   4dc725c01819d19b6dbcaa843e168f6d881de0d7e1339dfeb52511fd3e5edff0
# Verified Classes:   StaleContractError, Manifest, SLAContract
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class StaleContractError(RuntimeError):
    """Raised when an SLA contract was priced against a manifest no longer in force."""
    pass


@dataclass
class Manifest:
    pdf_extract_version: str
    ocr_quota_remaining: int
    p95_latency_s_per_page: float
    description: str = ""

    def semantic_digest(self) -> str:
        # Digest only over fields that enter SLA arithmetic.
        payload = {
            "pdf": self.pdf_extract_version,
            "quota": self.ocr_quota_remaining,
            "lat": round(self.p95_latency_s_per_page, 3),
        }
        return hashlib.sha256(
            json.dumps(payload, sort_keys=True).encode()
        ).hexdigest()


@dataclass
class SLAContract:
    task_id: str
    pages: int
    deadline_s: float
    quality_floor: float
    bid_manifest_digest: str
    hard_terms: list = field(default_factory=lambda: ["deadline", "quality", "quota"])


def bind_and_validate(
    contract: SLAContract,
    current_manifest: Manifest,
    safety_factor: float = 1.15,
) -> None:
    live_digest = current_manifest.semantic_digest()

    # Immaterial drift (description only) does not change semantic_digest,
    # so a digest match here already excludes cosmetic skew.
    if live_digest == contract.bid_manifest_digest:
        return  # invariant holds; execute

    # Digest diverged. Determine materiality against hard terms.
    infeasible = []

    expected_completion = (
        contract.pages * current_manifest.p95_latency_s_per_page
    )
    if expected_completion > contract.deadline_s * safety_factor:
        infeasible.append(
            f"deadline: expected {expected_completion:.1f}s "
            f"> {contract.deadline_s * safety_factor:.1f}s budget"
        )

    if current_manifest.ocr_quota_remaining < contract.pages:
        infeasible.append(
            f"quota: need {contract.pages}, "
            f"have {current_manifest.ocr_quota_remaining}"
        )

    if infeasible:
        raise StaleContractError(
            f"task {contract.task_id}: manifest skew is material; "
            f"bid_digest={contract.bid_manifest_digest[:8]} "
            f"live_digest={live_digest[:8]} "
            f"infeasible={infeasible}; "
            f"action=reject_and_request_renegotiation"
        )

    # Material but non-fatal drift: execute, emit advisory.
    # (Caller is responsible for forwarding the advisory to the coordinator.)
    return


# --- observed incident, reconstructed ---
bid_manifest = Manifest("v3", 200, 1.4)
contract = SLAContract(
    task_id="doc-analyze-17",
    pages=60,
    deadline_s=90.0,
    quality_floor=0.92,
    bid_manifest_digest=bid_manifest.semantic_digest(),
)

# Manifest mutated between bid and bind: rollout + quota consumption.
live_manifest = Manifest("v4", 8, 2.6)

try:
    bind_and_validate(contract, live_manifest)
    print("executing")  # would have produced the 141s silent breach
except StaleContractError as e:
    print(f"REJECTED: {e}")  # correct behavior
