# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-poisoned-memory-after-successful-rollback-the-tombstone-epoch-gap-in-persistent-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-poisoned-memory-after-successful-rollback-the-tombstone-epoch-gap-in-persistent-agent-memory-stores.warrant.json
# Markdown SHA-256:   a8f088fd515537540aeac8a747281651791944f73e7651bb3dc4a8ea420887e5
# Code AST SHA-256:   de161a981d0b61857e173f6309922514ef6311a3cbfe5fb0892aa9b6c7d97929
# Verified Classes:   UntaintableDerivativeError, PoisonLineageGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UntaintableDerivativeError(RuntimeError):
    """Raised when a memory derivative cannot be traced to its sources,
    making provenance-invalidation rollback unsound for this node."""
    pass


class PoisonLineageGuard:
    """Enforces forward taint propagation over a derivation graph so that
    rollback-by-flag is correct even when derivatives are backward-dated."""

    def __init__(self, graph):
        # graph: dict[node_id -> {"epoch": int, "derived_from": list[str], "tainted": bool}]
        self.graph = graph

    def register_derivative(self, node_id, derived_from, epoch):
        if not derived_from:
            # A distilled fact with no recorded sources cannot be invalidated
            # later if a source is flagged. Refuse it at write time.
            raise UntaintableDerivativeError(
                f"node {node_id} has no derivation edges; "
                f"backward-dated or orphaned derivatives are un-taintable"
            )
        for parent in derived_from:
            if parent not in self.graph:
                raise UntaintableDerivativeError(
                    f"node {node_id} derives from unknown parent {parent}"
                )
        self.graph[node_id] = {
            "epoch": epoch,
            "derived_from": list(derived_from),
            "tainted": False,
        }

    def flag_and_propagate(self, poisoned_id):
        if poisoned_id not in self.graph:
            raise UntaintableDerivativeError(
                f"cannot flag unknown node {poisoned_id}"
            )
        # Forward closure over descendants, independent of epoch ordering.
        stack = [poisoned_id]
        tainted = set()
        while stack:
            current = stack.pop()
            if current in tainted:
                continue
            tainted.add(current)
            self.graph[current]["tainted"] = True
            for node_id, meta in self.graph.items():
                if current in meta["derived_from"]:
                    stack.append(node_id)
        return tainted

    def retrieve(self, candidate_ids):
        # Retrieval must filter on taint, not on epoch.
        clean = []
        for node_id in candidate_ids:
            meta = self.graph.get(node_id)
            if meta is None:
                continue
            if meta["tainted"]:
                continue
            clean.append(node_id)
        return clean


def rollback_to_epoch(guard, cutoff_epoch, poisoned_id):
    """Rollback is flag+propagate, never truncation. Truncation alone would
    leave backward-dated derivatives (epoch < cutoff) alive and trusted."""
    tainted = guard.flag_and_propagate(poisoned_id)
    survivors = [
        n for n, m in guard.graph.items()
        if n not in tainted and m["epoch"] >= cutoff_epoch
    ]
    # Any tainted node with epoch < cutoff is exactly the failure case:
    # it would have survived truncation. Assert it is now filtered.
    for n in tainted:
        if guard.graph[n]["epoch"] < cutoff_epoch:
            assert n not in survivors, (
                f"backward-dated tainted node {n} survived rollback"
            )
    return survivors
