# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-telemetry-from-silently-mis-binning-memory-compaction-events-into-the-wrong-operation-class.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-telemetry-from-silently-mis-binning-memory-compaction-events-into-the-wrong-operation-class.warrant.json
# Markdown SHA-256:   5515c021f7f60f58816b68d6d60bb610ebf77a519d0ab60907f436461cf26499
# Code AST SHA-256:   32b7bd6359b5b36f15d1d4456103d3175b6b89e77cf0246b383fabbbf5e5dd88
# Verified Classes:   UnlinkedCompactionForgetError, MemorySpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnlinkedCompactionForgetError(RuntimeError):
    """Raised when a memory.forget span drops content that was folded into a
    memory.write span in the same trace without an explicit linkage attribute."""


@dataclass
class MemorySpan:
    operation: str  # "read" | "write" | "forget"
    target: str
    source: Optional[str] = None
    trace_id: str = ""
    span_id: str = ""
    compaction_source_span_id: Optional[str] = None
    compaction_lossy: bool = False
    dropped_source_count: Optional[int] = None


def validate_compaction_trace(spans: list[MemorySpan]) -> None:
    """Enforce the linkage invariant over a single trace's memory spans.

    A forget span is valid only if either:
      (a) no write in the trace lists its target as a source, or
      (b) the paired write carries compaction_source_span_id == forget.span_id
          and compaction_lossy is True.
    """
    writes_by_source: dict[str, MemorySpan] = {}
    for s in spans:
        if s.operation == "write" and s.source is not None:
            writes_by_source.setdefault(s.source, s)

    for s in spans:
        if s.operation != "forget":
            continue
        paired_write = writes_by_source.get(s.target)
        if paired_write is None:
            continue  # independent eviction, not a compaction drop
        linked = (
            paired_write.compaction_source_span_id == s.span_id
            and paired_write.compaction_lossy
            and s.compaction_source_span_id == paired_write.span_id
        )
        if not linked:
            raise UnlinkedCompactionForgetError(
                f"forget span {s.span_id} drops target '{s.target}' that was "
                f"folded into write span {paired_write.span_id} "
                f"(trace {s.trace_id}) without compaction linkage; "
                f"downstream durability auditors will mis-bin this as a "
                f"policy eviction rather than a lossy transform."
            )


def emit_compaction(
    trace_id: str,
    summary_span_id: str,
    forget_span_id: str,
    source_count: int,
) -> list[MemorySpan]:
    """Correct emission: write and forget are cross-linked and marked lossy."""
    write = MemorySpan(
        operation="write",
        target="episodic_store",
        source="context_window",
        trace_id=trace_id,
        span_id=summary_span_id,
        compaction_source_span_id=forget_span_id,
        compaction_lossy=True,
        dropped_source_count=source_count,
    )
    forget = MemorySpan(
        operation="forget",
        target="context_window",
        trace_id=trace_id,
        span_id=forget_span_id,
        compaction_source_span_id=summary_span_id,
        compaction_lossy=True,
    )
    spans = [write, forget]
    validate_compaction_trace(spans)
    return spans
