# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-rolled-back-speculative-branch-has-already-leaked-side-effects-into-a-sibling-branch-s-shared-tool-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-rolled-back-speculative-branch-has-already-leaked-side-effects-into-a-sibling-branch-s-shared-tool-cache.warrant.json
# Markdown SHA-256:   7f4c5c57aaeb0de0e843cfd03f54fc7c23b90c09d1ab4013e4627be5d3276e3c
# Code AST SHA-256:   41f528785617053920dbe133065aa171116ca7152ca5d03e0507ccab66450c25
# Verified Classes:   GhostCacheReadError, CacheEntry, Branch, SharedToolCache
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple

class GhostCacheReadError(RuntimeError):
    """Raised when a surviving branch reads a cache entry produced by a rolled-back sibling."""
    pass

@dataclass
class CacheEntry:
    value: object
    producer_branch: str
    write_epoch: int
    co_writers: set = field(default_factory=set)

@dataclass
class Branch:
    id: str
    start_epoch: int
    status: str = "live"   # live | rolled_back

class SharedToolCache:
    def __init__(self) -> None:
        self._store: Dict[Tuple[str, str], CacheEntry] = {}
        self._epoch = 0

    def write(self, key: Tuple[str, str], value: object, branch: Branch) -> None:
        self._epoch += 1
        existing = self._store.get(key)
        if existing is None:
            self._store[key] = CacheEntry(value, branch.id, self._epoch, {branch.id})
        else:
            existing.co_writers.add(branch.id)
            existing.value = value
            existing.write_epoch = self._epoch

    def read(self, key: Tuple[str, str], consumer: Branch,
             branches: Dict[str, Branch]) -> object:
        entry = self._store.get(key)
        if entry is None:
            return None
        producer = branches.get(entry.producer_branch)
        # Ghost detection: producer is dead AND this entry was written after the
        # consumer even started, AND no surviving branch co-wrote it.
        if (producer is not None
                and producer.status == "rolled_back"
                and entry.write_epoch > consumer.start_epoch
                and not (entry.co_writers - {entry.producer_branch})):
            raise GhostCacheReadError(
                f"branch {consumer.id} hit cache key {key} produced solely by "
                f"rolled-back branch {entry.producer_branch} (epoch {entry.write_epoch} "
                f"> consumer start {consumer.start_epoch}); must re-execute under own lineage"
            )
        return entry.value

    def invalidate_producer(self, branch_id: str) -> None:
        # Rollback barrier: drop keys whose sole writer died.
        for key in [k for k, e in self._store.items()
                    if e.co_writers == {branch_id}]:
            del self._store[key]
        for e in self._store.values():
            e.co_writers.discard(branch_id)
