# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-agent-plan-branches-have-silently-outlived-their-rollback-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-agent-plan-branches-have-silently-outlived-their-rollback-horizon.warrant.json
# Markdown SHA-256:   7cdb1fbbc9c1b1387ae9c31e174fdb1e7c2f1d7584ca6a5bf1ff55dee474077c
# Code AST SHA-256:   c39ff392a8b234ce8950d61d9ababa0b7b60404574b30cc76e378271d3b22339
# Verified Classes:   RollbackStatus, SpeculationLeakError, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RollbackStatus(Enum):
    VERIFIED_ABSENT = "verified_absent"
    UNVERIFIED = "unverified"          # 404, 202, "accepted" — NOT success
    LEAKED = "leaked"                  # downstream effect still live


class SpeculationLeakError(RuntimeError):
    """Raised when a speculative branch's effects escaped the rollback horizon."""


@dataclass
class Branch:
    branch_id: str
    effect_set: set[str]                       # declared mutations from plan
    compensation_log: set[str] = field(default_factory=set)
    owned_channels_only: bool = True

    @property
    def coverage_ratio(self) -> float:
        if not self.effect_set:
            return 1.0
        return len(self.compensation_log & self.effect_set) / len(self.effect_set)


def cancel_branch(branch: Branch, rollback_results: dict[str, RollbackStatus]) -> None:
    # Guard 1: coverage — every declared effect must be compensable.
    if branch.coverage_ratio < 1.0:
        raise SpeculationLeakError(
            f"branch {branch.branch_id}: compensation coverage "
            f"{branch.coverage_ratio:.2f} < 1.0; unrollbackable effects: "
            f"{branch.effect_set - branch.compensation_log}"
        )

    # Guard 2: non-owned channels make cancellation advisory, not sound.
    if not branch.owned_channels_only:
        raise SpeculationLeakError(
            f"branch {branch.branch_id}: touches non-owned channel; "
            f"rollback is advisory and must be quarantined, not cancelled"
        )

    # Guard 3: rollback success != verified absent. 404/202 are UNVERIFIED.
    for action, status in rollback_results.items():
        if status is not RollbackStatus.VERIFIED_ABSENT:
            raise SpeculationLeakError(
                f"branch {branch.branch_id}: rollback of '{action}' returned "
                f"{status.value}; effect may still be live — reconcile by "
                f"provenance before committing any sibling branch"
            )
