# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-prefetching-when-rollback-of-an-externalized-side-effect-is-not-guaranteed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-prefetching-when-rollback-of-an-externalized-side-effect-is-not-guaranteed.warrant.json
# Markdown SHA-256:   7bc447d05f5188d165140a3aa8573a6fb67091791c5a06d3f10d5b03b3d673c1
# Code AST SHA-256:   270ddbbd26dfa389581a60db7862bb8e69abfbc986021b0e67bf22eb4e57c0ec
# Verified Classes:   UnsafeSpeculativePrefetch, EffectScope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsafeSpeculativePrefetch(RuntimeError):
    """Raised when a speculative tool call is issued for a tool whose
    effect scope is not verifiably 'staged'. Speculation on an
    immediate-effect tool is an unretractable side effect."""
    pass


class EffectScope:
    STAGED = "staged"       # externalization gated on commit token
    IMMEDIATE = "immediate"  # effect reaches observer before return


def classify_speculatable(adapter_manifest: dict) -> bool:
    # Silent manifest is treated as immediate, never staged.
    scope = adapter_manifest.get("effect_scope")
    return scope == EffectScope.STAGED


def prefetch(tool_name: str, adapter_manifest: dict, args: dict):
    if not classify_speculatable(adapter_manifest):
        # Do not speculate. Defer to committed branch.
        raise UnsafeSpeculativePrefetch(
            f"tool {tool_name!r} has effect_scope="
            f"{adapter_manifest.get('effect_scope', '<undeclared>')!r}; "
            f"speculative prefetch would externalize an effect that "
            f"rollback cannot retract. Defer to commit."
        )
    # Safe: effect is gated on a staging token we control.
    return adapter_manifest["adapter"].stage(args)


def rollback(handle, adapter_manifest: dict):
    if adapter_manifest.get("effect_scope") != EffectScope.STAGED:
        # A 'rolled_back' status from an immediate-scope adapter only
        # retracts its local record, not the external effect. Escalate.
        raise UnsafeSpeculativePrefetch(
            "rollback invoked on non-staged tool; external effect may "
            "already be observable. Treating handle as live, not rolled back."
        )
    return handle.release()
