# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-hierarchical-summarization-as-a-lossy-transform-and-checkpoint-before-compaction-rather-than-after.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-hierarchical-summarization-as-a-lossy-transform-and-checkpoint-before-compaction-rather-than-after.warrant.json
# Markdown SHA-256:   d77712a5d1bdf657fd0adbe59e56482842e2e33d5e2e1112c8a376384ff7cc75
# Code AST SHA-256:   7f6e38b9c737a2583bcd415a37d10ef2c326ec897c318cda79824981f70443cf
# Verified Classes:   CompactionOrderViolation, WorkingState, CheckpointStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CompactionOrderViolation(RuntimeError):
    """Raised when compaction is attempted without a prior durable checkpoint,
    or when a post-resume re-derivation diverges from the checkpointed fact."""
    pass


@dataclass
class WorkingState:
    raw_spans: list[str]
    pinned_constraints: list[str]  # negations / bounds / entity bindings
    entity_bindings: dict[str, str]

    def fingerprint(self) -> str:
        blob = json.dumps(
            {
                "spans": self.raw_spans,
                "pins": self.pinned_constraints,
                "bindings": self.entity_bindings,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class CheckpointStore:
    _store: dict[str, WorkingState] = field(default_factory=dict)

    def commit(self, state: WorkingState) -> str:
        fp = state.fingerprint()
        # Deep-ish copy: checkpoint must be a superset of anything the summary keeps.
        self._store[fp] = WorkingState(
            raw_spans=list(state.raw_spans),
            pinned_constraints=list(state.pinned_constraints),
            entity_bindings=dict(state.entity_bindings),
        )
        return fp

    def load(self, fp: str) -> WorkingState:
        if fp not in self._store:
            raise CompactionOrderViolation(f"no checkpoint at {fp}; cannot replay")
        return self._store[fp]


def compact_with_guard(
    state: WorkingState,
    store: CheckpointStore,
    summarizer,
    checkpoint_fp: str | None,
) -> tuple[str, str]:
    """Enforce checkpoint-before-compaction. Returns (checkpoint_fp, summary)."""
    if checkpoint_fp is None:
        # The failure ordering: summarizing/evicting before committing.
        raise CompactionOrderViolation(
            "compaction attempted with no prior checkpoint; "
            "summarization is lossy and non-invertible — commit first"
        )
    # Pin constraints verbatim; never let the salience-ranked summarizer drop them.
    summary = summarizer(
        spans=state.raw_spans,
        pinned=state.pinned_constraints,
    )
    for pin in state.pinned_constraints:
        if pin not in summary:
            raise CompactionOrderViolation(
                f"pinned constraint dropped by summarizer: {pin!r}"
            )
    return checkpoint_fp, summary


def verify_resume(
    checkpoint_fp: str,
    store: CheckpointStore,
    rederived: dict[str, str],
) -> None:
    """After resume, any re-derived fact must match the checkpoint, else rollback."""
    cp = store.load(checkpoint_fp)
    for key, value in rederived.items():
        expected = cp.entity_bindings.get(key)
        if expected is not None and expected != value:
            raise CompactionOrderViolation(
                f"compaction-induced divergence on {key!r}: "
                f"checkpoint={expected!r} rederived={value!r} -> rollback required"
            )
