# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-and-roll-back-a-poisoned-speculative-branch-before-commit-in-a-multi-agent-pipeline.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-and-roll-back-a-poisoned-speculative-branch-before-commit-in-a-multi-agent-pipeline.warrant.json
# Markdown SHA-256:   eb4c47959b0a801da174c5a1c7a0e14e61cdfa53e0c6c8364067af0a178d4d9d
# Code AST SHA-256:   020f13905dc02c7bebe46d53bed84610f387bfe3221314d4f034670aa47bdb70
# Verified Classes:   SpeculativeBranchPoisonedError, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpeculativeBranchPoisonedError(RuntimeError):
    """Raised when a speculative branch is internally coherent but derived from an abandoned premise."""


@dataclass(frozen=True)
class SpeculativeBranch:
    branch_id: str
    pinned_premise: str          # write-once, assigned at dispatch
    verification_score: float
    error_count: int
    outputs: tuple


def commit_speculative_branch(
    branch: SpeculativeBranch,
    committed_premise: str,
    quality_threshold: float = 0.80,
) -> tuple:
    # Order matters: attribution is checked BEFORE quality.
    # A high verification_score on a dead premise must not pass.
    if branch.pinned_premise != committed_premise:
        raise SpeculativeBranchPoisonedError(
            f"branch {branch.branch_id} pinned to premise "
            f"{branch.pinned_premise!r} but committed premise is "
            f"{committed_premise!r}; verification_score="
            f"{branch.verification_score:.2f} is irrelevant — discard branch"
        )

    if branch.error_count > 0:
        raise SpeculativeBranchPoisonedError(
            f"branch {branch.branch_id} has {branch.error_count} errors; "
            f"retry on sound premise {committed_premise!r}"
        )

    if branch.verification_score < quality_threshold:
        # Premise is sound; quality failure is recoverable by re-dispatch.
        raise SpeculativeBranchPoisonedError(
            f"branch {branch.branch_id} below quality threshold on sound "
            f"premise; re-dispatch safe"
        )

    return branch.outputs


def reconcile(branches, committed_premise: str) -> list:
    committed = []
    for b in branches:
        try:
            committed.extend(commit_speculative_branch(b, committed_premise))
        except SpeculativeBranchPoisonedError:
            # Roll back: discard branch outputs entirely, never repair in place.
            continue
    return committed
