# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-fidelity-budget-floor-and-the-post-compaction-tool-call-replay-hazard.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-fidelity-budget-floor-and-the-post-compaction-tool-call-replay-hazard.warrant.json
# Markdown SHA-256:   210061eb68ac074b8dda08af315f9548683e3b9adb5cef3662d9201adc6c8927
# Code AST SHA-256:   7edcaf6162ed81ec5a0027cd14bb224c5556e8d69a61cb333d30e66df5eeb899
# Verified Classes:   InadmissibleCompactionError, Turn, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

class InadmissibleCompactionError(RuntimeError):
    """Raised when a compaction step would destroy an unsettled load-bearing commitment."""
    pass

@dataclass
class Turn:
    index: int
    kind: Literal["read", "reasoning", "side_effect"]
    settled: bool = False          # confirmed by independent read-back
    exact_args: dict = field(default_factory=dict)

@dataclass
class CompactionPlan:
    span: list[Turn]
    window_tokens_left: int
    external_store_available: bool

def is_load_bearing(t: Turn) -> bool:
    # side-effecting and not yet settled by read-back => must survive verbatim
    return t.kind == "side_effect" and not t.settled

def authorize_compaction(plan: CompactionPlan, spill_cost_per_turn: int = 40) -> list[Turn]:
    """
    Returns the list of turns that MUST be spilled verbatim before compaction.
    Raises InadmissibleCompactionError if spill is impossible and F is non-empty.
    """
    fidelity_set = [t for t in plan.span if is_load_bearing(t)]
    reclaimable = [t for t in plan.span if not is_load_bearing(t)]

    if not fidelity_set:
        # F is empty: any lossy summary over `reclaimable` is safe.
        return []

    spill_cost = len(fidelity_set) * spill_cost_per_turn
    if plan.external_store_available and spill_cost <= plan.window_tokens_left:
        # Spill exact args verbatim; compact only the reclaimable remainder.
        return fidelity_set

    # Cannot spill and cannot preserve F verbatim: compaction is inadmissible.
    raise InadmissibleCompactionError(
        f"Refusing to compact span {plan.span[0].index}-{plan.span[-1].index}: "
        f"{len(fidelity_set)} unsettled load-bearing commitment(s) "
        f"(indices {[t.index for t in fidelity_set]}), spill_cost={spill_cost} "
        f"> window_left={plan.window_tokens_left}, external_store="
        f"{plan.external_store_available}. Force read-back settlement first."
    )

# --- trigger trace ---
span = [
    Turn(19, "side_effect", settled=False, exact_args={"path": "/etc/agent/conf.d/limits.yaml"}),
    Turn(20, "read", settled=True),
    Turn(31, "side_effect", settled=False, exact_args={"service": "agentd", "precondition": "config_validated"}),
]
plan = CompactionPlan(span=span, window_tokens_left=500, external_store_available=False)

try:
    spill = authorize_compaction(plan)
    print(f"compact reclaimable; spill verbatim: {[t.index for t in spill]}")
except InadmissibleCompactionError as e:
    # Correct behavior: halt mutating phase, settle F via read-back, retry.
    print(f"BLOCKED: {e}")
    raise
