# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-divergence-outruns-the-verification-quorum-s-ability-to-re-converge.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-divergence-outruns-the-verification-quorum-s-ability-to-re-converge.warrant.json
# Markdown SHA-256:   52bea5b48377d5797db76046d9ac4d33bbdf6600e95b6d9dad9e1858e2f3c8f3
# Code AST SHA-256:   47e302915a4b3bb175e427a8f31285e5c65b18069c2344b19d2c9c627c0e9be3
# Verified Classes:   SpeculativeRollbackViolation, BranchProfile, FanOutPlan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class SpeculativeRollbackViolation(RuntimeError):
    """Raised when fan-out or effect routing would let a leaked side effect
    contaminate the verification quorum before a durable verdict exists."""
    pass


@dataclass
class BranchProfile:
    branch_id: str
    has_write_capable_tool: bool
    overlay_routed: bool          # True => writes go to branch-local overlay


@dataclass
class FanOutPlan:
    branches: list[BranchProfile]
    time_to_verdict_p95_s: float
    p_leak_per_branch_per_s: float | None  # None => unmeasured
    verifiers_read_live_state: bool
    contamination_budget: float = 1.0


def assert_speculation_safe(plan: FanOutPlan) -> None:
    # Invariant 1: no write-capable branch may write through to shared substrate.
    for b in plan.branches:
        if b.has_write_capable_tool and not b.overlay_routed:
            raise SpeculativeRollbackViolation(
                f"branch {b.branch_id} holds a write-capable tool without "
                f"overlay routing; rollback cannot undo its effects"
            )

    # Invariant 2: verifiers must not read substrate that branches can mutate.
    if plan.verifiers_read_live_state:
        raise SpeculativeRollbackViolation(
            "verifiers read live substrate; a leaked effect can produce a "
            "self-fulfilling verdict biased toward the earliest writer"
        )

    # Invariant 3: expected leaked effects before verdict must stay under budget.
    if plan.p_leak_per_branch_per_s is None:
        # Unmeasured leak rate with write-capable tools is treated as unsafe
        # unless overlay routing already drove p_leak to zero (checked above).
        if any(b.has_write_capable_tool for b in plan.branches):
            raise SpeculativeRollbackViolation(
                "p_leak is unmeasured while write-capable branches are present; "
                "cannot bound contamination, refusing fan-out"
            )
        return

    expected_leaks = (
        len(plan.branches)
        * plan.p_leak_per_branch_per_s
        * plan.time_to_verdict_p95_s
    )
    if expected_leaks >= plan.contamination_budget:
        raise SpeculativeRollbackViolation(
            f"expected leaked effects before verdict = {expected_leaks:.2f} "
            f">= budget {plan.contamination_budget:.2f}; "
            f"reduce fan-out or serialize commit"
        )
