# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-tool-call-prefetching-when-verification-latency-exceeds-the-prefetch-window.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-tool-call-prefetching-when-verification-latency-exceeds-the-prefetch-window.warrant.json
# Markdown SHA-256:   35343e159e3f380c4b5a38553d061e09dcf4924dfccedd222c0dc264844e2589
# Code AST SHA-256:   78af508ac30537049255da81b557a3e4f29252581293a57c4ec8ff125cd6605d
# Verified Classes:   PrefetchInvariantViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PrefetchInvariantViolation(RuntimeError):
    """Raised when speculative prefetch verification cannot close before commitment."""
    pass


def should_prefetch(tool_class: str, measured_p99_latency_s: float,
                    commit_barrier_s: float | None, safety_margin_s: float = 0.05) -> bool:
    # Read-only tools have no commitment point: T_c is effectively infinite.
    if tool_class == "read_only":
        return True

    # Effectful tool with no enforced commitment barrier: unsafe to speculate.
    if commit_barrier_s is None:
        raise PrefetchInvariantViolation(
            f"effectful tool '{tool_class}' has no commitment barrier; "
            "verification latency cannot be bounded against T_c"
        )

    # Effectful tool: require L_v + margin < T_c at the tail, not the median.
    if measured_p99_latency_s + safety_margin_s >= commit_barrier_s:
        raise PrefetchInvariantViolation(
            f"tool '{tool_class}': p99 verification latency "
            f"{measured_p99_latency_s:.3f}s + margin {safety_margin_s:.3f}s "
            f">= commit barrier {commit_barrier_s:.3f}s; "
            "must degrade to sequential invocation for this class"
        )

    return True


def plan_prefetch(plan_tools: list[tuple[str, float]],
                  commit_barriers: dict[str, float | None],
                  measured_p99: dict[str, float]) -> list[str]:
    safe: list[str] = []
    for tool_class, _ in plan_tools:
        try:
            if should_prefetch(tool_class, measured_p99[tool_class],
                               commit_barriers.get(tool_class)):
                safe.append(tool_class)
        except PrefetchInvariantViolation:
            # Degrade this class to sequential; do not abort the whole plan.
            continue
    return safe
