# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-semantic-drift-introduced-by-hierarchical-summarization-before-committing-a-compacted-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-semantic-drift-introduced-by-hierarchical-summarization-before-committing-a-compacted-checkpoint.warrant.json
# Markdown SHA-256:   0dfad0314a6f8dc0f7502f29534c3988c3499398898a75563101cceca9118e68
# Code AST SHA-256:   bd779323e71906e28e8866476c847e92960d2d406367377580c4e60efcdfd02c
# Verified Classes:   CompactionDriftError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CompactionDriftError(RuntimeError):
    """Raised when a compacted checkpoint mutates the frozen predicate set."""
    pass


def compact_with_predicate_guard(
    pre_state_spans: list[str],
    frozen_predicates: set[str],
    summarizer,
) -> dict:
    """
    Perform hierarchical compaction but refuse to commit if the merge step
    mutates, drops, or temporally collapses any frozen predicate.
    """
    # 1. Summarize (lossy, non-deterministic).
    summary = summarizer.summarize(pre_state_spans)

    # 2. Extract predicates from the post-merge summary.
    post_predicates = summarizer.extract_predicates(summary)

    # 3. Drift check: equality under normalization, not subset, not superset.
    missing = frozen_predicates - post_predicates
    mutated = {
        p for p in frozen_predicates
        if p in post_predicates and not summarizer.equivalent(p, post_predicates)
    }
    # Temporal-collapse detector: a constraint whose "until" qualifier vanished.
    collapsed = {
        p for p in frozen_predicates
        if summarizer.has_temporal_scope(p) and not summarizer.has_temporal_scope_in(summary, p)
    }

    if missing or mutated or collapsed:
        raise CompactionDriftError(
            f"compaction rejected: missing={sorted(missing)} "
            f"mutated={sorted(mutated)} temporal_collapse={sorted(collapsed)}; "
            f"re-summarize with predicates pinned verbatim or abort."
        )

    # 4. Only now is the checkpoint admissible as resumable state.
    return {
        "summary": summary,
        "predicates": sorted(post_predicates),
        "loss_declaration": summarizer.loss_list(summary),
        "committed": True,
    }
