# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-compaction-event-as-an-unverified-state-mutation-rather-than-an-idempotent-maintenance-op.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-compaction-event-as-an-unverified-state-mutation-rather-than-an-idempotent-maintenance-op.warrant.json
# Markdown SHA-256:   b6435824286836bcdafaaec5c337a18cb419e5be6dae087fe6dea48312730063
# Code AST SHA-256:   a2976d41cc173c462d96d8927a07af64e9464132e0b3b1eb375126ad1509dc3e
# Verified Classes:   UnverifiedCompactionError, DerivedMemory, CompactionEvent
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnverifiedCompactionError(RuntimeError):
    """Raised when a compaction event cannot satisfy the provenance/forget invariant."""
    pass


@dataclass
class DerivedMemory:
    memory_id: str
    source_ids: list[str]
    truncated: bool = False
    truncated_count: int = 0


@dataclass
class CompactionEvent:
    event_id: str
    as_of_generation: Optional[int]
    derived: list[DerivedMemory] = field(default_factory=list)
    tombstoned: set[str] = field(default_factory=set)


def admit_compaction(
    event: CompactionEvent,
    live_or_tombstoned: set[str],
    pending_forgets: set[str],
    audit_retention_days: int,
    tombstone_ttl_days: int,
) -> None:
    # Invariant 1: ordering witness must be recorded.
    if event.as_of_generation is None:
        raise UnverifiedCompactionError(
            f"compaction {event.event_id} has no as_of_generation; "
            "retrievals in window are generation-ambiguous"
        )

    # Invariant 2: tombstones must outlive the audit retention window.
    if tombstone_ttl_days < audit_retention_days:
        raise UnverifiedCompactionError(
            f"tombstone_ttl={tombstone_ttl_days}d < audit_retention={audit_retention_days}d; "
            "forget-audit entries will orphan"
        )

    for mem in event.derived:
        # Invariant 3: provenance must be complete or explicitly flagged.
        if not mem.source_ids and not mem.truncated:
            raise UnverifiedCompactionError(
                f"derived {mem.memory_id} has empty source_ids without truncation flag; "
                "provenance is fabricated-empty"
            )
        if mem.truncated and mem.truncated_count <= 0:
            raise UnverifiedCompactionError(
                f"derived {mem.memory_id} flagged truncated but count is {mem.truncated_count}"
            )

        # Invariant 4: every source must resolve to live row or durable tombstone.
        for sid in mem.source_ids:
            if sid not in live_or_tombstoned:
                raise UnverifiedCompactionError(
                    f"derived {mem.memory_id} references source {sid} that is neither "
                    "live nor tombstoned; provenance chain broken"
                )

        # Invariant 5: pending forgets on sources must be propagated into derived memory.
        leaked = pending_forgets.intersection(mem.source_ids)
        if leaked:
            raise UnverifiedCompactionError(
                f"derived {mem.memory_id} absorbed sources {sorted(leaked)} with pending "
                "forgets; forget-audit would be a false positive"
            )


def run_compaction_gate(event: CompactionEvent, **ctx) -> str:
    admit_compaction(event, **ctx)
    return "admitted"
