# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculatively-executed-branch-has-already-leaked-side-effects-before-rollback-is-authorized.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculatively-executed-branch-has-already-leaked-side-effects-before-rollback-is-authorized.warrant.json
# Markdown SHA-256:   cb99ed6542d1ebf212f3957dd76857822cdadb7ea332ccefbcc71803b83f4fa2
# Code AST SHA-256:   6a5d6379433217915b116ced6f394204bf05af987ddf7a0fec3f27849a5fa589
# Verified Classes:   EffectClass, Effect, Branch, SpeculativeLeakError, CommitGateViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class EffectClass(Enum):
    COMPENSABLE = "compensable"
    COMMITTED = "committed"


@dataclass
class Effect:
    tool: str
    cls: EffectClass
    timestamp: float
    acked: bool = False


@dataclass
class Branch:
    branch_id: str
    journal: List[Effect] = field(default_factory=list)
    status: str = "speculating"


class SpeculativeLeakError(RuntimeError):
    """Raised when rollback is authorized on a branch that already committed an effect."""


class CommitGateViolation(SpeculativeLeakError):
    """Raised when an executor reaches a committed-class tool call without a commit token."""


def classify_tool(tool: str, manifest: Dict[str, str]) -> EffectClass:
    # Conservative default: unclassified tools are treated as committed.
    return EffectClass(manifest.get(tool, EffectClass.COMMITTED.value))


def record_effect(branch: Branch, tool: str, manifest: Dict[str, str],
                  now: float, commit_token: bool) -> Effect:
    cls = classify_tool(tool, manifest)
    if cls is EffectClass.COMMITTED and not commit_token:
        raise CommitGateViolation(
            f"branch {branch.branch_id} reached committed tool {tool!r} "
            f"at t={now} without commit token; speculative execution unsound"
        )
    eff = Effect(tool=tool, cls=cls, timestamp=now)
    branch.journal.append(eff)
    return eff


def leaked(branch: Branch, rollback_authorized_at: float) -> bool:
    return any(
        e.cls is EffectClass.COMMITTED and e.timestamp < rollback_authorized_at
        for e in branch.journal
    )


def authorize_rollback(branch: Branch, rollback_authorized_at: float) -> None:
    if leaked(branch, rollback_authorized_at):
        offenders = [
            e.tool for e in branch.journal
            if e.cls is EffectClass.COMMITTED and e.timestamp < rollback_authorized_at
        ]
        branch.status = "leaked_committed"
        raise SpeculativeLeakError(
            f"branch {branch.branch_id} leaked committed effects {offenders} "
            f"before rollback at t={rollback_authorized_at}; "
            f"escalate to reconciliation, do not commit winner"
        )
    branch.status = "rolled_back"


# Trace reproducing the observed incident.
manifest = {"query_crm": "compensable", "write_ticket": "compensable"}  # send_email omitted
b2 = Branch("B2")
record_effect(b2, "query_crm", manifest, now=1.1, commit_token=False)
record_effect(b2, "send_email", manifest, now=1.9, commit_token=False)  # default -> committed
authorize_rollback(b2, rollback_authorized_at=4.3)  # raises SpeculativeLeakError
