# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-automatic-context-compaction-when-the-eviction-target-is-a-live-causal-dependency-of-an-in-flight-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-automatic-context-compaction-when-the-eviction-target-is-a-live-causal-dependency-of-an-in-flight-tool-call.warrant.json
# Markdown SHA-256:   b8325f915fdc8de79be11177c4bda8cf363ddab93463d171683596da3f0813de
# Code AST SHA-256:   024b0daa4bc4762369f0584975f883ffb02bdb92b29add1cb7fdf97f112a3ee6
# Verified Classes:   CompactionBoundaryViolation, PendingCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CompactionBoundaryViolation(RuntimeError):
    """Raised when automatic compaction would evict a span reachable
    from an outstanding tool call's reconciliation set."""


@dataclass(frozen=True)
class PendingCall:
    call_id: str
    tool: str
    idempotent: bool
    provenance_spans: FrozenSet[str]   # spans the args were derived from
    interpretation_keys: FrozenSet[str]  # schema/unit/locale markers
    commitments: FrozenSet[str]        # assertions to validate result against

    def closure(self) -> FrozenSet[str]:
        return self.provenance_spans | self.interpretation_keys | self.commitments


def select_eviction(
    candidate_spans: FrozenSet[str],
    pending: FrozenSet[PendingCall],
    resummarization_depth: dict,
) -> FrozenSet[str]:
    """Return the spans safe to evict. Refuse (raise) if the request
    would cross a live causal dependency; the caller must pin instead."""
    live: set[str] = set()
    for call in pending:
        live |= call.closure()

    protected = candidate_spans & live
    if protected:
        # Non-idempotent effect in flight touching the eviction set.
        non_idem = [c for c in pending if not c.idempotent and c.closure() & candidate_spans]
        if non_idem:
            raise CompactionBoundaryViolation(
                f"refusing compaction: pending non-idempotent call(s) "
                f"{[c.call_id for c in non_idem]} depend on spans {sorted(protected)}"
            )
        # Idempotent but interpretation/commitment still live.
        raise CompactionBoundaryViolation(
            f"refusing compaction: live interpretation/commitment spans "
            f"{sorted(protected)} must be pinned, not summarized"
        )

    for span in candidate_spans:
        if resummarization_depth.get(span, 0) >= 2:
            raise CompactionBoundaryViolation(
                f"refusing re-summarization of {span!r} at depth "
                f"{resummarization_depth[span]}; re-derive from source by ID"
            )

    return candidate_spans


def compact(candidate_spans, pending, resummarization_depth):
    evictable = select_eviction(candidate_spans, pending, resummarization_depth)
    return {"evicted": sorted(evictable), "pinned": sorted(candidate_spans - evictable)}
