# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-committed-irreversible-side-effects-before-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-committed-irreversible-side-effects-before-rollback-reconciliation.warrant.json
# Markdown SHA-256:   69d144b50439361560f1568b03b302d6283fd34fc0c7a76eb204fa639137290f
# Code AST SHA-256:   46f15322065baae8858243c1256fc2c5b15bc6dbb69e12a01140cbe37018aab9
# Verified Classes:   EffectClass, BranchState, Invocation, Branch, UnreconciledLeakageError
# 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):
    NONE = "none"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class BranchState(Enum):
    PROVISIONAL = "provisional"
    QUARANTINED = "quarantined"
    ROLLED_BACK = "rolled_back"
    COMMITTED_WITH_LEAKAGE = "committed_with_leakage"
    COMMITTED = "committed"


@dataclass
class Invocation:
    tool: str
    declared_effect: EffectClass
    runtime_effect: EffectClass
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.PROVISIONAL
    invocations: list[Invocation] = field(default_factory=list)
    leaked_artifacts: list[str] = field(default_factory=list)


class UnreconciledLeakageError(RuntimeError):
    """Raised when a branch would be marked terminal while irreversible
    side effects remain unreconciled. Collapsing this into ROLLED_BACK
    is the exact failure this guard exists to prevent."""


def reconcile(branch: Branch, won_vote: bool) -> Branch:
    # Step 1: detect runtime effect-class escalation (schema-default override).
    for inv in branch.invocations:
        if inv.runtime_effect.value > inv.declared_effect.value:
            branch.state = BranchState.QUARANTINED
            raise UnreconciledLeakageError(
                f"branch {branch.branch_id}: tool {inv.tool} escalated "
                f"{inv.declared_effect.value}->{inv.runtime_effect.value} at "
                f"invocation time; declared-effect accounting is invalid"
            )

    # Step 2: winning branch commits, but only if it carries no leakage.
    if won_vote:
        leaked = [i for i in branch.invocations
                  if i.runtime_effect is EffectClass.IRREVERSIBLE]
        if leaked:
            branch.state = BranchState.COMMITTED_WITH_LEAKAGE
            branch.leaked_artifacts = [i.tool for i in leaked]
        else:
            branch.state = BranchState.COMMITTED
        return branch

    # Step 3: losing branch. Rollback is only honest if every
    # irreversible invocation is either absent or explicitly acknowledged.
    uncompensated = [
        i for i in branch.invocations
        if i.runtime_effect is EffectClass.IRREVERSIBLE and not i.compensated
    ]
    if uncompensated:
        # Cannot claim ROLLED_BACK. Must surface leakage to consumers.
        branch.state = BranchState.COMMITTED_WITH_LEAKAGE
        branch.leaked_artifacts = [i.tool for i in uncompensated]
        raise UnreconciledLeakageError(
            f"branch {branch.branch_id} lost vote but leaked "
            f"{len(uncompensated)} irreversible effect(s): "
            f"{[i.tool for i in uncompensated]}; "
            f"terminal state must be COMMITTED_WITH_LEAKAGE, not ROLLED_BACK"
        )

    branch.state = BranchState.ROLLED_BACK
    return branch
