# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantically-identical-memory-poisoning-after-a-legitimate-write-supersedes-the-poisoned-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantically-identical-memory-poisoning-after-a-legitimate-write-supersedes-the-poisoned-entry.warrant.json
# Markdown SHA-256:   412ca9e2f077923d20cbb2a4ed2fb9383d4ed4e6f819be8f8c3d74a4f7c98188
# Code AST SHA-256:   8bc0e1d6de21e4b0b0d9214052ac1c1e9feecff1a1a3c8f7449f6592bff8e433
# Verified Classes:   TrustTier, Span, MemoryRecord, RollbackInvariantViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum


class TrustTier(IntEnum):
    UNTRUSTED_WEB = 0
    AGENT_INFERRED = 1
    TRUSTED_HUMAN = 2


@dataclass
class Span:
    text: str
    source_write_id: str | None      # None => unattributable (paraphrased)
    tier: TrustTier | None


@dataclass
class MemoryRecord:
    record_id: str
    spans: list[Span] = field(default_factory=list)


class RollbackInvariantViolation(RuntimeError):
    """Raised when a rollback would excise a span more trusted than the poison."""


def excise_poisoned_spans(
    record: MemoryRecord,
    poisoned_write_ids: set[str],
    poison_tier: TrustTier,
) -> MemoryRecord:
    survivors: list[Span] = []
    for span in record.spans:
        is_poison = span.source_write_id in poisoned_write_ids

        if is_poison and span.tier is not None and span.tier > poison_tier:
            # The poison is entangled with a higher-trust span; span-level
            # excision is unsafe. Abort and force reconstruction.
            raise RollbackInvariantViolation(
                f"record {record.record_id}: span {span.text!r} carries tier "
                f"{span.tier.name} but is attributed to poisoned write "
                f"{span.source_write_id}; excision would destroy trusted content"
            )

        if is_poison:
            continue  # safely excise

        if span.source_write_id is None:
            # Unattributable span: cannot certify it is clean. Retain but mark
            # for re-verification rather than silently trusting it.
            survivors.append(span)
            continue

        survivors.append(span)

    return MemoryRecord(record_id=record.record_id, spans=survivors)


def rollback_record(record: MemoryRecord, poisoned_write_ids: set[str]) -> MemoryRecord:
    try:
        return excise_poisoned_spans(
            record, poisoned_write_ids, poison_tier=TrustTier.UNTRUSTED_WEB
        )
    except RollbackInvariantViolation:
        # Fall back to reconstruction: keep only spans attributable to
        # non-poisoned writes, drop everything else, require operator confirm.
        rebuilt = [
            s for s in record.spans
            if s.source_write_id is not None
            and s.source_write_id not in poisoned_write_ids
        ]
        if not rebuilt:
            raise RollbackInvariantViolation(
                f"record {record.record_id}: no attributable clean spans survive; "
                "reconstruction requires fresh trusted re-query"
            )
        return MemoryRecord(record_id=record.record_id, spans=rebuilt)
