# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-plan-commitment-that-has-reached-byzantine-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-plan-commitment-that-has-reached-byzantine-quorum.warrant.json
# Markdown SHA-256:   9b852d1bad4d0a262c0f9c178dda22708dbb9c188245b3dd0d31e5004f576aa8
# Code AST SHA-256:   7075c9fc173afe524c64618ed713f2706911523efb6684a48504151129f0e055
# Verified Classes:   UnsoundCommitmentError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsoundCommitmentError(RuntimeError):
    """Raised when a quorum-certified plan is locally refutable."""
    def __init__(self, plan_id: str, precondition: str, evidence: str):
        self.plan_id = plan_id
        self.precondition = precondition
        self.evidence = evidence
        super().__init__(
            f"Plan {plan_id} has valid quorum but precondition "
            f"'{precondition}' is locally refuted: {evidence}"
        )


def decide_commitment(
    plan,
    certificate,
    local_evidence,
    quorum_size: int,
    voted_commit: bool,
    now: float,
) -> str:
    # 1. Classical safety: certificate must be cryptographically and
    #    arithmetically valid.
    if not certificate.verify(quorum=quorum_size):
        raise UnsoundCommitmentError(
            plan.id, "quorum", "certificate failed verification"
        )

    # 2. Validity boundary: a committer may not reject on validity grounds.
    if voted_commit:
        return "commit"  # rejection here would be a protocol violation

    # 3. Check local refutation against plan preconditions.
    for pre in plan.preconditions:
        ev = local_evidence.get(pre.key)
        if ev is None:
            continue
        fresh = (now - ev.timestamp) <= plan.validity_window
        specific = ev.refutes(pre)  # evidence targets this precondition
        independent = ev.source_is_local()  # not peer-supplied
        if fresh and specific and independent:
            raise UnsoundCommitmentError(
                plan.id, pre.key, ev.describe()
            )
        # stale or non-specific evidence: do not reject, flag re-read
        if not fresh or not specific:
            return "commit_with_reread"

    return "commit"
