# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-quarantine-a-committed-task-when-the-quorum-that-signed-it-has-since-forked-its-view-of-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-quarantine-a-committed-task-when-the-quorum-that-signed-it-has-since-forked-its-view-of-shared-state.warrant.json
# Markdown SHA-256:   8a02d975cc3d8a1edae210b4fcfd690a2b6d4e07c5f7ae4147b2b8e4fa6962ac
# Code AST SHA-256:   0a00de4b4794bb9ecd1e01d5a77114f32abfbe8209ecd778290137cafd4c837e
# Verified Classes:   ViewPoisonedError, CommitCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ViewPoisonedError(RuntimeError):
    """Raised when two valid certificates at the same view carry divergent member sets.

    This is not equivocation by a single agent (handled elsewhere); it is proof that
    the view's membership derivation forked, so no commitment at this view is safe.
    """


@dataclass(frozen=True)
class CommitCertificate:
    task_id: str
    view: int
    member_set: FrozenSet[str]
    signers: FrozenSet[str]
    payload_hash: str
    threshold: int

    def is_valid(self) -> bool:
        # A certificate is valid iff its signers are a subset of its declared
        # member set AND meet the threshold for that member set. Note: this
        # does NOT prove the member set is the *canonical* one for this view.
        return self.signers <= self.member_set and len(self.signers) >= self.threshold


def reconcile(
    local: CommitCertificate,
    incoming: CommitCertificate,
) -> CommitCertificate:
    """Reconcile two certificates. Returns the accepted one, or raises if the
    view is poisoned (Policy S)."""
    if not (local.is_valid() and incoming.is_valid()):
        raise ValueError("cannot reconcile invalid certificate; discard it")

    if local.task_id == incoming.task_id and local.payload_hash == incoming.payload_hash:
        return local  # identical commitment, nothing to do

    if local.view != incoming.view:
        # Different views: adopt the higher-view certificate only if it is
        # a strict extension (its member set is committed by the chain).
        # Without a chain check we cannot safely adopt; escalate.
        raise ViewPoisonedError(
            f"cross-view conflict: local view {local.view} vs incoming {incoming.view}; "
            "require chain-verified adoption, not local max()"
        )

    # Same view, different task or payload.
    if local.member_set != incoming.member_set:
        # THE BOUNDARY: both certificates are internally valid, but they were
        # ratified by different member sets at the same view. This is the
        # quorum-view-divergence failure. Quarantine the view.
        raise ViewPoisonedError(
            f"view {local.view} poisoned: divergent member sets "
            f"{sorted(local.member_set)} vs {sorted(incoming.member_set)}; "
            f"tasks {local.task_id!r} and {incoming.task_id!r} both committed"
        )

    # Same view, same member set, different payload: ordinary equivocation.
    # Handled by slashing the signers in the symmetric difference.
    equivocators = local.signers ^ incoming.signers
    raise ViewPoisonedError(
        f"equivocation at view {local.view} by {sorted(equivocators)}; "
        "slash and re-run commitment with fresh view"
    )
