# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconcile-a-speculative-branch-whose-rollback-witness-is-incomplete.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconcile-a-speculative-branch-whose-rollback-witness-is-incomplete.warrant.json
# Markdown SHA-256:   a6fcfc7a283c8a4a40a47df4e54818748441eae60c495d692ea3bba5640a2665
# Code AST SHA-256:   60636f5dc086ff253b1b194df8239b406131fae8aba7cc8f797b5e8c50966daf
# Verified Classes:   UnsoundRollbackWitness, Compensation, RollbackWitness
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class UnsoundRollbackWitness(RuntimeError):
    """Raised when a speculative branch's rollback witness cannot be trusted for reconciliation."""
    pass


@dataclass
class Compensation:
    effect_id: str
    inverse_op: str
    precondition_hash: str
    postcondition_hash: Optional[str]
    compensation_idempotency_key: Optional[str]
    commit_barrier_id: Optional[str] = None


@dataclass
class RollbackWitness:
    branch_id: str
    effects: list[str] = field(default_factory=list)
    compensations: list[Compensation] = field(default_factory=list)


def validate_witness(w: RollbackWitness) -> None:
    # Completeness: every effect has a compensation.
    covered = {c.effect_id for c in w.compensations}
    missing = [e for e in w.effects if e not in covered]
    if missing:
        raise UnsoundRollbackWitness(
            f"branch {w.branch_id}: incomplete witness, effects {missing} have no compensation"
        )

    for c in w.compensations:
        # Soundness: inverse must prove it restored the exact precondition state.
        if c.postcondition_hash is None or c.postcondition_hash != c.precondition_hash:
            raise UnsoundRollbackWitness(
                f"branch {w.branch_id}: unsound inverse for effect {c.effect_id}; "
                f"postcondition {c.postcondition_hash} != precondition {c.precondition_hash}"
            )
        # Idempotency: reconciler crash-replay must be a no-op.
        if not c.compensation_idempotency_key:
            raise UnsoundRollbackWitness(
                f"branch {w.branch_id}: compensation for {c.effect_id} lacks idempotency key; "
                f"replay would double-apply"
            )
        # Ordering closure: compensation must be barriered against the commit phase.
        if not c.commit_barrier_id:
            raise UnsoundRollbackWitness(
                f"branch {w.branch_id}: compensation for {c.effect_id} has no commit barrier; "
                f"interleaving with winning commit is unconstrained"
            )


def reconcile(w: RollbackWitness, commit_token: str) -> str:
    validate_witness(w)
    # Only reachable when witness is complete, sound, ordering-closed, idempotent.
    # Caller must hold commit_token serialization lock before invoking.
    return hashlib.sha256(commit_token.encode()).hexdigest()
