# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-lossy-compaction-has-silently-dropped-a-recovery-critical-fact-before-the-checkpoint-it-depends-on-is-overwri.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-lossy-compaction-has-silently-dropped-a-recovery-critical-fact-before-the-checkpoint-it-depends-on-is-overwri.warrant.json
# Markdown SHA-256:   b9ffde9fb41c60e377892b9030d7316720633fa8789419edb09ffb189c3c636d
# Code AST SHA-256:   52cfb7cbd5d2c4f4613c467396e255e66ea77e3e202f4b3218512a74fef223d1
# Verified Classes:   CompactionCheckpointViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionCheckpointViolation(RuntimeError):
    """Raised when a lossy compaction would seal a distorted fact into a recovery checkpoint."""
    pass


def seal_checkpoint(summary: str, raw_spans: dict[str, str], pinned_facts: set[str],
                    pre_compaction_checkpoint: str | None) -> dict:
    """
    Enforce the invariant: a checkpoint may only be sealed from a summary if every
    constraint-bearing fact in the summary is either pinned verbatim or recoverable
    from a pre-compaction checkpoint that still holds the raw span.
    """
    distorted = []
    for fact in extract_constraint_facts(summary):
        span = raw_spans.get(fact.key)
        if span is None:
            # Fact has no traceable raw span: it was invented or the span was already dropped.
            distorted.append((fact.key, "no_raw_span"))
            continue
        if fact.text not in span and not is_exact_restatement(fact.text, span):
            # Summary rendering is not verbatim and not an exact restatement -> lossy/distorted.
            if fact.key not in pinned_facts and pre_compaction_checkpoint is None:
                distorted.append((fact.key, "lossy_and_unrecoverable"))

    if distorted:
        raise CompactionCheckpointViolation(
            f"Refusing to seal checkpoint: {len(distorted)} constraint fact(s) distorted "
            f"with no pinned entry or pre-compaction recovery source: {distorted}. "
            f"Write a raw-retention checkpoint pointing at pre-compaction state instead."
        )

    return {
        "summary": summary,
        "pinned_facts": sorted(pinned_facts),
        "derived_from": pre_compaction_checkpoint,
        "sealed": True,
    }


def extract_constraint_facts(summary: str):
    """Yield numeric literals, named entities, and constraint phrases from a summary."""
    raise NotImplementedError("domain-specific extractor")


def is_exact_restatement(candidate: str, span: str) -> bool:
    """True only if candidate is a verbatim substring or an exact normalized restatement of span."""
    raise NotImplementedError("domain-specific normalizer")
