# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-cache-reuse-when-peer-agents-may-be-byzantine.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-cache-reuse-when-peer-agents-may-be-byzantine.warrant.json
# Markdown SHA-256:   dbe5de63840747f4f74ef1dbc33a1ab8a5c0074651d9fe4f3f53d6427d2b2f61
# Code AST SHA-256:   204cf9145ec30054bca1dbce2f17b30a91a3d8bf7c8f895941bffa06b81d883a
# Verified Classes:   ByzantineCacheReuseError, ExecutionReceipt, CacheEntry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ByzantineCacheReuseError(RuntimeError):
    """Raised when a cross-agent cache hit cannot be safely reused under Byzantine assumptions."""


@dataclass(frozen=True)
class ExecutionReceipt:
    worker_id: str
    tool_name: str
    args_digest: str
    result_digest: str
    signature: str  # verified against roster before use


@dataclass(frozen=True)
class CacheEntry:
    tool_name: str
    args_digest: str
    result: object
    receipts: tuple[ExecutionReceipt, ...]
    has_side_effects: bool


def _digest(obj) -> str:
    return hashlib.sha256(
        json.dumps(obj, sort_keys=True, default=str).encode()
    ).hexdigest()


def admit_cache_reuse(
    entry: CacheEntry,
    roster: frozenset[str],
    byzantine_threshold_f: int,
    consumer_can_rederive: bool,
) -> object:
    if entry.has_side_effects:
        raise ByzantineCacheReuseError(
            f"tool {entry.tool_name!r} has side effects; cross-agent cache reuse is unsound"
        )

    distinct = {r.worker_id for r in entry.receipts if r.worker_id in roster}
    if len(distinct) != len(entry.receipts):
        raise ByzantineCacheReuseError(
            f"receipt set for {entry.tool_name!r} contains unknown or duplicate workers: "
            f"{sorted(r.worker_id for r in entry.receipts)} vs roster"
        )

    for r in entry.receipts:
        if r.args_digest != entry.args_digest:
            raise ByzantineCacheReuseError(
                f"receipt args_digest mismatch for worker {r.worker_id!r}"
            )
        if r.result_digest != _digest(entry.result):
            raise ByzantineCacheReuseError(
                f"receipt result_digest mismatch for worker {r.worker_id!r}"
            )
        if not r.signature:
            raise ByzantineCacheReuseError(
                f"unsigned receipt from worker {r.worker_id!r}; refusing reuse"
            )

    required = 2 * byzantine_threshold_f + 1
    if len(distinct) >= required:
        return entry.result

    if consumer_can_rederive and len(distinct) >= 1:
        # Single attested observation + local re-derivation is acceptable for pure tools.
        return entry.result

    raise ByzantineCacheReuseError(
        f"insufficient independent execution receipts for {entry.tool_name!r}: "
        f"have {len(distinct)} distinct, need {required} (f={byzantine_threshold_f})"
    )
