# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mutates-memory-inside-a-span-whose-parent-trace-was-already-exported.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mutates-memory-inside-a-span-whose-parent-trace-was-already-exported.warrant.json
# Markdown SHA-256:   8179c65ae59ad1fa32ff4dc9837b1a438765fbdea0e90461dbf0af7fb3749e3b
# Code AST SHA-256:   3ccd939e84882abd1c848bdce414804c505ee0c8cfe0f1fadc9ebd4780ed31d0
# Verified Classes:   StaleParentSpanError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleParentSpanError(RuntimeError):
    """Raised when a memory mutation attempts to parent to an already-exported span."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    end_time: float | None  # None means still open


def emit_memory_mutation(
    ctx: SpanContext,
    mutation_commit_ts: float,
    now: float | None = None,
) -> dict:
    """
    Emit a memory-mutation span. Enforces the lifetime invariant:
    a mutation may only be a child of a span that is still open and
    whose end_time is <= mutation start.
    """
    now = now if now is not None else time.time()

    if ctx.end_time is not None and ctx.end_time <= now:
        # Parent already exported. Parent-child would fabricate a causal edge.
        raise StaleParentSpanError(
            f"cannot parent memory.mutate to span {ctx.span_id} in trace "
            f"{ctx.trace_id}: parent closed at {ctx.end_time:.3f} "
            f"but mutation starts at {now:.3f}. "
            f"Emit as root span with Link to {ctx.trace_id}/{ctx.span_id} instead."
        )

    if mutation_commit_ts < now - 0.001:
        raise StaleParentSpanError(
            f"mutation commit {mutation_commit_ts:.3f} precedes span start "
            f"{now:.3f}; ordering invariant violated for trace {ctx.trace_id}"
        )

    return {
        "trace_id": ctx.trace_id,
        "parent_span_id": ctx.span_id,
        "name": "memory.mutate",
        "start_time": now,
        "attributes": {"mutation.deferred": False},
    }
