# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-account-for-eviction-induced-attention-debt-when-a-self-editing-context-window-evicts-by-model-judged-salience-rather-than-by-t.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-account-for-eviction-induced-attention-debt-when-a-self-editing-context-window-evicts-by-model-judged-salience-rather-than-by-t.warrant.json
# Markdown SHA-256:   32d885ee1ed624e72dfea3c78b4417bf9e957955a2b190b540896439800c573d
# Code AST SHA-256:   40cbf71377c3d06135bd49af961516b00e9ecd22ee1fa56f4204f5b89887e64c
# Verified Classes:   AttentionDebtError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class AttentionDebtError(RuntimeError):
    """Raised when eviction would orphan a surviving span's antecedent."""
    pass


@dataclass
class Span:
    span_id: str
    salience: int
    references: Set[str] = field(default_factory=set)   # antecedent span_ids this span leans on
    self_grounding: bool = True                          # antecedent in-window or pointer-backed


def compaction_pass(spans: Dict[str, Span], evict_threshold: int = 2) -> Dict[str, Span]:
    """Evict low-salience spans unless doing so orphans a surviving span.

    Invariant: no surviving span may reference an evicted span.
    """
    candidates = {sid for sid, s in spans.items() if s.salience <= evict_threshold}
    survivors = {sid for sid in spans if sid not in candidates}

    # Reverse-dependency: which survivors lean on each candidate?
    for sid in candidates:
        dependents = {s for s in survivors if sid in spans[s].references}
        if dependents:
            # Demote the orphaned consequents instead of silently keeping them.
            for d in dependents:
                spans[d].self_grounding = False
            raise AttentionDebtError(
                f"eviction of {sid} would orphan {sorted(dependents)}; "
                f"demote to UNVERIFIED and re-fetch antecedent before evicting"
            )

    # Self-grounding audit of survivors.
    for sid in survivors:
        if not spans[sid].self_grounding:
            raise AttentionDebtError(
                f"surviving span {sid} is an orphan assertion; "
                f"re-fetch antecedent or demote before proceeding"
            )

    return {sid: s for sid, s in spans.items() if sid in survivors}


def run_compaction(spans: Dict[str, Span]) -> Dict[str, Span]:
    try:
        return compaction_pass(spans)
    except AttentionDebtError as e:
        # Surface the gap; do not launder it into a summary.
        raise AttentionDebtError(f"compaction blocked: {e}") from e
