# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-priority-weighted-compaction-from-silently-evicting-a-high-priority-subagent-s-working-set-when-the-shared-context-budget-is.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-priority-weighted-compaction-from-silently-evicting-a-high-priority-subagent-s-working-set-when-the-shared-context-budget-is.warrant.json
# Markdown SHA-256:   79ede6ec8cdb75f8ec3ad24659b62be0f101510962f9b5e6fd414abfc06c9710
# Code AST SHA-256:   2c758900135159120c85260032b04ce5824704ee955e537820e5df3034a42c4b
# Verified Classes:   ContinuityInvariantViolation, Segment, CompactionResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class ContinuityInvariantViolation(RuntimeError):
    """Raised when priority-weighted compaction evicts below a subagent's
    quota floor or splits a contiguous reasoning trace."""
    pass


@dataclass
class Segment:
    agent_id: str
    index: int          # position within the agent's working set
    tokens: int
    kind: str           # "head" | "tail"
    trace_id: str | None = None  # non-None for reasoning-trace segments


@dataclass
class CompactionResult:
    kept: List[Segment] = field(default_factory=list)
    evicted: List[Segment] = field(default_factory=list)


def compact_with_invariants(
    segments: List[Segment],
    weights: Dict[str, float],
    budget: int,
) -> CompactionResult:
    total_weight = sum(weights.values())
    if total_weight <= 0:
        raise ContinuityInvariantViolation("priority weights must sum to > 0")

    # Invariant 1: compute per-agent quota floors BEFORE any global pass.
    quotas = {aid: int(budget * w / total_weight) for aid, w in weights.items()}

    by_agent: Dict[str, List[Segment]] = {aid: [] for aid in weights}
    for seg in segments:
        by_agent.setdefault(seg.agent_id, []).append(seg)

    result = CompactionResult()

    # Invariant 2: each agent is compacted to its own quota; tail traces are
    # atomic. We never let a global ranking evict across a quota boundary.
    for aid, segs in by_agent.items():
        quota = quotas.get(aid, 0)
        segs.sort(key=lambda s: (s.kind != "head", s.index))
        used = 0
        kept_traces: Dict[str, List[Segment]] = {}
        for seg in segs:
            if used + seg.tokens > quota:
                # A trace segment that would be split triggers the guard.
                if seg.trace_id is not None and seg.trace_id in kept_traces:
                    raise ContinuityInvariantViolation(
                        f"compaction would split trace {seg.trace_id} "
                        f"for agent {aid} at segment {seg.index}"
                    )
                result.evicted.append(seg)
                continue
            used += seg.tokens
            result.kept.append(seg)
            if seg.trace_id is not None:
                kept_traces.setdefault(seg.trace_id, []).append(seg)

        # Invariant 3: quota floor must be honored; if head segments alone
        # exceed the quota, the agent is continuity-degraded, not silently
        # truncated.
        if used > quota:
            raise ContinuityInvariantViolation(
                f"agent {aid} exceeded quota {quota} with {used} tokens"
            )

    # Invariant 4: global budget must still hold after per-agent compaction.
    total_kept = sum(s.tokens for s in result.kept)
    if total_kept > budget:
        raise ContinuityInvariantViolation(
            f"post-compaction usage {total_kept} exceeds budget {budget}"
        )
    return result
