# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-forget-tool-audit-span-as-authoritative-evidence-that-a-memory-mutation-occurred-and-when-must-it-distrust.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-forget-tool-audit-span-as-authoritative-evidence-that-a-memory-mutation-occurred-and-when-must-it-distrust.warrant.json
# Markdown SHA-256:   58e64977e4e3a5865deb3351f7ad6945c3306cbafe2b6d52ef5aab90eded8999
# Code AST SHA-256:   b745b49dd47f41d4a073f627730d33b1d164f2fdd2189156ac27000dde549219
# Verified Classes:   MutationVerificationError, MutationState, ForgetSpan, CompactionDiff
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class MutationVerificationError(RuntimeError):
    """Raised when a mutation cannot be attributed to an effect-channel observation."""


class MutationState(Enum):
    PENDING = "pending"
    VERIFIED = "verified"
    CONTRADICTED = "contradicted"


@dataclass(frozen=True)
class ForgetSpan:
    memory_id: str
    record_id: Optional[str]          # store-assigned; None if tool was optimistic
    generation: Optional[int]         # namespace generation at write time
    result: str                       # "deleted" | "not_found" | "deferred"
    barrier_active: bool              # compaction barrier during write window


@dataclass(frozen=True)
class CompactionDiff:
    generation: int
    removed: frozenset[str]           # record_ids absent from output snapshot
    retained: frozenset[str]          # record_ids present in output snapshot
    merged_into: dict[str, str] = field(default_factory=dict)


def reconcile(
    span: ForgetSpan,
    diff: Optional[CompactionDiff],
    store_exists: "callable[[str], bool]",
) -> MutationState:
    # Invariant 1: an optimistic or barrier-overlapped span is never authoritative.
    if span.barrier_active or span.result == "deferred":
        return MutationState.PENDING

    # Invariant 2: without a joinable key we cannot attribute the diff to the span.
    if span.record_id is None or span.generation is None:
        # Fall back to direct probe; do not resolve toward the span.
        if store_exists(span.memory_id):
            return MutationState.CONTRADICTED
        return MutationState.PENDING

    # Invariant 3: effect channel must be present and generation-aligned.
    if diff is None or diff.generation < span.generation:
        return MutationState.PENDING

    if span.record_id in diff.removed:
        return MutationState.VERIFIED
    if span.record_id in diff.retained or span.record_id in diff.merged_into:
        return MutationState.CONTRADICTED

    # Record_id appears in neither set: diff is incomplete, treat as unverified.
    raise MutationVerificationError(
        f"compaction diff at gen {diff.generation} is incomplete for "
        f"record {span.record_id!r} (span memory_id={span.memory_id!r}); "
        f"cannot classify mutation as verified or contradicted"
    )


def assert_forgotten(span: ForgetSpan, state: MutationState) -> None:
    if state is not MutationState.VERIFIED:
        raise MutationVerificationError(
            f"refusing to assert forget of {span.memory_id!r}: "
            f"state={state.value}, result_claimed={span.result!r}, "
            f"barrier_active={span.barrier_active}"
        )
