# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-auto-compaction-when-lossy-summarization-would-violate-a-downstream-replay-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-auto-compaction-when-lossy-summarization-would-violate-a-downstream-replay-invariant.warrant.json
# Markdown SHA-256:   812c5779db89d96329949878b318546832ec9284396de97204819ff662c444df
# Code AST SHA-256:   4a7bde45ca923eb53495b8866188fbbe14076634d30448411d5bf3eac776a99f
# Verified Classes:   BoundaryInvariantViolation, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Optional


class BoundaryInvariantViolation(RuntimeError):
    """Raised when auto-compaction would break cross-segment replay joins."""
    pass


@dataclass(frozen=True)
class Segment:
    events: tuple
    first_event: dict
    last_event: dict


def assert_compaction_safe(
    segments: Iterable[Segment],
    join_keys: frozenset,
    segmentation_is_content_anchored: bool,
    summarizer_boundary_lossless_over_join_keys: bool,
) -> None:
    """
    Gate auto-compaction. Refuse (raise) when the lossy-summarization
    guarantee is stated over segments but consumers replay across boundaries.
    """
    if not join_keys:
        return  # no cross-boundary joins; lossy compaction is safe

    if not segmentation_is_content_anchored:
        raise BoundaryInvariantViolation(
            "segmentation depends on ingestion batching; boundaries are unstable "
            "and the cross-boundary join invariant cannot be verified. "
            "Disable auto-compaction until cuts are anchored at turn/plan markers."
        )

    if not summarizer_boundary_lossless_over_join_keys:
        raise BoundaryInvariantViolation(
            f"summarizer contract does not guarantee boundary-lossless emission of "
            f"join keys {sorted(join_keys)}; per-segment lossy guarantee is stated "
            f"over the wrong scope. Refusing compaction."
        )

    segs = list(segments)
    for i in range(len(segs) - 1):
        trailing = segs[i].last_event
        leading = segs[i + 1].first_event
        for key in join_keys:
            if key in trailing and key not in leading:
                raise BoundaryInvariantViolation(
                    f"join key {key!r} present on trailing event of segment {i} "
                    f"but absent on leading event of segment {i + 1}; "
                    f"compaction would orphan the pair."
                )
