# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-diverged-from-its-rollback-anchor-in-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-diverged-from-its-rollback-anchor-in-multi-agent-execution.warrant.json
# Markdown SHA-256:   81db646c28986ae4e00e91973fb7895da935801169a5ce8f36703d96c86ffc53
# Code AST SHA-256:   26cc6adb2885630c5b5f056530e4212c37f7295403c0e90268f0e6cf8f682daf
# Verified Classes:   SpeculativeDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeDivergenceError(RuntimeError):
    """Raised when a replay read-set intersects keys created after the rollback anchor."""


def reconcile(winner_branch, rollback_anchor, shared_anchor, replay_fn):
    # Compute the read-set the replay will touch before executing it.
    read_set = replay_fn.dry_run_read_set(winner_branch, shared_anchor)

    contaminated = []
    for key in read_set:
        created_seq = shared_anchor.creation_sequence(key)
        if created_seq is None:
            # Anchor cannot prove provenance; speculation over it is unsound.
            raise SpeculativeDivergenceError(
                f"anchor {shared_anchor.id} exposes no creation sequence for key {key!r}; "
                "cannot distinguish pre-existing from contaminated"
            )
        if created_seq > rollback_anchor.sequence:
            contaminated.append((key, created_seq))

    if contaminated:
        # Fail closed: value-consistency checks cannot detect this class of divergence.
        raise SpeculativeDivergenceError(
            f"replay read-set intersects {len(contaminated)} key(s) created after "
            f"rollback anchor seq={rollback_anchor.sequence}: {contaminated!r}"
        )

    return replay_fn.execute(winner_branch, shared_anchor)
