# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-a-rollback-restores-a-sibling-branch-s-tool-side-effects-but-not-its-memory-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-a-rollback-restores-a-sibling-branch-s-tool-side-effects-but-not-its-memory-writes.warrant.json
# Markdown SHA-256:   ed9fe6a7820f2c2cc71cb51f9b007a3d4d9463d680eb7710c2ac9a585c142b66
# Code AST SHA-256:   1dca7d19f9df17075120b023f40a13f4f7789e4aae2dee400d203ebc82755043
# Verified Classes:   SpeculativeContaminationError, MemoryRecord, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpeculativeContaminationError(RuntimeError):
    """Raised when a surviving branch retrieves a world-state assertion
    written by a rolled-back sibling branch against reverted substrate."""


@dataclass
class MemoryRecord:
    branch_id: str
    substrate_epoch: str
    text: str
    kind: str  # "world_state" | "process_narration"
    cites_reverted_effect: bool = False
    revalidated_epoch: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    fork_epoch: str
    committed: bool = False
    rolled_back: bool = False


def retrieve_for_branch(
    reader: Branch,
    store: list[MemoryRecord],
    committed_epoch: str,
    k: int = 5,
) -> list[MemoryRecord]:
    """Retrieval that enforces the speculative-isolation invariant."""
    candidates = store[:k]
    safe: list[MemoryRecord] = []
    for rec in candidates:
        if rec.branch_id == reader.branch_id:
            safe.append(rec)
            continue
        if rec.kind == "process_narration":
            safe.append(rec)
            continue
        # world_state from a sibling: must be re-validated against committed substrate
        if rec.revalidated_epoch == committed_epoch:
            safe.append(rec)
            continue
        if rec.cites_reverted_effect:
            raise SpeculativeContaminationError(
                f"branch {reader.branch_id} retrieved world-state assertion "
                f"{rec.text!r} from rolled-back branch {rec.branch_id}; "
                f"record cites reverted effect and was never re-validated "
                f"against committed epoch {committed_epoch}"
            )
    return safe


def resume_after_commit(
    reader: Branch,
    store: list[MemoryRecord],
    committed_epoch: str,
) -> list[MemoryRecord]:
    if not reader.committed:
        raise SpeculativeContaminationError(
            f"branch {reader.branch_id} attempted resume without commit"
        )
    return retrieve_for_branch(reader, store, committed_epoch)
