# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sla-bound-delegation-from-accepting-a-cryptographically-valid-but-semantically-stale-completion-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sla-bound-delegation-from-accepting-a-cryptographically-valid-but-semantically-stale-completion-attestation.warrant.json
# Markdown SHA-256:   1d404f461d14eac1bfe401a1415d35675f17654cc33d0f36e75404de113ce43a
# Code AST SHA-256:   047cade3afae64a5e05d130e283bfc2af496c3f3b2e345f1045f112737e71580
# Verified Classes:   StaleAttestationError, Contract, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a signed attestation does not bind to the live contract epoch."""
    pass


@dataclass(frozen=True)
class Contract:
    task_id: str
    epoch: int
    input_hash: str
    deadline: float


@dataclass(frozen=True)
class Attestation:
    task_id: str
    contract_epoch: int
    input_hash: str          # captured at input-fetch time, NOT at signing time
    result_hash: str
    timestamp: float
    signature: bytes


def _verify_signature(att: Attestation, executor_key: bytes) -> bool:
    # Placeholder for real Ed25519 / ECDSA verification over the canonical payload.
    payload = f"{att.task_id}:{att.contract_epoch}:{att.input_hash}:{att.result_hash}:{att.timestamp}"
    return hashlib.sha256(payload.encode() + executor_key).digest() == att.signature


def accept_attestation(
    att: Attestation,
    live: Contract,
    executor_key: bytes,
    max_epoch_retries_exceeded: bool,
) -> None:
    # 1. Cryptographic integrity over the attestation payload.
    if not _verify_signature(att, executor_key):
        raise StaleAttestationError(f"signature invalid for task {att.task_id}")

    # 2. Semantic binding: attestation must commit to the LIVE epoch and input.
    #    This is the invariant that naive verifiers omit.
    if att.contract_epoch != live.epoch:
        raise StaleAttestationError(
            f"epoch mismatch: attestation={att.contract_epoch} live={live.epoch} "
            f"task={att.task_id}"
        )
    if att.input_hash != live.input_hash:
        raise StaleAttestationError(
            f"input hash mismatch: attestation={att.input_hash} live={live.input_hash} "
            f"task={att.task_id}"
        )

    # 3. SLA check is a separate decision, only meaningful once binding holds.
    if att.timestamp > live.deadline:
        raise StaleAttestationError(
            f"SLA breach: ts={att.timestamp} deadline={live.deadline} task={att.task_id}"
        )

    # 4. Livelock guard: bound re-dispatch churn under rapid amendment.
    if max_epoch_retries_exceeded:
        raise StaleAttestationError(
            f"epoch churn exceeded retry budget for task {att.task_id}; coalesce amendments"
        )
