# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-when-token-budget-and-semantic-drift-heuristics-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-when-token-budget-and-semantic-drift-heuristics-disagree.warrant.json
# Markdown SHA-256:   4b91d1c6f1fd502e795cdae04e2e198670c956571ae840f28487cd3f3f1e5597
# Code AST SHA-256:   bb9b038d92789dcfc24f91d77e96e3f9c7a5986e042d00a3e9dbfdb7e553edc5
# Verified Classes:   CompactionBoundaryError, Trigger, ContextState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionBoundaryError(RuntimeError):
    """Raised when a compaction decision would evict the referential closure
    of the active phase, or when trigger and policy are decoupled."""
    pass


class Trigger(Enum):
    NONE = "none"
    DRIFT = "drift"
    BUDGET = "budget"
    BOTH = "both"


@dataclass
class ContextState:
    tokens: int
    budget_fraction: float          # tokens / window
    drift_score: float
    drift_threshold: float
    budget_threshold: float
    # entities introduced before the current span that the span references
    live_referents: set = field(default_factory=set)
    # entities defined only in turns that a naive eviction would drop
    sole_definition_of: dict = field(default_factory=dict)  # entity -> turn_id


def classify_trigger(state: ContextState) -> Trigger:
    drift = state.drift_score >= state.drift_threshold
    budget = state.budget_fraction >= state.budget_threshold
    if drift and budget:
        return Trigger.BOTH
    if drift:
        return Trigger.DRIFT
    if budget:
        return Trigger.BUDGET
    return Trigger.NONE


def select_policy(state: ContextState, trigger: Trigger) -> str:
    """Policy is a function of the trigger, never a fixed default."""
    if trigger is Trigger.NONE:
        return "noop"
    if trigger is Trigger.DRIFT:
        # conservative: preserve pre-drift prefix as immutable referent
        return "preserve_prefix_summarize_suffix"
    if trigger is Trigger.BUDGET:
        # aggressive by age, but pin sole definitions
        return "evict_by_age_pin_definitions"
    # BOTH: drift owns the decision; budget target applies to suffix only
    return "preserve_prefix_summarize_suffix_budget_suffix_only"


def compact(state: ContextState, eviction_plan: list) -> None:
    """Validate an eviction plan against the trigger-derived policy before
    applying it. This is the guard that the observed failures lacked."""
    trigger = classify_trigger(state)
    policy = select_policy(state, trigger)

    if trigger in (Trigger.DRIFT, Trigger.BOTH):
        # The pre-drift prefix is the referent for the post-drift span.
        # Evicting it to satisfy a budget target is the observed failure.
        evicted_referents = {
            turn for turn in eviction_plan
            if turn in state.sole_definition_of.values()
        }
        if evicted_referents:
            raise CompactionBoundaryError(
                f"policy={policy} trigger={trigger.value}: eviction plan drops "
                f"turns {sorted(evicted_referents)} that are the sole definition "
                f"of live referents {sorted(state.live_referents)}. "
                f"Drift-triggered compaction must preserve referential closure."
            )

    if trigger is Trigger.BUDGET:
        # Low drift licenses evicting content, not definitions.
        dropped_defs = {
            ent for ent, turn in state.sole_definition_of.items()
            if turn in eviction_plan
        }
        if dropped_defs:
            raise CompactionBoundaryError(
                f"policy={policy} trigger=budget: eviction plan drops sole "
                f"definitions for {sorted(dropped_defs)}. Budget pressure does "
                f"not license evicting entity definitions."
            )

    if trigger is Trigger.BOTH and state.budget_fraction >= state.budget_threshold:
        # BOTH with the eviction plan sized to the full window rather than the
        # post-drift suffix is the decoupled-trigger failure.
        if policy != "preserve_prefix_summarize_suffix_budget_suffix_only":
            raise CompactionBoundaryError(
                "BOTH trigger requires suffix-scoped budget target; "
                f"got policy={policy}."
            )

    # plan validated; apply
    for turn in eviction_plan:
        state.tokens -= 1  # placeholder for actual eviction accounting


def attempt_compaction(state: ContextState, eviction_plan: list) -> Optional[str]:
    try:
        compact(state, eviction_plan)
        return None
    except CompactionBoundaryError as exc:
        return str(exc)
