# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-side-effects-when-parallel-branch-rollouts-converge-on-the-same-external-resource.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-side-effects-when-parallel-branch-rollouts-converge-on-the-same-external-resource.warrant.json
# Markdown SHA-256:   0091dc8141d3580b10dbb5ac818a4a800f4180e6c94bfcb6bf1c0d2bd6d913f5
# Code AST SHA-256:   79b8dcfe6ef9b9d85bc46388181c5e751b122d99286a8fc7b1a058d02127d0e0
# Verified Classes:   ReconciliationError, EffectStatus, JournalEntry, Resource, Reconciler
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class ReconciliationError(RuntimeError):
    """Raised when speculative branch reconciliation cannot proceed safely."""
    pass


class EffectStatus(Enum):
    PENDING = "pending"          # journaled, dispatch not yet confirmed
    CONFIRMED = "confirmed"      # response observed as success
    INDETERMINATE = "indeterminate"  # timeout / ambiguous; effect may have landed
    ROLLED_BACK = "rolled_back"
    SUPERSEDED = "superseded_by_commit"
    UNRECOVERABLE = "unrecoverable"


@dataclass
class JournalEntry:
    branch_id: str
    resource_key: str
    prior_state: Optional[dict]        # captured BEFORE dispatch
    captured_version: int              # resource version at dispatch
    idempotency_key: str
    status: EffectStatus = EffectStatus.PENDING


@dataclass
class Resource:
    key: str
    version: int
    state: dict


class Reconciler:
    def __init__(self, resources: dict[str, Resource]):
        self.resources = resources

    def compensate_losing_branch(self, entry: JournalEntry, winning_branch: str) -> EffectStatus:
        if entry.status is EffectStatus.INDETERMINATE:
            # Must read back before deciding; do not assume failure.
            raise ReconciliationError(
                f"branch {entry.branch_id}: effect on {entry.resource_key} is "
                f"INDETERMINATE; read-back reconcile required before compensation"
            )

        if entry.prior_state is None:
            entry.status = EffectStatus.UNRECOVERABLE
            raise ReconciliationError(
                f"branch {entry.branch_id}: no captured prior state for "
                f"{entry.resource_key}; cannot restore, rollout must not finalize"
            )

        res = self.resources[entry.resource_key]

        # Commit fencing: refuse to compensate if the resource moved past
        # the version this branch captured (winning branch or peer wrote).
        if res.version != entry.captured_version:
            entry.status = EffectStatus.SUPERSEDED
            return entry.status

        # State-restore, never literal inverse.
        res.state = dict(entry.prior_state)
        res.version += 1
        entry.status = EffectStatus.ROLLED_BACK
        return entry.status

    def finalize(self, journal: list[JournalEntry]) -> None:
        blocking = [
            e for e in journal
            if e.status in (EffectStatus.INDETERMINATE, EffectStatus.UNRECOVERABLE)
        ]
        if blocking:
            raise ReconciliationError(
                f"cannot finalize rollout: {len(blocking)} unresolved journal "
                f"entries ({[e.branch_id for e in blocking]})"
            )


# --- failure demonstration: A's rollback must be fenced out after B commits ---
res = Resource(key="ticket:4471", version=1, state={"status": "in_progress"})

# Branch A journals prior state, then writes "resolved" (version -> 2).
entry_a = JournalEntry("A", "ticket:4471", {"status": "in_progress"}, 1, "idem-a")
res.state = {"status": "resolved"}; res.version = 2

# Branch B wins and writes "escalated" (version -> 3).
res.state = {"status": "escalated"}; res.version = 3

r = Reconciler({"ticket:4471": res})
status = r.compensate_losing_branch(entry_a, winning_branch="B")
assert status is EffectStatus.SUPERSEDED, status
assert res.state == {"status": "escalated"}, "winning commit must survive"

# An INDETERMINATE effect blocks finalization rather than being silently dropped.
entry_c = JournalEntry("C", "ticket:4471", {"status": "escalated"}, 3, "idem-c",
                       status=EffectStatus.INDETERMINATE)
try:
    r.compensate_losing_branch(entry_c, winning_branch="B")
except ReconciliationError as exc:
    print("blocked:", exc)
    raise ReconciliationError("rollout halted pending read-back of branch C") from exc
