# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-compaction-triggered-cost-latency-inversion-in-agent-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-compaction-triggered-cost-latency-inversion-in-agent-context-windows.warrant.json
# Markdown SHA-256:   d756da8d525c8a9bae1dcfef31333635698f2be4598ab8004aefc5d352b1cdad
# Code AST SHA-256:   20fff3e8393c3cb49da7f81d86a59d0389fd006fd598b5d6c7c5fb08dd1dde50
# Verified Classes:   CompactionInversionError, CompactionEvent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class CompactionInversionError(RuntimeError):
    """Raised when compaction cost exceeds the headroom it reclaims."""
    pass


@dataclass
class CompactionEvent:
    tokens_summarized_in: int   # S_in
    summary_tokens_out: int     # S_out
    turns_until_next: int       # ΔT (k)
    productive_tokens: int      # P over that interval

    @property
    def reclaimed(self) -> int:
        return self.tokens_summarized_in - self.summary_tokens_out

    @property
    def generation_cost(self) -> int:
        return self.tokens_summarized_in + self.summary_tokens_out

    @property
    def productive_ratio(self) -> float:
        return self.productive_tokens / max(self.reclaimed, 1)


def should_compact(
    occupancy: int,
    threshold: int,
    remaining_subtasks: int,
    expected_tokens_per_subtask: int,
    reclaimed_estimate: int,
    summary_tax_per_turn: int,
    generation_cost: int,
    min_amortization_turns: int = 3,
    min_productive_ratio: float = 0.5,
) -> bool:
    """Gate compaction on projected remaining work, not occupancy alone."""
    if occupancy < threshold:
        return False
    # Amortization horizon: summary must pay back before re-trigger.
    if remaining_subtasks < min_amortization_turns:
        return False
    if expected_tokens_per_subtask < reclaimed_estimate:
        return False
    # Net-benefit inequality: c + s*k < R*u, with u ~ 1 token/token.
    horizon = remaining_subtasks
    net = reclaimed_estimate - (generation_cost + summary_tax_per_turn * horizon)
    if net <= 0:
        raise CompactionInversionError(
            f"compaction net-negative: reclaimed={reclaimed_estimate} "
            f"cost={generation_cost} tax={summary_tax_per_turn}x{horizon} "
            f"net={net}"
        )
    return True


def check_breaker(history: list[CompactionEvent], min_ratio: float = 0.5) -> None:
    """Halt compaction when productive spend per reclaimed token collapses."""
    if len(history) < 2:
        return
    recent = history[-2:]
    if all(ev.productive_ratio < min_ratio for ev in recent):
        raise CompactionInversionError(
            "compaction-inversion: P/R below threshold for two cycles; "
            f"ratios={[round(e.productive_ratio, 3) for e in recent]}"
        )
