# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-branch-pruning-when-byzantine-merge-finality-outruns-local-verification-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-branch-pruning-when-byzantine-merge-finality-outruns-local-verification-quorum.warrant.json
# Markdown SHA-256:   c15a5ff62d7306363ccbecbe5528f8c0549069ffb31da2a78b0e8b57ed47c5d7
# Code AST SHA-256:   be8a9501107ec9ce49e61c5f5c96436837dd5b00249c5115170fac5c9240d1b7
# Verified Classes:   FinalityInversionError, Branch, QuorumState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class FinalityInversionError(RuntimeError):
    """Raised when a branch would be reclaimed before its merge finality is resolved."""


@dataclass
class Branch:
    plan_seed: str
    parent_root: str
    score: float
    ticks_below: int = 0

    @property
    def branch_id(self) -> str:
        # Content-addressed: a respawned attempt can never alias an in-flight cert.
        h = hashlib.sha256(f"{self.plan_seed}:{self.parent_root}".encode()).hexdigest()
        return f"br-{h[:16]}"


@dataclass
class QuorumState:
    k: int
    n: int
    signed_roots: dict = field(default_factory=dict)   # auditor -> root
    refusals: set = field(default_factory=set)          # auditors that signed refusal

    def certificate_root(self) -> Optional[str]:
        counts = {}
        for root in self.signed_roots.values():
            counts[root] = counts.get(root, 0) + 1
        for root, c in counts.items():
            if c >= self.k:
                return root
        return None

    def quorum_impossible(self) -> bool:
        # Impossible only if too few honest signers remain to ever reach k.
        return len(self.refusals) >= (self.n - self.k + 1)


def decide_reclaim(branch: Branch, live_root: str, quorum: QuorumState,
                   score_threshold: float = 0.35, ticks: int = 2) -> str:
    cert = quorum.certificate_root()

    if cert is not None:
        if cert != live_root:
            # Certificate exists but for a different root: identity collision / equivocation.
            raise FinalityInversionError(
                f"certificate root {cert} != live root {live_root} for {branch.branch_id}; "
                "branch_id aliasing detected — refuse to reclaim"
            )
        return "RECLAIM"  # finalized and consistent

    low = branch.score < score_threshold and branch.ticks_below >= ticks
    if low and not quorum.quorum_impossible():
        # The inversion: score decay is a liveness signal, NOT finality evidence.
        raise FinalityInversionError(
            f"branch {branch.branch_id} scored {branch.score} but quorum still possible "
            f"({len(quorum.signed_roots)}/{quorum.n} signed, k={quorum.k}); must HOLD, "
            "not reclaim — force view change on timeout instead"
        )

    if low and quorum.quorum_impossible():
        return "RECLAIM"  # provably dead quorum; safe to free

    return "HOLD"
