# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-instrumentation-from-silently-mis-attributing-memory-forget-operations-under-concurrent-read-modify-write.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-instrumentation-from-silently-mis-attributing-memory-forget-operations-under-concurrent-read-modify-write.warrant.json
# Markdown SHA-256:   7d21cb045b53fe08c6f8dfd0cfc0540016731fb5948fdd0eab26065617eb5e84
# Code AST SHA-256:   ee24d04d2fd23916cb3af1b31380237632ccd89e58b282bf0c5331ab9952f3b1
# Verified Classes:   ForgetAttributionError, RemovedRecord, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional, Protocol


class ForgetAttributionError(RuntimeError):
    """Raised when a forget span cannot be bound to the record it removed."""
    pass


@dataclass(frozen=True)
class RemovedRecord:
    key: str
    store: str
    version: int
    present: bool


class MemoryStore(Protocol):
    def compare_and_delete(self, key: str, expected_version: int) -> Optional[RemovedRecord]:
        ...


def emit_forget_span(store: MemoryStore, key: str, expected_version: int,
                     reason: str, span_builder) -> RemovedRecord:
    # The delete must return the removed record atomically; the span is built
    # from that return value, inside the store's critical section.
    removed = store.compare_and_delete(key, expected_version)

    if removed is None:
        # No atomic return value: the adapter cannot prove what it removed.
        raise ForgetAttributionError(
            f"store {getattr(store, 'name', '?')} did not return removed record "
            f"for key={key}; forget span would be intent-only"
        )

    if removed.present and removed.version != expected_version:
        # A concurrent writer superseded the record between read and forget.
        # The span must record the version actually removed, and the caller
        # must treat the distillation source as stale.
        span_builder(
            name="memory.forget",
            attributes={
                "memory.key": removed.key,
                "memory.store": removed.store,
                "memory.reason": reason,
                "memory.removed.version": removed.version,
                "memory.removed.present": True,
                "memory.expected.version": expected_version,
                "memory.superseded": True,
            },
        )
        raise ForgetAttributionError(
            f"forget on key={key} removed version {removed.version}, "
            f"expected {expected_version}; distillation source is stale"
        )

    span_builder(
        name="memory.forget",
        attributes={
            "memory.key": removed.key,
            "memory.store": removed.store,
            "memory.reason": reason,
            "memory.removed.version": removed.version if removed.present else -1,
            "memory.removed.present": removed.present,
            "memory.expected.version": expected_version,
        },
    )
    return removed
