# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-across-a-trust-boundary-before-the-consensus-quorum-has-acknowledged-the-parent-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-across-a-trust-boundary-before-the-consensus-quorum-has-acknowledged-the-parent-checkpoint.warrant.json
# Markdown SHA-256:   84a72d7ada0dca82376868e34d315f8653ba4ee9064453a6d836e12d9c3ab6b2
# Code AST SHA-256:   3d10f52631fca6e8182239334f0cbb119294a323a9a2fd552cf213c0a8a8df55
# Verified Classes:   UnfencedSpeculativeCommitError, Checkpoint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnfencedSpeculativeCommitError(RuntimeError):
    """Raised when a speculative branch attempts to emit an external effect
    without a commit certificate proving quorum ancestry of every parent
    checkpoint. Signature validity is NOT sufficient."""
    pass


@dataclass(frozen=True)
class Checkpoint:
    branch_id: str
    parent_hash: str
    quorum_attestations: tuple  # instance IDs that acknowledged this checkpoint


def ancestry_is_quorum_committed(
    branch: list[Checkpoint], required_quorum: int
) -> bool:
    """A branch may publish external effects only if every ancestor
    checkpoint carries >= required_quorum attestations. Local contiguity
    and signatures are deliberately NOT checked here."""
    return all(
        len(cp.quorum_attestations) >= required_quorum for cp in branch
    )


def emit_external_effect(
    branch: list[Checkpoint],
    effect_payload: dict,
    required_quorum: int,
    registry_namespace: str,
) -> str:
    """Publish a speculative branch's effect to the shared registry.
    Fails closed when the ancestry is not quorum-committed."""
    if not ancestry_is_quorum_committed(branch, required_quorum):
        # The committing instance saw a locally valid chain, but the
        # ancestry certificate is incomplete. Emitting here produces an
        # orphan that consumers cannot resolve and that pollutes retrieval.
        raise UnfencedSpeculativeCommitError(
            f"branch {branch[-1].branch_id} lacks quorum-committed ancestry "
            f"(required {required_quorum} attestations per checkpoint); "
            f"stage into '{registry_namespace}.staged' or withhold"
        )
    # Idempotency key derives from the COMMITTED ancestor set, so a
    # re-derived effect on the winning branch collides and deduplicates.
    committed_lineage = "|".join(cp.parent_hash for cp in branch)
    idem_key = hashlib.sha256(
        (committed_lineage + repr(sorted(effect_payload.items()))).encode()
    ).hexdigest()
    return f"{registry_namespace}/{idem_key}"
