# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-equivocating-replicas-from-crashed-replicas-in-byzantine-fault-tolerant-task-commitment-without-permanently-stallin.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-equivocating-replicas-from-crashed-replicas-in-byzantine-fault-tolerant-task-commitment-without-permanently-stallin.warrant.json
# Markdown SHA-256:   6828069320a524c3bdc37ca94ff724a5c5b29aea3f37580e53bc1cc98024cf99
# Code AST SHA-256:   991d65887f12849f81a5a1db07d715241c3a1c3a7eb8d88b612e5843464e0f1e
# Verified Classes:   EquivocationUnresolvedError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class EquivocationUnresolvedError(RuntimeError):
    """Raised when a replica's silence cannot be classified as crash vs equivocation
    within the accusation window, and the caller attempts to treat it as a crash
    (which would be a safety violation)."""
    pass


SUSPECT = "suspect"
EXCLUDED = "excluded"
CRASHED = "crashed"


def classify_replica(
    replica_id: str,
    conflict_certificates: int,
    accusation_threshold: int,
    timeout_windows_elapsed: int,
    max_windows: int = 2,
) -> str:
    """
    Decide how to treat a silent replica.

    Returns one of SUSPECT, EXCLUDED, CRASHED.

    Raises EquivocationUnresolvedError if the caller's intent was to declare
    CRASHED while accusations are still accumulating — that is the boundary
    violation this record documents.
    """
    if conflict_certificates >= accusation_threshold:
        return EXCLUDED

    if timeout_windows_elapsed < max_windows:
        # Still within the accusation window: hold the view, do not classify.
        return SUSPECT

    if conflict_certificates > 0:
        # Below threshold but non-zero: equivocation is suspected but unproven.
        # Advancing the view here is permitted ONLY with SUSPECT marking.
        return SUSPECT

    # Zero accusations after the full window: consistent with a true crash.
    return CRASHED


def advance_view_safely(
    replica_id: str,
    conflict_certificates: int,
    accusation_threshold: int,
    timeout_windows_elapsed: int,
    caller_declares_crash: bool,
) -> str:
    classification = classify_replica(
        replica_id,
        conflict_certificates,
        accusation_threshold,
        timeout_windows_elapsed,
    )
    if caller_declares_crash and classification != CRASHED:
        raise EquivocationUnresolvedError(
            f"refusing to declare {replica_id} crashed: "
            f"classification={classification}, "
            f"certificates={conflict_certificates}/{accusation_threshold}, "
            f"windows={timeout_windows_elapsed}. "
            f"Advance view with SUSPECT marking or gather more accusations."
        )
    return classification
