# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-persistent-agent-stores-and-why-write-audit-trails-alone-cannot-localize-the-corrupting-write.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-persistent-agent-stores-and-why-write-audit-trails-alone-cannot-localize-the-corrupting-write.warrant.json
# Markdown SHA-256:   0393120025fa24bb5fcd604f6a5ee50a1cd16687823e4b6e15e1ae33b4f54f9c
# Code AST SHA-256:   576f7dfa9ae0d0ea3e734eb324c2bac55803c3181225e164239de2da4d5210cb
# Verified Classes:   ProvenanceCycleError, Fact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List

class ProvenanceCycleError(RuntimeError):
    """Raised when a fact's provenance graph reaches the store's own fact space
    without passing through an external evidence leaf. This is the epistemic-cycle
    condition under which localized rollback is unsound."""
    pass

@dataclass
class Fact:
    fact_id: str
    confidence: float
    evidence_refs: Set[str] = field(default_factory=set)  # external doc IDs or internal fact IDs
    is_external: bool = False

def check_provenance_acyclic(facts: Dict[str, Fact], start: str, seen: Set[str] = None) -> bool:
    if seen is None:
        seen = set()
    if start in seen:
        return False  # cycle detected
    seen.add(start)
    fact = facts.get(start)
    if fact is None:
        return True  # dangling ref, treat as external-ish; caller decides
    if fact.is_external:
        return True
    if not fact.evidence_refs:
        return False  # no evidence and not external: unrooted
    return all(check_provenance_acyclic(facts, ref, seen.copy()) for ref in fact.evidence_refs)

def safe_rollback(facts: Dict[str, Fact], poisoned_id: str) -> List[str]:
    if not check_provenance_acyclic(facts, poisoned_id):
        raise ProvenanceCycleError(
            f"Fact {poisoned_id} has cyclic/unrooted provenance; "
            f"localized rollback is unsound. Quarantine SCC and re-derive from external evidence."
        )
    # acyclic and rooted: roll back poisoned fact and reverse-provenance dependents
    to_remove = {poisoned_id}
    changed = True
    while changed:
        changed = False
        for fid, f in facts.items():
            if fid not in to_remove and f.evidence_refs & to_remove:
                to_remove.add(fid)
                changed = True
    return sorted(to_remove)
