# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-a-lossy-non-commutative-rewrite-rather-than-a-garbage-collection-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-a-lossy-non-commutative-rewrite-rather-than-a-garbage-collection-pass.warrant.json
# Markdown SHA-256:   268f7d55cce2d7e6080349af49699b6ba91c45df19fe84fc259ff820ff97b893
# Code AST SHA-256:   4ee3d46b6b63272a078cca5fe85bd6b1e65540d49253b78b18e89bdf7100ddc6
# Verified Classes:   PruneSupersetViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PruneSupersetViolation(RuntimeError):
    """Raised when a model-driven context prune would drop a fact required by an open goal."""
    pass


def apply_prune(prune_span_ids, context, open_goals, provenance_log):
    # 1. Re-entry hazard: refuse to re-prune derived spans.
    derived_ids = {s.id for s in context.spans if s.derived}
    if derived_ids & set(prune_span_ids):
        raise PruneSupersetViolation(
            f"prune targets derived spans {derived_ids & set(prune_span_ids)}; "
            "re-summarizing a summary is lossy and non-idempotent"
        )

    # 2. Build the residue by replacing targets with model-proposed summaries.
    residue = context.with_replacements(prune_span_ids)

    # 3. Superset check: every open goal's fact-set must survive in the residue.
    required = set()
    for goal in open_goals:
        required |= set(goal.fact_set)
    missing = {f for f in required if not residue.contains_fact(f)}
    if missing:
        raise PruneSupersetViolation(
            f"post-prune residue drops required facts {missing}; "
            "abort prune, restore from provenance or restart from checkpoint"
        )

    # 4. Only commit provenance after the check passes.
    provenance_log.record(prune_span_ids, residue.new_span_ids, context.model_version)
    return residue
