# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-boundary-be-drawn-between-lossy-summarization-checkpoints-and-compaction-eligibility-in-long-horizon-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-boundary-be-drawn-between-lossy-summarization-checkpoints-and-compaction-eligibility-in-long-horizon-agent-traces.warrant.json
# Markdown SHA-256:   517ad753e110532b0205faa1d4ec1080a0d811857f835c361ef88212cd2730fa
# Code AST SHA-256:   fe9a0df2f01aa6d1b731ef5ae65773e601ac13b305c224314ba45bae2fd54277
# Verified Classes:   UncoveredCompactionError, Checkpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from typing import Iterable


class UncoveredCompactionError(RuntimeError):
    """Raised when a compaction range is not safely covered by a committed,
    causally complete, hash-verified checkpoint."""


@dataclass(frozen=True)
class Checkpoint:
    start: int
    end: int
    committed: bool          # quorum-acknowledged and read back
    causal_units: tuple[tuple[int, int], ...]  # (first_event, last_event) fully subsumed
    source_hash: str         # hash of the source event range it replaces


def _hash_range(events: Iterable[tuple[int, bytes]]) -> str:
    h = hashlib.sha256()
    for seq, payload in events:
        h.update(seq.to_bytes(8, "big"))
        h.update(payload)
    return h.hexdigest()


def _causal_boundary_inside(cp: Checkpoint, lo: int, hi: int) -> int:
    """Largest b' <= hi such that [lo, b'] cuts no causal unit."""
    best = lo
    for first, last in cp.causal_units:
        if first < lo:
            continue
        if last <= hi:
            best = max(best, last)
        else:
            break  # this unit straddles hi; cannot extend past its start
    return best


def compact_range(
    cp: Checkpoint,
    events: list[tuple[int, bytes]],
    lo: int,
    hi: int,
) -> int:
    """Return the exclusive end offset actually compacted, or raise."""
    if not cp.committed:
        raise UncoveredCompactionError(
            f"checkpoint [{cp.start},{cp.end}] not quorum-committed; refusing to compact"
        )
    if not (cp.start <= lo and hi <= cp.end):
        raise UncoveredCompactionError(
            f"range [{lo},{hi}] not contained in checkpoint [{cp.start},{cp.end}]"
        )
    if _hash_range(events) != cp.source_hash:
        raise UncoveredCompactionError(
            "checkpoint source_hash mismatch; summary is not bound to these events"
        )
    b_prime = _causal_boundary_inside(cp, lo, hi)
    if b_prime <= lo:
        raise UncoveredCompactionError(
            f"no causal-unit boundary inside [{lo},{hi}]; shrink and retry"
        )
    # Caller may now delete [lo, b_prime) — never a partial causal unit.
    return b_prime
