# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-dedup-compaction-from-silently-erasing-the-only-witness-of-a-causal-edge.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-dedup-compaction-from-silently-erasing-the-only-witness-of-a-causal-edge.warrant.json
# Markdown SHA-256:   c61b8930f256ee8e241dae5c274115db7bc4ecb99c1ba8937ea94ca6e6268214
# Code AST SHA-256:   49d37391e33afcf7ee2d1ee87e329cd1d5c615e67fba8aef115fedbf59a43a55
# Verified Classes:   WitnessLossError, Chunk, Ledger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class WitnessLossError(RuntimeError):
    """Raised when compaction would drop the only witness of a causal edge."""


@dataclass
class Chunk:
    key: str            # event key, e.g. ("read_config", "retries")
    timestamp: int
    text: str
    is_witness: bool    # records a transition, not re-derivable payload


@dataclass
class Ledger:
    entries: dict[str, list[Chunk]] = field(default_factory=dict)

    def record(self, c: Chunk) -> None:
        self.entries.setdefault(c.key, []).append(c)

    def latest(self, key: str) -> Chunk | None:
        bucket = self.entries.get(key)
        return max(bucket, key=lambda c: c.timestamp) if bucket else None


def compact(chunks: list[Chunk], ledger: Ledger, sim_threshold: float = 0.92) -> list[Chunk]:
    """Similarity-dedup payload; never similarity-drop witnesses."""
    kept: list[Chunk] = []
    for c in chunks:
        if c.is_witness:
            # Witnesses are retained by event key + max-timestamp, not similarity.
            latest = ledger.latest(c.key)
            if latest is None or latest.timestamp != c.timestamp:
                raise WitnessLossError(
                    f"chunk {c.key}@{c.timestamp} is a witness but not the "
                    f"ledger's latest for key {c.key!r}; compaction would "
                    f"flatten a temporal distinction"
                )
            kept.append(c)
            continue
        # Payload: safe to drop if a near-duplicate is already kept.
        if any(_similar(c.text, k.text) >= sim_threshold for k in kept):
            continue
        kept.append(c)
    return kept


def _similar(a: str, b: str) -> float:
    # Placeholder for the embedding cosine used in production.
    sa, sb = set(a.split()), set(b.split())
    return len(sa & sb) / max(1, len(sa | sb))
