# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-execution-as-non-committable-when-a-rollback-safe-side-effect-has-already-been-observe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-execution-as-non-committable-when-a-rollback-safe-side-effect-has-already-been-observe.warrant.json
# Markdown SHA-256:   24cc90938aa7667031672b80ca2d9533e3c443ec072bdad50e22645128649885
# Code AST SHA-256:   20d05476f33ba672fb9f90675cbc864c62bef172c1efa2c3e39204ccb64eda9b
# Verified Classes:   NonAbortableBranchError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set


class NonAbortableBranchError(RuntimeError):
    """Raised when a speculative branch is aborted after its effects were observed."""
    pass


@dataclass
class Branch:
    branch_id: str
    tool_rollback_safe: bool
    published_to_bus: bool = False
    observers: Set[str] = field(default_factory=set)  # agents that read this branch's output
    committed: bool = False


def abort_branch(branch: Branch, release_fn) -> None:
    # Tool-level rollback-safety is necessary but NOT sufficient.
    # The abort is only valid if no committed agent observed the effect.
    if branch.observers:
        raise NonAbortableBranchError(
            f"branch {branch.branch_id} has observers {sorted(branch.observers)}; "
            f"tool_rollback_safe={branch.tool_rollback_safe} is insufficient — "
            f"compensation restores the resource but cannot un-write derived state. "
            f"Escalate to compensating-transaction protocol."
        )
    if branch.published_to_bus and not branch.committed:
        raise NonAbortableBranchError(
            f"branch {branch.branch_id} published to bus before version check resolved; "
            f"effect may be in flight to undiscovered consumers."
        )
    release_fn(branch.branch_id)


def record_observation(branch: Branch, consumer: str) -> None:
    if branch.committed or branch.published_to_bus:
        branch.observers.add(consumer)
    # observation of an unpublished, uncommitted branch is a no-op:
    # the consumer could not have seen it.
