# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-when-reconstructing-tool-call-causality-across-a-res.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-when-reconstructing-tool-call-causality-across-a-res.warrant.json
# Markdown SHA-256:   847cb6a1043fc0101ddec1a616cfc7466375bb34641a7713daf409ebbb21bb8c
# Code AST SHA-256:   db23593840386f67b59cbcb9259bc9ea5a14803be83440943b1f9b0b2e6c0a31
# Verified Classes:   NonAuthoritativeTraceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class NonAuthoritativeTraceError(RuntimeError):
    """Raised when tool-call causality is reconstructed from GenAI spans
    that cross a checkpoint/resume discontinuity without ID-derivation
    state persisted in the durable store."""
    pass


def reconstruct_tool_causality(trace_spans: list[dict], checkpoint: dict) -> list[dict]:
    # A trace is only a valid causal ledger if every tool span's call_id
    # is unique across the whole trace AND the checkpoint records the
    # ID-derivation state that produced those IDs.
    tool_spans = [s for s in trace_spans if s.get("gen_ai.operation.name") == "execute_tool"]
    call_ids = [s["gen_ai.tool.call.id"] for s in tool_spans]

    if len(call_ids) != len(set(call_ids)):
        raise NonAuthoritativeTraceError(
            f"duplicate gen_ai.tool.call.id across trace: "
            f"{len(call_ids)} spans, {len(set(call_ids))} unique; "
            "resume likely re-initialized the step counter"
        )

    if "id_derivation_state" not in checkpoint:
        raise NonAuthoritativeTraceError(
            "checkpoint does not persist id_derivation_state; "
            "span call_ids cannot be trusted as causal identity across resume"
        )

    if checkpoint.get("resumed_at") is not None:
        # Timestamps are unreliable across the discontinuity; refuse to sort.
        raise NonAuthoritativeTraceError(
            "trace crosses a resume boundary; start_time ordering is "
            "non-authoritative. Use checkpoint.committed_steps as the ledger."
        )

    return sorted(tool_spans, key=lambda s: s["start_time"])
