# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-parallel-branches-when-optimistic-tool-invocations-have-already-committed-external-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-parallel-branches-when-optimistic-tool-invocations-have-already-committed-external-side-effects.warrant.json
# Markdown SHA-256:   24d8e85e58a6ae035fac5aeb5c1557941b838e50b31bdbe57d28404c86255db3
# Code AST SHA-256:   f0666295b41338bf4cb71077c8d8a0ae863efa1ca86c160a544ae11408580fcd
# Verified Classes:   SpeculativeEffectConflict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeEffectConflict(RuntimeError):
    """Raised when a merge barrier detects tier-3 effects that cannot be
    reconciled because the intent-scoped idempotency invariant did not hold."""
    pass


TIER_PURE = 1
TIER_IDEMPOTENT = 2
TIER_IRREVERSIBLE = 3


def reconcile_branches(branches, effect_ledger):
    """
    branches: list of dicts with branch_id, plan_score
    effect_ledger: list of dicts:
        {branch_id, intent_id, idempotency_key, tier, committed_at}

    Invariant required for safe optimistic merge:
      For every tier-3 effect, idempotency_key == derive(intent_id),
      so at most one committed effect exists per intent_id.
    """
    tier3 = [e for e in effect_ledger if e["tier"] == TIER_IRREVERSIBLE]

    # Group irreversible effects by logical intent.
    by_intent = {}
    for e in tier3:
        by_intent.setdefault(e["intent_id"], []).append(e)

    for intent_id, effects in by_intent.items():
        committed = [e for e in effects if e["committed_at"] is not None]
        if len(committed) > 1:
            # Two branches materialized the same intent -> keys were per-call,
            # not per-intent. The world state is already divergent.
            raise SpeculativeEffectConflict(
                f"intent {intent_id!r} has {len(committed)} committed tier-3 "
                f"effects from branches "
                f"{[e['branch_id'] for e in committed]}; "
                f"idempotency keys "
                f"{[e['idempotency_key'] for e in committed]} "
                f"did not collapse. Merge is unsafe."
            )

    # Safe path: at most one committed effect per intent. Select winner by score,
    # but require the winner's committed effects to match its plan.
    winner = max(branches, key=lambda b: b["plan_score"])
    winner_effects = [e for e in tier3 if e["branch_id"] == winner["branch_id"]]
    if not winner_effects and any(
        e["committed_at"] is not None for e in tier3
    ):
        # Another branch committed an effect the winner's plan does not contain.
        raise SpeculativeEffectConflict(
            f"winner branch {winner['branch_id']!r} has no committed tier-3 "
            f"effects, but a discarded branch did. Winner plan and effect "
            f"ledger disagree; cannot merge cleanly."
        )

    return {"winner": winner["branch_id"], "status": "merged_clean"}


def commit_optimistic(branch_id, intent_id, tool, tier, idempotency_derive):
    """
    Wrapper enforcing the invariant at invocation time.
    idempotency_derive: callable(intent_id) -> key, must be deterministic
    and independent of branch_id / wall clock.
    """
    key = idempotency_derive(intent_id)
    if tier == TIER_IRREVERSIBLE and key is None:
        raise SpeculativeEffectConflict(
            f"branch {branch_id!r} attempted irreversible tool {tool!r} "
            f"for intent {intent_id!r} without an intent-scoped idempotency "
            f"key; gate this tool behind the merge barrier."
        )
    return tool(idempotency_key=key)
