# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fork-on-speculative-execution-and-then-silently-merge-a-losing-branch-into-canonical-state.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fork-on-speculative-execution-and-then-silently-merge-a-losing-branch-into-canonical-state.warrant.json
# Markdown SHA-256:   4ce3ed54e4986463b6d7c0c018d90bff1559649bc797290d72ba8c43b3059d9f
# Code AST SHA-256:   f160adff73d6215133065c0a26f88494f3871f11134e36608f92e0e360236e7f
# Verified Classes:   ReconciliationAliasingError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ReconciliationAliasingError(RuntimeError):
    """Raised when selective replay would merge a discarded branch's writes."""


@dataclass
class Branch:
    branch_id: str
    declared_write_keys: set[str]
    event_log: list[tuple[str, Any]] = field(default_factory=list)


def reachable_keys(substrate: dict, root: str) -> set[str]:
    """Walk the aliasing graph from a root key; shallow COW hides these."""
    seen: set[str] = set()
    stack = [root]
    while stack:
        key = stack.pop()
        if key in seen or key not in substrate:
            continue
        seen.add(key)
        value = substrate[key]
        if isinstance(value, dict):
            stack.extend(value.keys())
    return seen


def reconcile(
    substrate: dict,
    branches: list[Branch],
    winner_id: str,
    deep_snapshot_taken: bool,
) -> dict:
    winner = next(b for b in branches if b.branch_id == winner_id)
    losers = [b for b in branches if b.branch_id != winner_id]

    # The invariant: no loser may be able to reach a key the winner's
    # selective replay will not overwrite.
    for loser in losers:
        loser_reach = set()
        for key in loser.declared_write_keys:
            loser_reach |= reachable_keys(substrate, key)
        winner_replay = winner.declared_write_keys
        leaked = loser_reach - winner_replay
        if leaked and not deep_snapshot_taken:
            raise ReconciliationAliasingError(
                f"branch {loser.branch_id} can mutate {sorted(leaked)} "
                f"through aliasing, but winner {winner_id} will not replay "
                f"those keys; selective merge would absorb discarded writes. "
                f"Require deep snapshot restore or immutable substrate."
            )

    merged = dict(substrate)
    for key, value in winner.event_log:
        merged[key] = value
    return merged
