# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-prefetches-a-tool-call-whose-guard-evaluates-green-against-a-stale-world-state-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-prefetches-a-tool-call-whose-guard-evaluates-green-against-a-stale-world-state-snapshot.warrant.json
# Markdown SHA-256:   5092f10b2cca5b238c4afbfb5b91dce717d5e200a34e1ced118894a7e62cf081
# Code AST SHA-256:   a5d78e0df7ba4f96a7cd4985baa58fbb227427bbe07fdad5ae1886ac341c093f
# Verified Classes:   StalePrefetchGuardError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StalePrefetchGuardError(RuntimeError):
    """Raised when a speculative prefetch guard passed against a world-state
    snapshot that is no longer valid at call-issue time, and the prefetched
    call is not safe to execute against the current world."""
    pass


def issue_speculative_prefetch(
    call,
    guard,
    snapshot_version: int,
    live_store,
    *,
    max_skew_retries: int = 1,
) -> object:
    """Issue a speculative prefetch only if the guard is sound.

    A prefetch is sound iff the call is pure/idempotent AND the guard's
    predicate is monotone over the speculative window. Mutating calls are
    rejected outright; stale snapshots are re-checked once, then aborted.
    """
    if not call.is_pure_and_idempotent:
        # Mutating calls must be committed, not prefetched. The latency win
        # is never worth the silent ledger drift.
        raise StalePrefetchGuardError(
            f"refusing to prefetch non-pure call {call.name!r}; "
            "route through commit-time atomic guard instead"
        )

    current_version = live_store.version()
    if current_version != snapshot_version:
        # Re-evaluate once against the live store.
        if max_skew_retries <= 0:
            raise StalePrefetchGuardError(
                f"snapshot version {snapshot_version} stale at issue time "
                f"(live={current_version}); prefetch aborted"
            )
        if not guard.evaluate(live_store.snapshot()):
            raise StalePrefetchGuardError(
                f"guard rejected {call.name!r} on re-evaluation against "
                f"live version {current_version}"
            )
        snapshot_version = current_version

    result = call.execute()
    # Tag the result so reconciliation can attribute any orphaned side effect
    # to this plan version if the world moves again before commit.
    result.prefetch_origin_version = snapshot_version
    return result
