# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-consensus-gated-speculative-task-graph-when-a-quorum-visible-branch-commits-against-an-uncommitted-speculat.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-consensus-gated-speculative-task-graph-when-a-quorum-visible-branch-commits-against-an-uncommitted-speculat.warrant.json
# Markdown SHA-256:   9ce7e9693dd0ed8b15377dc0f9cb557558a0f9ff9543a6fb0ff3c36cbf1ca9bf
# Code AST SHA-256:   a487652440d5ca256f04c4264b21b9f2c3477cb29117f04529291d175f0f8c0b
# Verified Classes:   NodeState, CommitSafetyError, TaskNode, CommitLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Optional, Set


class NodeState(Enum):
    SPECULATIVE = "speculative"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"


class CommitSafetyError(RuntimeError):
    """Raised when a consensus-gated commit violates ancestry-closure."""
    pass


@dataclass
class TaskNode:
    node_id: str
    parent_id: Optional[str]
    state: NodeState
    payload_consumes_parent: bool  # is parent output load-bearing in committed payload?


class CommitLedger:
    def __init__(self) -> None:
        self.nodes: Dict[str, TaskNode] = {}

    def add(self, node: TaskNode) -> None:
        self.nodes[node.node_id] = node

    def ancestors(self, node_id: str) -> List[str]:
        chain: List[str] = []
        cur = self.nodes[node_id].parent_id
        while cur is not None:
            chain.append(cur)
            cur = self.nodes[cur].parent_id
        return chain

    def commit(self, node_id: str, quorum: Set[str]) -> None:
        node = self.nodes[node_id]
        if len(quorum) < 2:
            raise CommitSafetyError(f"quorum too small for {node_id}: {quorum}")

        # Ancestry-closure check must be atomic with the commit write.
        for anc_id in self.ancestors(node_id):
            anc = self.nodes[anc_id]
            if anc.state is NodeState.COMMITTED:
                continue
            if anc.state is NodeState.ROLLED_BACK:
                if node.payload_consumes_parent:
                    # Load-bearing orphan: laundering a rejected judgment. Abort.
                    raise CommitSafetyError(
                        f"cannot commit {node_id}: load-bearing parent {anc_id} "
                        f"is ROLLED_BACK; commit would launder rejected output"
                    )
                # Informational edge: repair lineage to nearest committed ancestor.
                self._repair_edge(node_id)
                break
            if anc.state is NodeState.SPECULATIVE:
                raise CommitSafetyError(
                    f"ancestry-closure violated: {node_id} has uncommitted "
                    f"speculative ancestor {anc_id}; commit parent first"
                )

        node.state = NodeState.COMMITTED

    def _repair_edge(self, node_id: str) -> None:
        node = self.nodes[node_id]
        cur = node.parent_id
        while cur is not None and self.nodes[cur].state is not NodeState.COMMITTED:
            cur = self.nodes[cur].parent_id
        node.parent_id = cur  # may be None if no committed ancestor exists


def verify_committed_graph(ledger: CommitLedger) -> None:
    """Replay verifier: reject any committed node with a non-committed ancestor
    that was load-bearing, or any dangling edge that escaped repair."""
    for node in ledger.nodes.values():
        if node.state is not NodeState.COMMITTED:
            continue
        for anc_id in ledger.ancestors(node.node_id):
            anc = ledger.nodes[anc_id]
            if anc.state is not NodeState.COMMITTED:
                if node.payload_consumes_parent:
                    raise CommitSafetyError(
                        f"replay found load-bearing orphan: {node.node_id} "
                        f"depends on non-committed {anc_id} ({anc.state.value})"
                    )
                raise CommitSafetyError(
                    f"replay found unrepaired informational edge: "
                    f"{node.node_id} -> {anc_id} ({anc.state.value})"
                )
