# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-cancel-a-speculative-tool-call-after-a-sibling-branch-has-already-committed-its-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-cancel-a-speculative-tool-call-after-a-sibling-branch-has-already-committed-its-effects.warrant.json
# Markdown SHA-256:   e8763ef90ca3c8e780d4334d73ba9cdc5196a42cb16b63b80bc5f64f65941e94
# Code AST SHA-256:   c71cbabca455e44018c9d60a046bfa52687e49f9c45df57d67882603cafdb7dd
# Verified Classes:   UnsafeReleaseError, EffectState, EffectFootprint, Branch, MergeFrontier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class UnsafeReleaseError(RuntimeError):
    """Raised when a teardown path attempts to release an effect footprint
    that a commit-eligible sibling still references."""


class EffectState(Enum):
    LIVE = "live"
    ORPHANED_PINNED = "orphaned_pinned"
    RELEASED = "released"


@dataclass
class EffectFootprint:
    lease_token: str
    owner_branch: str
    state: EffectState = EffectState.LIVE
    referenced_by: set[str] = field(default_factory=set)


@dataclass
class Branch:
    name: str
    committed: bool = False
    commit_eligible: bool = True


class MergeFrontier:
    """Owns release authority for all effect footprints in the fork.

    The cancelling branch must never release directly; it must ask the
    frontier, which is the only object that can see sibling references.
    """

    def __init__(self) -> None:
        self._footprints: dict[str, EffectFootprint] = {}
        self._branches: dict[str, Branch] = {}

    def register_branch(self, branch: Branch) -> None:
        self._branches[branch.name] = branch

    def register_effect(self, fp: EffectFootprint) -> None:
        self._footprints[fp.lease_token] = fp

    def record_reference(self, lease_token: str, by_branch: str) -> None:
        fp = self._footprints[lease_token]
        fp.referenced_by.add(by_branch)

    def _live_referrers(self, fp: EffectFootprint) -> set[str]:
        return {
            name
            for name in fp.referenced_by
            if (b := self._branches.get(name)) is not None
            and b.commit_eligible
            and not b.committed
            or (b is not None and b.committed)
        }

    def request_release(self, lease_token: str, by_branch: str) -> EffectState:
        """Called by a cancelling branch during teardown.

        Returns the resulting state. Raises UnsafeReleaseError only if the
        caller attempts to bypass the frontier; the frontier itself never
        releases a footprint with live referrers.
        """
        fp = self._footprints.get(lease_token)
        if fp is None:
            raise UnsafeReleaseError(
                f"release requested for unknown lease {lease_token!r} by {by_branch!r}"
            )
        if fp.owner_branch != by_branch:
            raise UnsafeReleaseError(
                f"branch {by_branch!r} attempted to release lease {lease_token!r} "
                f"owned by {fp.owner_branch!r}"
            )

        referrers = self._live_referrers(fp)
        if referrers:
            # Defer: cancel the future, pin the effect, hand authority to merge.
            fp.state = EffectState.ORPHANED_PINNED
            return fp.state

        fp.state = EffectState.RELEASED
        return fp.state

    def resolve_at_merge(self, lease_token: str, consumed: bool) -> EffectState:
        fp = self._footprints[lease_token]
        if fp.state != EffectState.ORPHANED_PINNED:
            raise UnsafeReleaseError(
                f"merge resolution for lease {lease_token!r} in unexpected state "
                f"{fp.state.value!r}"
            )
        fp.state = EffectState.RELEASED if consumed else EffectState.ORPHANED_PINNED
        return fp.state


def cancel_branch(frontier: MergeFrontier, branch: Branch, lease_tokens: list[str]) -> dict[str, EffectState]:
    """Cancel an uncommitted branch. Futures are cancelled unconditionally;
    effect release is deferred to the frontier."""
    if branch.committed:
        raise UnsafeReleaseError(
            f"refusing to cancel committed branch {branch.name!r}"
        )
    outcomes: dict[str, EffectState] = {}
    for token in lease_tokens:
        outcomes[token] = frontier.request_release(token, by_branch=branch.name)
    branch.commit_eligible = False
    return outcomes
