# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-late-speculative-fan-out-branches-rather-than-wait-for-consensus-arbitration.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-late-speculative-fan-out-branches-rather-than-wait-for-consensus-arbitration.warrant.json
# Markdown SHA-256:   2fcf3a4588df9a1f8877e0f256640394fad31fb5c4fcad010dfe20a967055acd
# Code AST SHA-256:   7a2159338858a45a710d94f6a81f24e2b82c159323712d9bab91537d4618dea3
# Verified Classes:   ConsensusInvariantError, LateCommitFromAbandonedBranch, Branch, ArbitrationRound
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class ConsensusInvariantError(RuntimeError):
    """Raised when arbitration would violate the issued-set quorum invariant."""


class LateCommitFromAbandonedBranch(ConsensusInvariantError):
    """A branch abandoned for latency attempted to commit after arbitration."""


@dataclass
class Branch:
    id: str
    issued_at: float
    completed_at: float | None = None
    abandoned: bool = False
    fenced: bool = False
    shard: str = ""
    candidate: object | None = None


@dataclass
class ArbitrationRound:
    issued: list[Branch]
    quorum: int
    deadline: float
    committed: bool = False
    ledger: list[dict] = field(default_factory=list)

    def _survivors(self) -> list[Branch]:
        return [b for b in self.issued if b.completed_at is not None and not b.abandoned]

    def _independent(self, survivors: Sequence[Branch]) -> bool:
        # Independence is a measured property; here approximated by shard diversity.
        return len({b.shard for b in survivors}) == len(survivors)

    def abandon_late(self, now: float) -> list[Branch]:
        dropped = []
        for b in self.issued:
            if b.completed_at is None and not b.abandoned and now >= self.deadline:
                b.abandoned = True
                b.fenced = True  # fence before arbitration commits
                dropped.append(b)
        return dropped

    def arbitrate(self, now: float) -> dict:
        if self.committed:
            raise ConsensusInvariantError("round already committed; re-arbitration would double-count")

        # Any late commit from an abandoned branch invalidates the round.
        for b in self.issued:
            if b.abandoned and b.completed_at is not None:
                raise LateCommitFromAbandonedBranch(
                    f"branch {b.id} committed at {b.completed_at} after abandonment; "
                    f"ledger no longer reflects issued set"
                )

        survivors = self._survivors()
        if len(survivors) < self.quorum:
            # Fail closed against the ISSUED-set quorum. Do not shrink the denominator.
            return {
                "status": "unresolved",
                "reason": "surviving_below_issued_quorum",
                "surviving": len(survivors),
                "quorum": self.quorum,
                "issued": len(self.issued),
            }

        if not self._independent(survivors):
            raise ConsensusInvariantError(
                "survivors are correlated (shared shard); agreement is not evidence of correctness"
            )

        winner = max(survivors, key=lambda b: b.completed_at or 0.0)
        self.committed = True
        self.ledger.append({
            "winner": winner.id,
            "surviving": len(survivors),
            "issued": len(self.issued),
            "quorum": self.quorum,
        })
        return {"status": "achieved", "winner": winner.id, "agreement": f"{len(survivors)}/{len(self.issued)}"}


def run_round(branches: list[Branch], quorum: int, deadline: float, now: float) -> dict:
    rnd = ArbitrationRound(issued=branches, quorum=quorum, deadline=deadline)
    rnd.abandon_late(now)
    return rnd.arbitrate(now)
