# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-replaying-a-cached-tool-call-trace-whose-embedded-timestamps-and-nonce-seeds-diverge-from-the-recorded-causal-vector.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-replaying-a-cached-tool-call-trace-whose-embedded-timestamps-and-nonce-seeds-diverge-from-the-recorded-causal-vector.warrant.json
# Markdown SHA-256:   4ca8983f028114a92f576f839ca22d2ebb1ea4dd44338b79f00892b3c217a61c
# Code AST SHA-256:   f028b21f7877dcb988b27c266d0a11daefa3a665540d56559851bde520b1dafb
# Verified Classes:   CausalVectorDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalVectorDivergence(RuntimeError):
    """Raised when replay-derived and cache-embedded causal vectors disagree."""
    pass


def replay_node(node, event_log, tool_cache):
    # Reconstruct the expected causal vector from the append-only log prefix,
    # including retry edges (the incident's bug: retry edges were ignored).
    expected = reconstruct_vector(event_log.prefix_upto(node.parent_edges),
                                  include_retry_edges=True)

    cache_key = (node.tool_name, node.args_hash, expected.epoch)  # epoch-aware
    cached = tool_cache.get(cache_key)

    if cached is None:
        return execute_live(node, expected)

    embedded = cached["causal_vector"]

    if embedded.epoch != expected.epoch or embedded.parents != expected.parents:
        # Causal disagreement: never reconcile in favor of the cache.
        # Quarantine downstream and refuse the replay step.
        raise CausalVectorDivergence(
            f"node={node.id} replay_epoch={expected.epoch} "
            f"cache_epoch={embedded.epoch} "
            f"replay_parents={expected.parents} cache_parents={embedded.parents}"
        )

    if embedded.nonce_seed != expected.nonce_seed:
        # Non-causal metadata drift: payload may be reused, vector discarded.
        tool_cache.mark_stale(cache_key)
        return inject_payload(cached["body"], vector=expected)

    return inject_payload(cached["body"], vector=expected)


def auditor_verify(mismatch_node, upstream_flags):
    # Provenance gate: self-doubt is only licensed when upstream is clean.
    if upstream_flags.get(mismatch_node.id) in ("STALE", "INCONSISTENT"):
        raise CausalVectorDivergence(
            f"auditor refusing self-attribution at {mismatch_node.id}: "
            f"upstream flag={upstream_flags[mismatch_node.id]}"
        )
    return recompute_and_compare(mismatch_node)
