# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-tool-call-span-silently-lose-its-parent-when-otel-genai-gen-ai-operation-name-is-re-emitted-across-a-mid-task-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-tool-call-span-silently-lose-its-parent-when-otel-genai-gen-ai-operation-name-is-re-emitted-across-a-mid-task-resume.warrant.json
# Markdown SHA-256:   6c469205dfdc1af6396731e4d9ed0c6e5343d26b6fda53089837c1e342440169
# Code AST SHA-256:   0edf00c271673535079c4c40e3c85d99f3d76b5a2803635272fae839a459e2d8
# Verified Classes:   SpanContinuityViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpanContinuityViolation(RuntimeError):
    """Raised when a resumed agent would emit a duplicate billable tool-call span."""
    pass


def resolve_tool_span(checkpoint: dict, fingerprint: str, tool_name: str) -> dict:
    """
    Decide whether to adopt an in-flight tool-call span or open a new one.
    Enforces: at most one completed billable span per
    (trace_id, tool_name, fingerprint), with resolvable parentage.
    """
    trace_id = checkpoint.get("trace_id")
    in_flight = checkpoint.get("in_flight_tool_spans", [])

    matches = [
        s for s in in_flight
        if s.get("gen_ai.tool.name") == tool_name
        and s.get("argument_fingerprint") == fingerprint
    ]

    if len(matches) > 1:
        # Two prior attempts already exist: invariant already broken upstream.
        raise SpanContinuityViolation(
            f"trace {trace_id}: {len(matches)} in-flight spans for "
            f"tool={tool_name} fp={fingerprint}; checkpoint is inconsistent"
        )

    if matches:
        prior = matches[0]
        if not prior.get("span_id") or not prior.get("parent_span_id"):
            # Cannot adopt: span identity was not checkpointed.
            # Must mark abandoned, not silently re-emit.
            raise SpanContinuityViolation(
                f"trace {trace_id}: prior span for tool={tool_name} lacks "
                f"span_id/parent_span_id; emit 'abandoned' status span "
                f"before re-invoking, do not open a duplicate"
            )
        return {"action": "adopt", "span": prior}

    return {"action": "open_new", "span": None}
