# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-a-self-editing-context-policy-mid-turn-the-rewrite-commitment-boundary-and-the-divergence-between-policy-visibl.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-a-self-editing-context-policy-mid-turn-the-rewrite-commitment-boundary-and-the-divergence-between-policy-visibl.warrant.json
# Markdown SHA-256:   3110e6ae991c57fe5f0bbc1984e7fe3ad8f140c32167a3191622f80571f59dff
# Code AST SHA-256:   09f6e34de2d0badfbedfbd04b56a1e9b02205de58ff88eaba80a11eaf7ad3ed1
# Verified Classes:   RewriteCommitmentViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RewriteCommitmentViolation(RuntimeError):
    """Raised when a self-editing context policy attempts to commit a prune
    that intersects live references or cannot guarantee cache invalidation."""
    pass


def commit_context_rewrite(policy, prune_set, live_refs, cache_invalidatable):
    """
    Gate a self-editing context policy rewrite.

    policy            : mutable policy object (carries pending_prune intent)
    prune_set         : set of segment ids the salience heuristic wants to drop
    live_refs         : set of segment ids referenced by open obligations
    cache_invalidatable: callable(segment_id) -> bool, backend cache contract
    """
    intersecting = prune_set & live_refs
    if intersecting:
        # Do not apply. Record intent so the prune survives this rewrite.
        policy.pending_prune = getattr(policy, "pending_prune", set()) | intersecting
        raise RewriteCommitmentViolation(
            f"prune intersects live references {sorted(intersecting)}; "
            f"rewrite deferred to next quiescent point"
        )

    for seg in prune_set:
        if not cache_invalidatable(seg):
            # Partial prune leaves cached attention reachable -> divergence.
            # Promote to prefix rewrite or abandon.
            raise RewriteCommitmentViolation(
                f"segment {seg} cannot be cache-invalidated; "
                f"partial prune would fork policy-visible and executor-visible state"
            )

    # Safe: no live refs, full invalidation guaranteed.
    policy.apply_prune(prune_set)
    policy.pending_prune = getattr(policy, "pending_prune", set()) - prune_set
    return policy.materialize()
