# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-quorum-weight-when-byzantine-peers-return-heterogeneous-typed-outputs-under-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-quorum-weight-when-byzantine-peers-return-heterogeneous-typed-outputs-under-bft-consensus.warrant.json
# Markdown SHA-256:   e5bae1fcfcece756dd289e6aa550e95ddfda892e8b5a912be517fa8acd59cace
# Code AST SHA-256:   bbc902c0ae9c604987d09c3159343434188c0ee3a0c9b274f2307126decb2c33
# Verified Classes:   QuorumCoercionError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class QuorumCoercionError(RuntimeError):
    """Raised when a round's tally would require normalizing non-conforming
    outputs into the canonical vote space, assigning weight to values no
    replica cast in typed form."""
    pass


SCHEMA_KEYS = {"intent": str, "confidence": float, "target": str}


def validate_vote(raw: dict) -> dict:
    """Return a canonical vote, or raise if the output is not schema-conformant.
    No coercion, no default-filling, no regex extraction."""
    if not isinstance(raw, dict):
        raise QuorumCoercionError(f"non-object output: {type(raw).__name__}")
    extra = set(raw) - set(SCHEMA_KEYS)
    missing = set(SCHEMA_KEYS) - set(raw)
    if extra or missing:
        raise QuorumCoercionError(f"schema mismatch extra={extra} missing={missing}")
    for key, typ in SCHEMA_KEYS.items():
        if not isinstance(raw[key], typ) or isinstance(raw[key], bool):
            raise QuorumCoercionError(
                f"type violation on {key!r}: got {type(raw[key]).__name__}, want {typ.__name__}"
            )
    return {k: raw[k] for k in SCHEMA_KEYS}


def tally(outputs: list[dict], n: int, f: int) -> dict:
    """Tally only type-admissible votes. Type violations consume the fault budget.
    Abort if violations exceed f — do not normalize, do not resolve."""
    if n < 3 * f + 1:
        raise QuorumCoercionError(f"n={n} cannot tolerate f={f}")
    votes, violations = [], 0
    for raw in outputs:
        try:
            votes.append(validate_vote(raw))
        except QuorumCoercionError:
            violations += 1
    if violations > f:
        raise QuorumCoercionError(
            f"type violations {violations} exceed fault budget f={f}; "
            f"round aborted, no certificate issued"
        )
    counts: dict[str, int] = {}
    for v in votes:
        counts[v["target"]] = counts.get(v["target"], 0) + 1
    winner, weight = max(counts.items(), key=lambda kv: kv[1])
    if weight < 2 * f + 1:
        raise QuorumCoercionError(
            f"no target reaches quorum 2f+1={2 * f + 1}; max={weight} for {winner!r}"
        )
    return {"target": winner, "weight": weight, "violations": violations}
