# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-commit-divergence-when-optimistic-quorum-certificates-race-cross-org-byzantine-auditors.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-commit-divergence-when-optimistic-quorum-certificates-race-cross-org-byzantine-auditors.warrant.json
# Markdown SHA-256:   7bc3296fa7743790763f33eb58494f601bcbbb2ab76fdd6d3e254edb58156e8b
# Code AST SHA-256:   18f946ff163c81cfd66e4d0b6921fe01675b3b0a1b2c3fa9e0cf50c9a02e2c39
# Verified Classes:   QuorumStabilityViolation, Signer, OQC
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class QuorumStabilityViolation(RuntimeError):
    """Raised when a speculative commit would outlive its OQC's warrant set."""
    pass


@dataclass
class Signer:
    org: str
    signer_id: str
    warrant_expiry: float  # monotonic seconds


@dataclass
class OQC:
    signers: list[Signer]
    threshold: int


def assert_quorum_stable(
    oqc: OQC,
    now: float,
    delta_audit_max: float | None,
    epsilon_safety: float = 0.050,
) -> None:
    """
    Enforce the quorum-stability invariant before speculative commit.

    Speculation is sound only if the signer set valid across the full audit
    window still meets threshold. Otherwise the caller must downgrade to
    finality-gated commit.
    """
    if delta_audit_max is None:
        raise QuorumStabilityViolation(
            "cross-org audit latency unknown; speculation unprovable, "
            "downgrade to finality-gated commit"
        )

    horizon = now + delta_audit_max + epsilon_safety
    stable_signers = [s for s in oqc.signers if s.warrant_expiry > horizon]

    if len(stable_signers) < oqc.threshold:
        lapsing = [s.signer_id for s in oqc.signers if s.warrant_expiry <= horizon]
        raise QuorumStabilityViolation(
            f"OQC has {len(oqc.signers)} signers but only "
            f"{len(stable_signers)} remain valid across audit window "
            f"{delta_audit_max:.3f}s; threshold={oqc.threshold}; "
            f"lapsing={lapsing}. Speculative commit would diverge at audit."
        )


def speculative_commit(
    oqc: OQC,
    delta_audit_max: float | None,
    dispatch_side_effect,
) -> str:
    now = time.monotonic()
    try:
        assert_quorum_stable(oqc, now, delta_audit_max)
    except QuorumStabilityViolation:
        # Downgrade: wait for audit, then commit. Caller handles slow path.
        return "FINALITY_GATED"

    dispatch_side_effect()
    return "SPECULATIVE_COMMITTED"
