# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-transform-rather-than-a-safe-truncation-and-how-does-the-compaction-boundary-itsel.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-transform-rather-than-a-safe-truncation-and-how-does-the-compaction-boundary-itsel.warrant.json
# Markdown SHA-256:   1e91a7b6510aed6aeed5c7011615cc6bf64b060f05c616492c1a5eb58afe948f
# Code AST SHA-256:   0b798aca1c1f06ba42977e6b2706521c98c4ef0e3696eb4bce138bfa65dc03b2
# Verified Classes:   CompactionInvalid, SpanClass, Span, PinnedRegion
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class CompactionInvalid(RuntimeError):
    """Raised when an auto-compaction would evict load-bearing state into a lossy summary."""
    pass


class SpanClass(Enum):
    NARRATIVE = "narrative"      # safe to summarize
    CONSTRAINT = "constraint"    # pin verbatim; never summarize
    CREDENTIAL = "credential"    # pin verbatim
    OPEN_ARTIFACT = "open_artifact"  # boundary must not fall inside


@dataclass
class Span:
    start: int
    end: int
    kind: SpanClass
    artifact_id: str | None = None
    closed: bool = True


@dataclass
class PinnedRegion:
    facts: dict[str, str] = field(default_factory=dict)  # key -> verbatim payload

    def pin(self, key: str, payload: str) -> None:
        self.facts[key] = payload


def compact(spans: list[Span], boundary: int, pinned: PinnedRegion,
            durable_source: dict[str, str]) -> list[Span]:
    """Evict spans ending before `boundary`. Refuse if the boundary is unsafe."""
    evicted, retained = [], []

    for span in spans:
        crosses = span.start < boundary <= span.end
        if crosses and span.kind is SpanClass.OPEN_ARTIFACT:
            # Boundary falls inside an unclosed structured artifact.
            raise CompactionInvalid(
                f"boundary {boundary} lands inside open artifact {span.artifact_id!r} "
                f"[{span.start},{span.end}); flush or advance boundary"
            )
        if span.end <= boundary:
            if span.kind in (SpanClass.CONSTRAINT, SpanClass.CREDENTIAL):
                # Must be pinned verbatim, not summarized.
                key = f"{span.kind.value}:{span.start}"
                payload = durable_source.get(key)
                if payload is None:
                    raise CompactionInvalid(
                        f"load-bearing span {key} has no durable source; "
                        f"cannot pin before eviction"
                    )
                pinned.pin(key, payload)
            evicted.append(span)
        else:
            retained.append(span)

    return retained


def resume_check(pinned: PinnedRegion, expected_keys: set[str]) -> None:
    """Post-compaction invariant: every held constraint must be enumerable."""
    missing = expected_keys - set(pinned.facts)
    if missing:
        raise CompactionInvalid(
            f"post-compaction invariant violated: constraints {sorted(missing)} "
            f"were not preserved; roll back to pre-eviction checkpoint"
        )
