# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-byzantine-resistant-quorum-from-committing-a-speculatively-planned-action-when-the-plan-s-provenance-dag-is-acyclic-but-its.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-byzantine-resistant-quorum-from-committing-a-speculatively-planned-action-when-the-plan-s-provenance-dag-is-acyclic-but-its.warrant.json
# Markdown SHA-256:   9e6a2af3cbebc1f165e3cc03be383f4e47f148affec6a57a842b4bd208121a84
# Code AST SHA-256:   df2e9756c7ffbcac6329ce795a646d66fa41f355fe82b78ff383f3e0a58991de
# Verified Classes:   UnsoundQuorumCommit, PlanNode, Plan, VerifierVote, CommitDecision
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class UnsoundQuorumCommit(RuntimeError):
    """Raised when a quorum commits a plan the executor cannot soundly admit."""


@dataclass(frozen=True)
class PlanNode:
    node_id: str
    reads: FrozenSet[str] = frozenset()
    writes: FrozenSet[str] = frozenset()
    exclusive_resources: FrozenSet[str] = frozenset()


@dataclass(frozen=True)
class Plan:
    nodes: tuple
    edges: FrozenSet[tuple]  # (from_id, to_id), provenance DAG


@dataclass(frozen=True)
class VerifierVote:
    verifier_id: str
    snapshot_version: int
    commit: bool


@dataclass
class CommitDecision:
    plan_hash: str
    snapshot_version: int
    lease_set: FrozenSet[str]
    token: str


def _provenance_acyclic(plan: Plan) -> bool:
    # Kahn's algorithm over provenance edges only.
    indeg = {n.node_id: 0 for n in plan.nodes}
    adj = {n.node_id: [] for n in plan.nodes}
    for a, b in plan.edges:
        adj[a].append(b)
        indeg[b] += 1
    ready = [n for n, d in indeg.items() if d == 0]
    seen = 0
    while ready:
        cur = ready.pop()
        seen += 1
        for nxt in adj[cur]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                ready.append(nxt)
    return seen == len(plan.nodes)


def _resource_conflicts(plan: Plan) -> FrozenSet[str]:
    # Any exclusive resource touched by two provenance-independent nodes
    # is a hidden execution-order dependency the DAG did not model.
    conflicts = set()
    for i, a in enumerate(plan.nodes):
        for b in plan.nodes[i + 1:]:
            if (a.node_id, b.node_id) in plan.edges or (b.node_id, a.node_id) in plan.edges:
                continue
            shared = a.exclusive_resources & b.exclusive_resources
            if shared:
                conflicts.update(f"{r}:{a.node_id}|{b.node_id}" for r in shared)
    return frozenset(conflicts)


def commit(
    plan: Plan,
    votes: list,
    commit_threshold: int,
    expected_snapshot_version: int,
) -> CommitDecision:
    if not _provenance_acyclic(plan):
        raise UnsoundQuorumCommit("plan provenance DAG is cyclic; cannot speculate")

    conflicts = _resource_conflicts(plan)
    if conflicts:
        raise UnsoundQuorumCommit(
            f"provenance-independent nodes share exclusive resources: {sorted(conflicts)}"
        )

    # Votes on a stale snapshot are abstentions, not commits.
    aligned = [v for v in votes if v.snapshot_version == expected_snapshot_version and v.commit]
    if len(aligned) < commit_threshold:
        raise UnsoundQuorumCommit(
            f"only {len(aligned)} votes on snapshot {expected_snapshot_version}; "
            f"threshold {commit_threshold} not met by coherent voters"
        )

    plan_hash = hashlib.sha256(
        repr((plan.edges, [(n.node_id, n.reads, n.writes, n.exclusive_resources) for n in plan.nodes])).encode()
    ).hexdigest()
    lease_set = frozenset(r for n in plan.nodes for r in n.exclusive_resources)
    token = hashlib.sha256(
        f"{plan_hash}|{expected_snapshot_version}|{sorted(lease_set)}".encode()
    ).hexdigest()
    return CommitDecision(plan_hash, expected_snapshot_version, lease_set, token)


def executor_admit(decision: CommitDecision, plan: Plan, live_snapshot_version: int) -> None:
    # Executor's admission predicate must be a subset of the commit predicate.
    if live_snapshot_version != decision.snapshot_version:
        raise UnsoundQuorumCommit(
            f"snapshot drifted: committed {decision.snapshot_version}, live {live_snapshot_version}"
        )
    if _resource_conflicts(plan):
        raise UnsoundQuorumCommit("committed plan carries unmodeled resource conflict")
    expected = hashlib.sha256(
        f"{decision.plan_hash}|{decision.snapshot_version}|{sorted(decision.lease_set)}".encode()
    ).hexdigest()
    if expected != decision.token:
        raise UnsoundQuorumCommit("commit token does not bind plan, snapshot, and lease set")
