# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-in-place-scratchpad-mutation-as-a-non-commutative-operation-requiring-a-mutation-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-in-place-scratchpad-mutation-as-a-non-commutative-operation-requiring-a-mutation-ledger.warrant.json
# Markdown SHA-256:   e13b489d2e8a01f3040cf32a0c1ba26dc22084f138e4b7bdb3b3fd195ce629e4
# Code AST SHA-256:   b45a4b8e8662484c5447fe0db77cefbcc6286c96345c569452702c8997d0f175
# Verified Classes:   DanglingReferentError, Span, Marker, MutationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DanglingReferentError(RuntimeError):
    """Raised when an in-place context rewrite would sever a live marker's referent."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    closed: bool = False          # True once no live marker references it


@dataclass
class Marker:
    marker_id: str
    kind: str                     # "conditional" | "comparison" | "derivation"
    referent_span_ids: list[str]


@dataclass
class MutationLedger:
    entries: list[dict] = field(default_factory=list)

    def record(self, rewrite_id: str, removed: list[str],
               retained: list[str], broken: list[str]) -> None:
        # Logged BEFORE the mutation is applied, so replay can reconstruct pre-state.
        self.entries.append({
            "rewrite_id": rewrite_id,
            "removed": removed,
            "retained": retained,
            "referents_broken": broken,
        })


def self_edit(
    spans: dict[str, Span],
    markers: list[Marker],
    spans_to_remove: list[str],
    ledger: Optional[MutationLedger],
    rewrite_id: str,
) -> None:
    """Apply an in-place compaction, refusing if it would orphan a live referent."""
    removed = set(spans_to_remove)

    broken: list[str] = []
    for m in markers:
        live_refs = [r for r in m.referent_span_ids if r not in removed]
        if len(live_refs) != len(m.referent_span_ids):
            broken.append(m.marker_id)

    if broken:
        if ledger is None:
            # No write barrier available: fail closed rather than corrupt silently.
            raise DanglingReferentError(
                f"rewrite {rewrite_id} would sever referents of markers {broken} "
                f"with no mutation ledger; refusing compaction"
            )
        # Ledger present: record the break, but require explicit tombstoning.
        ledger.record(
            rewrite_id=rewrite_id,
            removed=sorted(removed),
            retained=sorted(k for k in spans if k not in removed),
            broken=broken,
        )
        for m in markers:
            if m.marker_id in broken:
                raise DanglingReferentError(
                    f"marker {m.marker_id} left dangling by rewrite {rewrite_id}; "
                    f"must re-bind or tombstone before further reads"
                )

    # Safe path: no live referent severed. Apply the mutation.
    for sid in removed:
        del spans[sid]
    if ledger is not None:
        ledger.record(rewrite_id, sorted(removed), sorted(spans), [])
