# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-from-a-lossy-compaction-checkpoint-rather-than-silently-reconstructing-dropped-detail.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-from-a-lossy-compaction-checkpoint-rather-than-silently-reconstructing-dropped-detail.warrant.json
# Markdown SHA-256:   818b2ba5c8531ee9a6977a99069f00d076dfab07676996df655206597099ae50
# Code AST SHA-256:   85795f7063afaed75a79aea30351ddf20583bc09e6d936b020a34de37b6dddf8
# Verified Classes:   CompactionResumeError, FactClass, Disposition, ManifestEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class CompactionResumeError(RuntimeError):
    """Raised when a lossy compaction checkpoint cannot be safely resumed from."""


class FactClass(Enum):
    POSITIVE_STATE = "positive_state"
    NEGATIVE_CONSTRAINT = "negative_constraint"
    NUMERIC_PARAMETER = "numeric_parameter"
    ABANDONED_BRANCH = "abandoned_branch"
    UNRESOLVED_QUESTION = "unresolved_question"


class Disposition(Enum):
    RETAINED_VERBATIM = "retained_verbatim"
    FETCHABLE = "fetchable"
    DROPPED_IRRELEVANT = "dropped_irrelevant"


@dataclass(frozen=True)
class ManifestEntry:
    fact_id: str
    cls: FactClass
    disposition: Disposition
    handle: Optional[str] = None


# Facts each remaining planned step depends on. Absence here is itself a failure:
# an unenumerated dependency cannot be proven to have survived compaction.
REMAINING_STEP_PRECONDITIONS: dict[str, set[str]] = {
    "step_23_migrate_remaining": {"svc_billing_excluded", "batch_size_250"},
    "step_24_parallel_write": {"parallel_8_deadlocked"},
}


def verify_checkpoint_resumable(
    manifest: dict[str, ManifestEntry],
    preconditions: dict[str, set[str]],
    *,
    scope_confirmed_irrelevant: set[str],
) -> list[str]:
    """
    Returns the list of fact_ids that must be re-fetched before acting.
    Raises CompactionResumeError if any dependency cannot be proven to survive.
    """
    must_refetch: list[str] = []

    for step, needed_facts in preconditions.items():
        for fact_id in needed_facts:
            entry = manifest.get(fact_id)

            if entry is None:
                raise CompactionResumeError(
                    f"{step} depends on '{fact_id}', which is absent from the "
                    f"compaction manifest. The summary cannot be proven complete; "
                    f"refusing to reconstruct by inference."
                )

            if entry.disposition is Disposition.RETAINED_VERBATIM:
                continue

            if entry.disposition is Disposition.FETCHABLE:
                if not entry.handle:
                    raise CompactionResumeError(
                        f"'{fact_id}' is marked fetchable but carries no handle; "
                        f"cannot re-establish state for {step}."
                    )
                # Negative constraints and abandoned branches must be re-read
                # into context before the next action, not lazily.
                if entry.cls in (
                    FactClass.NEGATIVE_CONSTRAINT,
                    FactClass.ABANDONED_BRANCH,
                ):
                    must_refetch.append(fact_id)
                continue

            # DROPPED_IRRELEVANT: only acceptable if scope check confirms it.
            if fact_id not in scope_confirmed_irrelevant:
                raise CompactionResumeError(
                    f"'{fact_id}' (class={entry.cls.value}) was dropped as "
                    f"irrelevant but is a precondition of {step} and its "
                    f"irrelevance is unconfirmed. Halt and escalate."
                )

    return must_refetch


def resume_from_checkpoint(
    manifest: dict[str, ManifestEntry],
    preconditions: dict[str, set[str]],
    scope_confirmed_irrelevant: set[str],
    fetch,
) -> dict[str, object]:
    refetch = verify_checkpoint_resumable(
        manifest, preconditions, scope_confirmed_irrelevant=scope_confirmed_irrelevant
    )
    if refetch:
        # Re-establish authoritative state from the durable store before acting.
        return {fact_id: fetch(fact_id) for fact_id in refetch}
    return {}
