# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-mid-tool-call-and-the-summarizer-drops-an-uncommitted-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-mid-tool-call-and-the-summarizer-drops-an-uncommitted-side-effect.warrant.json
# Markdown SHA-256:   f3cf72014373890d4ac06100d58ed9facf716e9c48d6258f3f173c8597cb9794
# Code AST SHA-256:   b0f20c6aa01c4f743d35cc8597e0b6973598baa8f6001f999a0988efeb877e3c
# Verified Classes:   CompactionIntegrityError, EffectStatus, EffectRecord, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CompactionIntegrityError(RuntimeError):
    """Raised when a resumed instance attempts to mutate before reconciling
    effects whose status exists only in lossy summary prose."""


class EffectStatus(Enum):
    COMMITTED = "committed"
    IN_FLIGHT = "in_flight"
    UNKNOWN = "unknown"          # summary mentioned it, ledger has no entry
    ABANDONED = "abandoned"      # handle lost across compaction


@dataclass
class EffectRecord:
    step: str
    idempotency_key: str
    status: EffectStatus
    handle: Optional[str] = None


@dataclass
class Checkpoint:
    epoch: int
    summary: str
    ledger: dict[str, EffectRecord] = field(default_factory=dict)
    reconciled: bool = False


def resume_and_execute(cp: Checkpoint, pending_mutations: list[str], read_ground_truth):
    # Invariant: any effect named in pending_mutations must have a ledger
    # entry; if it does not, the summary is the only record of its status
    # and we must NOT mutate until it is reconciled against ground truth.
    unresolved = [
        step for step in pending_mutations
        if step not in cp.ledger
        or cp.ledger[step].status in (EffectStatus.UNKNOWN, EffectStatus.IN_FLIGHT)
    ]

    if unresolved and not cp.reconciled:
        # Reconcile: read authoritative state for each unresolved effect.
        for step in unresolved:
            truth = read_ground_truth(step)
            rec = cp.ledger.get(step)
            if rec is None:
                cp.ledger[step] = EffectRecord(
                    step=step,
                    idempotency_key=f"reconciled:{cp.epoch}:{step}",
                    status=EffectStatus.COMMITTED if truth.committed else EffectStatus.UNKNOWN,
                    handle=None,
                )
            elif truth.committed:
                rec.status = EffectStatus.COMMITTED
            elif rec.status is EffectStatus.IN_FLIGHT and rec.handle is None:
                # Original handle was orphaned by compaction.
                rec.status = EffectStatus.ABANDONED
        cp.reconciled = True

    # After reconciliation, only genuinely-uncommitted steps may mutate.
    for step in pending_mutations:
        rec = cp.ledger.get(step)
        if rec is None:
            raise CompactionIntegrityError(
                f"step {step!r} has no ledger entry after reconciliation; "
                f"refusing to mutate on summary-only evidence at epoch {cp.epoch}"
            )
        if rec.status is EffectStatus.COMMITTED:
            continue  # already durable; do not re-execute
        if rec.status is EffectStatus.ABANDONED:
            raise CompactionIntegrityError(
                f"step {step!r} was in flight when compaction orphaned handle "
                f"{rec.handle!r}; status indeterminate, manual reconcile required"
            )
        # UNKNOWN or explicit pending -> safe to execute under idempotency key
        execute(step, rec.idempotency_key)


def execute(step: str, key: str):
    ...  # transport-level call, idempotent on key
