# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciliation-deadlock-under-partial-quorum-loss.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciliation-deadlock-under-partial-quorum-loss.warrant.json
# Markdown SHA-256:   0206d2aa1abcc5e53a6d71489229565120a55542cd5df869ac5495d15246b1af
# Code AST SHA-256:   967b32e7c4623887d0074eeabdf16cd6e66929feb6f450d83b78f1f78d84f695
# Verified Classes:   ReconciliationError, Verdict, QuorumState, BranchCertificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReconciliationError(RuntimeError):
    pass


class Verdict(Enum):
    VALID = "valid"
    INVALID = "invalid"
    TIMEOUT = "timeout"


class QuorumState(Enum):
    COMMITTED = "committed"
    REJECTED = "rejected"
    UNRESOLVED = "unresolved"


@dataclass(frozen=True)
class BranchCertificate:
    branch_id: str          # stable across re-dispatch — the identity invariant
    attempt: int
    content_hash: str
    commit_token: str       # lease-bound, changes per attempt


def stable_branch_id(plan_text: str) -> str:
    # Identity derived from content, not from dispatch order.
    return hashlib.sha256(plan_text.encode()).hexdigest()[:16]


def reconcile(
    cert: BranchCertificate,
    verdicts: dict[str, Verdict],
    quorum_size: int,
    lease_observed_expired: bool,
    lease_observable: bool,
) -> QuorumState:
    valid = sum(1 for v in verdicts.values() if v is Verdict.VALID)
    invalid = sum(1 for v in verdicts.values() if v is Verdict.INVALID)
    timeouts = sum(1 for v in verdicts.values() if v is Verdict.TIMEOUT)
    needed = (quorum_size // 2) + 1

    if valid >= needed:
        return QuorumState.COMMITTED
    if invalid >= needed:
        return QuorumState.REJECTED
    if timeouts > 0 and not lease_observable:
        # Cannot prove the branch is non-committing. Do not re-dispatch.
        raise ReconciliationError(
            f"branch {cert.branch_id} attempt {cert.attempt}: "
            f"{timeouts} auditor(s) unresponsive and lease unobservable; "
            f"state UNRESOLVED, escalate rather than re-dispatch"
        )
    if timeouts > 0 and not lease_observed_expired:
        # Lease still live: branch may commit at any moment.
        raise ReconciliationError(
            f"branch {cert.branch_id} attempt {cert.attempt}: "
            f"lease still live despite {timeouts} timeout(s); "
            f"re-dispatch would race the original commit"
        )
    return QuorumState.UNRESOLVED
