# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-membership-drift-is-silently-invalidating-byzantine-commit-certificates-in-multi-agent-task-ledgers.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-membership-drift-is-silently-invalidating-byzantine-commit-certificates-in-multi-agent-task-ledgers.warrant.json
# Markdown SHA-256:   8f6e89d1eb76255df4d6b872826f627bcdd4bb0757a2c98622c698ce752e2fff
# Code AST SHA-256:   d289431ef39d3719a46d1f011e943e54865f1b0928397ac79da7db7e3e5f8994
# Verified Classes:   EpochUnresolvable, EpochAheadOfLocalView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EpochUnresolvable(RuntimeError):
    """Raised when a certificate's epoch cannot be resolved to a membership snapshot.
    Must halt audit, NOT signal invalidity to the proposal layer."""
    pass


class EpochAheadOfLocalView(RuntimeError):
    """Verifier is lagging the certificate's epoch. Must sync, not reject."""
    pass


def verify_commit_certificate(cert, verifier_epoch, membership_store):
    """
    Two-phase BFT certificate verification.
    Phase 1: resolve membership snapshot for cert.epoch (deterministic).
    Phase 2: count signatures against THAT snapshot only.
    """
    # --- Phase 1: epoch resolution (no LLM judgment permitted here) ---
    if cert.epoch > verifier_epoch:
        raise EpochAheadOfLocalView(
            f"cert epoch {cert.epoch} ahead of local view {verifier_epoch}; "
            f"sync required before verification"
        )

    snapshot = membership_store.get_snapshot(cert.epoch)
    if snapshot is None:
        # Historical membership unavailable. Do NOT fall back to current registry.
        raise EpochUnresolvable(
            f"no membership snapshot for epoch {cert.epoch}; "
            f"refusing to verify against current epoch {verifier_epoch} registry"
        )

    # --- Phase 2: signature count against the resolved snapshot ---
    recognized = [s for s in cert.signers if s in snapshot.validators]
    if len(recognized) < snapshot.quorum:
        # Genuine invalidity under the correct epoch -> safe to reject.
        return False
    return True


def audit_task_commitment(cert, verifier_epoch, membership_store, proposal_layer):
    try:
        valid = verify_commit_certificate(cert, verifier_epoch, membership_store)
    except (EpochUnresolvable, EpochAheadOfLocalView) as e:
        # HALT: propagate to orchestrator as a sync/recovery signal.
        # Critically, do NOT call proposal_layer.reject() -- that triggers re-proposal
        # and the double-commit cascade observed in T-4471.
        raise type(e)(f"audit halted for {cert.task_id}: {e}") from e

    if not valid:
        proposal_layer.reject(cert.task_id)
    return valid
