# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-semantic-convention-extension-drift-when-memory-operation-spans-are-re-ingested-across-tracing-backends.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-semantic-convention-extension-drift-when-memory-operation-spans-are-re-ingested-across-tracing-backends.warrant.json
# Markdown SHA-256:   6b2ccd56ddc2f4db19e562ba6a86adbdbff6a20c17dd6cbb1be3fe12e790f807
# Code AST SHA-256:   f99588fc50f3a178c5b6292aa4e91d69eb44ef23af2e6a6f40cc89bd40aafd9f
# Verified Classes:   SemanticRevisionDriftError, MemorySpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SemanticRevisionDriftError(RuntimeError):
    """Raised when a memory-operation span's schema revision does not match
    the backend's registered extension revision for that attribute namespace,
    and the attribute feeds an automated consumer that cannot tolerate drift."""
    pass


@dataclass(frozen=True)
class MemorySpan:
    attribute: str          # e.g. "agent.memory.consolidate.source_count"
    schema_revision: str    # e.g. "r7" — stamped at span creation
    value: object
    feeds_automated_consumer: bool


def admit_span(span: MemorySpan, backend_registry: dict[str, str]) -> MemorySpan:
    """Gate re-ingestion. Returns a possibly revision-qualified span, or raises
    if the span cannot be safely admitted under the invariant:
    (attribute name, schema revision) must be unique per backend namespace."""
    if not span.attribute.startswith("agent.memory."):
        return span  # out of scope for this invariant

    registered = backend_registry.get(span.attribute)
    if registered is None:
        # Unknown attribute: admit but qualify, since we cannot vouch for meaning.
        return MemorySpan(
            attribute=f"{span.attribute}.rev_{span.schema_revision}",
            schema_revision=span.schema_revision,
            value=span.value,
            feeds_automated_consumer=span.feeds_automated_consumer,
        )

    if registered == span.schema_revision:
        return span  # exact match, safe

    # Revision mismatch. Coercion is forbidden if an automated consumer reads it.
    if span.feeds_automated_consumer:
        raise SemanticRevisionDriftError(
            f"attribute {span.attribute!r} emitted at revision {span.schema_revision!r} "
            f"but backend registered {registered!r}; automated consumer present, "
            f"refusing silent coercion. Qualify namespace or reject span."
        )

    # Human-only consumer: qualify the namespace rather than coerce.
    return MemorySpan(
        attribute=f"{span.attribute}.rev_{span.schema_revision}",
        schema_revision=span.schema_revision,
        value=span.value,
        feeds_automated_consumer=False,
    )


def eviction_trigger(spans: list[MemorySpan], evictor_revision: str) -> float:
    """Compute eviction pressure from consolidate spans, excluding any span
    whose revision does not match the evictor's own registry."""
    total = 0
    for s in spans:
        if s.attribute != "agent.memory.consolidate.source_count":
            continue
        if s.schema_revision != evictor_revision:
            # Cross-revision aggregate is the exact failure that caused the burst.
            raise SemanticRevisionDriftError(
                f"eviction trigger encountered span at revision {s.schema_revision!r} "
                f"while evictor runs at {evictor_revision!r}; refusing to aggregate."
            )
        total += int(s.value)
    return float(total)
