# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-compaction-consistency-when-sibling-agents-write-during-its-summarization-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-compaction-consistency-when-sibling-agents-write-during-its-summarization-window.warrant.json
# Markdown SHA-256:   2ef6f0ef5800087f63f176a267c3b1eb1ebeea430e33a0809ef325de81888217
# Code AST SHA-256:   b99e2403ac12b03172ed6264f49f743aaea8dd52b371a782eaebf89ce9490cb5
# Verified Classes:   CompactionConsistencyError, CompactionCommit
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CompactionConsistencyError(RuntimeError):
    """Raised when a compaction commit would advance the watermark past
    events that are neither in the summary input nor the retained tail."""


@dataclass(frozen=True)
class CompactionCommit:
    read_cursor: int          # watermark before compaction
    covered_seq: int          # max seq actually fed to the summarizer
    tail_starts_at: int       # first seq retained verbatim
    store_max_seq: int        # max seq in the shared store at commit time


def verify_and_commit(commit: CompactionCommit, present_seqs: set[int]) -> int:
    """Enforce the continuity invariant and return the new watermark.

    Invariant: every seq in (read_cursor, covered_seq] must be in the summary
    input; every seq in (covered_seq, store_max_seq] must be in the tail.
    No gap, no double-count.
    """
    if commit.tail_starts_at != commit.covered_seq + 1:
        raise CompactionConsistencyError(
            f"tail boundary mismatch: tail_starts_at={commit.tail_starts_at} "
            f"must equal covered_seq+1={commit.covered_seq + 1}"
        )

    # Sibling writes that landed after the summarizer's sealed snapshot.
    intervening = set(range(commit.covered_seq + 1, commit.store_max_seq + 1))
    missing = intervening - present_seqs
    if missing:
        raise CompactionConsistencyError(
            f"compaction gap: seqs {sorted(missing)} were written during the "
            f"summarization window and are absent from the retained tail; "
            f"refusing to advance watermark to {commit.covered_seq}"
        )

    # The watermark may never exceed what the summary provably covered.
    if commit.covered_seq < commit.read_cursor:
        raise CompactionConsistencyError(
            f"watermark regression: covered_seq={commit.covered_seq} < "
            f"read_cursor={commit.read_cursor}"
        )

    return commit.covered_seq


def compact(commit: CompactionCommit, present_seqs: set[int]) -> int:
    try:
        return verify_and_commit(commit, present_seqs)
    except CompactionConsistencyError:
        # Fail closed: abort compaction, force a re-seal and retry.
        raise CompactionConsistencyError(
            "compaction aborted; re-seal snapshot and re-read tail from "
            f"{commit.covered_seq + 1} before retrying"
        )
