# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-between-memory-tool-read-and-write-spans-in-genai-instrumentation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-between-memory-tool-read-and-write-spans-in-genai-instrumentation.warrant.json
# Markdown SHA-256:   89052447dbb695a9efc7d6a4369d8627d37a76e21a9c7b12f1a6f689022d5f7d
# Code AST SHA-256:   36d5f4ead4b7f953951c3617e37b3465f9eea31905927ff294e6fdb57a655270
# Verified Classes:   UnpairedMemoryWriteError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

"""Fail-closed reconciliation for paired memory read/write spans."""

from dataclasses import dataclass


class UnpairedMemoryWriteError(RuntimeError):
    """A memory mutation exists with no joinable preceding read.

    This is an unaudited mutation, not orphan telemetry. Halt the segment.
    """


@dataclass(frozen=True)
class Span:
    op: str                 # "read" | "write"
    schema_version: str     # emitter-declared convention revision
    key_attr: str           # attribute name carrying the logical key
    key_value: str          # attribute value


def _reconcile(spans: list[Span], mapping: dict[tuple[str, str], str]) -> list[tuple[Span, Span]]:
    reads: dict[tuple[str, str], Span] = {}
    for s in spans:
        if s.op == "read":
            reads[(s.schema_version, s.key_value)] = s

    pairs: list[tuple[Span, Span]] = []
    for w in (s for s in spans if s.op == "write"):
        # Try same-revision join first, then declared cross-revision mapping.
        candidates = [(w.schema_version, w.key_value)]
        for (from_ver, to_ver), _ in mapping.items():
            if w.schema_version == from_ver:
                candidates.append((to_ver, w.key_value))

        match = next((reads[c] for c in candidates if c in reads), None)
        if match is None:
            raise UnpairedMemoryWriteError(
                f"write to {w.key_attr}={w.key_value!r} under schema "
                f"{w.schema_version!r} has no joinable read; "
                f"treat as unaudited mutation and halt segment"
            )
        pairs.append((match, w))
    return pairs


def audit_segment(spans: list[Span], mapping: dict[tuple[str, str], str] | None = None):
    return _reconcile(spans, mapping or {})
