# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-fan-out-orchestrator-silently-accept-a-byzantine-subagent-s-result-when-the-quorum-witness-set-is-itself-drawn-f.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-fan-out-orchestrator-silently-accept-a-byzantine-subagent-s-result-when-the-quorum-witness-set-is-itself-drawn-f.warrant.json
# Markdown SHA-256:   4781c39bf327d6e12dd9b29b45072e62a5b883d56e130d4d0b2bb108a393d3c8
# Code AST SHA-256:   235e5e3be9b19ea92a58509418e5880f0a9dab21bca8347d4c0fea217c13ee87
# Verified Classes:   WitnessIndependenceViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class WitnessIndependenceViolation(RuntimeError):
    """Raised when a reconciliation quorum is drawn from the speculative candidate pool,
    or when a witness has not completed the full verification path."""
    pass


def reconcile_speculative_fanout(
    candidates: dict[str, dict],
    witnesses: list[str],
    f: int,
    required_path_calls: set[str],
) -> dict:
    """
    candidates: branch_id -> {"answer": ..., "completed_calls": set[str]}
    witnesses:  branch ids elected to vote (must be disjoint from candidates)
    f:          tolerated Byzantine faults; quorum size must be >= 2f+1
    """
    if len(witnesses) < 2 * f + 1:
        raise WitnessIndependenceViolation(
            f"quorum too small: {len(witnesses)} witnesses for f={f}, need >= {2*f+1}"
        )

    overlap = set(witnesses) & set(candidates)
    if overlap:
        raise WitnessIndependenceViolation(
            f"witness set overlaps candidate pool on branches {sorted(overlap)}; "
            "agreement among siblings is not evidence of correctness"
        )

    for w in witnesses:
        if w not in candidates:
            raise WitnessIndependenceViolation(f"witness {w} has no recorded execution trace")
        completed = candidates[w].get("completed_calls", set())
        missing = required_path_calls - completed
        if missing:
            raise WitnessIndependenceViolation(
                f"witness {w} short-circuited; missing verification calls {sorted(missing)}. "
                "Fastest-completion witnesses are ineligible."
            )

    votes: dict[str, int] = {}
    for w in witnesses:
        ans = candidates[w]["answer"]
        votes[ans] = votes.get(ans, 0) + 1

    winner, count = max(votes.items(), key=lambda kv: kv[1])
    if count < f + 1:
        raise WitnessIndependenceViolation(
            f"no answer reached f+1={f+1} quorum; votes={votes}. Escalate to out-of-pool check."
        )
    return {"answer": winner, "votes": votes, "quorum_size": count, "certified": True}
