# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-speculative-agent-branch-from-committing-side-effects-it-never-reconciled.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-speculative-agent-branch-from-committing-side-effects-it-never-reconciled.warrant.json
# Markdown SHA-256:   f4e4a92519b9ae82e68f4c7adac1888a40664eb2d49ce002fd695f4f6fd2a40d
# Code AST SHA-256:   6086529d8baa81ce917fe77e467447e937b103c16cfd22f56b7008315e4a59c5
# Verified Classes:   ReconciliationBarrierError, BranchState, IntentRecord, BranchLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ReconciliationBarrierError(RuntimeError):
    """Raised when the commit barrier cannot prove every branch's effects are accounted for."""


class BranchState(Enum):
    COMMITTED = "committed"
    COMPENSATED = "compensated"
    PROVEN_ABSENT = "proven_absent"
    UNKNOWN = "unknown"


@dataclass
class IntentRecord:
    intent_seq: int
    idempotency_key: str
    target: str
    queryable: bool
    state: Optional[BranchState] = None


@dataclass
class BranchLedger:
    branch_id: str
    intents: dict[int, IntentRecord] = field(default_factory=dict)
    killed_mid_call: bool = False

    def register_intent(self, seq: int, target: str, queryable: bool) -> IntentRecord:
        # Must be durable BEFORE the external call. In production: fsync here.
        key = hashlib.sha256(f"{self.branch_id}:{seq}:{target}".encode()).hexdigest()
        rec = IntentRecord(seq, key, target, queryable)
        self.intents[seq] = rec
        return rec


def resolve_branch(ledger: BranchLedger, external_lookup) -> dict[int, BranchState]:
    """Resolve every intent to a terminal state. external_lookup(key) -> bool present."""
    resolved: dict[int, BranchState] = {}
    for seq, rec in ledger.intents.items():
        if rec.state in (BranchState.COMMITTED, BranchState.COMPENSATED, BranchState.PROVEN_ABSENT):
            resolved[seq] = rec.state
            continue
        if not rec.queryable:
            # Non-queryable: only safe if the branch itself confirmed. Otherwise unknown.
            resolved[seq] = BranchState.UNKNOWN
            continue
        present = external_lookup(rec.idempotency_key)
        resolved[seq] = BranchState.COMMITTED if present else BranchState.PROVEN_ABSENT
    return resolved


def commit_barrier(ledgers: list[BranchLedger], external_lookup, winner_id: str) -> None:
    """Two-phase wait: no commit until every ledger is terminal. Unknowns block."""
    blocked: list[str] = []
    for ledger in ledgers:
        states = resolve_branch(ledger, external_lookup)
        for seq, state in states.items():
            if state == BranchState.UNKNOWN:
                blocked.append(f"{ledger.branch_id}#{seq}")
        # A branch killed mid-call with zero intents is the dangerous case: we cannot
        # prove absence because we cannot prove no intent was ever written.
        if ledger.killed_mid_call and not ledger.intents:
            blocked.append(f"{ledger.branch_id}#pre-intent-window")
    if blocked:
        raise ReconciliationBarrierError(
            f"commit blocked for winner={winner_id}: unresolved effects {blocked}; "
            f"escalate to query-by-key or serialized retry"
        )
    # Safe to commit winner's side of the transaction.
    return None
