# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-auto-compaction-boundary-violation-when-lossy-summarization-drops-the-last-writer-s-witness-token.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-auto-compaction-boundary-violation-when-lossy-summarization-drops-the-last-writer-s-witness-token.warrant.json
# Markdown SHA-256:   8e8546168a88d868a83aa6b724aa4513fa3da0375b47ca917bb3d6fc6403fadc
# Code AST SHA-256:   896076bac63278ba1f951df00b75660bb70f0543ee176fd2d3fb006f67c0335b
# Verified Classes:   CompactionWitnessViolation, Write, CompactionPlan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionWitnessViolation(RuntimeError):
    """Raised when a lossy compaction would drop or invert the last-writer witness
    for a state key that is read in the retained verbatim suffix."""


@dataclass(frozen=True)
class Write:
    key: str
    value: str
    writer: str          # agent identity, e.g. "primary" or "peer-7"
    seq: int             # total order over transcript steps


@dataclass
class CompactionPlan:
    suffix_reads: set[str]                       # keys read in the kept verbatim suffix
    retained_witnesses: dict[str, list[Write]]   # key -> witnesses kept in the summary
    full_witnesses: dict[str, list[Write]]       # key -> all witnesses pre-compaction


def _last_writer(writes: list[Write]) -> Optional[Write]:
    return max(writes, key=lambda w: w.seq) if writes else None


def enforce_witness_monotonicity(plan: CompactionPlan) -> None:
    """Bound the compaction boundary: every suffix-read key must retain a witness
    whose seq is >= the seq of every other retained witness for that key, and that
    witness must equal the true last writer. Otherwise refuse compaction."""
    for key in plan.suffix_reads:
        true_last = _last_writer(plan.full_witnesses.get(key, []))
        if true_last is None:
            # Read of a key never written in this transcript: no witness to retain,
            # but this is itself suspicious and must be surfaced, not silently allowed.
            raise CompactionWitnessViolation(
                f"suffix reads key {key!r} with no writer in transcript; "
                f"witness set empty — refuse lossy compaction"
            )
        retained = plan.retained_witnesses.get(key, [])
        if not retained:
            raise CompactionWitnessViolation(
                f"suffix reads {key!r} but compaction retained no witness "
                f"(true last writer: {true_last.writer} seq={true_last.seq})"
            )
        retained_last = _last_writer(retained)
        if retained_last.seq < true_last.seq:
            raise CompactionWitnessViolation(
                f"monotonicity inversion for {key!r}: retained last witness "
                f"{retained_last.writer} seq={retained_last.seq} is older than "
                f"true last writer {true_last.writer} seq={true_last.seq}; "
                f"compaction would silently revert peer write"
            )
        if retained_last.value != true_last.value:
            raise CompactionWitnessViolation(
                f"witness value drift for {key!r}: retained {retained_last.value!r} "
                f"!= true last {true_last.value!r}"
            )
