# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-speculative-branches-before-merge-when-a-tool-call-s-side-effects-are-only-conditionally-reversible.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-speculative-branches-before-merge-when-a-tool-call-s-side-effects-are-only-conditionally-reversible.warrant.json
# Markdown SHA-256:   b7d79c4c31a340fc358138d6a875feebe15dfb2485f39e293247d4db887bafb3
# Code AST SHA-256:   f8d480dfa7bc84e5c3a08192e2a17098ca9088f3fea78244ca9b0cb0d75a22d6
# Verified Classes:   SpeculativeSideEffectLeak, EffectClass
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class SpeculativeSideEffectLeak(RuntimeError):
    """Raised when a discarded or merged branch leaves an unretracted
    mutating side effect that diverges from the committed lineage."""
    pass


class EffectClass:
    PURE = "pure"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


def validate_merge(branches, merge_deadline, lease_table):
    """
    Enforce the speculative side-effect invariant before committing a merge.

    branches: list of dicts with keys
        id, effect_class, dispatch_time, compensation_window, resource
    merge_deadline: absolute time the merge decision completes
    lease_table: dict resource -> branch_id currently holding the write lease
    """
    winners = [b for b in branches if b.get("won")]
    losers = [b for b in branches if not b.get("won")]

    if len(winners) != 1:
        raise SpeculativeSideEffectLeak(
            f"merge produced {len(winners)} winners; exactly one required"
        )
    winner = winners[0]

    # Rule 1: irreversible effects must never be speculative.
    for b in branches:
        if b["effect_class"] == EffectClass.IRREVERSIBLE and not b.get("lease_held"):
            raise SpeculativeSideEffectLeak(
                f"branch {b['id']} dispatched IRREVERSIBLE effect on "
                f"{b['resource']} without a pre-dispatch lease"
            )

    # Rule 2: at most one branch may hold a mutating effect per resource.
    mutating = {}
    for b in branches:
        if b["effect_class"] in (EffectClass.COMPENSABLE, EffectClass.IRREVERSIBLE):
            res = b["resource"]
            if res in mutating:
                raise SpeculativeSideEffectLeak(
                    f"branches {mutating[res]} and {b['id']} both mutated "
                    f"{res}; speculative writes to a contended resource "
                    f"are not compensable"
                )
            mutating[res] = b["id"]

    # Rule 3: losing branches with landed effects must be compensable
    # within the window, and the merge must complete inside it.
    for b in losers:
        if b["effect_class"] == EffectClass.PURE:
            continue
        window_end = b["dispatch_time"] + b["compensation_window"]
        if b["effect_class"] == EffectClass.COMPENSABLE:
            if merge_deadline > window_end:
                raise SpeculativeSideEffectLeak(
                    f"branch {b['id']} compensation window closed at "
                    f"{window_end} before merge deadline {merge_deadline}; "
                    f"effect on {b['resource']} is de facto irreversible"
                )
        elif b["effect_class"] == EffectClass.IRREVERSIBLE:
            raise SpeculativeSideEffectLeak(
                f"losing branch {b['id']} performed IRREVERSIBLE effect on "
                f"{b['resource']}; cannot discard, must reopen merge"
            )

    # Rule 4: winner's side effect must not be invalidated by a sibling's
    # still-live effect on the same resource (anti-correlation guard).
    for b in losers:
        if b["resource"] == winner["resource"] and b.get("effect_landed"):
            raise SpeculativeSideEffectLeak(
                f"winner {winner['id']} shares resource {winner['resource']} "
                f"with losing branch {b['id']} whose effect already landed; "
                f"external reconciler may invert the winner"
            )

    return True
