# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-speculative-pre-execution-divergence-before-byzantine-quorum-commit-in-federated-agent-scheduling.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-speculative-pre-execution-divergence-before-byzantine-quorum-commit-in-federated-agent-scheduling.warrant.json
# Markdown SHA-256:   282b6edbe93c9ddad371dca0b49da2cc60ab584bf17b939aa9a35e8dc987947e
# Code AST SHA-256:   739841204c3d5205027bec8865814a3386b7a60c3c348aee40a281b0baf78307
# Verified Classes:   SpeculativeDivergenceError, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SpeculativeDivergenceError(RuntimeError):
    """Raised when speculative pre-execution cannot be committed under Byzantine quorum
    because lineage skew exceeds the tolerated Byzantine budget."""


@dataclass(frozen=True)
class Attestation:
    agent_id: str
    pre_state_hash: str
    output_hash: str
    trace_hash: str


def commit_speculative(
    lineage_hash: str,
    attestations: list[Attestation],
    n: int,
    f: int,
) -> str:
    """Commit a speculative step only if the residual honest set attests to the
    composite (pre_state, output, trace) triple and still meets the Byzantine quorum.

    quorum = ceil(2N/3) + 1
    """
    quorum = (2 * n) // 3 + 1

    # Partition by pre-state agreement with the dispatched canonical lineage.
    aligned = [a for a in attestations if a.pre_state_hash == lineage_hash]
    skewed = [a for a in attestations if a.pre_state_hash != lineage_hash]

    if len(skewed) > f:
        # Skew exceeds Byzantine budget: indistinguishable from forged lineage.
        # Must abandon speculation and force a synchronous lineage barrier.
        raise SpeculativeDivergenceError(
            f"lineage skew {len(skewed)} exceeds Byzantine budget f={f} "
            f"for lineage {lineage_hash}; fall back to synchronous execution"
        )

    if len(aligned) < quorum:
        raise SpeculativeDivergenceError(
            f"aligned set {len(aligned)} below quorum {quorum} after excluding "
            f"{len(skewed)} skewed agents; cannot commit speculatively"
        )

    # Composite agreement: pre_state + output + trace must all match within aligned set.
    keys = {(a.output_hash, a.trace_hash) for a in aligned}
    if len(keys) != 1:
        raise SpeculativeDivergenceError(
            f"aligned agents disagree on composite attestation: {len(keys)} distinct "
            f"(output, trace) pairs among {len(aligned)} agents"
        )

    output_hash, trace_hash = keys.pop()
    return hashlib.sha256(
        f"{lineage_hash}:{output_hash}:{trace_hash}".encode()
    ).hexdigest()
