# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-result-before-its-quorum-certificate-is-durably-replicated-the-attestation-before-quorum-race-in-bft-a.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-result-before-its-quorum-certificate-is-durably-replicated-the-attestation-before-quorum-race-in-bft-a.warrant.json
# Markdown SHA-256:   4994c69414c981b1459062c5d725f70c6d86d1d00df510535a8f8e7adcb47de9
# Code AST SHA-256:   27090141dfb3f8b7c073eac64b7aea36f8610bb3cdcc59fafc4f422dd0d5365d
# Verified Classes:   PhantomCommitmentError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class PhantomCommitmentError(RuntimeError):
    """Raised when an instance attempts to emit an externally visible
    commitment before its quorum certificate is durably replicated to
    >= 2f+1 peers (including self), or when a view-change re-proposal
    finds an in-flight certificate and mints a divergent nonce."""
    pass


def emit_commitment(
    task_id: str,
    result_nonce: str,
    durable_receipts: set[str],
    expected_quorum: int,
    irreversible_downstream: bool,
    view_number: int,
) -> str:
    """
    Enforce the quorum-durability invariant before any externally visible
    commitment is emitted.

    durable_receipts: peer IDs that have fsync-acknowledged the commit
        certificate for (task_id, result_nonce, view_number).
    expected_quorum: 2f+1 for the configured n >= 3f+1 swarm.
    """
    if len(durable_receipts) < expected_quorum:
        raise PhantomCommitmentError(
            f"task {task_id} nonce {result_nonce} view {view_number}: "
            f"only {len(durable_receipts)} durable receipts, need "
            f"{expected_quorum}. Emitting now would create a phantom "
            f"commitment unreconstructible after crash."
        )

    if irreversible_downstream and len(durable_receipts) < expected_quorum:
        # Defensive: irreversible effects require the full quorum, not
        # merely a locally-collected signature set.
        raise PhantomCommitmentError(
            f"task {task_id}: irreversible downstream effect requires "
            f"durable quorum before emission."
        )

    # Nonce must be bound to the view that attested it; a re-proposal in a
    # new view must adopt the existing certificate's nonce, not mint fresh.
    if not result_nonce.endswith(f":v{view_number}"):
        raise PhantomCommitmentError(
            f"task {task_id}: nonce {result_nonce} not bound to view "
            f"{view_number}; divergent nonce would break downstream "
            f"provenance on replay."
        )

    return result_nonce


def handle_view_change_reproposal(
    task_id: str,
    in_flight_certificates: dict[str, str],
    proposed_nonce: str,
) -> str:
    """
    On view change, the new primary must adopt any existing durable
    certificate's nonce rather than re-minting one.
    """
    if task_id in in_flight_certificates:
        existing_nonce = in_flight_certificates[task_id]
        if proposed_nonce != existing_nonce:
            raise PhantomCommitmentError(
                f"task {task_id}: re-proposal minted nonce {proposed_nonce} "
                f"but durable certificate holds {existing_nonce}; "
                f"downstream artifacts bound to the old nonce would "
                f"become unverifiable."
            )
        return existing_nonce
    return proposed_nonce
