# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-provenance-collapse-false-positive-in-memory-poisoning-detection-during-selective-forgetting.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-provenance-collapse-false-positive-in-memory-poisoning-detection-during-selective-forgetting.warrant.json
# Markdown SHA-256:   41c4fa70c7b325afece580ba96fcffdac7d2c76929fb51e392fd56696d205cd3
# Code AST SHA-256:   f88536d37cc1c9ba4353f40279b706ae7a2ca0be916e189f173ffd5bad1d4625
# Verified Classes:   ProvenanceCollapseError, EvictionReason, Tombstone, SemanticRecord, ForgettingPass
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ProvenanceCollapseError(RuntimeError):
    """Raised when detection runs against a provenance graph mutated by eviction."""
    pass


class EvictionReason(Enum):
    POISONED = "poisoned"
    DEDUP_INCIDENTAL = "dedup_incidental"
    USER_REQUESTED = "user_requested"


@dataclass
class Tombstone:
    record_id: str
    reason: EvictionReason
    evicted_at: float


@dataclass
class SemanticRecord:
    record_id: str
    derived_from: Set[str]
    trust_tier: int
    status: str = "active"


class ForgettingPass:
    def __init__(self, records: Dict[str, SemanticRecord],
                 tombstones: Dict[str, Tombstone]):
        self.records = records
        self.tombstones = tombstones

    def detect(self, snapshot_tombstones: Dict[str, Tombstone]) -> List[str]:
        """Detection MUST read a pre-eviction snapshot, not live tombstones."""
        suspects: List[str] = []
        for rec in self.records.values():
            if rec.status != "active":
                continue
            for src in rec.derived_from:
                tomb = snapshot_tombstones.get(src)
                if tomb is None:
                    continue
                if tomb.reason is EvictionReason.POISONED:
                    suspects.append(rec.record_id)
                    break
                # incidental eviction -> orphan, NOT a poisoning suspect
        return suspects

    def evict(self, target_ids: Set[str], reason: EvictionReason, now: float) -> None:
        live_tombstones = dict(self.tombstones)
        for rid in target_ids:
            self.tombstones[rid] = Tombstone(rid, reason, now)
            if rid in self.records:
                self.records[rid].status = "evicted"
        # Guard: if detection is invoked after this point against live
        # tombstones, incidental evictions will be misread as contamination.
        fan_out = self._fan_out(target_ids)
        if fan_out > 0.05 * len(self.records):
            raise ProvenanceCollapseError(
                f"fan-out {fan_out}/{len(self.records)} exceeds budget; "
                f"stage eviction and re-parent orphans before detection"
            )

    def _fan_out(self, target_ids: Set[str]) -> int:
        return sum(
            1 for rec in self.records.values()
            if rec.status == "active" and rec.derived_from & target_ids
        )


def run_forgetting(pass_: ForgettingPass, targets: Set[str],
                   reason: EvictionReason, now: float) -> List[str]:
    # Snapshot BEFORE mutation — this is the invariant.
    snapshot = dict(pass_.tombstones)
    pass_.evict(targets, reason, now)
    # Detection reads the snapshot, so incidental evictions are invisible
    # to the poisoning rule and cannot trigger a quarantine cascade.
    return pass_.detect(snapshot)
