# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-memory-write-span-whose-semantic-convention-attributes-are-structurally-valid-but-semantically-unbound.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-memory-write-span-whose-semantic-convention-attributes-are-structurally-valid-but-semantically-unbound.warrant.json
# Markdown SHA-256:   6d7924855bb0a5d13df1ca1285c3d4a3a6154593ac31281ee2b2785032b4e125
# Code AST SHA-256:   e98b0a11188e8a39c3409ebefc7e8124ba63e8155d6bb63edfa9d42a6b3c78af
# Verified Classes:   MemoryProvenanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class MemoryProvenanceError(RuntimeError):
    """Raised when a memory span is schema-valid but semantically unbound."""
    pass


REQUIRED_BINDING_ATTRS = (
    "gen_ai.memory.episode.id",
    "gen_ai.agent.incarnation",
)


def admit_memory_span(span: dict, store_provenance: dict) -> None:
    op = span.get("gen_ai.memory.operation")
    if op not in ("write", "forget"):
        # Reads are downgraded by the consumer, not rejected here.
        return

    for attr in REQUIRED_BINDING_ATTRS:
        if not span.get(attr):
            raise MemoryProvenanceError(
                f"{op} span missing binding attribute {attr!r}; "
                "span is schema-valid but unaddressable for replay/audit"
            )

    incarnation = span["gen_ai.agent.incarnation"]
    store_id = span["gen_ai.memory.store.id"]
    for key in span.get("gen_ai.memory.record.keys", []):
        prior = store_provenance.get((store_id, key))
        if prior is None:
            continue
        if prior["incarnation"] != incarnation and not span.get(
            "gen_ai.memory.write.cross_incarnation"
        ):
            raise MemoryProvenanceError(
                f"{op} on key {key!r} crosses incarnation boundary "
                f"({prior['incarnation']} -> {incarnation}) without "
                "cross_incarnation=true and supersedes pointer"
            )
