# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-as-a-lossy-non-idempotent-state-transition-rather-than-a-cache-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-as-a-lossy-non-idempotent-state-transition-rather-than-a-cache-eviction.warrant.json
# Markdown SHA-256:   7b825e7f38a27960e2be1f8f49cc76f6dd7f4f9ef390359c91fa6028429cd4df
# Code AST SHA-256:   1e4193cd55be7db891ae19421361b25c3db55670b7fed62b32546981d78565e4
# Verified Classes:   CompactionIntegrityError, StateLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Verdict = Literal["confirmed", "contradicted", "unverified"]


class CompactionIntegrityError(RuntimeError):
    """Raised when a compaction step would silently drop carried-forward state."""


@dataclass
class StateLedger:
    step: int
    source_range: tuple[int, int]
    completed: list[str] = field(default_factory=list)
    commitments: dict[str, str] = field(default_factory=dict)   # key -> constraint
    verdicts: dict[str, Verdict] = field(default_factory=dict)  # claim -> verdict
    remaining: list[str] = field(default_factory=list)
    retired: dict[str, int] = field(default_factory=dict)       # key -> step retired

    def compact(self, prior: "StateLedger", new_step: int) -> "StateLedger":
        # Invariant 1: every prior verdict must survive or be explicitly retired.
        for claim, verdict in prior.verdicts.items():
            if claim not in self.verdicts and claim not in self.retired:
                raise CompactionIntegrityError(
                    f"verdict for {claim!r} ({verdict}) dropped by compaction "
                    f"at step {new_step}; must carry forward or mark retired_by."
                )
        # Invariant 2: open commitments are never silently discarded.
        for key, constraint in prior.commitments.items():
            if key not in self.commitments and key not in self.retired:
                raise CompactionIntegrityError(
                    f"open commitment {key!r} ({constraint}) dropped at step "
                    f"{new_step}; downstream output may violate it."
                )
        # Invariant 3: negative results are first-class; a 'contradicted' verdict
        # may only be retired with an explicit reason, never merely omitted.
        for claim, verdict in prior.verdicts.items():
            if verdict == "contradicted" and claim in self.retired:
                if not self.retired[claim]:
                    raise CompactionIntegrityError(
                        f"contradicted claim {claim!r} retired without reason at "
                        f"step {new_step}."
                    )
        return self


def apply_compaction(prior: StateLedger, candidate: StateLedger, step: int) -> StateLedger:
    if candidate.source_range[0] <= prior.source_range[0]:
        raise CompactionIntegrityError(
            f"compaction at step {step} overlaps already-compacted range; "
            "re-compaction must be append-only and versioned."
        )
    return candidate.compact(prior, step)
