# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-context-compaction-debt-before-a-latency-budget-is-breached.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-context-compaction-debt-before-a-latency-budget-is-breached.warrant.json
# Markdown SHA-256:   cdcc02e01bf63cd4949afd22576e9a729f8df55710030e6a172598105c1fd192
# Code AST SHA-256:   51e8db11142fe4a54265d48f254e8a66773d9ab6ee562e8421873d36db2774bc
# Verified Classes:   CompactionBudgetError, InstanceState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class CompactionBudgetError(RuntimeError):
    """Raised when a compaction recommendation cannot be honored within budget."""
    pass


@dataclass
class InstanceState:
    context_tokens: int
    tier_capacity_tokens: int
    remaining_budget_ms: float
    tokens_per_ms_compaction: float = 12.0  # throughput of the summarizer
    marginal_ms_per_token: float = 0.004   # per-step attention penalty
    requests_per_minute: float = 30.0


def headroom_fraction(state: InstanceState) -> float:
    if state.tier_capacity_tokens <= 0:
        raise CompactionBudgetError("tier capacity must be positive")
    return max(0.0, (state.tier_capacity_tokens - state.context_tokens)
               / state.tier_capacity_tokens)


def projected_debt_ms(state: InstanceState, horizon_requests: int,
                      growth_tokens_per_request: float) -> float:
    """Integral of marginal cost over expected growth, plus spill penalty."""
    debt = 0.0
    ctx = state.context_tokens
    for _ in range(horizon_requests):
        ctx += growth_tokens_per_request
        if ctx > state.tier_capacity_tokens:
            # spill penalty: 6x decode cost for the remainder of the horizon
            debt += 6.0 * state.marginal_ms_per_token * ctx
        else:
            debt += state.marginal_ms_per_token * ctx
    return debt


def compaction_cost_ms(state: InstanceState, target_tokens: int) -> float:
    to_reduce = max(0, state.context_tokens - target_tokens)
    return to_reduce / state.tokens_per_ms_compaction


def should_compact(state: InstanceState, horizon_requests: int,
                   growth_tokens_per_request: float,
                   target_tokens: int) -> bool:
    headroom = headroom_fraction(state)
    if headroom <= 0.0:
        # already spilled; compaction is mandatory but must still fit budget
        cost = compaction_cost_ms(state, target_tokens)
        if cost > state.remaining_budget_ms:
            raise CompactionBudgetError(
                f"context already spilled and compaction ({cost:.0f}ms) "
                f"exceeds remaining budget ({state.remaining_budget_ms:.0f}ms)"
            )
        return True

    debt = projected_debt_ms(state, horizon_requests, growth_tokens_per_request)
    cost = compaction_cost_ms(state, target_tokens)

    # Gate: compaction must fit within remaining budget headroom.
    if cost > state.remaining_budget_ms:
        # Compaction is not a remedy here; defer and accept the step change.
        return False

    # Boundary: debt scaled by inverse headroom vs. cost.
    return debt / max(headroom, 1e-6) > cost


def enforce(state: InstanceState, horizon_requests: int,
            growth_tokens_per_request: float, target_tokens: int) -> str:
    if target_tokens >= state.context_tokens:
        raise CompactionBudgetError(
            f"target ({target_tokens}) must be smaller than current "
            f"context ({state.context_tokens})"
        )
    if should_compact(state, horizon_requests, growth_tokens_per_request,
                      target_tokens):
        cost = compaction_cost_ms(state, target_tokens)
        return f"compact now ({cost:.0f}ms, headroom={headroom_fraction(state):.2f})"
    return "defer"
