# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-prompt-tool-and-memory-spans-when-a-memory-write-span-is-emitted-after-the-tool-span-closes-but-befor.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-prompt-tool-and-memory-spans-when-a-memory-write-span-is-emitted-after-the-tool-span-closes-but-befor.warrant.json
# Markdown SHA-256:   5afb31ca32bf84f2142703fe30e8fc76e096dcd4c7248c750d71c1e19697d934
# Code AST SHA-256:   f7c821a5aaf9283598984287f8cb9521cf23be1f6cfea7f5a2034c98797faab0
# Verified Classes:   CausalLinkageError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CausalLinkageError(RuntimeError):
    """Raised when a memory-write span's causal parent cannot be reconciled
    with the structural span tree under the backend's ordering invariant."""
    pass


def assemble_trace(spans, response_finalized_at):
    """
    spans: list of dicts with keys span_id, parent, causal_parent,
           kind ('prompt'|'tool'|'memory'), start, end.
    response_finalized_at: timestamp of the prompt span's response.finalized event.
    """
    by_id = {s["span_id"]: s for s in spans}
    tree = {}

    for s in spans:
        # Structural parent must be open at child start.
        parent = by_id.get(s["parent"])
        if parent is not None and s["start"] < parent["start"]:
            raise CausalLinkageError(
                f"span {s['span_id']} starts before its parent {parent['span_id']}"
            )

        # Memory spans must have their causal parent resolved, and the
        # causal parent must NOT be the tool span when the write was
        # triggered by the tool result (sibling semantics).
        if s["kind"] == "memory":
            cp = s.get("causal_parent")
            if cp is None:
                raise CausalLinkageError(
                    f"memory span {s['span_id']} has no causal_parent; "
                    "cannot disambiguate tool-triggered vs prompt-triggered write"
                )
            if cp not in by_id:
                raise CausalLinkageError(
                    f"memory span {s['span_id']} references unknown causal_parent {cp}"
                )
            # Boundary check: if the memory span ends after response
            # finalization, the backend's ordering invariant would
            # re-parent or drop it. We refuse to silently mutate the tree.
            if s["end"] > response_finalized_at:
                raise CausalLinkageError(
                    f"memory span {s['span_id']} ends at {s['end']} after "
                    f"response.finalized at {response_finalized_at}; "
                    "backend would re-parent to nearest open span (likely the tool) "
                    "or drop the span. Fix flush ordering or relax the invariant."
                )
            tree.setdefault(cp, []).append(s["span_id"])

    return tree


# Trigger the failure: a lazy memory write that ends after finalization.
spans = [
    {"span_id": "P", "parent": None, "causal_parent": None,
     "kind": "prompt", "start": 0, "end": 100},
    {"span_id": "T", "parent": "P", "causal_parent": "P",
     "kind": "tool", "start": 10, "end": 40},
    {"span_id": "M", "parent": "P", "causal_parent": "T",
     "kind": "memory", "start": 45, "end": 120},  # ends after finalization
]

assemble_trace(spans, response_finalized_at=100)
