# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-windows-from-corrupting-the-reasoning-trace-during-model-driven-pruning-and-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-windows-from-corrupting-the-reasoning-trace-during-model-driven-pruning-and-rewrite.warrant.json
# Markdown SHA-256:   c2114b6826622091c63ace6fe53879ccf15ed5a990882d43b9cee3b9d452d604
# Code AST SHA-256:   a3e7f246cae7e36e5b6edddbfb5d50e252c616027ae3c45e9e4d64d6238ca58d
# Verified Classes:   DerivationIntegrityError, ConstraintLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DerivationIntegrityError(RuntimeError):
    """Raised when a prune would orphan a retained derivation from its premises."""
    pass


class ConstraintLedger:
    """Append-only store of load-bearing constraints, outside the mutable window."""

    def __init__(self):
        self._entries = {}  # key -> (value, premise_turn_ids)

    def record(self, key, value, premise_turn_ids):
        self._entries[key] = (value, frozenset(premise_turn_ids))

    def retract(self, key, reason):
        if key not in self._entries:
            raise DerivationIntegrityError(
                f"retract of unknown constraint {key!r}: {reason}"
            )
        del self._entries[key]

    def lookup(self, key):
        return self._entries.get(key, (None, frozenset()))[0]

    def keys(self):
        return frozenset(self._entries)


def prune_window(window_turns, retained_ids, ledger, evidence_refetchable):
    """
    window_turns: dict turn_id -> {'class': 'evidence'|'derivation', 'cites': set}
    retained_ids: set of turn_ids the pruner wishes to keep
    Returns the set of turn_ids that are safe to evict.
    Raises DerivationIntegrityError if the requested retention is unsafe.
    """
    evictable = set()
    for tid in window_turns:
        if tid in retained_ids:
            continue
        turn = window_turns[tid]
        if turn["class"] == "evidence":
            if not evidence_refetchable(tid):
                raise DerivationIntegrityError(
                    f"evidence turn {tid} not re-fetchable; cannot evict"
                )
            evictable.add(tid)
        else:  # derivation
            # A derivation turn may be evicted only if its conclusion is
            # externalized to the ledger with premise pointers intact.
            if tid not in ledger.keys():
                raise DerivationIntegrityError(
                    f"derivation turn {tid} has no ledger entry; "
                    f"eviction would orphan its conclusion"
                )
            evictable.add(tid)

    # Second check: no retained turn may cite an evicted turn.
    for tid in retained_ids:
        deps = window_turns[tid]["cites"]
        orphaned = deps & evictable
        if orphaned:
            raise DerivationIntegrityError(
                f"retained turn {tid} cites evicted turns {sorted(orphaned)}"
            )
    return evictable
