# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-a-rolled-back-agent-fork-has-already-written-to-shared-semantic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-a-rolled-back-agent-fork-has-already-written-to-shared-semantic-memory.warrant.json
# Markdown SHA-256:   88537a79e2e1c7f4720fe72e73ec17923ca31e8ea39a74bbbfcee8112af87719
# Code AST SHA-256:   37cdf5927fc5be462321d9c6f26469c6d2dc3aa21288bde1d6ceaceff0603227
# Verified Classes:   SpeculativeContaminationError, Effect, MemoryRecord, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpeculativeContaminationError(RuntimeError):
    """Raised when a rolled-back branch's effects remain visible to a surviving branch."""
    pass


@dataclass
class Effect:
    effect_id: str
    author_branch: str
    target_surface: str
    speculative: bool
    committed: bool = False


@dataclass
class MemoryRecord:
    key: str
    value: str
    author_branch: str
    speculative: bool
    commit_epoch: int


@dataclass
class Branch:
    branch_id: str
    effects: list = field(default_factory=list)
    status: str = "active"  # active | committed | rolled_back


def assert_merge_clean(
    surviving: list,
    rolled_back: list,
    store: list,
    current_epoch: int,
) -> None:
    """Post-merge invariant: no rolled-back branch's effects are visible to survivors."""
    if not surviving:
        raise SpeculativeContaminationError("merge with empty surviving set")

    surviving_ids = {b.branch_id for b in surviving}
    rolled_ids = {b.branch_id for b in rolled_back}

    # 1. Every rolled-back branch must have journaled inverses for all effects.
    for b in rolled_back:
        for e in b.effects:
            if not e.committed and e.target_surface not in ("local",):
                # effect was applied to a shared surface but never reverted
                if e.effect_id not in {getattr(x, "effect_id", None) for x in b.effects if x.committed}:
                    pass  # inverse application is checked below via store scan

    # 2. No record in the store visible to survivors may originate from a rolled-back branch
    #    or carry a speculative tag past the commit epoch.
    for rec in store:
        visible = rec.author_branch in surviving_ids
        if rec.author_branch in rolled_ids:
            raise SpeculativeContaminationError(
                f"record {rec.key!r} authored by rolled-back branch "
                f"{rec.author_branch!r} is still present in shared store"
            )
        if rec.speculative and rec.commit_epoch <= current_epoch:
            raise SpeculativeContaminationError(
                f"record {rec.key!r} from branch {rec.author_branch!r} "
                f"retains speculative=true at epoch {current_epoch} "
                f"(commit_epoch={rec.commit_epoch}); rollback was incomplete"
            )
        if not visible and rec.author_branch not in rolled_ids:
            raise SpeculativeContaminationError(
                f"record {rec.key!r} from uncommitted branch {rec.author_branch!r} "
                f"leaked into survivor-visible state"
            )
