# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-semantic-convention-attribute-mapping-as-a-lossy-projection-across-memory-read-write-telemetry-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-semantic-convention-attribute-mapping-as-a-lossy-projection-across-memory-read-write-telemetry-boundaries.warrant.json
# Markdown SHA-256:   9e6dc04cc6d2d8d4209c5ec737a595e0aa88f6dfacbd73101cc7f2eccd43551f
# Code AST SHA-256:   7188356448bf1d85b9535c296475dba1c0c0ec97104f6f26d975af64e402c331
# Verified Classes:   ProjectionInjectivityError, MemorySpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProjectionInjectivityError(RuntimeError):
    """Raised when a memory telemetry span cannot be proven injective over its effect."""
    pass


@dataclass(frozen=True)
class MemorySpan:
    schema_url: str
    operation: str          # "write" | "read" | "retract"
    agent_id: str
    memory_key: str
    causal_parent: Optional[str]
    is_root: bool


VALIDATED_SCHEMAS = {"genai-memory/v1.3"}
REGISTERED_KEY_DERIVATIONS = {"sha256_full_content_v2"}


def validate_span_for_replay(span: MemorySpan, key_derivation: str) -> None:
    if span.schema_url not in VALIDATED_SCHEMAS:
        raise ProjectionInjectivityError(
            f"unvalidated schema {span.schema_url!r}; refusing authoritative replay"
        )
    if span.operation == "write":
        if not span.is_root and span.causal_parent is None:
            raise ProjectionInjectivityError(
                f"write to {span.memory_key!r} by {span.agent_id!r} has no causal parent "
                "and is not marked root; ordering is non-deterministic"
            )
        if key_derivation not in REGISTERED_KEY_DERIVATIONS:
            raise ProjectionInjectivityError(
                f"key derivation {key_derivation!r} is not registered; "
                "injectivity over effect-determining fields cannot be proven"
            )
    if span.operation == "retract" and span.schema_url not in VALIDATED_SCHEMAS:
        raise ProjectionInjectivityError(
            "retract under unvalidated schema; effect may be indistinguishable from write"
        )


def reconstruct_memory_state(spans: list[MemorySpan], derivation: str) -> dict:
    index: dict[str, MemorySpan] = {}
    for span in spans:
        validate_span_for_replay(span, derivation)
        if span.memory_key in index and index[span.memory_key].operation == "retract":
            # a retracted key must not be silently re-written without explicit root
            if not span.is_root:
                raise ProjectionInjectivityError(
                    f"write to retracted key {span.memory_key!r} without root marker; "
                    "successor would cite retracted evidence"
                )
        index[span.memory_key] = span
    return index
