# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-edges-when-its-observability-trace-is-sampled-at-the-span-boundary-rather-than-the-decision-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-edges-when-its-observability-trace-is-sampled-at-the-span-boundary-rather-than-the-decision-boundary.warrant.json
# Markdown SHA-256:   430d45216ca560a40d3c4b9ae1441089ca3aa86dc3c472a81ed9582718080682
# Code AST SHA-256:   3295505a3c26456d00cb26b483663c37e39ac4626e919aad26450bedcc1c19cf
# Verified Classes:   CausalityReconstructionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalityReconstructionError(RuntimeError):
    """Raised when a reconstructed causality graph fabricates an edge
    by reparenting a tool span whose true decision parent was sampled out."""
    pass


DECISION_SPAN_KINDS = {"llm.reason", "llm.plan", "agent.decide"}
TOOL_SPAN_KINDS = {"tool.lookup_order", "tool.refund_order", "tool.notify"}


def reconstruct_edge(child_span: dict, spans_by_id: dict) -> dict:
    """
    Resolve the causal parent of a tool-call span.
    Fails closed: never infers a parent from trace-order adjacency.
    """
    if child_span["kind"] not in TOOL_SPAN_KINDS:
        return {"parent_id": child_span.get("parent_span_id"), "parent_dropped": False}

    parent_id = child_span.get("parent_span_id")
    if parent_id is None:
        # A tool call with no parent id is only valid if the runtime
        # explicitly marked it as a root dispatch. Anything else is a gap.
        if not child_span.get("root_dispatch", False):
            raise CausalityReconstructionError(
                f"tool span {child_span['span_id']} has null parent and is not a "
                f"declared root dispatch; refusing to coalesce to root"
            )
        return {"parent_id": None, "parent_dropped": False}

    parent = spans_by_id.get(parent_id)
    if parent is None:
        # True parent was sampled out. Mark the gap honestly; do NOT reparent.
        return {"parent_id": parent_id, "parent_dropped": True}

    if parent["kind"] not in DECISION_SPAN_KINDS:
        raise CausalityReconstructionError(
            f"tool span {child_span['span_id']} resolved to non-decision parent "
            f"{parent_id} (kind={parent['kind']}); this indicates a fabricated "
            f"edge from trace-order fallback, not a real causal link"
        )

    return {"parent_id": parent_id, "parent_dropped": False}
