# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-semantic-convention-gaps-as-a-correctness-hazard-rather-than-an-observability-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-semantic-convention-gaps-as-a-correctness-hazard-rather-than-an-observability-gap.warrant.json
# Markdown SHA-256:   23e05fb59e84317ecd51967609065ae8c58c44c8a5ccee00c82fb5915c53ed9c
# Code AST SHA-256:   f90c88ca27f587a31bab3be428e72fc2f13c1c33bdcbfeff637b007ae6f24884
# Verified Classes:   MemoryStateWitnessError, MemoryState, SpanSignal, StoreWitness
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class MemoryStateWitnessError(RuntimeError):
    """Raised when a memory-state decision would rest solely on telemetry spans."""


class MemoryState(Enum):
    DURABLE = "durable"
    LOST = "lost"
    FORGOTTEN_BY_POLICY = "forgotten_by_policy"
    NEVER_EXISTED = "never_existed"
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class SpanSignal:
    """What the GenAI semantic conventions actually give us for a memory op."""
    operation_name: str | None      # e.g. "execute_tool"; None if unspanned (out-of-process forget)
    status: str                     # "OK" reflects the RPC, not durability
    returned_rows: int              # 0 is ambiguous: forgotten, lost, or never written


@dataclass(frozen=True)
class StoreWitness:
    """The authoritative, in-band acknowledgment. This is what we are allowed to trust."""
    key: str
    sequence: int
    durability: str                 # "flushed" | "buffered" | "tombstoned"
    eviction_reason: str | None     # set only for policy-driven forget


def classify_memory_state(
    span: SpanSignal,
    witness: StoreWitness | None,
) -> MemoryState:
    """
    Decide memory state for resume/replay/audit.

    Invariant: telemetry is corroborating, never authoritative. A decision
    that cannot cite a non-telemetry witness MUST raise, not guess.
    """
    # No witness: the span cannot distinguish durable / lost / forgotten / never-existed.
    if witness is None:
        raise MemoryStateWitnessError(
            "cannot classify memory state from span alone: "
            f"operation={span.operation_name!r} status={span.status!r} "
            f"rows={span.returned_rows}. The GenAI semantic conventions do not "
            "carry durability, eviction reason, or a forget-vs-miss discriminator. "
            "Perform an authoritative reconciliation read before proceeding."
        )

    if witness.durability == "tombstoned":
        if witness.eviction_reason is None:
            # A tombstone without a reason is a forget we cannot attribute.
            raise MemoryStateWitnessError(
                f"tombstone for key {witness.key!r} has no eviction_reason; "
                "cannot distinguish policy forget from corruption."
            )
        return MemoryState.FORGOTTEN_BY_POLICY

    if witness.durability == "flushed":
        return MemoryState.DURABLE

    if witness.durability == "buffered":
        # Accepted but not durable. The span would have said OK; we must not.
        return MemoryState.LOST

    raise MemoryStateWitnessError(
        f"unrecognized durability class {witness.durability!r} for key {witness.key!r}"
    )


def resume_decision(span: SpanSignal, witness: StoreWitness | None) -> str:
    state = classify_memory_state(span, witness)
    if state is MemoryState.DURABLE:
        return "skip_rederivation"
    if state is MemoryState.FORGOTTEN_BY_POLICY:
        return "rederive_authorized"
    if state is MemoryState.LOST:
        # Must re-derive, but also flag the lost write for the durability audit.
        return "rederive_and_flag_loss"
    raise MemoryStateWitnessError(f"unhandled state {state!r}")
