# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-when-priority-weighted-retention-scoring-collides-with-a-pending-tool-call-cont.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-when-priority-weighted-retention-scoring-collides-with-a-pending-tool-call-cont.warrant.json
# Markdown SHA-256:   bdaffd3eff7d4dc0d1e830a37b7726404da46e66aa83fdacf5ba26f8e65d2288
# Code AST SHA-256:   1984427c58f43b268e107b29c14208c9ff740c9cb25b38e7f0d15f4c6a3ff0f3
# Verified Classes:   OrphanedContractError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedContractError(RuntimeError):
    """Raised when a prune would sever the sole carrier of an open tool-call contract."""
    pass


@dataclass
class Segment:
    seg_id: str
    score: float
    call_ids: set[str] = field(default_factory=set)   # open call_ids this segment carries
    checkpoint_refs: set[str] = field(default_factory=set)
    is_tombstone: bool = False


def prune_batch(
    segments: list[Segment],
    threshold: float,
    batch_already_partially_applied: bool = False,
) -> list[Segment]:
    """
    Model-driven prune with obligation veto.
    Scoring decides *candidates*; reachability decides *permission*.
    Returns the retained segments (pruned ones are dropped or tombstoned).
    """
    # Build the set of call_ids / checkpoint refs that survive independent of each candidate.
    retained: list[Segment] = []
    pruned_ids: set[str] = set()

    for seg in segments:
        if seg.score >= threshold:
            retained.append(seg)
            continue

        # Candidate for pruning. Check whether it is the sole carrier of any obligation.
        other_carriers = {
            cid
            for other in segments
            if other.seg_id != seg.seg_id and other.seg_id not in pruned_ids
            for cid in other.call_ids
        }
        other_checkpoints = {
            ref
            for other in segments
            if other.seg_id != seg.seg_id and other.seg_id not in pruned_ids
            for ref in other.checkpoint_refs
        }

        orphaned_calls = seg.call_ids - other_carriers
        orphaned_ckpts = seg.checkpoint_refs - other_checkpoints

        if orphaned_calls or orphaned_ckpts:
            if batch_already_partially_applied:
                # Partial application + orphaning = compounding corruption. Hard stop.
                raise OrphanedContractError(
                    f"Prune refused at segment {seg.seg_id}: sole carrier of "
                    f"call_ids={orphaned_calls} checkpoints={orphaned_ckpts} "
                    f"during a partially-applied batch. Checkpoint open contracts "
                    f"and restart; do not delete."
                )
            # Safe path: demote to tombstone, preserving the binding at low token cost.
            retained.append(
                Segment(
                    seg_id=seg.seg_id,
                    score=seg.score,
                    call_ids=set(seg.call_ids),
                    checkpoint_refs=set(seg.checkpoint_refs),
                    is_tombstone=True,
                )
            )
            continue

        # No obligation orphaned: prune is permitted.
        pruned_ids.add(seg.seg_id)

    return retained


def assert_no_orphan_results(context_results: list[str], retained: list[Segment]) -> None:
    """Post-arrival guard: every tool_result must have a surviving call_id carrier."""
    carried = {cid for seg in retained for cid in seg.call_ids}
    for result_call_id in context_results:
        if result_call_id not in carried:
            raise OrphanedContractError(
                f"tool_result for call_id={result_call_id} arrived with no surviving "
                f"carrier; model would fabricate a reconciling call. Lineage unsound."
            )
