# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-speculative-execution-before-quorum-attestation-the-pre-attestation-divergence-trap-in-consensus-backed-agent-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-speculative-execution-before-quorum-attestation-the-pre-attestation-divergence-trap-in-consensus-backed-agent-swarms.warrant.json
# Markdown SHA-256:   1055e492503bc0db3386ac3e9a4a1a187a12d37a935fb0693f4588a8aa2ac29c
# Code AST SHA-256:   529f74bb6fb43fe576805f79cc406ccf5399f8d177bbfc78c634c0d8b1798642
# Verified Classes:   PreAttestationEmitError, Snapshot, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class PreAttestationEmitError(RuntimeError):
    """Raised when a speculative branch attempts to emit before quorum attestation
    of its base state, under conditions where snapshot intersection is unproven."""


@dataclass(frozen=True)
class Snapshot:
    read_token: str
    base_state_hash: str


@dataclass(frozen=True)
class Branch:
    instance_id: str
    claim: str
    snapshot: Snapshot
    confidence: float
    effect_reversible: bool


def _intersects(a: Snapshot, b: Snapshot) -> bool:
    # Intersection requires a shared read-token; wall-clock proximity is not intersection.
    return a.read_token == b.read_token


def emit_speculative(branch: Branch, quorum: Iterable[Branch]) -> str:
    quorum = list(quorum)

    if not branch.effect_reversible:
        if not all(_intersects(branch.snapshot, q.snapshot) for q in quorum):
            raise PreAttestationEmitError(
                f"instance {branch.instance_id} attempted irreversible emit "
                f"claim={branch.claim!r} base={branch.snapshot.base_state_hash[:8]} "
                f"with unproven snapshot intersection across quorum "
                f"(confidence {branch.confidence:.2f} is not authorization)"
            )

    # Quorum must attest (claim, base_state_hash), not claim alone.
    attested = {
        (q.claim, q.snapshot.base_state_hash)
        for q in quorum
        if _intersects(branch.snapshot, q.snapshot)
    }
    key = (branch.claim, branch.snapshot.base_state_hash)
    if key not in attested:
        raise PreAttestationEmitError(
            f"instance {branch.instance_id} claim={branch.claim!r} "
            f"base={branch.snapshot.base_state_hash[:8]} not attested by "
            f"intersecting quorum; downgrade to propose"
        )

    return hashlib.sha256(f"{branch.instance_id}:{key}".encode()).hexdigest()
