# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-side-effects-when-speculative-multi-agent-branches-roll-back-after-a-shared-tool-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-side-effects-when-speculative-multi-agent-branches-roll-back-after-a-shared-tool-commit.warrant.json
# Markdown SHA-256:   adb37e44059f77ccc94afef07c35e8ed2760a0e4b3bef2ec49ecbb0e4c33a419
# Code AST SHA-256:   0f2d510f1eaa5d4850007bd4907c713d100c1c46ff02f5ec7d8cd6dd12bee3a3
# Verified Classes:   UnreconcilableSpeculativeFrame
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconcilableSpeculativeFrame(RuntimeError):
    """Raised when a losing branch's side effects were observed by survivors
    or the external world and cannot be safely compensated or deduplicated."""
    pass


def reconcile_speculative_frame(
    winner_id: str,
    discarded: dict[str, list[dict]],
    effect_ledger: dict[str, dict],
    verifier_warants: list[dict],
) -> dict:
    """
    discarded: branch_id -> list of effect_ids it emitted
    effect_ledger: effect_id -> {idempotency_key, payload_hash, observed_by:set, non_idempotent:bool}
    Returns committed effect set after dedup/adoption, or raises.
    """
    committed_effects: dict[str, str] = {}
    compensations: list[str] = []

    for branch_id, effect_ids in discarded.items():
        for eid in effect_ids:
            eff = effect_ledger[eid]
            observers = eff["observed_by"] - {branch_id}
            if not observers:
                continue  # true no-op in the world; safe discard

            # Attempt cheap dedup-adoption path.
            matching = [
                cid for cid, ckey in committed_effects.items()
                if effect_ledger[cid]["idempotency_key"] == eff["idempotency_key"]
                and effect_ledger[cid]["payload_hash"] == eff["payload_hash"]
            ]
            if matching and not eff["non_idempotent"]:
                continue  # winner already produced an identical effect; dedup

            if eff["non_idempotent"] or not matching:
                raise UnreconcilableSpeculativeFrame(
                    f"branch {branch_id} effect {eid} observed by "
                    f"{sorted(observers)} cannot be rolled back at branch "
                    f"granularity (non_idempotent={eff['non_idempotent']}, "
                    f"idempotent_match={bool(matching)}); abort frame and "
                    f"compensate: {compensations + [eid]}"
                )
            committed_effects[eid] = eff["idempotency_key"]

    committed_branches = {winner_id}
    for w in verifier_warants:
        if not w["provenance_branch"] <= committed_branches:
            raise UnreconcilableSpeculativeFrame(
                f"warrant {w['id']} attests branches "
                f"{sorted(w['provenance_branch'])} but committed set is "
                f"{sorted(committed_branches)}; re-verify against committed state"
            )

    return {"committed_effects": committed_effects, "committed_branches": committed_branches}
