# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-memory-write-provenance-when-otel-memory-tool-spans-drop-the-forget-semantic-convention.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-memory-write-provenance-when-otel-memory-tool-spans-drop-the-forget-semantic-convention.warrant.json
# Markdown SHA-256:   1dffbc546384d7d25ae309394f2fa0751689ade5a87c1dd5e24f7415199efd48
# Code AST SHA-256:   069d73793facfcfb0e1c0e9527d2130cf023ae9366759923c2966552763b9c38
# Verified Classes:   ConventionCoverageError, MemoryOp
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from enum import Enum
from typing import Callable

class ConventionCoverageError(RuntimeError):
    """Raised when the memory-tool operation set cannot be totally and
    injectively mapped onto the memory.operation semantic-convention enum."""

class MemoryOp(str, Enum):
    READ = "read"
    WRITE = "write"
    FORGET = "forget"
    UNKNOWN = "unknown"  # barrier: consumers must not resolve across it

# Operations that commute with WRITE in final-state terms may coerce to WRITE.
# Everything else must be first-class or the exporter must refuse to start.
COMMUTES_WITH_WRITE = {"read", "touch", "peek"}

def build_convention_map(
    runtime_ops: set[str],
    mapped: dict[str, MemoryOp],
    is_commutative: Callable[[str, str], bool],
) -> dict[str, MemoryOp]:
    """Construct a total, injective operation->enum map or raise.

    Invariant enforced: for every runtime op not in `mapped`, either it
    commutes with every op already mapped to a candidate enum value, or
    it has no candidate and the map is rejected.
    """
    result = dict(mapped)
    for op in runtime_ops:
        if op in result:
            continue
        candidates = [v for v in MemoryOp if v is not MemoryOp.UNKNOWN]
        safe = [
            v for v in candidates
            if all(
                is_commutative(op, other)
                for other, mapped_v in result.items()
                if mapped_v is v
            )
        ]
        if not safe:
            # Non-commutative with every mapped op and no first-class value.
            # Coercion to WRITE here is the exact silent-corruption path.
            raise ConventionCoverageError(
                f"memory op {op!r} has no safe enum value; "
                f"mapping would coerce to WRITE and break "
                f"write/forget order-isomorphism"
            )
        result[op] = safe[0]
    # Injectivity check across the final map.
    seen: dict[MemoryOp, str] = {}
    for op, v in result.items():
        if v in seen and not is_commutative(op, seen[v]):
            raise ConventionCoverageError(
                f"non-injective mapping: {op!r} and {seen[v]!r} "
                f"both -> {v.value!r} but do not commute"
            )
        seen.setdefault(v, op)
    return result

def export_memory_span(op: str, convention_map: dict[str, MemoryOp]) -> dict:
    if op not in convention_map:
        raise ConventionCoverageError(
            f"op {op!r} not in convention map; refusing to emit "
            f"span with fallback operation"
        )
    return {"memory.operation": convention_map[op].value}
