# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-causal-trace-divergence-when-a-multi-hop-tool-invocation-silently-reorders-span-completion.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-causal-trace-divergence-when-a-multi-hop-tool-invocation-silently-reorders-span-completion.warrant.json
# Markdown SHA-256:   6aa3afaeb182966f0b4dbd6af3e050f0143ce3b784e9f81931b491e0a43fdf59
# Code AST SHA-256:   d0dc0b5f47b43b2d294e9822cdadcb5b734c8950ec518f70ab724af41e7e257e
# Verified Classes:   InferredEdgeAmbiguity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class InferredEdgeAmbiguity(RuntimeError):
    """Raised when causal reconstruction cannot attribute a span to a declared parent
    and interval containment yields an ambiguous or multi-parent result."""
    pass


def reconstruct_edge(span, declared_parents, enclosing_spans, reentry_gap_ms, tool_p99_ms):
    """
    span: dict with start, end, span_id
    declared_parents: list of span_ids that explicitly claim this span as child
    enclosing_spans: list of span_ids whose [start,end] contains span's interval
    """
    if len(declared_parents) == 1:
        parent = declared_parents[0]
        # consistency check only; never override declared parentage
        if parent not in enclosing_spans and reentry_gap_ms > 3 * tool_p99_ms:
            # declared parent closed late (reasoning re-entry); this is expected, not an error
            pass
        return {"parent": parent, "provenance": "DECLARED"}

    if len(declared_parents) > 1:
        raise InferredEdgeAmbiguity(
            f"span {span['span_id']} declares multiple parents {declared_parents}; "
            "trace context propagation is corrupt"
        )

    # No declared parent: fall back to containment, but fail closed on ambiguity
    if len(enclosing_spans) != 1:
        raise InferredEdgeAmbiguity(
            f"span {span['span_id']} has no declared parent and "
            f"{len(enclosing_spans)} enclosing candidates {enclosing_spans}; "
            "refusing to infer causal edge"
        )

    if reentry_gap_ms > 3 * tool_p99_ms:
        raise InferredEdgeAmbiguity(
            f"span {span['span_id']} sole enclosing candidate {enclosing_spans[0]} "
            f"exceeds re-entry threshold ({reentry_gap_ms}ms > 3x p99 {tool_p99_ms}ms); "
            "likely a non-parent ancestor enclosing a completed child"
        )

    return {"parent": enclosing_spans[0], "provenance": "INFERRED"}
