# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-equivocating-agent-s-partial-commit-as-a-committed-but-poisoned-write-rather-than-a-crash-fault-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-equivocating-agent-s-partial-commit-as-a-committed-but-poisoned-write-rather-than-a-crash-fault-rollback.warrant.json
# Markdown SHA-256:   36951fb6edff18e413f574ee84b5e788c652b15cfe39e48b823528520c1701d3
# Code AST SHA-256:   24c2c1c12284cf9757652c079704b31c0108d1db6b8919bb71631fdbf4831c2b
# Verified Classes:   EquivocationWitnessError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EquivocationWitnessError(RuntimeError):
    """Raised when a finalized outcome's witness set double-counts an agent
    with divergent signed votes, making crash-fault rollback unsound."""
    pass


def classify_divergence(
    outcome_a: dict,   # {"value": str, "witness": dict[agent_id -> signed_vote]}
    outcome_b: dict,
    reachable: set,
    quorum: int,
) -> str:
    wa, wb = outcome_a["witness"], outcome_b["witness"]
    overlap = set(wa) & set(wb)

    if not overlap:
        # Disjoint witnesses: at most one can have reached quorum honestly.
        if len(wa) >= quorum and len(wb) >= quorum:
            raise EquivocationWitnessError(
                f"two quorums with disjoint witnesses: {sorted(wa)} vs {sorted(wb)}"
            )
        return "single_valid_outcome"

    for agent in overlap:
        if agent in reachable and wa[agent] != wb[agent]:
            # Live agent, divergent signatures -> committed-but-poisoned.
            return "poisoned_write"

    # Overlap exists but no live divergent signer: crash-fault rollback is sound.
    return "crash_fault_rollback"


def resolve(outcome_a, outcome_b, reachable, quorum):
    verdict = classify_divergence(outcome_a, outcome_b, reachable, quorum)
    if verdict == "poisoned_write":
        poisoned = set(outcome_a["witness"]) ^ set(outcome_b["witness"])
        raise EquivocationWitnessError(
            f"poisoned write at task key; exclude {sorted(poisoned)} from recovery quorum"
        )
    return verdict
