# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-prefetching-has-crossed-the-byzantine-commit-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-prefetching-has-crossed-the-byzantine-commit-boundary.warrant.json
# Markdown SHA-256:   d2cdf6ebba2879d60747c01087fb0ec8142decf714e6f4db74b1ca852ce33f89
# Code AST SHA-256:   c564035a95167115d9c38a6ef271768ca71ea03245f74212e0f1fc0a9a446dd7
# Verified Classes:   SpeculativeCommitBoundaryError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeCommitBoundaryError(RuntimeError):
    """Raised when a speculative tool call crosses the Byzantine commit boundary."""
    pass


IDEMPOTENT_TOOLS = frozenset({"fetch_account_balance", "get_order_status", "read_ledger"})
WRITE_TOOLS_WITH_IDEMPOTENCY_KEY = frozenset({"reserve_funds", "ship_order"})


def admit_prefetch(tool: str, args: dict, speculation_id: str,
                   tombstone_readable: bool, warrant_join_supported: bool,
                   commit_log: list[dict]) -> str:
    """Return disposition: 'prefetch', 'speculative_write', or raise."""
    if tombstone_readable:
        raise SpeculativeCommitBoundaryError(
            f"speculation {speculation_id} result is readable before warrant join; "
            "planner can observe an unwarranted effect"
        )

    if tool in IDEMPOTENT_TOOLS:
        return "prefetch"

    if tool in WRITE_TOOLS_WITH_IDEMPOTENCY_KEY and warrant_join_supported:
        if "idempotency_key" not in args:
            raise SpeculativeCommitBoundaryError(
                f"non-idempotent tool {tool} prefetched without idempotency_key; "
                "warrant join cannot deduplicate replay"
            )
        return "speculative_write"

    # Last-resort structural check: any prior non-idempotent effect with
    # result index < warrant index is a boundary crossing already in flight.
    for entry in commit_log:
        if entry.get("idempotent") is False and entry.get("result_index", 0) < entry.get("warrant_index", 0):
            raise SpeculativeCommitBoundaryError(
                f"commit log already contains unwarranted effect {entry['effect_id']} "
                f"(result@{entry['result_index']} < warrant@{entry['warrant_index']}); "
                f"refusing to issue {tool} under speculation {speculation_id}"
            )

    raise SpeculativeCommitBoundaryError(
        f"tool {tool} is not safe to prefetch: not idempotent, no idempotency key, "
        "or commit protocol lacks warrant join"
    )
