# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-between-memory-write-emission-and-memory-read-attribution-in-opentelemetry-genai-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-between-memory-write-emission-and-memory-read-attribution-in-opentelemetry-genai-spans.warrant.json
# Markdown SHA-256:   7185189cdb19c783ab055b763332e4963e30b0908b77adbc47a8c9b4d7115ac8
# Code AST SHA-256:   a5494e9ee7e3588b841e8f68331849478e41629e8b693dacb6d5f5ce143df3f4
# Verified Classes:   MemoryAttributionDriftError, MemorySpan
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class MemoryAttributionDriftError(RuntimeError):
    """Raised when a memory-read span's GenAI semantic-convention tuple
    diverges from its correlated memory-write span without an explicit
    scope-widening override."""


@dataclass(frozen=True)
class MemorySpan:
    record_id: str
    memory_type: str
    scope: Optional[str]          # None == attribute absent
    retention_class: Optional[str]
    scope_widened: bool = False
    origin_scope: Optional[str] = None
    is_write: bool = True


_REQUIRED_TUPLE = ("memory_type", "scope", "retention_class")


def validate_read_write_attribution(write: MemorySpan, read: MemorySpan) -> None:
    if write.is_write is not True or read.is_write is not False:
        raise MemoryAttributionDriftError(
            f"span orientation mismatch: write.is_write={write.is_write} "
            f"read.is_write={read.is_write}"
        )

    if write.record_id != read.record_id:
        raise MemoryAttributionDriftError(
            f"correlation key mismatch: {write.record_id!r} != {read.record_id!r}"
        )

    for field in _REQUIRED_TUPLE:
        w = getattr(write, field)
        r = getattr(read, field)

        if w is None:
            raise MemoryAttributionDriftError(
                f"write span {write.record_id} missing required tuple member {field!r}; "
                f"attribution invariant cannot be established"
            )

        if r is None:
            if read.scope_widened:
                # Widening override does not excuse a missing tuple member;
                # the override must still name the origin.
                raise MemoryAttributionDriftError(
                    f"read span {read.record_id} missing {field!r} despite "
                    f"scope_widened=True; origin_scope={read.origin_scope!r}"
                )
            raise MemoryAttributionDriftError(
                f"silent schema drift: read span {read.record_id} omits {field!r} "
                f"present on write span (write value={w!r}); no scope_widened override"
            )

        if w != r:
            if field == "scope" and read.scope_widened:
                if read.origin_scope != w:
                    raise MemoryAttributionDriftError(
                        f"widened read {read.record_id} declares origin_scope="
                        f"{read.origin_scope!r} but write scope={w!r}; widening "
                        f"override is inconsistent with the write record"
                    )
                continue  # legitimate, recorded widening
            raise MemoryAttributionDriftError(
                f"tuple divergence on {field!r} for record {read.record_id}: "
                f"write={w!r} read={r!r} (scope_widened={read.scope_widened}); "
                f"read attribute likely describes retrieval path, not record"
            )


def audit_pairs(pairs):
    failures = []
    for write, read in pairs:
        try:
            validate_read_write_attribution(write, read)
        except MemoryAttributionDriftError as exc:
            failures.append((read.record_id, str(exc)))
    if failures:
        raise MemoryAttributionDriftError(
            f"{len(failures)} drifted memory read/write pair(s) detected; "
            f"first: {failures[0][0]} -> {failures[0][1]}"
        )
