# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-an-llm-span-and-the-memory-read-that-fed-it-when-the-observability-pipeline-batches-spans-by-wall-clo.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-an-llm-span-and-the-memory-read-that-fed-it-when-the-observability-pipeline-batches-spans-by-wall-clo.warrant.json
# Markdown SHA-256:   293dfbff6b266335402f7837204dbddac5da4c49e9d5b6df0c74331805500131
# Code AST SHA-256:   e0bf6ba73becdf80fb6cf679eaf288bcf295d01854fe9d19cfacac3c8d644595
# Verified Classes:   CausalEdgeMissingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalEdgeMissingError(RuntimeError):
    """Raised when a span cannot be attached to a generation by a producer-stamped causal edge."""
    pass


def attach_span(span: dict, generations_by_id: dict) -> dict:
    """
    Attach a memory/tool span to the LLM generation that requested it.

    The ONLY admissible edge is span['request_token'], stamped by the producer
    at request-issue time. Timestamp proximity is never used to invent an edge.
    """
    token = span.get("request_token")
    if token is None:
        # Producer did not stamp an edge (e.g. third-party tool). Do not guess.
        raise CausalEdgeMissingError(
            f"span {span.get('span_id')} has no request_token; "
            f"refusing proximity attachment (end_time={span.get('end_time')})"
        )

    gen = generations_by_id.get(token)
    if gen is None:
        raise CausalEdgeMissingError(
            f"span {span.get('span_id')} references unknown generation {token}"
        )

    # Sanity: a span cannot close before the generation it fed even opened.
    # Violation means clock skew or out-of-order flush; do not silently sort.
    if span["end_time"] < gen["start_time"]:
        raise CausalEdgeMissingError(
            f"span {span['span_id']} end_time {span['end_time']} precedes "
            f"requested generation {token} start_time {gen['start_time']} "
            f"(clock skew or reordered flush)"
        )

    return {
        "span_id": span["span_id"],
        "attached_to": token,
        "inferred": False,        # producer-stamped, safe for causal metrics
        "parent": gen.get("parent_span_id"),
    }
