# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-certified-plan-forks-when-a-byzantine-planner-replays-divergent-sub-plans-to-disjoint-agent-cohorts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-certified-plan-forks-when-a-byzantine-planner-replays-divergent-sub-plans-to-disjoint-agent-cohorts.warrant.json
# Markdown SHA-256:   2180cbcbb0509392c60cbd9bb6a39bef11db0d0772042f953e6218b72f4ce577
# Code AST SHA-256:   78eb69bd8b7f277aeed35d277868d71128a3009a6b0b4a4ea99f379da7ffa905
# Verified Classes:   PlanRootForkDetected, Attestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class PlanRootForkDetected(RuntimeError):
    """Raised when cohorts cannot agree on a single committed plan root."""


@dataclass(frozen=True)
class Attestation:
    cohort_id: str
    sub_plan_hash: str
    root: str          # commitment to the full DAG this result belongs to
    result_hash: str


def commit_root(plan_dag: str) -> str:
    return hashlib.sha256(plan_dag.encode()).hexdigest()


def establish_committed_root(
    cohort_roots: dict[str, str],
    quorum: int,
) -> str:
    """Phase 1: agree on ONE root before any sub-plan dispatches.

    cohort_roots maps cohort_id -> root that cohort independently received
    from the planner. If no single root reaches quorum, the planner is
    equivocating (or restarted non-deterministically): abort before execution.
    """
    tally: dict[str, int] = {}
    for root in cohort_roots.values():
        tally[root] = tally.get(root, 0) + 1

    winner, count = max(tally.items(), key=lambda kv: kv[1])
    if count < quorum:
        raise PlanRootForkDetected(
            f"no root reached quorum {quorum}; tally={tally}. "
            f"Planner issued divergent DAGs to disjoint cohorts; "
            f"aborting before any sub-plan executes."
        )
    return winner


def certify_result(
    att: Attestation,
    committed_root: str,
    quorum_attestations: list[Attestation],
) -> bool:
    """Phase 2: count quorum over (root, sub_plan, result), never results alone."""
    if att.root != committed_root:
        raise PlanRootForkDetected(
            f"attestation from {att.cohort_id} bound to root {att.root[:12]} "
            f"but committed root is {committed_root[:12]}; "
            f"result belongs to a foreign world and cannot count toward quorum."
        )

    agreeing = [
        a for a in quorum_attestations
        if a.root == committed_root
        and a.sub_plan_hash == att.sub_plan_hash
        and a.result_hash == att.result_hash
    ]
    return len(agreeing) >= 2  # cohort-level quorum, f=1 of 3
