# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-kv-cache-aligned-compaction-from-silently-re-billing-cached-prefix-tokens-as-fresh-input.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-kv-cache-aligned-compaction-from-silently-re-billing-cached-prefix-tokens-as-fresh-input.warrant.json
# Markdown SHA-256:   84f241ec7efb17ebd5f87c5b2209ee312b176ee3dced51b4d955d0c626cc8167
# Code AST SHA-256:   13f2469d042dbd9905f4dea36e91b4a1b07de098b32b03368fefb62ed8e47078
# Verified Classes:   CacheInvalidatingCompaction
# Defensive Guards:   2 fail-closed invariants (zero external deps)

BLOCK = 1024  # provider cache block size in tokens
CACHE_READ_RATE = 0.1  # fraction of input price billed on cache hit
INPUT_RATE = 1.0


class CacheInvalidatingCompaction(RuntimeError):
    """Raised when a proposed compaction would re-bill more suffix than it evicts."""


def plan_compaction(occupancy: int, evict_start: int, evict_end: int,
                    digest_tokens: int, anchor_frozen: bool) -> dict:
    """
    Decide whether a head-eviction compaction is cost-positive under prefix caching.
    Returns a plan dict if safe; raises CacheInvalidatingCompaction otherwise.
    """
    if not (0 <= evict_start < evict_end <= occupancy):
        raise CacheInvalidatingCompaction(
            f"eviction span [{evict_start},{evict_end}) outside occupancy {occupancy}"
        )

    evicted = evict_end - evict_start
    suffix = occupancy - evict_end
    block_aligned = (evict_end % BLOCK == 0)

    # Cost model: evicted tokens stop being billed; suffix tokens re-bill at full
    # input rate on the next call unless the surviving prefix stays block-resident.
    evict_saving = evicted * (INPUT_RATE - CACHE_READ_RATE)
    suffix_penalty = 0 if (block_aligned and anchor_frozen) else suffix * (INPUT_RATE - CACHE_READ_RATE)
    digest_cost = digest_tokens * (INPUT_RATE - CACHE_READ_RATE)

    net = evict_saving - suffix_penalty - digest_cost
    if net <= 0:
        raise CacheInvalidatingCompaction(
            f"compaction is a cost amplifier: evict_saving={evict_saving:.0f} "
            f"suffix_penalty={suffix_penalty:.0f} digest_cost={digest_cost:.0f} net={net:.0f}; "
            f"block_aligned={block_aligned} anchor_frozen={anchor_frozen}. "
            f"Evict from tail or freeze anchor instead."
        )

    return {
        "evict": (evict_start, evict_end),
        "digest_tokens": digest_tokens,
        "net_token_saving": net,
        "freeze_anchor": True,  # digest bytes must never be regenerated
    }


def maybe_compact(occupancy: int, budget: int, head_span: tuple[int, int],
                  digest_tokens: int, anchor_frozen: bool) -> dict | None:
    if occupancy < int(0.85 * budget):
        return None
    try:
        return plan_compaction(occupancy, head_span[0], head_span[1],
                               digest_tokens, anchor_frozen)
    except CacheInvalidatingCompaction as e:
        # Correct fallback: do not compact the head; spill tail or ride closer to limit.
        return {"action": "defer", "reason": str(e)}
