# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-memory-retrieve-span-because-the-retrieval-mutated-the-store.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-memory-retrieve-span-because-the-retrieval-mutated-the-store.warrant.json
# Markdown SHA-256:   df0148b23bc9d5906bbb196899564ba255b84be5ddc41f408116b5b3f7517cc4
# Code AST SHA-256:   ab485790e2b1e7fa917e611d05f8f60a598c90d1d8503473b9a0782e05bec8a9
# Verified Classes:   MemoryMutationUnrecordedError, StoreDelta, RetrieveSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class MemoryMutationUnrecordedError(RuntimeError):
    """Raised when a memory operation mutated store state but the emitted
    span does not carry a mutation delta sufficient for replay reconstruction."""


@dataclass(frozen=True)
class StoreDelta:
    evicted_ids: FrozenSet[str] = frozenset()
    ttl_refreshed_ids: FrozenSet[str] = frozenset()
    reindexed_ids: FrozenSet[str] = frozenset()
    self_recency_promoted: bool = False
    access_count_changed: bool = False

    def is_pure(self) -> bool:
        return not (
            self.evicted_ids
            or self.ttl_refreshed_ids
            or self.reindexed_ids
            or self.self_recency_promoted
            or self.access_count_changed
        )


@dataclass
class RetrieveSpan:
    span_name: str
    returned_id: str
    delta: StoreDelta
    mutation_span_emitted: bool = False


def emit_retrieve_span(
    returned_id: str,
    delta: StoreDelta,
    store_satisfies_read_idempotence: bool,
) -> RetrieveSpan:
    span = RetrieveSpan(
        span_name="memory.retrieve",
        returned_id=returned_id,
        delta=delta,
        mutation_span_emitted=False,
    )

    if store_satisfies_read_idempotence:
        # Pure-read store: a non-empty delta is a store contract violation,
        # not a telemetry problem. Surface it rather than silently emitting.
        if not delta.is_pure():
            raise MemoryMutationUnrecordedError(
                f"store declared read-idempotent but retrieve({returned_id}) "
                f"produced delta {delta!r}; the idempotence contract is broken "
                f"and the trace cannot be trusted"
            )
        return span

    # Non-idempotent store: mutation must be representable in the trace.
    if delta.is_pure():
        return span

    # Self-only mutation can ride on the retrieve span via delta annotation.
    if (
        delta.self_recency_promoted or delta.access_count_changed
    ) and not (delta.evicted_ids or delta.ttl_refreshed_ids or delta.reindexed_ids):
        return span

    # Cross-record mutation requires a dedicated span, because replay cannot
    # infer affected IDs from the retrieve's return value.
    if delta.evicted_ids or delta.ttl_refreshed_ids or delta.reindexed_ids:
        if not span.mutation_span_emitted:
            raise MemoryMutationUnrecordedError(
                f"retrieve({returned_id}) mutated sibling records "
                f"(evicted={sorted(delta.evicted_ids)}, "
                f"ttl={sorted(delta.ttl_refreshed_ids)}, "
                f"reindexed={sorted(delta.reindexed_ids)}) but no "
                f"memory.evict/memory.mutate span was emitted; replay will "
                f"reconstruct a store the live agent never had"
            )

    return span


def guarded_retrieve(
    client,
    key: str,
    store_satisfies_read_idempotence: bool,
) -> RetrieveSpan:
    result = client.retrieve(key)
    delta: Optional[StoreDelta] = getattr(result, "delta", None)
    if delta is None:
        # A store that cannot report its delta cannot be safely traced as a
        # read. Fail closed rather than emit a span that may be a lie.
        raise MemoryMutationUnrecordedError(
            f"retrieve({key}) returned no delta; cannot determine whether the "
            f"operation mutated the store, refusing to emit memory.retrieve"
        )
    return emit_retrieve_span(
        returned_id=result.id,
        delta=delta,
        store_satisfies_read_idempotence=store_satisfies_read_idempotence,
    )
