# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-rewrite-the-compaction-oscillation-trap-in-budgeted-working-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-rewrite-the-compaction-oscillation-trap-in-budgeted-working-memory.warrant.json
# Markdown SHA-256:   0d8ca24e5f7c841a1861b9aa37e075a810b6df924f7e1ababe0872349a0dc56f
# Code AST SHA-256:   cd76593e473551bab83f68a0580548078216affcf844cb03a333dad0ebb1e92a
# Verified Classes:   NonIdempotentRewriteError, Obligation, WorkingBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable, Hashable


class NonIdempotentRewriteError(RuntimeError):
    """Raised when a self-rewrite would compress live obligations non-idempotently."""


@dataclass(frozen=True)
class Obligation:
    key: Hashable
    provenance: str          # immutable origin tag: tool:step:hash
    consumer_has_run: bool   # False => still live


@dataclass
class WorkingBuffer:
    obligations: dict[Hashable, Obligation] = field(default_factory=dict)
    checkpoint: dict[Hashable, Obligation] | None = None

    def live(self) -> dict[Hashable, Obligation]:
        return {k: o for k, o in self.obligations.items() if not o.consumer_has_run}


def _provenance_preserved(before: dict[Hashable, Obligation],
                          after: dict[Hashable, Obligation]) -> bool:
    for k, o in before.items():
        if k not in after:
            return False
        if after[k].provenance != o.provenance:
            return False  # reconstructed/inferred provenance => not preserved
    return True


def safe_self_rewrite(
    buf: WorkingBuffer,
    rewrite: Callable[[dict[Hashable, Obligation]], dict[Hashable, Obligation]],
    *,
    budget_tokens: int,
    estimate_tokens: Callable[[dict[Hashable, Obligation]], int],
) -> dict[Hashable, Obligation]:
    """
    Apply a self-rewrite only if it is a fixed point on live obligations,
    carries provenance verbatim, and a checkpoint exists to re-inflate from.
    """
    live_before = buf.live()

    # Guard 1: checkpoint must exist before mutating live obligations.
    if buf.checkpoint is None:
        raise NonIdempotentRewriteError(
            "refusing rewrite of live obligations: no checkpoint to re-inflate from"
        )

    candidate = rewrite(dict(buf.obligations))

    # Guard 2: provenance must be carried, not reconstructed.
    if not _provenance_preserved(live_before, candidate):
        raise NonIdempotentRewriteError(
            "refusing rewrite: provenance not preserved verbatim on live obligations"
        )

    # Guard 3: idempotence on the obligation set -- re-applying must be a no-op.
    second = rewrite(dict(candidate))
    if second != candidate:
        raise NonIdempotentRewriteError(
            "refusing rewrite: routine is not idempotent on its own output "
            "(compaction-oscillation risk)"
        )

    # Guard 4: only commit if the rewrite actually buys budget headroom.
    if estimate_tokens(candidate) >= budget_tokens:
        raise NonIdempotentRewriteError(
            "refusing rewrite: candidate still exceeds budget; escalate instead"
        )

    buf.obligations = candidate
    return candidate
