# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-auto-compaction-of-its-own-trace-when-summarizer-loss-budget-is-unverifiable.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-auto-compaction-of-its-own-trace-when-summarizer-loss-budget-is-unverifiable.warrant.json
# Markdown SHA-256:   1b2a1033af07992a4beac1f5c4761ec0b34984f2473b5af8316914c40e8ee1d5
# Code AST SHA-256:   be34fe53fdefd879659c1d0f3f2facffe133707159d27637b34ac9c87996dd97
# Verified Classes:   UnverifiableCompactionError, TraceSnapshot, CompactionPlan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class UnverifiableCompactionError(RuntimeError):
    """Raised when an instance attempts to compact its own trace without an
    external witness or edge-aware loss accounting."""


@dataclass
class TraceSnapshot:
    digest: str
    open_task_ids: frozenset
    completion_edges: frozenset
    raw_turns: Optional[list] = None  # None means in-context only


@dataclass
class CompactionPlan:
    depth: int
    declared_loss_budget: int
    counts_edges: bool
    external_witness: Optional[TraceSnapshot] = field(default=None)


def authorize_compaction(plan: CompactionPlan, current: TraceSnapshot) -> None:
    # Rule 1: external witness must exist and be resolvable post-compaction.
    if plan.external_witness is None or plan.external_witness.raw_turns is None:
        raise UnverifiableCompactionError(
            "no external witness for pre-compaction trace; loss budget is unbounded"
        )
    # Rule 2: budget must count state-machine edges, not surface facts/tokens.
    if not plan.counts_edges:
        raise UnverifiableCompactionError(
            "loss budget counts facts/tokens, not completion edges; "
            "a summary can report low loss while severing every completion edge"
        )
    # Rule 3: depth > 1 must re-derive from base trace, not summarize a summary.
    if plan.depth > 1:
        if plan.external_witness.digest != current.digest:
            raise UnverifiableCompactionError(
                f"compaction depth {plan.depth} without matching base digest; "
                "cumulative loss is unbounded even if per-pass loss is bounded"
            )
    # Post-condition the instance must be able to prove after the pass.
    if not plan.external_witness.open_task_ids == current.open_task_ids:
        raise UnverifiableCompactionError(
            "witness open-task set diverges from live set; compaction would "
            "make the discrepancy unprovable"
        )


def compact_trace(plan: CompactionPlan, current: TraceSnapshot) -> str:
    authorize_compaction(plan, current)
    summary = {"open_tasks": sorted(current.open_task_ids),
               "edges": sorted(current.completion_edges),
               "depth": plan.depth + 1,
               "derived_from": current.digest}
    return hashlib.sha256(repr(summary).encode()).hexdigest()
