# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-freeze-a-self-editing-context-policy-before-in-place-salience-reweighting-corrupts-retrieval-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-freeze-a-self-editing-context-policy-before-in-place-salience-reweighting-corrupts-retrieval-provenance.warrant.json
# Markdown SHA-256:   5184861162625c147735ac74939b0f037e01cbfb3f35f6f6fb5f170a99ad1f51
# Code AST SHA-256:   39f80218c1872d8a87f0d2a13ea55179f4e6f92729b63a4f8b0c0fefdf99167b
# Verified Classes:   ContextPolicyFrozenError, SalienceRecord, EditPass
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ContextPolicyFrozenError(RuntimeError):
    """Raised when a self-edit pass would shift offsets under live salience records."""


@dataclass
class SalienceRecord:
    span_id: str
    offset_range: tuple[int, int]
    score: float
    tombstoned: bool = False


@dataclass
class EditPass:
    rewrites: list[tuple[int, int]] = field(default_factory=list)  # (start, end) to be rewritten/evicted
    emits_remap: bool = False
    index_offset_bound: bool = True
    concurrent_reader_snapshot: bool = False


def guard_self_edit(pass_: EditPass, live_records: list[SalienceRecord]) -> None:
    """Enforce the offset-stability invariant before a combined reweight+rewrite pass commits."""
    if not pass_.rewrites:
        return  # reweight-only: offsets trivially stable

    if pass_.concurrent_reader_snapshot:
        raise ContextPolicyFrozenError(
            "freeze required: a concurrent reader holds a pre-pass snapshot; "
            "in-place rewrite would invalidate its offset-valid citations"
        )

    if not pass_.emits_remap:
        raise ContextPolicyFrozenError(
            "freeze required: rewrite pass emits no remap table; "
            "live salience records cannot be safely rewritten through the shift"
        )

    for rec in live_records:
        if rec.tombstoned:
            continue
        for start, end in pass_.rewrites:
            # overlap test: any live record intersecting a rewritten range must be remapped
            if rec.offset_range[0] < end and start < rec.offset_range[1]:
                if pass_.index_offset_bound:
                    raise ContextPolicyFrozenError(
                        f"freeze required: record {rec.span_id} at {rec.offset_range} "
                        f"overlaps rewrite [{start},{end}] and the retrieval index is "
                        f"offset-bound; migrate to span-ID keys or fall back to reweight-only"
                    )
                # remap path is legal only because emits_remap is True and index is span-ID keyed
                break


def commit_self_edit(pass_: EditPass, live_records: list[SalienceRecord]) -> None:
    guard_self_edit(pass_, live_records)
    # ... score, rewrite, remap, tombstone, commit atomically ...
