# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rollback-resurrect-a-sibling-branch-s-poisoned-tool-cache-during-speculative-multi-agent-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rollback-resurrect-a-sibling-branch-s-poisoned-tool-cache-during-speculative-multi-agent-merge.warrant.json
# Markdown SHA-256:   e9a3052b03e175ea8880485d11692a19490842573bf284489288fc8f202beec0
# Code AST SHA-256:   66d608219e36ebf9994af2b255f354ceffc4eadf067c752180a1e80767b6687a
# Verified Classes:   StaleEpochCacheRead, CacheEntry, LineageScopedToolCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class StaleEpochCacheRead(RuntimeError):
    """Raised when a branch reads a memoized tool result produced under a
    branch epoch that a rollback has since invalidated."""
    pass


@dataclass
class CacheEntry:
    value: Any
    epoch: int
    written_by_branch: str
    rolled_back: bool = False


class LineageScopedToolCache:
    def __init__(self) -> None:
        self._store: dict[tuple[str, str], CacheEntry] = {}
        self._lineage_epoch: dict[str, int] = {}

    def epoch_for(self, lineage: str) -> int:
        return self._lineage_epoch.get(lineage, 0)

    def read(self, tool: str, args_key: str, lineage: str) -> Any:
        entry = self._store.get((tool, args_key))
        if entry is None:
            raise KeyError(f"cache miss for {tool}|{args_key}")
        current = self.epoch_for(lineage)
        if entry.rolled_back or entry.epoch < current:
            # A sibling branch's result was invalidated by a rollback on this
            # lineage. Returning it would launder the rolled-back defect into
            # the surviving branch. Force a re-fetch instead.
            raise StaleEpochCacheRead(
                f"read of {tool}|{args_key} from branch {entry.written_by_branch} "
                f"at epoch {entry.epoch} under lineage {lineage} at epoch {current}: "
                f"entry was invalidated by rollback"
            )
        return entry.value

    def write(self, tool: str, args_key: str, value: Any, lineage: str,
              branch_id: str) -> None:
        self._store[(tool, args_key)] = CacheEntry(
            value=value,
            epoch=self.epoch_for(lineage),
            written_by_branch=branch_id,
        )

    def rollback(self, lineage: str, branch_id: str) -> None:
        """Roll back a speculative branch: bump the lineage epoch and mark
        every entry that branch wrote as invalidated. Entries written by
        other branches under the prior epoch remain readable only by callers
        whose lineage epoch still matches -- i.e. never, for this lineage."""
        self._lineage_epoch[lineage] = self.epoch_for(lineage) + 1
        for entry in self._store.values():
            if entry.written_by_branch == branch_id:
                entry.rolled_back = True


def merge_branch_result(cache: LineageScopedToolCache, lineage: str,
                        branch_id: str, required_tool: str,
                        args_key: str) -> Any:
    """Verifier-side gate: a branch may only merge if its required tool
    result is readable under the current lineage epoch. A stale-epoch read
    aborts the merge rather than accepting laundered state."""
    try:
        return cache.read(required_tool, args_key, lineage)
    except StaleEpochCacheRead as exc:
        raise StaleEpochCacheRead(
            f"merge rejected for branch {branch_id}: {exc}; "
            f"branch must re-fetch under current epoch before merge"
        ) from exc
