# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-speculative-tool-call-window-when-a2a-task-graph-cancellation-races-against-prefetch-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-speculative-tool-call-window-when-a2a-task-graph-cancellation-races-against-prefetch-commit.warrant.json
# Markdown SHA-256:   6ecc092f0c72d9c21dabc665e8cd68acdbbf37fcc5e8ab0e8cb91db0f7cbb54a
# Code AST SHA-256:   848f677642a17dc3052b6cce376c183d6c140a2c2bda9a08bbf1448144ee7b89
# Verified Classes:   OrphanedPrefetchError, PrefetchHandle, EdgeState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class OrphanedPrefetchError(RuntimeError):
    """Raised when a speculative prefetch commits after its justification
    token's epoch has been superseded by an ancestor cancellation."""

    def __init__(self, prefetch_id: str, justification_edge: str,
                 dispatch_epoch: int, commit_epoch: int) -> None:
        super().__init__(
            f"prefetch {prefetch_id} orphaned: edge {justification_edge} "
            f"epoch advanced {dispatch_epoch} -> {commit_epoch} "
            f"(cancellation arrived inside in-flight window)"
        )
        self.prefetch_id = prefetch_id
        self.justification_edge = justification_edge
        self.dispatch_epoch = dispatch_epoch
        self.commit_epoch = commit_epoch


@dataclass(frozen=True)
class PrefetchHandle:
    prefetch_id: str
    justification_edge: str
    dispatch_epoch: int


@dataclass
class EdgeState:
    epoch: int = 0
    cancelled: bool = False

    def bump_cancellation(self) -> None:
        self.epoch += 1
        self.cancelled = True


def commit_prefetch(handle: PrefetchHandle, edge: EdgeState,
                    result: Optional[object]) -> object:
    """Commit a speculative tool-call result into the task graph.

    The commit is valid only if the justification edge's epoch has not
    advanced since dispatch. A cancellation that arrived after dispatch
    but before commit produces an orphaned window; the result is
    poisoned and must not mutate graph state.
    """
    if edge.epoch != handle.dispatch_epoch:
        raise OrphanedPrefetchError(
            prefetch_id=handle.prefetch_id,
            justification_edge=handle.justification_edge,
            dispatch_epoch=handle.dispatch_epoch,
            commit_epoch=edge.epoch,
        )
    if edge.cancelled:
        # Defensive: epoch bump and cancelled flag should co-occur, but
        # a partial cancellation write could leave the flag set alone.
        raise OrphanedPrefetchError(
            prefetch_id=handle.prefetch_id,
            justification_edge=handle.justification_edge,
            dispatch_epoch=handle.dispatch_epoch,
            commit_epoch=edge.epoch,
        )
    return result
