# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-compaction-the-semantic-floor-invariant-and-lossy-recall-budget-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-compaction-the-semantic-floor-invariant-and-lossy-recall-budget-collapse.warrant.json
# Markdown SHA-256:   ad14d04fc412c3c390a4d854f187ab06a55bfd5eb72da9166e89ea625c6d0e7a
# Code AST SHA-256:   0637c418c685d0d7f7f88d515fc59b07a64fd2d2aecf796fde2bedcb60beec86
# Verified Classes:   SemanticFloorViolation, SummaryNode, PendingSubgoal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class SemanticFloorViolation(RuntimeError):
    """Raised when a compaction would drop a fact required by a pending sub-goal,
    or when a surviving fact has no live provenance pointer."""
    pass


@dataclass(frozen=True)
class SummaryNode:
    text: str
    source_pointer: str | None          # resolvable call-id / offset / hash
    fact_manifest: FrozenSet[str]       # facts this node asserts survive
    tokens: int


@dataclass
class PendingSubgoal:
    name: str
    required_facts: FrozenSet[str]


def compact_with_floor_check(
    candidate: SummaryNode,
    pending: list[PendingSubgoal],
    live_sources: set[str],
    token_budget: int,
) -> SummaryNode:
    # C1: every surviving fact must have a live provenance pointer.
    if candidate.source_pointer is None or candidate.source_pointer not in live_sources:
        raise SemanticFloorViolation(
            f"summary node has no live provenance pointer "
            f"({candidate.source_pointer!r}); fact is terminal and unverifiable"
        )

    # C3: the required-fact union of all pending sub-goals must survive.
    required_union: set[str] = set()
    for sg in pending:
        required_union |= sg.required_facts

    dropped = required_union - candidate.fact_manifest
    if dropped:
        raise SemanticFloorViolation(
            f"compaction crosses semantic floor: dropped load-bearing facts "
            f"{sorted(dropped)} required by pending sub-goals "
            f"{[sg.name for sg in pending if sg.required_facts & dropped]}"
        )

    # Token budget is advisory, not authoritative: overage is accepted
    # rather than trading away a required fact.
    if candidate.tokens > token_budget:
        # Caller decides whether to accept overage or checkpoint; we surface it
        # by returning the node and letting the scheduler log the overage.
        pass

    return candidate


def safe_compact_or_checkpoint(
    candidate: SummaryNode,
    pending: list[PendingSubgoal],
    live_sources: set[str],
    token_budget: int,
) -> str:
    try:
        node = compact_with_floor_check(candidate, pending, live_sources, token_budget)
        return f"compacted: {node.tokens} tokens, {len(node.fact_manifest)} facts preserved"
    except SemanticFloorViolation as exc:
        # Loud halt is the correct outcome; never compact harder.
        raise SemanticFloorViolation(
            f"refusing to compact; checkpoint full transcript and escalate: {exc}"
        ) from exc
