# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-its-own-memory-rewrite-the-self-edit-commit-hazard-under-budget-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-its-own-memory-rewrite-the-self-edit-commit-hazard-under-budget-pressure.warrant.json
# Markdown SHA-256:   cea72ecf58ad266fd69256d37a92454cf79dbf04f1c1839f6883ab9977d09e0e
# Code AST SHA-256:   f40e3f65f9c7ac35a5c56bb74a03218dd3f6c33f80b4b0b9001a12ddeae1a659
# Verified Classes:   UnverifiableRewriteError, Span, RewriteProposal
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UnverifiableRewriteError(RuntimeError):
    """Raised when a self-rewrite cannot be validated against a live source buffer."""
    pass


@dataclass
class Span:
    span_id: str
    load_bearing: bool  # derived from structure, never from the compressor's judgment


@dataclass
class RewriteProposal:
    token_count: int
    budget: int
    retained_span_ids: set[str] = field(default_factory=set)
    tombstoned_span_ids: set[str] = field(default_factory=set)


def commit_self_rewrite(
    source_buffer: list[Span] | None,
    proposal: RewriteProposal,
    validator_saw_source: bool,
) -> RewriteProposal:
    # Referent test: source must still be addressable at validation time.
    if source_buffer is None:
        raise UnverifiableRewriteError(
            "pre-rewrite buffer already released; rewrite is unverifiable, "
            "downgrade to eviction or persist an external checkpoint"
        )

    # Oracle-independence test: the faithfulness check must have read the source.
    if not validator_saw_source:
        raise UnverifiableRewriteError(
            "faithfulness check was self-graded over the rewritten buffer; "
            "the check is vacuous"
        )

    # Tombstone test: every load-bearing span must survive or be explicitly tombstoned.
    load_bearing = {s.span_id for s in source_buffer if s.load_bearing}
    silently_dropped = load_bearing - proposal.retained_span_ids - proposal.tombstoned_span_ids
    if silently_dropped:
        raise UnverifiableRewriteError(
            f"load-bearing spans silently discarded with no tombstone: "
            f"{sorted(silently_dropped)}; post-rewrite instance cannot detect the loss"
        )

    if proposal.token_count > proposal.budget:
        raise UnverifiableRewriteError(
            f"rewrite exceeds budget ({proposal.token_count} > {proposal.budget})"
        )

    return proposal
