# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-merge-has-silently-inherited-a-divergent-tool-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-merge-has-silently-inherited-a-divergent-tool-side-effect.warrant.json
# Markdown SHA-256:   16787425ae5196430da0d233a210a74b89b9d9d19f58bef535c6f8ed5f5901a4
# Code AST SHA-256:   92d7667381663c264911da31918a8b927e9142efdd74f1f0ee40398bcd14a98b
# Verified Classes:   UnreconciledBranchEffect, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class UnreconciledBranchEffect(RuntimeError):
    """Raised when a merge would let the survivor inherit a side effect
    committed by an abandoned or losing speculative branch."""
    pass


@dataclass
class Effect:
    branch_id: str
    tool: str
    resource: str
    committed_at: float
    reversible: bool
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: list = field(default_factory=list)


def merge_speculative_branches(
    survivor: Branch,
    abandoned: list,
    shared_namespace: str,
    fork_time: float,
    compensate,
):
    """Merge is valid only if every effect committed by a non-surviving
    branch is either compensated or adopted into the survivor's provenance.
    Any effect that is neither is a hard merge failure."""
    inherited = []
    for b in abandoned:
        for e in b.effects:
            if e.resource != shared_namespace:
                continue
            if e.committed_at <= fork_time:
                continue
            if e.compensated:
                continue
            if not e.reversible:
                # Irreversible effect from a discarded branch: cannot be
                # silently rolled back. Must be surfaced, never swallowed.
                raise UnreconciledBranchEffect(
                    f"branch {b.branch_id} committed irreversible "
                    f"{e.tool} on {e.resource} at {e.committed_at}; "
                    f"survivor {survivor.branch_id} cannot inherit this silently"
                )
            compensate(e)
            e.compensated = True
            inherited.append(e)

    # Survivor provenance must now reflect the true world, not the snapshot.
    survivor.effects.extend(inherited)
    return {
        "survivor": survivor.branch_id,
        "compensated": [e.tool for e in inherited],
        "inherited_count": len(inherited),
    }


def post_merge_ledger_check(survivor: Branch, ledger: list, fork_time: float):
    """Called by the survivor before its first post-merge action.
    A tool read contradicting restored memory is evidence, not staleness."""
    live = [
        e for e in ledger
        if e.branch_id != survivor.branch_id
        and e.committed_at > fork_time
        and not e.compensated
    ]
    if live:
        raise UnreconciledBranchEffect(
            f"survivor {survivor.branch_id} has {len(live)} unreconciled "
            f"effect(s) from other branches: "
            f"{[(e.branch_id, e.tool) for e in live]}"
        )
    return True
