# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-after-a-self-edit-to-prevent-provenance-collapse-in-salience-based-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-after-a-self-edit-to-prevent-provenance-collapse-in-salience-based-pruning.warrant.json
# Markdown SHA-256:   a978cb6060764cfd8f19d89b64efdf89578cedb1dc1b3e38efa3e1de3fb76ad1
# Code AST SHA-256:   ae9422b20d08ad1308d60a98c0f8cf7ac66c29fabe10ed92a00420193a76573a
# Verified Classes:   ProvenanceCollapseError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceCollapseError(RuntimeError):
    """Raised when a context self-edit removes a span without emitting a resolvable tombstone."""
    pass


def apply_salience_edit(context, evictions, goal_entities, revision):
    """
    Rewrite context per salience evictions, emitting tombstones for any evicted
    span reachable from the current goal. Atomic: tombstones written before the
    edit commits, so a crash leaves orphans, never collapse.
    """
    tombstones = []
    for span in evictions:
        if span.entity in goal_entities:
            tombstones.append({
                "span_id": span.id,
                "source": span.source,
                "confidence": span.confidence,
                "staleness_flag": span.staleness_flag,
                "evicted_at_revision": revision,
                "reason": "low_salience",
                "committed": False,
            })

    # Write tombstones first (orphans are safe; collapse is not).
    for t in tombstones:
        context.tombstones.append(t)

    # Now rewrite. If this raises, tombstones remain as harmless orphans.
    try:
        context.spans = [s for s in context.spans if s.id not in {e.id for e in evictions}]
        context.revision = revision
    except Exception as exc:
        raise ProvenanceCollapseError(
            f"edit at rev {revision} failed mid-commit; {len(tombstones)} tombstones orphaned"
        ) from exc

    # Verify every reachable eviction has a committed tombstone.
    evicted_ids = {e.id for e in evictions}
    tombstoned_ids = {t["span_id"] for t in tombstones}
    missing = evicted_ids & goal_entities_ids(evictions, goal_entities) - tombstoned_ids
    if missing:
        raise ProvenanceCollapseError(
            f"rev {revision}: reachable spans evicted without tombstone: {missing}"
        )

    for t in tombstones:
        t["committed"] = True
    return context


def goal_entities_ids(evictions, goal_entities):
    return {s.id for s in evictions if s.entity in goal_entities}
