# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-prefetch-divergence-in-optimistic-swarm-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-prefetch-divergence-in-optimistic-swarm-execution.warrant.json
# Markdown SHA-256:   12a55df6294c5091b5603358844bad00cb0d22f8a06cc37e83a121046ffbcb53
# Code AST SHA-256:   fe95659fca7bb17d6b13ab7a2bdd1ccba123865516951ef8797780cdd04375ea
# Verified Classes:   DerivationClosureError, PrefetchToken, Dispatch, DerivationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set

class DerivationClosureError(RuntimeError):
    """Raised when a stale prefetch has derived effects that cannot be unwound."""
    pass

@dataclass
class PrefetchToken:
    resource_id: str
    version: int
    epoch: int

@dataclass
class Dispatch:
    call_id: str
    ancestor_tokens: Set[PrefetchToken]
    external: bool  # True if non-idempotent side effect already left the agent

class DerivationLedger:
    def __init__(self) -> None:
        self._dispatches: Dict[str, Dispatch] = {}
        self._by_token: Dict[PrefetchToken, List[str]] = {}

    def record(self, d: Dispatch) -> None:
        self._dispatches[d.call_id] = d
        for tok in d.ancestor_tokens:
            self._by_token.setdefault(tok, []).append(d.call_id)

    def invalidate(self, stale: PrefetchToken) -> List[str]:
        affected = self._by_token.get(stale, [])
        external = [cid for cid in affected if self._dispatches[cid].external]
        if external:
            raise DerivationClosureError(
                f"prefetch {stale.resource_id}@v{stale.version} stale; "
                f"external effects already dispatched: {external}. "
                f"Cannot unwind by discard alone; compensation required."
            )
        for cid in affected:
            self._dispatches.pop(cid, None)
        self._by_token.pop(stale, None)
        return affected

def resolve_conflict(ledger: DerivationLedger, stale: PrefetchToken) -> None:
    # Point check is insufficient; must sweep derivation closure.
    affected = ledger.invalidate(stale)
    if not affected:
        raise DerivationClosureError(
            f"no derivation edges recorded for {stale}; "
            f"version token did not propagate — provenance untracked."
        )
