# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-anchor-collision-invalidation-in-lossless-recall-auto-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-anchor-collision-invalidation-in-lossless-recall-auto-compaction.warrant.json
# Markdown SHA-256:   0a26d5e483f5412af2ee258d83f5c782e479618b1a992ced4b84a90f5d300c0b
# Code AST SHA-256:   0aa7d89decde41df14adac63b41cc99516c4e53cb6dede340df5dc8218f3ad95
# Verified Classes:   AnchorCollisionError, StaleSnapshotError, Anchor, CompactionInput, CompactionSummary
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field
from typing import Optional


class AnchorCollisionError(RuntimeError):
    """Raised when a compaction summary reproduces bytes belonging to a lossless recall anchor."""
    pass


class StaleSnapshotError(RuntimeError):
    """Raised when an anchor was registered after the compactor's input snapshot was taken."""
    pass


@dataclass
class Anchor:
    anchor_id: str
    span_bytes: str
    registered_at_turn: int


@dataclass
class CompactionInput:
    snapshot_turn: int
    excised_anchor_ids: list[str] = field(default_factory=list)


@dataclass
class CompactionSummary:
    text: str
    produced_at_turn: int


def validate_compaction(
    summary: CompactionSummary,
    anchors: list[Anchor],
    comp_input: CompactionInput,
    anchor_registry_high_water: int,
) -> None:
    # Guard 1: snapshot consistency. If an anchor was registered after the
    # compactor's snapshot, the compactor could not have excised it, and any
    # incidental reproduction is unguarded.
    if anchor_registry_high_water > comp_input.snapshot_turn:
        raise StaleSnapshotError(
            f"anchor registry high-water {anchor_registry_high_water} exceeds "
            f"compactor snapshot turn {comp_input.snapshot_turn}; compaction is "
            f"anchor-unsafe and must be re-snapshotted"
        )

    # Guard 2: excision completeness. Every anchor that overlaps the compacted
    # span must have been excised before summarization.
    excised = set(comp_input.excised_anchor_ids)
    for a in anchors:
        if a.registered_at_turn <= comp_input.snapshot_turn and a.anchor_id not in excised:
            raise AnchorCollisionError(
                f"anchor {a.anchor_id} overlaps compacted span but was not excised; "
                f"compactor input is contaminated"
            )

    # Guard 3: post-generation scan. The summary must not contain any anchor
    # bytes verbatim. This runs on the *final* summary text, after any rewrite
    # pass (e.g., C2 over C1), because rewrite is where normalization drift
    # enters.
    for a in anchors:
        if a.span_bytes and a.span_bytes in summary.text:
            raise AnchorCollisionError(
                f"summary produced at turn {summary.produced_at_turn} reproduces "
                f"anchor {a.anchor_id} bytes; anchors must be referenced via "
                f"placeholder, never inlined"
            )


def compact(
    summary_text: str,
    anchors: list[Anchor],
    comp_input: CompactionInput,
    anchor_registry_high_water: int,
) -> CompactionSummary:
    summary = CompactionSummary(text=summary_text, produced_at_turn=comp_input.snapshot_turn)
    validate_compaction(summary, anchors, comp_input, anchor_registry_high_water)
    return summary
