# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-session-whose-lossy-summary-would-cross-a-semantic-retention-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-session-whose-lossy-summary-would-cross-a-semantic-retention-boundary.warrant.json
# Markdown SHA-256:   515eaa5d9c0277f4709529acd8049bc199961028f4604e369205953dc154c200
# Code AST SHA-256:   5e6822d943be671124612316598bdbd184584f79c3fc5dec4b5d9277cb4de691
# Verified Classes:   RetentionBoundaryError, RetentionItem, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class RetentionBoundaryError(RuntimeError):
    """Raised when a compaction span cannot honor the stated retention guarantee."""
    pass


@dataclass
class RetentionItem:
    key: str
    value: str
    encodable_in_summary: bool


@dataclass
class Span:
    span_id: str
    turns: list
    retention_items: list = field(default_factory=list)


def classify(span: Span) -> Iterable[RetentionItem]:
    # Placeholder for the measured-recall classifier. Must not be assumed perfect.
    return span.retention_items


def persist_sidecar(items: Iterable[RetentionItem]) -> bool:
    # Durable, non-summarized store. Returns False if the write cannot be verified.
    try:
        store = {it.key: it.value for it in items}
        return all(store.get(it.key) == it.value for it in items)
    except Exception:
        return False


def compact_span(span: Span, occupancy_target_met: bool) -> str:
    """
    Compact a span only if the retention guarantee can be honored.
    Budget pressure (occupancy_target_met) is NOT sufficient cause.
    """
    flagged = list(classify(span))
    unencodable = [it for it in flagged if not it.encodable_in_summary]

    if unencodable:
        # Attempt durable persistence before any summarization.
        if not persist_sidecar(flagged):
            raise RetentionBoundaryError(
                f"span {span.span_id}: {len(unencodable)} retention items "
                f"({[it.key for it in unencodable]}) are not encodable in the "
                f"permitted summary schema and the sidecar write could not be "
                f"verified; refusing to compact. Escalate or widen budget."
            )

    if not occupancy_target_met:
        raise RetentionBoundaryError(
            f"span {span.span_id}: compaction invoked without budget pressure; "
            f"refusing to mutate transcript speculatively."
        )

    return f"[summary of {span.span_id}; {len(flagged)} retention items in sidecar]"
