# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-when-salience-rewriting-invalidates-its-own-retrieval-keys.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-when-salience-rewriting-invalidates-its-own-retrieval-keys.warrant.json
# Markdown SHA-256:   fc6e231a6361c216f0a06f96947847a12d0cb6c944ec9c003b7f66ac0a632c1f
# Code AST SHA-256:   45307fce4f31ff25072e89671f053fbbaec5f8d63359b77d6e3ab64310d4c9a7
# Verified Classes:   AddressabilityInvariantError, Span, ContextWindow
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class AddressabilityInvariantError(RuntimeError):
    """Raised when a salience rewrite would invalidate a future retrieval key."""


@dataclass
class Span:
    span_id: str
    exact: str
    surrogate: str | None = None


@dataclass
class ContextWindow:
    spans: dict[str, Span] = field(default_factory=dict)

    def add(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def rewrite_salience(self, span_id: str, surrogate: str,
                         protected_keys: Iterable[str]) -> None:
        span = self.spans[span_id]
        # Invariant: any token in the projected future query vocabulary
        # must survive verbatim in the retained exact span.
        for key in protected_keys:
            if key in span.exact and key not in surrogate:
                raise AddressabilityInvariantError(
                    f"rewrite of {span_id!r} drops protected key {key!r}; "
                    f"future retrieval would miss exact-match. "
                    f"Defer rewrite or use dual representation."
                )
        # Dual representation: keep exact bytes, attach surrogate for weighting.
        span.surrogate = surrogate

    def retrieve(self, query: str) -> list[Span]:
        # Exact-match over preserved spans first, then surrogate fallback.
        hits = [s for s in self.spans.values() if query in s.exact]
        if hits:
            return hits
        return [s for s in self.spans.values()
                if s.surrogate and query.lower() in s.surrogate.lower()]


def prune_and_rewrite(window: ContextWindow, survivors: list[str],
                      surrogates: dict[str, str],
                      projected_query_keys: list[str]) -> None:
    for sid in survivors:
        if sid in surrogates:
            window.rewrite_salience(sid, surrogates[sid], projected_query_keys)
    for sid in list(window.spans):
        if sid not in survivors:
            del window.spans[sid]


# Trigger: plan step 11 will query "leftpad 3.2.1 integrity sha512".
w = ContextWindow()
w.add(Span("lock", "package: leftpad\nresolved: 3.2.1\nintegrity: sha512-abc"))
try:
    prune_and_rewrite(
        w,
        survivors=["lock"],
        surrogates={"lock": "leftpad pinned to a recent 3.x release; hash retained."},
        projected_query_keys=["3.2.1", "sha512"],
    )
except AddressabilityInvariantError as e:
    # Correct behavior: defer rewrite, keep exact span, retrieval stays valid.
    print(f"rewrite blocked: {e}")
