# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-fidelity-loss-budget-boundary-during-hierarchical-context-compaction-and-what-breaks-when-retrieval-backfill-re-inflat.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-fidelity-loss-budget-boundary-during-hierarchical-context-compaction-and-what-breaks-when-retrieval-backfill-re-inflat.warrant.json
# Markdown SHA-256:   96e9be73d2fbaf1acf753d6feb51480b28886cd316c783a0b10de13332a2b844
# Code AST SHA-256:   8effdf13a2fddc39fbf82ff3ddc994e8c37650b966067d4027c8b12480e5be57
# Verified Classes:   FidelityBudgetViolation, SummaryNode, CompactionPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class FidelityBudgetViolation(RuntimeError):
    """Raised when cumulative hierarchy loss or backfill reserve breaks the invariant."""


@dataclass
class SummaryNode:
    node_id: str
    depth: int
    per_event_loss: float          # loss reported for THIS event, vs its input
    ancestry: list[str] = field(default_factory=list)  # parent node ids, root-first
    abstracts_retrieval_keys: bool = False


@dataclass
class CompactionPolicy:
    window_limit: int
    trigger_threshold: int          # must leave room for backfill
    backfill_reserve: int           # R
    per_event_budget: float         # B, valid only at depth 1
    cumulative_budget: float        # budget on root-to-leaf path loss


def cumulative_loss(node: SummaryNode, by_id: dict[str, SummaryNode]) -> float:
    """Product of (1 - loss_i) over ancestry, then 1 minus that product."""
    survived = 1.0
    for ancestor_id in node.ancestry:
        ancestor = by_id[ancestor_id]
        survived *= (1.0 - ancestor.per_event_loss)
    survived *= (1.0 - node.per_event_loss)
    return 1.0 - survived


def validate_compaction(
    node: SummaryNode,
    policy: CompactionPolicy,
    by_id: dict[str, SummaryNode],
    projected_window_after_backfill: int,
) -> None:
    # Invariant 1: backfill reserve must be excluded from the trigger.
    if policy.trigger_threshold + policy.backfill_reserve > policy.window_limit:
        raise FidelityBudgetViolation(
            f"trigger {policy.trigger_threshold} + reserve {policy.backfill_reserve} "
            f"exceeds window {policy.window_limit}; backfill will re-trigger compaction"
        )

    # Invariant 2: depth >= 2 invalidates the per-event budget as a control.
    if node.depth >= 2 and node.per_event_loss <= policy.per_event_budget:
        # per-event looks fine, but it is measured against a summary, not originals.
        # Fall through to cumulative check; do NOT accept on per-event alone.
        pass

    # Invariant 3: cumulative root-to-leaf loss must respect the cumulative budget.
    cum = cumulative_loss(node, by_id)
    if cum > policy.cumulative_budget:
        raise FidelityBudgetViolation(
            f"node {node.node_id} depth {node.depth} cumulative loss {cum:.3f} "
            f"exceeds cumulative budget {policy.cumulative_budget:.3f}"
        )

    # Invariant 4: summarizing over a retrieval key destroys the backfill handle.
    if node.abstracts_retrieval_keys and node.depth >= 2:
        raise FidelityBudgetViolation(
            f"node {node.node_id} abstracts over retrieval keys at depth {node.depth}; "
            f"backfill cannot recover keys that were summarized away"
        )

    # Invariant 5: projected post-backfill window must not cross the trigger.
    if projected_window_after_backfill >= policy.trigger_threshold:
        raise FidelityBudgetViolation(
            f"projected window {projected_window_after_backfill} after backfill "
            f"crosses trigger {policy.trigger_threshold}; oscillation imminent"
        )


def compact_and_backfill(
    node: SummaryNode,
    policy: CompactionPolicy,
    by_id: dict[str, SummaryNode],
    expected_backfill_tokens: int,
    current_window: int,
) -> int:
    projected = current_window + expected_backfill_tokens
    validate_compaction(node, policy, by_id, projected)
    return projected
