# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-agent-branch-has-crossed-the-point-of-no-rollback-during-merge-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-agent-branch-has-crossed-the-point-of-no-rollback-during-merge-reconciliation.warrant.json
# Markdown SHA-256:   ef54d6fd46f1641780e1054b8f1b4c579ee2e49df378ac1f50334ec25ecd0235
# Code AST SHA-256:   9c9a05b49b0eff3007f6a7407ddd1f6838ecc685bb1d8d69d7efc99916ab6a7e
# Verified Classes:   EffectClass, UnsafeSpeculativeMerge, Effect, GlobalEffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE_IDEMPOTENT = "compensable_idempotent"
    COMPENSABLE_NON_IDEMPOTENT = "compensable_non_idempotent"
    IRREVERSIBLE = "irreversible"


class UnsafeSpeculativeMerge(RuntimeError):
    """Raised when a speculative merge would commit a winner while a losing
    branch holds an un-compensated irreversible or non-idempotent effect."""
    pass


@dataclass
class Effect:
    branch_id: str
    effect_id: str
    effect_class: EffectClass
    compensation_status: str = "none"  # none | succeeded | failed | undefined


@dataclass
class GlobalEffectLedger:
    effects: list = field(default_factory=list)

    def committed(self, branch_id: str):
        return [e for e in self.effects if e.branch_id == branch_id]

    def orphaned(self, losing_branches):
        orphans = []
        for e in self.effects:
            if e.branch_id not in losing_branches:
                continue
            if e.effect_class in (EffectClass.IRREVERSIBLE,
                                  EffectClass.COMPENSABLE_NON_IDEMPOTENT):
                if e.compensation_status != "succeeded":
                    orphans.append(e)
        return orphans


def reconcile_merge(winner: str, losers, ledger: GlobalEffectLedger,
                    winner_effects_disjoint: Optional[bool] = None) -> str:
    """Gate a speculative merge on the global effect ledger.

    Returns 'commit' or 'commit_with_quarantine'. Raises
    UnsafeSpeculativeMerge when the merge cannot be made safe.
    """
    orphans = ledger.orphaned(losers)

    if not orphans:
        return "commit"

    # Orphans exist. Only a proven effect-disjoint winner may proceed.
    if winner_effects_disjoint is True:
        return "commit_with_quarantine"

    if winner_effects_disjoint is None:
        raise UnsafeSpeculativeMerge(
            f"cannot prove effect-disjointness for winner {winner!r} against "
            f"{len(orphans)} orphaned effect(s): "
            f"{[e.effect_id for e in orphans]}"
        )

    raise UnsafeSpeculativeMerge(
        f"winner {winner!r} shares substrate with orphaned effects from losers: "
        f"{[(e.branch_id, e.effect_id, e.effect_class.value) for e in orphans]}"
    )


def detect_cross_branch_read_after_write(winner_reads, ledger: GlobalEffectLedger,
                                         losers) -> list:
    """Flag winner reads whose observed value was produced by a losing branch's
    committed write. These are invisible to the effect-class check and must be
    surfaced as reconciliation hazards."""
    hazards = []
    loser_writes = {e.effect_id: e for e in ledger.committed_effects_for(losers)}
    for r in winner_reads:
        if r.observed_effect_id in loser_writes:
            hazards.append((r, loser_writes[r.observed_effect_id]))
    return hazards
