# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-span-level-token-accounting-with-its-own-context-budget-allocator-when-the-two-disagree-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-span-level-token-accounting-with-its-own-context-budget-allocator-when-the-two-disagree-mid-run.warrant.json
# Markdown SHA-256:   41881a25962ea15582456cb1a19e43ac8b5a87235820c82c41c69750c76fce1a
# Code AST SHA-256:   a91126a94113e40a5bd39d380b0a983afaabe81f7822c19d704ac953a06155f8
# Verified Classes:   BudgetWindupError, BudgetState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class BudgetWindupError(RuntimeError):
    """Raised when span-driven feedback has driven the context ceiling below
    the mandatory working set, indicating fixed-overhead double-counting."""


@dataclass
class BudgetState:
    window: int
    target_fraction: float
    calibrated_overhead: int
    mandatory_preamble: int
    current_tool_schema: int
    minimum_working_set: int
    tolerance: float = 0.08
    stale_steps: int = 0

    @property
    def floor(self) -> int:
        return (
            self.mandatory_preamble
            + self.current_tool_schema
            + self.minimum_working_set
        )


def update_ceiling(state: BudgetState, packed_content: int, measured_input: int) -> int:
    """Derive the next-step input ceiling from a single span measurement.

    Admits only the variable residual as feedback. Fixed provider overhead is
    applied as a constant, never re-subtracted from headroom.
    """
    residual = measured_input - packed_content - state.calibrated_overhead
    within_band = abs(residual) <= state.tolerance * max(packed_content, 1)

    if not within_band:
        state.stale_steps += 1
        if state.stale_steps >= 2:
            # Overhead model is stale (toolset/template/cache shift).
            # Hold last known-good ceiling; do not shrink on bad signal.
            state.stale_steps = 0
            return int(state.window * state.target_fraction) - state.calibrated_overhead
    else:
        state.stale_steps = 0

    ceiling = (
        int(state.window * state.target_fraction)
        - state.calibrated_overhead
        - max(residual, 0)  # only reclaim genuine content overshoot
    )

    if ceiling < state.floor:
        raise BudgetWindupError(
            f"derived ceiling {ceiling} < mandatory floor {state.floor} "
            f"(residual={residual}, overhead={state.calibrated_overhead}); "
            f"allocator windup — reset integrator, do not abort run"
        )
    return ceiling
