# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-synthesize-a-gen-ai-tool-call-id-for-a-tool-invocation-that-arrives-without-one.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-synthesize-a-gen-ai-tool-call-id-for-a-tool-invocation-that-arrives-without-one.warrant.json
# Markdown SHA-256:   9c1c3dbdc2c4f77de7bf642305e991f3bd3ddba014f836fb06534847bfb077bf
# Code AST SHA-256:   924123661669475762dc8837ef24b55b911eee1f7a1bd84cb552194d1b582108
# Verified Classes:   ToolCallIdInvariantError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ToolCallIdInvariantError(RuntimeError):
    """Raised when instrumentation is asked to fabricate a tool-call ID
    that cannot be threaded back to the request-side span."""
    pass


def resolve_tool_call_id(invocation, shared_record) -> str:
    """
    Return a tool-call ID that is guaranteed to appear on the request span,
    the execute_tool span, and the follow-up result message.

    `invocation` is the framework's tool-call object as seen at execution time.
    `shared_record` is the mutable record shared with the request-side span
    builder, or None if the framework exposes no such shared state.
    """
    existing = getattr(invocation, "id", None)
    if existing:
        return existing

    # No ID from the model/framework: we may only repair correlation if we
    # own a shared record that the request span will also read.
    if shared_record is None:
        raise ToolCallIdInvariantError(
            "tool invocation has no gen_ai.tool.call.id and no shared record "
            "exists to thread a generated ID back to the request span; "
            "emit the execute_tool span as explicitly uncorrelated instead "
            "of fabricating an ID"
        )

    # Thread-through path: generate once, persist in shared state so the
    # request span and the result message observe the same value.
    generated = _new_stable_id(invocation)
    shared_record.tool_call_id = generated
    return generated


def emit_execute_tool_span(tracer, invocation, shared_record):
    with tracer.start_as_current_span("execute_tool") as span:
        try:
            tool_call_id = resolve_tool_call_id(invocation, shared_record)
        except ToolCallIdInvariantError:
            # Honest degradation: no fabricated correlation.
            span.set_attribute("gen_ai.tool.call.id.present", False)
            span.add_event("tool_call_id_missing", {"reason": "no_shared_record"})
            raise
        span.set_attribute("gen_ai.tool.call.id", tool_call_id)
        span.set_attribute("gen_ai.tool.call.id.present", True)
        return span
