# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-tool-call-prefetch-when-the-commit-quorum-is-byzantine-fault-tolerant-but-the-prefetch-payl.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-tool-call-prefetch-when-the-commit-quorum-is-byzantine-fault-tolerant-but-the-prefetch-payl.warrant.json
# Markdown SHA-256:   4fe3b5d67978d2ebb3f0ce1fabc2020ea4e431091280d4a77951a1febfb44b61
# Code AST SHA-256:   e2367ec541bdd9c0fa47c0ad6940b5af622ebda31dcaa5fc95458cb097e95d05
# Verified Classes:   PrefetchCommitDissociationError, Prefetch, CommitCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class PrefetchCommitDissociationError(RuntimeError):
    """Raised when a prefetched tool payload cannot be bound to the commit certificate."""


@dataclass(frozen=True)
class Prefetch:
    payload: bytes
    issued_at_logical: int
    tool_is_content_addressed: bool
    server_declared_etag: Optional[str]  # NOT trusted; a claim, not a hash


@dataclass(frozen=True)
class CommitCertificate:
    decision_id: str
    committed_at_logical: int
    payload_hashes: dict  # decision_id -> sha256 hex; may be empty if unbound


def payload_hash(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def resolve_prefetch_for_commit(
    prefetch: Prefetch,
    cert: CommitCertificate,
    current_logical: int,
    prefetch_issuer_is_byzantine: bool,
) -> bytes:
    # Boundary 1: prefetch depth > 1 commit epoch is never reusable.
    if current_logical - prefetch.issued_at_logical > 1:
        raise PrefetchCommitDissociationError(
            f"prefetch depth exceeds 1 commit epoch "
            f"(issued={prefetch.issued_at_logical}, now={current_logical}); re-execute required"
        )

    # Boundary 2: Byzantine-issued payload without independent corroboration.
    if prefetch_issuer_is_byzantine:
        raise PrefetchCommitDissociationError(
            "payload issued by replica later identified as Byzantine; "
            "no independent corroboration; re-execute required"
        )

    # Boundary 3: certificate must carry the payload hash, or the payload
    # must be content-addressed (hash derived from bytes, not server claim).
    bound_hash = cert.payload_hashes.get(cert.decision_id)
    if bound_hash is not None:
        if payload_hash(prefetch.payload) != bound_hash:
            raise PrefetchCommitDissociationError(
                f"payload hash mismatch for decision {cert.decision_id}: "
                f"local={payload_hash(prefetch.payload)} cert={bound_hash}"
            )
        return prefetch.payload

    if prefetch.tool_is_content_addressed:
        # Content-addressed: hash is recomputed from bytes; safe to reuse
        # provided temporal binding holds (checked at caller via issued_at).
        return prefetch.payload

    # Unbound, non-content-addressed payload: the commit certificate
    # authenticates the decision but not the bytes. Reuse is unsound.
    raise PrefetchCommitDissociationError(
        f"decision {cert.decision_id} committed without payload hash and tool "
        f"is not content-addressed; prefetch payload cannot cross commit boundary"
    )


def consume_committed_tool_result(
    prefetches: list,
    cert: CommitCertificate,
    current_logical: int,
    byzantine_issuers: set,
) -> bytes:
    """Reuse a bound prefetch, else re-execute. Never reuse an unbound payload."""
    for pf in prefetches:
        try:
            return resolve_prefetch_for_commit(
                pf,
                cert,
                current_logical,
                prefetch_issuer_is_byzantine=id(pf) in byzantine_issuers,
            )
        except PrefetchCommitDissociationError:
            continue
    # No bound payload available: re-execute inside the committed decision.
    raise PrefetchCommitDissociationError(
        f"no prefetch for decision {cert.decision_id} satisfies payload-commit "
        f"binding; re-execute tool call within committed decision"
    )
