# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-parallel-subtasks-and-the-rollback-of-a-losing-branch-corrupts-a-shared-effect-buffer.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-parallel-subtasks-and-the-rollback-of-a-losing-branch-corrupts-a-shared-effect-buffer.warrant.json
# Markdown SHA-256:   6ff36255b7a366d1610999927c1861dfff8c1d62c9009bf89673fcf11ccdf33e
# Code AST SHA-256:   f4119ea4be5150e2c58d834d68f2a755438a583be0437bb7d5e2acf479f8e09e
# Verified Classes:   SpeculativeReconciliationError, Effect, EffectLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpeculativeReconciliationError(RuntimeError):
    """Raised when a losing branch's effect survives reconciliation into the committed view."""
    pass


@dataclass
class Effect:
    branch_id: str
    logical_key: str
    idempotency_key: str
    payload: dict
    seq: int  # total order in the durable effect log


@dataclass
class EffectLog:
    effects: list = field(default_factory=list)
    _seq: int = 0

    def append(self, branch_id: str, logical_key: str, idempotency_key: str, payload: dict) -> Effect:
        self._seq += 1
        e = Effect(branch_id, logical_key, idempotency_key, payload, self._seq)
        self.effects.append(e)
        return e


def reconcile(log: EffectLog, winner_id: str, quiesced_branches: set[str],
              drain_deadline_exceeded: bool) -> dict:
    """
    Deterministic filter over the effect log. Returns the committed view keyed by
    logical_key. Raises if the invariant cannot be established.
    """
    if drain_deadline_exceeded:
        # Fail closed: we cannot prove no losing-branch write lands after commit.
        raise SpeculativeReconciliationError(
            "drain deadline exceeded; cannot guarantee effect linearizability"
        )

    # Every branch that emitted an effect must be either the winner or quiesced.
    emitters = {e.branch_id for e in log.effects}
    unaccounted = emitters - quiesced_branches - {winner_id}
    if unaccounted:
        raise SpeculativeReconciliationError(
            f"branches emitted effects but were never quiesced: {sorted(unaccounted)}"
        )

    committed: dict[str, Effect] = {}
    seen_idem: set[str] = set()
    for e in log.effects:  # seq order
        if e.branch_id != winner_id:
            continue  # losing-branch effects filtered, never promoted
        if e.idempotency_key in seen_idem:
            continue  # dedupe winner's own retries
        seen_idem.add(e.idempotency_key)
        committed[e.logical_key] = e

    # Invariant check: no committed effect may originate from a non-winner.
    for key, e in committed.items():
        if e.branch_id != winner_id:
            raise SpeculativeReconciliationError(
                f"effect {key} attributed to {e.branch_id}, expected winner {winner_id}"
            )
    return committed
