# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-when-a-cached-tool-call-result-is-replayed-under-a-mutated-argument-hash.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-when-a-cached-tool-call-result-is-replayed-under-a-mutated-argument-hash.warrant.json
# Markdown SHA-256:   5530da07d352a7896f95561fedd75a4a3f048a1d696734c92f14c89e663041d7
# Code AST SHA-256:   684173fdb01e42d89f40f48701fc110a5769b2982dca8785ff2479f67fefcba3
# Verified Classes:   SpeculativeCacheDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeCacheDivergence(RuntimeError):
    """Raised when a cache hit cannot be proven to belong to the requesting branch."""
    pass


def resolve_tool_call(branch, call, cache, live_branches, rollback_epoch):
    # The branch's own identity for these arguments, computed the SAME way
    # the branch logs them. Never reuse the cache's canonicalizer here.
    branch_arg_hash = branch.argument_identity(call)

    entry = cache.lookup(branch_arg_hash)

    if entry is None:
        result = call.execute()
        cache.store(branch_arg_hash, result, branch_id=branch.id, generation=rollback_epoch)
        return result

    # Invariant 1: the key the cache matched must equal the branch's own hash.
    if entry.key_hash != branch_arg_hash:
        raise SpeculativeCacheDivergence(
            f"key mismatch: cache={entry.key_hash!r} branch={branch_arg_hash!r}"
        )

    # Invariant 3: no reading across the rollback fence.
    if entry.generation < rollback_epoch:
        raise SpeculativeCacheDivergence(
            f"zombie entry: entry.gen={entry.generation} epoch={rollback_epoch}"
        )

    # Invariant 3b: entry must originate from a currently live branch.
    if entry.branch_id not in live_branches:
        raise SpeculativeCacheDivergence(
            f"entry from dead branch {entry.branch_id!r}"
        )

    # Invariant 2 is a per-tool property; refuse to trust normalization
    # for tools declared non-transparent under canonicalization.
    if not call.tool.transparent_under_normalization:
        result = call.execute()
        cache.store(branch_arg_hash, result, branch_id=branch.id, generation=rollback_epoch)
        return result

    return entry.result
