# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-edit-rollback-that-would-re-inject-a-poisoned-memory-span.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-edit-rollback-that-would-re-inject-a-poisoned-memory-span.warrant.json
# Markdown SHA-256:   68e80a676152bbcc257ec90271b59a4b60c313cc3a6a4c276f51938b577a7468
# Code AST SHA-256:   b60dd0f2cbe1640bf12d9ce9a116d9d27124b8fae5f5f8ee979bddaaa77bdb9a
# Verified Classes:   RollbackTrustViolation, Span, TrustLedger, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class RollbackTrustViolation(RuntimeError):
    """Raised when a rollback would reinstate a span whose trust was downgraded post-checkpoint."""


@dataclass(frozen=True)
class Span:
    span_id: str
    content_hash: str
    load_bearing: bool


@dataclass
class TrustLedger:
    # content_hash -> current trust tier; lower is less trusted
    tiers: dict[str, int] = field(default_factory=dict)
    quarantined: set[str] = field(default_factory=set)

    def is_quarantined(self, content_hash: str) -> bool:
        return content_hash in self.quarantined


@dataclass
class Checkpoint:
    checkpoint_id: str
    reinstated_set: list[Span]  # spans that replaying inverse ops to here would restore


def rollback_to(
    target: Checkpoint,
    ledger: TrustLedger,
    allow_tombstone: bool = True,
) -> list[str]:
    """
    Attempt rollback to `target`. Returns list of span_ids tombstoned.
    Raises RollbackTrustViolation if a load-bearing quarantined span would be reinstated.
    """
    reinstated = target.reinstated_set
    poisoned = [s for s in reinstated if ledger.is_quarantined(s.content_hash)]

    if not poisoned:
        return []  # clean rollback

    load_bearing_poisoned = [s for s in poisoned if s.load_bearing]
    if load_bearing_poisoned:
        raise RollbackTrustViolation(
            f"rollback to {target.checkpoint_id} would reinstate load-bearing quarantined "
            f"spans {[s.span_id for s in load_bearing_poisoned]}; escalate to ancestor checkpoint"
        )

    if not allow_tombstone:
        raise RollbackTrustViolation(
            f"rollback to {target.checkpoint_id} would reinstate quarantined spans "
            f"{[s.span_id for s in poisoned]} and tombstones are disabled"
        )

    # conditional rollback: substitute tombstones, record as forward edit
    return [s.span_id for s in poisoned]


def select_rollback_target(
    candidates: Iterable[Checkpoint],
    ledger: TrustLedger,
) -> Checkpoint:
    """Pick the most recent checkpoint whose reinstated set is fully clean under current trust."""
    ordered = sorted(candidates, key=lambda c: c.checkpoint_id, reverse=True)
    for cp in ordered:
        if all(not ledger.is_quarantined(s.content_hash) for s in cp.reinstated_set):
            return cp
    raise RollbackTrustViolation("no clean checkpoint available; halt and escalate")
