# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-quorum-of-agreeing-peers-as-evidence-of-a-shared-hallucination-rather-than-a-committed-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-quorum-of-agreeing-peers-as-evidence-of-a-shared-hallucination-rather-than-a-committed-fact.warrant.json
# Markdown SHA-256:   cf1fd742947fc5f217889b1a761f275f3b3394f503286b4dcf4b583db0a5d4d7
# Code AST SHA-256:   d3e3e7fece5be729630c9e69eb3a3d4779cac640262190718239a4ed489b2529
# Verified Classes:   CorrelatedQuorumError, UnprovenCommitmentError, PeerClaim
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum's agreement is explained by shared evidence, not independent observation."""
    pass


class UnprovenCommitmentError(RuntimeError):
    """Raised when a task cannot be committed because effective quorum is below threshold."""
    pass


@dataclass
class PeerClaim:
    peer_id: str
    claim: str                      # e.g. "write_ledger_entry succeeded"
    evidence_hash: str              # hash of the RAW artifact this claim was derived from
    is_narration: bool              # True if derived from another peer's narration, not raw tool output
    fabricated_fields: list = field(default_factory=list)


def _effective_quorum(claims: list[PeerClaim], f: int) -> tuple[int, list[str]]:
    """
    Collapse claims that share an evidence_hash (or are narration-sourced) into
    single observations. Returns (effective_weight, collision_groups).
    """
    seen: dict[str, list[str]] = {}
    for c in claims:
        # narration claims are attributed to the narration's own hash, not a raw artifact
        key = c.evidence_hash if not c.is_narration else f"narration:{c.evidence_hash}"
        seen.setdefault(key, []).append(c.peer_id)

    effective = 0
    collisions = []
    for key, peers in seen.items():
        if len(peers) > 1:
            collisions.append(key)
            effective += 1          # n votes on one observation = weight 1
        else:
            effective += 1
    return effective, collisions


def commit_task(claims: list[PeerClaim], f: int, threshold: int) -> str:
    """
    Attempt to commit a task on quorum. Enforces the decorrelation gate.
    """
    if not claims:
        raise UnprovenCommitmentError("no claims submitted; cannot commit")

    # Rule 3: unanimity on an ambiguous source is a red flag, not a green light.
    fabricated = [c for c in claims if c.fabricated_fields]
    if fabricated:
        fields = {fld for c in fabricated for fld in c.fabricated_fields}
        raise CorrelatedQuorumError(
            f"fabricated fields present in claims: {sorted(fields)}; "
            f"peers {[c.peer_id for c in fabricated]} populated null raw fields"
        )

    effective, collisions = _effective_quorum(claims, f)

    if collisions and effective < threshold:
        raise CorrelatedQuorumError(
            f"evidence-hash collisions {collisions} collapsed quorum from "
            f"{len(claims)} to {effective} (< threshold {threshold}); "
            f"agreement is correlated, not independent"
        )

    if effective < threshold:
        raise UnprovenCommitmentError(
            f"effective quorum {effective} < required {threshold} "
            f"(nominal {len(claims)} claims, {len(collisions)} collision groups)"
        )

    # Only here is commitment warranted.
    return "COMPLETED"


# --- trace of the failure above ---
def replay_incident() -> None:
    narration_hash = hashlib.sha256(b"executor: 'write succeeded, txn pending'").hexdigest()
    claims = [
        PeerClaim("executor", "write ok", evidence_hash=narration_hash,
                  is_narration=False, fabricated_fields=[]),
        PeerClaim("auditor", "write ok, txn 0x9f", evidence_hash=narration_hash,
                  is_narration=True, fabricated_fields=["txn"]),
        PeerClaim("planner", "write ok", evidence_hash=narration_hash,
                  is_narration=True, fabricated_fields=[]),
    ]
    try:
        commit_task(claims, f=1, threshold=2)
    except CorrelatedQuorumError as e:
        print(f"BLOCKED: {e}")


if __name__ == "__main__":
    replay_incident()
