# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-when-a-byzantine-quorum-reports-task-success-but-the-local-grounding-ledger-disagrees.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-when-a-byzantine-quorum-reports-task-success-but-the-local-grounding-ledger-disagrees.warrant.json
# Markdown SHA-256:   75b891f3945a1ccd81e013ead1e9790d4706d78fe464cae800e18f5b38bca2e3
# Code AST SHA-256:   be95d059448e0eae42196d94d5b853636d5f8d0551a2d4665baa658061419c0c
# Verified Classes:   GroundingConflict, LivenessHazard, Receipt, GroundingLedger, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class GroundingConflict(RuntimeError):
    """Raised when a valid BFT quorum disagrees with locally verifiable grounding."""
    pass


class LivenessHazard(RuntimeError):
    """Raised when refusal conditions are not met but commit is also unsafe."""
    pass


@dataclass
class Receipt:
    stage: str
    resp_id: str
    digest: str
    timestamp: float


@dataclass
class GroundingLedger:
    entries: list = field(default_factory=list)

    def latest(self, stage: str) -> Optional[Receipt]:
        for r in reversed(self.entries):
            if r.stage == stage:
                return r
        return None

    def append(self, receipt: Receipt) -> None:
        self.entries.append(receipt)


@dataclass
class Attestation:
    node_id: str
    stage: str
    output_digest: str
    postcondition_locally_checkable: bool


def commit_task(
    task_id: str,
    stage: str,
    attestations: list,
    quorum: int,
    ledger: GroundingLedger,
    quorum_formed_at: float,
) -> str:
    """
    Commit a task stage under BFT quorum, subject to the grounding invariant.

    Refuses to overwrite the local ledger when a valid quorum disagrees with a
    pre-attestation local receipt on a locally-checkable postcondition.
    """
    # Tally quorum on output_digest.
    tally: dict = {}
    for a in attestations:
        tally[a.output_digest] = tally.get(a.output_digest, 0) + 1
    if not tally:
        raise LivenessHazard(f"{task_id}:{stage} no attestations; cannot commit")
    quorum_digest, count = max(tally.items(), key=lambda kv: kv[1])
    quorum_reached = count >= quorum

    local = ledger.latest(stage)
    locally_checkable = all(a.postcondition_locally_checkable for a in attestations)

    # Validity condition 2: local receipt must predate the attestation window.
    has_prior_receipt = local is not None and local.timestamp < quorum_formed_at

    # Validity condition 1 + 3: hard digest mismatch on a checkable predicate.
    hard_mismatch = (
        locally_checkable
        and has_prior_receipt
        and local.digest != quorum_digest
    )

    if quorum_reached and hard_mismatch:
        # Row 2 of the decision boundary: refuse, preserve evidence, escalate.
        raise GroundingConflict(
            f"{task_id}:{stage} quorum digest={quorum_digest} "
            f"conflicts with local receipt resp_id={local.resp_id} "
            f"digest={local.digest} at t={local.timestamp}; "
            f"refusing commit, preserving ledger, escalating decorrelated audit"
        )

    if quorum_reached:
        # Safe commit. Only overwrite ledger if it does not already hold
        # a contradicting pre-attestation receipt.
        if local is None or local.digest == quorum_digest:
            ledger.append(Receipt(
                stage=stage,
                resp_id=f"commit:{task_id}",
                digest=quorum_digest,
                timestamp=quorum_formed_at,
            ))
        return quorum_digest

    # Quorum not reached.
    if local is not None and locally_checkable:
        # Commit on local grounding alone only when idempotent+verifiable.
        return local.digest
    raise LivenessHazard(
        f"{task_id}:{stage} no quorum ({count}/{quorum}) and no local grounding; "
        f"failing closed"
    )
