← Back to Pull requests

fix(llmobs): bound tool call tracking used for span links #21665

Open
mansur-akhmadi opened this pull request with 257 lines diff across 3 files
View on GitHub
mansur-akhmadi mansur-akhmadi commented on Nov 11, 2026 04:45 UTC
Author

Description

Fixes #21664

LinkTracker kept every tool call an LLM returned until a message with that tool call id was later sent back to an instrumented LLM. Tool calls that never go back to an LLM (forced tool use, structured extraction, the last step of an agent, tools run outside instrumented code) stayed in _tool_calls and _lookup_tool_id for the life of the process.

Changes, all in ddtrace/llmobs/_utils.py:

  • _tool_calls is now an OrderedDict capped at _MAX_TRACKED_TOOL_CALLS (1000). When it's full, the oldest entry is evicted along with its lookup entry. This follows the bounded OrderedDict + popitem(last=False) pattern used by the prompt HotCache.

  • When a tool call's output is consumed (on_tool_call_output_used), its (tool name, arguments) lookup entry is removed too. Before, if the tool span never ran, that entry stayed and made on_llm_tool_choice skip every later identical tool call.

  • Re-registering an existing tool id replaces the previous call and its lookup entry, so every lookup entry points at a tracked call and the lookup is bounded by the same cap.

  • on_tool_call writes to the tool call it looked up rather than indexing _tool_calls again, since an entry can now be evicted between the two reads.

  • Registration, eviction and removal update _tool_calls and _lookup_tool_id together under one forksafe.Lock (reset in a forked child), and on_tool_call drops the lookup entry only if the call it resolved is still the tracked one, since ReAct derives tool ids from the tool name and input.
  • Testing

    New tests in tests/llmobs/test_utils.py:

  • more than the cap of never-executed tool calls: both maps stay at the cap and the oldest entries go first

  • tool calls that ran but were never fed back: bounded, lookup empty

  • output consumed without a tool span: the same call can be tracked again

  • a reused tool id: the lookup does not keep stale entries

  • a re-registered id isn't evicted first

  • the normal LLM -> tool -> LLM round trip still produces both span links and leaves the tracker empty
  • The first three fail on main. tests/llmobs/test_utils.py, tests/contrib/openai/test_openai_llmobs.py, tests/contrib/langgraph/test_langgraph_llmobs.py and tests/contrib/openai_agents pass. scripts/lint style, typing, spelling, security and suitespec checks pass on the changed files.

    After rebasing on current main (with ddtrace.llmobs now type-checked, #21998): tests/llmobs/test_utils.py 85 passed, mypy 1.15.0 reports no errors in ddtrace/llmobs/_utils.py, ruff check and format are clean.

    Fork: test_link_tracker_lock_is_reset_in_fork_child runs under @pytest.mark.subprocess and fails with a plain threading.Lock (the child cannot take a lock held at fork time).

    Performance: no scenario under benchmarks/ exercises LinkTracker, so I measured the tracker directly against its version on the base commit (CPython 3.12.13, Apple M5, best of 7 × 10,000 calls):

    | | base | this PR |
    |---|---|---|
    | tool choice + output used, one thread | 1.25 µs | 1.81 µs |
    | tool choice with 1,000 calls tracked (evicts on every call here) | 1.46 µs | 1.76 µs |
    | tool choice + output used, 8 threads | 1.34 µs | 1.90 µs |

    About +0.5 µs per tool call, paid on span-finish callbacks of LLM and tool spans; it doesn't touch spans without tool calls.

    Risks

    Eviction is by count and oldest-first. If more than 1000 new tool calls are registered in the process while one tool call is still in flight, that call loses its span links. Nothing else changes. I picked 1000 to stay well above normal concurrency. It can be raised, or turned into a config option if you'd rather.

    Additional Notes

    _active_guardrail_spans in the same class has a similar retention pattern for guardrail spans that no later LLM span consumes. I left it out to keep this change focused.

    Diff: 257 lines (+247 / -10) across 3 files Reviewer: mansur-akhmadi Review duration: 31517m
    All Vouch review confidence checks passed
    Residual risk 0.11 = Change Risk (0.58) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.58 · 257 lines diff across 3 files
    0.58
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    80%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.332
    Self Review self_review
    0.140
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    26 items
    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 11, 2026 04:45 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"75f2fa2d539f1a452bca946a91ea378d6c8bfbe6","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

    <details>
    <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-26T17:49:51.808239Z">2026-11-26T17:49:51.808239Z</relative-time> | 75f2fa2 | New commits |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on code on Nov 11, 2026 04:55 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1000,8 +1007,21 @@ def on_llm_tool_choice(
                 llm_span_context=llm_span_context,
                 tool_version=tool_version,
             )
    +        # A re-registered tool id replaces the previous call and moves to the newest position.
    +        previous = self._tool_calls.pop(tool_id, None)
    +        if previous is not None:
    +            self._forget_lookup(previous)
             self._tool_calls[tool_id] = tool_call
             self._lookup_tool_id[(tool_name, formatted_arguments)] = tool_id

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest-inline:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:d9b72c65555de07c6e2cdadfd2d2104f8d370f855fd5495d4905a2583e779d66:inline-0 -->

    <sub><sub>!P2</sub></sub> Synchronize lookup insertion with tool-call eviction

    <!-- autotest-finding-meta source=static_analysis prod_data_type=none production_evidence_effect=none finding_id=1fc38954-ad44-4ecb-b4a5-0a89676ad283 prod_effect=static -->
    A registration paused between inserting the tracked call and inserting its lookup can have its call evicted by 1,000 newer registrations from other threads. Resuming then inserts an orphan lookup that subsequent evictions cannot remove. A controlled reproduction left 1,003 lookup entries for 1,000 tracked calls. These entries can accumulate indefinitely and prevent later calls with matching tool names and arguments from being tracked. Use shared synchronization across registration, eviction, and removal to preserve consistency between both maps.

    <!-- datadog-autotest-feedback-legend:v1 -->
    React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
    <details><summary>What each reaction means</summary>

  • 👍 Useful: correct, and you're fixing it or will.

  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.

  • 😕 Unclear: you can't tell what it means or why it matters.

  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

  • </details>

    <sub>🤖 Bits Code Review</sub> <sub>· <a href="https://app.datadoghq.com/code/3f57c5b5-2ed5-4412-b440-ba0ba23c8767?referrer=autotest-pr-comment">Open Bits AI session</a></sub>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Nov 11, 2026 04:55 UTC
    Reviewer

    <img src="https://img.shields.io/badge/BITS%20CODE%20REVIEW-FAIL-CC0000?labelColor=632CA6&style=for-the-badge&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNjMuNTUsNzQuMzJhNTUuMiw1NS4yLDAsMCwxLTEwLTguMzJjLS4zMS0uMjMtLjI2LTEuMjUtLjI2LTEuMjVBNTUuODEsNTUuODEsMCwwLDAsNjguOTQsNzMuMWExMi43NCwxMi43NCwwLDAsMCw5LjgxLS44MywyNSwyNSwwLDAsMCw3LjUzLTYuNjRsLjM0LjU5YTE0LjkzLDE0LjkzLDAsMCwxLTEuMjksMy4wNiw4LDgsMCwwLDAsMi4yNC44MWw2LS45M2ExOC4xMiw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DAsMS4xOSw1LDUsMCwwLDAtMi42Mi0uNDMsOS40OSw5LjQ5LDAsMCwwLTEuMS4xMiw3Ljc4LDcuNzgsMCwwLDEtMy0zLjcxbC0uMTctLjM5LS4wNy0uMTcsMC0uMDhjLS40Mi0xLjMxLS4xNC0xLjU3LDAtMnMuODUtLjc2LS4xNS0xLjFhMS44LDEuOCwwLDAsMC0uMzEtLjA3QzgwLjQ3LDM0LjU0LDgyLjQ0LDM0LjM0LDgzLjg1LDM1Wm0tNC42LDIxLjYzYy43Mi0uNTcsNC0xLjYyLDcuMDktMiwxLjYtLjE5LDMuODgtLjI5LDQuMzcsMCwxLC41MywxLDIuMTguMzEsMy43Mi0xLDIuMjItMi4zMyw0LjY3LTMuODgsNC44Ny0yLjUyLjM0LTQuOTEtMS03LjYzLTMuMDZBMi4yMywyLjIzLDAsMCwxLDc5LjI1LDU2LjYyWk01NS4zNCwzOS43NWM0LTIuNzMsOS4xNi0xLjY1LDguMy0uODMtMS42NSwxLjU2LjU0LDEuMS43OCw0YTUsNSwwLDAsMS0xLjEyLDRBMjUuNDksMjUuNDksMCwwLDAsNTguNyw0OGEyNiwyNiwwLDAsMC0yLjg1LDEuMTMsNy4zMiw3LjMyLDAsMCwxLS43My0uNTVBNS41Myw1LjUzLDAsMCwxLDU1LjM0LDM5Ljc1Wm02MC4xMSwyNy44Mi0zMi41MSw1LjlhMTYsMTYsMCwwLDEtMy43NSwzLjMzLDExLjc1LDExLjc1LDAsMCwxLTkuMjkuODUsMjAsMjAsMCwwLDEtMy43MS0xLjE5bC03Ljk1LDEuMSw0LjgzLDQwLjIsNTUuNy0xMFpNNjUuODgsMTEzLjkybC0uNDYtNC4zNyw5LjA5LTEzLjg4LDEwLjMzLDMsOC44OC0xNC44NCwxMC42NSw3LDguMS0xNywyLjg3LDMwLjkxWiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg%3D%3D" alt="Bits Code Review: FAIL" height="36"/>

    Concurrent registrations can leave permanent orphan lookup entries after eviction, defeating the memory bound and suppressing future span links for matching tool calls.

    <sub>Open Bits AI session</sub>

    <sub>🤖 Bits Code Review · Commit 2577787</sub>

    <!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=FAIL ddrs_bucket=unknown session_id=3f57c5b5-2ed5-4412-b440-ba0ba23c8767 -->

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:d9b72c65555de07c6e2cdadfd2d2104f8d370f855fd5495d4905a2583e779d66:bundle -->

    mansur-akhmadi mansur-akhmadi commented on code on Nov 13, 2026 16:31 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1000,8 +1007,21 @@ def on_llm_tool_choice(
                 llm_span_context=llm_span_context,
                 tool_version=tool_version,
             )
    +        # A re-registered tool id replaces the previous call and moves to the newest position.
    +        previous = self._tool_calls.pop(tool_id, None)
    +        if previous is not None:
    +            self._forget_lookup(previous)
             self._tool_calls[tool_id] = tool_call
             self._lookup_tool_id[(tool_name, formatted_arguments)] = tool_id

    Confirmed and fixed in 865c1f02e3. A registration preempted between the two inserts could have its call evicted and then store a lookup entry that nothing removes; I reproduced the 1,001 vs 1,000 mismatch. LinkTracker now takes one lock around registration (duplicate check, both inserts, eviction) and both removal paths, with span link creation left outside it. test_link_tracker_registration_is_atomic_with_eviction forces that interleaving deterministically.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 13, 2026 16:35 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -969,8 +976,11 @@ class LinkTracker:
         """
     
         def __init__(self) -> None:
    -        self._tool_calls: dict[str, TrackedToolCall] = {}  # maps tool id's to tool call data
    +        # Bounded by _MAX_TRACKED_TOOL_CALLS, oldest entries are evicted first.
    +        self._tool_calls: OrderedDict[str, TrackedToolCall] = OrderedDict()  # maps tool id's to tool call data
             self._lookup_tool_id: dict[tuple[str, str], str] = {}  # maps (tool_name, arguments) to tool id's
    +        # Keeps both tool call maps consistent across registration, eviction and removal.
    +        self._lock = Lock()

    <sub><sub>!P2 Badge</sub></sub> Use a fork-safe lock for the shared tracker

    When a multithreaded process forks while another thread is inside this critical section, ddtrace.internal.threads.Lock is inherited in its locked state and the owning thread no longer exists in the child. LLMObs._child_after_fork() retains the same LinkTracker, so the child's next tool-choice/output event blocks forever; use forksafe.Lock() or recreate this lock in the child hook so Gunicorn, uWSGI, and multiprocessing children cannot deadlock.

    AGENTS.md reference: AGENTS.md:L85-L85

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 13, 2026 16:35 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1030,12 +1053,13 @@ def on_tool_call(
             )
             if tool_call.tool_version is not None:
                 _annotate_llmobs_span_data(tool_span, tool_version=tool_call.tool_version)
    -        self._tool_calls[tool_id].tool_span_context = {
    +        tool_call.tool_span_context = {
                 "span_id": str(tool_span.span_id),
                 "trace_id": format_trace_id(tool_span.trace_id),
             }
    -        self._tool_calls[tool_id].tool_kind = tool_kind
    -        self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)
    +        tool_call.tool_kind = tool_kind
    +        with self._lock:
    +            self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)

    <sub><sub>!P2 Badge</sub></sub> Preserve lookups installed after eviction

    When the tracker is at _MAX_TRACKED_TOOL_CALLS and concurrent requests interleave, this callback can resolve the oldest call, then other registrations can evict it and install a new call with the same (tool_name, arguments) before this block runs. The unconditional pop then deletes the new call's lookup, so ID-less callers such as _llmobs_set_tool_attributes() in the OpenAI Agents integration and the CrewAI tool callback can no longer match that call and silently omit its span link; remove the key only when its current value still equals the resolved tool_id, or keep resolution and removal in one critical section.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 13, 2026 16:35 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 865c1f02e3

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

    </details>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on code on Nov 13, 2026 16:37 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -22,6 +23,7 @@
     from ddtrace.internal._tagset import TagsetEncodeError
     from ddtrace.internal._tagset import encode_tagset_values
     from ddtrace.internal.logger import get_logger
    +from ddtrace.internal.threads import Lock

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest-inline:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:0d1d50394cfac2acb93d9acb30575dcf9b51e83c72151a69c2b5d6e3c113f3a3:inline-0 -->

    <sub><sub>!P1</sub></sub> Use a fork-resettable lock for the tracker

    <!-- autotest-finding-meta source=static_analysis prod_data_type=none production_evidence_effect=none finding_id=14c158f9-9932-4c61-957c-28ae88e8db9d prod_effect=static -->
    If the process forks while another thread holds the new lock, the child inherits a permanently locked primitive. LLMObs._child_after_fork() preserves the tracker without resetting this lock, so the child's next tool-choice or output-consumption callback blocks indefinitely, hanging the affected request or worker. Import the fork-resettable Lock instead.

    from ddtrace.internal.forksafe import Lock
    from ddtrace.internal.logger import get_logger
    

    <!-- datadog-autotest-feedback-legend:v1 -->
    React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
    <details><summary>What each reaction means</summary>

  • 👍 Useful: correct, and you're fixing it or will.

  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.

  • 😕 Unclear: you can't tell what it means or why it matters.

  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

  • </details>

    <sub>🤖 Bits Code Review</sub> <sub>· <a href="https://app.datadoghq.com/code/3f57c5b5-2ed5-4412-b440-ba0ba23c8767?referrer=autotest-pr-comment">Open Bits AI session</a></sub>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on code on Nov 13, 2026 16:37 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1030,12 +1053,13 @@ def on_tool_call(
             )
             if tool_call.tool_version is not None:
                 _annotate_llmobs_span_data(tool_span, tool_version=tool_call.tool_version)
    -        self._tool_calls[tool_id].tool_span_context = {
    +        tool_call.tool_span_context = {
                 "span_id": str(tool_span.span_id),
                 "trace_id": format_trace_id(tool_span.trace_id),
             }
    -        self._tool_calls[tool_id].tool_kind = tool_kind
    -        self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)
    +        tool_call.tool_kind = tool_kind
    +        with self._lock:
    +            self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest-inline:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:0d1d50394cfac2acb93d9acb30575dcf9b51e83c72151a69c2b5d6e3c113f3a3:inline-1 -->

    <sub><sub>!P2</sub></sub> Preserve newer lookups when an evicted call finishes

    <!-- autotest-finding-meta source=static_analysis prod_data_type=none production_evidence_effect=none finding_id=55a902e7-d78f-4ac1-9e39-810fa5596c68 prod_effect=static -->
    At capacity, on_tool_call can resolve call A, pause while adding its span link, and let another thread evict A and register call B with the same name and arguments. This unconditional removal then deletes B's lookup although B remains tracked. Callbacks that omit tool IDs, including OpenAI Agents, consequently cannot resolve B and lose its span links. Check that the resolved call is still current before removing its lookup.

            with self._lock:
                if self._tool_calls.get(tool_id) is tool_call:
                    self._forget_lookup(tool_call)
    

    <!-- datadog-autotest-feedback-legend:v1 -->
    React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
    <details><summary>What each reaction means</summary>

  • 👍 Useful: correct, and you're fixing it or will.

  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.

  • 😕 Unclear: you can't tell what it means or why it matters.

  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

  • </details>

    <sub>🤖 Bits Code Review</sub> <sub>· <a href="https://app.datadoghq.com/code/3f57c5b5-2ed5-4412-b440-ba0ba23c8767?referrer=autotest-pr-comment">Open Bits AI session</a></sub>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Nov 13, 2026 16:37 UTC
    Reviewer

    <img src="https://img.shields.io/badge/BITS%20CODE%20REVIEW-FAIL-CC0000?labelColor=632CA6&style=for-the-badge&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNjMuNTUsNzQuMzJhNTUuMiw1NS4yLDAsMCwxLTEwLTguMzJjLS4zMS0uMjMtLjI2LTEuMjUtLjI2LTEuMjVBNTUuODEsNTUuODEsMCwwLDAsNjguOTQsNzMuMWExMi43NCwxMi43NCwwLDAsMCw5LjgxLS44MywyNSwyNSwwLDAsMCw3LjUzLTYuNjRsLjM0LjU5YTE0LjkzLDE0LjkzLDAsMCwxLTEuMjksMy4wNiw4LDgsMCwwLDAsMi4yNC44MWw2LS45M2ExOC4xMiwxOC4xMiwwLDAsMCwyLTE0LjMxYy0uOTMtMy01Ljc5LTkuMS02LjE0LTkuNDMtMS4yMi0xLjE3LjIxLTUuNy0yLjIxLTEwLjY1Qzg0LjY1LDI5LjU0LDc4LDI0LjA5LDc1LjA5LDIxLjcyYy44NS42Miw2LjEsMi43NCw4LjU1LDUuNjkuMjMtLjMuMzItMS44OS41My0yLjI5LTIuMS0yLjc2LTIuMjYtNy42Ni0yLjI2LTlBMTQuODcs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gzLjg1LDM1Wm0tNC42LDIxLjYzYy43Mi0uNTcsNC0xLjYyLDcuMDktMiwxLjYtLjE5LDMuODgtLjI5LDQuMzcsMCwxLC41MywxLDIuMTguMzEsMy43Mi0xLDIuMjItMi4zMyw0LjY3LTMuODgsNC44Ny0yLjUyLjM0LTQuOTEtMS03LjYzLTMuMDZBMi4yMywyLjIzLDAsMCwxLDc5LjI1LDU2LjYyWk01NS4zNCwzOS43NWM0LTIuNzMsOS4xNi0xLjY1LDguMy0uODMtMS42NSwxLjU2LjU0LDEuMS43OCw0YTUsNSwwLDAsMS0xLjEyLDRBMjUuNDksMjUuNDksMCwwLDAsNTguNyw0OGEyNiwyNiwwLDAsMC0yLjg1LDEuMTMsNy4zMiw3LjMyLDAsMCwxLS43My0uNTVBNS41Myw1LjUzLDAsMCwxLDU1LjM0LDM5Ljc1Wm02MC4xMSwyNy44Mi0zMi41MSw1LjlhMTYsMTYsMCwwLDEtMy43NSwzLjMzLDExLjc1LDExLjc1LDAsMCwxLTkuMjkuODUsMjAsMjAsMCwwLDEtMy43MS0xLjE5bC03Ljk1LDEuMSw0LjgzLDQwLjIsNTUuNy0xMFpNNjUuODgsMTEzLjkybC0uNDYtNC4zNyw5LjA5LTEzLjg4LDEwLjMzLDMsOC44OC0xNC44NCwxMC42NSw3LDguMS0xNywyLjg3LDMwLjkxWiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg%3D%3D" alt="Bits Code Review: FAIL" height="36"/>

    The most critical issue is the use of a non-fork-safe lock for the tracker at line 26 of ddtrace/llmobs/_utils.py: if a fork occurs while another thread holds the lock, the child inherits a permanently locked primitive and blocks indefinitely on the next tool callback. A separate race condition in on_tool_call (line 1062) can cause an unconditional lookup removal to delete a newer registration, silently dropping span links for tool callbacks that omit tool IDs (e.g., OpenAI Agents).

    <sub>Open Bits AI session</sub>

    <sub>🤖 Bits Code Review · Commit 865c1f0</sub>

    <!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=FAIL ddrs_bucket=unknown session_id=3f57c5b5-2ed5-4412-b440-ba0ba23c8767 -->

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:0d1d50394cfac2acb93d9acb30575dcf9b51e83c72151a69c2b5d6e3c113f3a3:bundle -->

    mansur-akhmadi mansur-akhmadi commented on code on Nov 14, 2026 06:02 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -969,8 +976,11 @@ class LinkTracker:
         """
     
         def __init__(self) -> None:
    -        self._tool_calls: dict[str, TrackedToolCall] = {}  # maps tool id's to tool call data
    +        # Bounded by _MAX_TRACKED_TOOL_CALLS, oldest entries are evicted first.
    +        self._tool_calls: OrderedDict[str, TrackedToolCall] = OrderedDict()  # maps tool id's to tool call data
             self._lookup_tool_id: dict[tuple[str, str], str] = {}  # maps (tool_name, arguments) to tool id's
    +        # Keeps both tool call maps consistent across registration, eviction and removal.
    +        self._lock = Lock()

    Fixed in f9ac4f9712: the tracker now uses forksafe.Lock(), which is reset in the child. test_link_tracker_lock_is_reset_in_fork_child forks while the lock is held and checks the child can acquire it.

    mansur-akhmadi mansur-akhmadi commented on code on Nov 14, 2026 06:02 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -22,6 +23,7 @@
     from ddtrace.internal._tagset import TagsetEncodeError
     from ddtrace.internal._tagset import encode_tagset_values
     from ddtrace.internal.logger import get_logger
    +from ddtrace.internal.threads import Lock

    Fixed in f9ac4f9712: the tracker now uses forksafe.Lock(), which is reset in the child. test_link_tracker_lock_is_reset_in_fork_child forks while the lock is held and checks the child can acquire it.

    mansur-akhmadi mansur-akhmadi commented on code on Nov 14, 2026 06:02 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1030,12 +1053,13 @@ def on_tool_call(
             )
             if tool_call.tool_version is not None:
                 _annotate_llmobs_span_data(tool_span, tool_version=tool_call.tool_version)
    -        self._tool_calls[tool_id].tool_span_context = {
    +        tool_call.tool_span_context = {
                 "span_id": str(tool_span.span_id),
                 "trace_id": format_trace_id(tool_span.trace_id),
             }
    -        self._tool_calls[tool_id].tool_kind = tool_kind
    -        self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)
    +        tool_call.tool_kind = tool_kind
    +        with self._lock:
    +            self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)

    Fixed in f9ac4f9712: on_tool_call only drops the lookup entry if it still points at the resolved tool id. test_link_tracker_tool_call_keeps_lookup_of_newer_call_with_same_arguments evicts the call and registers a same-key one mid-resolution.

    mansur-akhmadi mansur-akhmadi commented on code on Nov 14, 2026 06:02 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1030,12 +1053,13 @@ def on_tool_call(
             )
             if tool_call.tool_version is not None:
                 _annotate_llmobs_span_data(tool_span, tool_version=tool_call.tool_version)
    -        self._tool_calls[tool_id].tool_span_context = {
    +        tool_call.tool_span_context = {
                 "span_id": str(tool_span.span_id),
                 "trace_id": format_trace_id(tool_span.trace_id),
             }
    -        self._tool_calls[tool_id].tool_kind = tool_kind
    -        self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)
    +        tool_call.tool_kind = tool_kind
    +        with self._lock:
    +            self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)

    Fixed in f9ac4f9712: on_tool_call only drops the lookup entry if it still points at the resolved tool id. test_link_tracker_tool_call_keeps_lookup_of_newer_call_with_same_arguments evicts the call and registers a same-key one mid-resolution.

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on code on Nov 14, 2026 06:06 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1030,12 +1054,16 @@ def on_tool_call(
             )
             if tool_call.tool_version is not None:
                 _annotate_llmobs_span_data(tool_span, tool_version=tool_call.tool_version)
    -        self._tool_calls[tool_id].tool_span_context = {
    +        tool_call.tool_span_context = {
                 "span_id": str(tool_span.span_id),
                 "trace_id": format_trace_id(tool_span.trace_id),
             }
    -        self._tool_calls[tool_id].tool_kind = tool_kind
    -        self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)
    +        tool_call.tool_kind = tool_kind
    +        with self._lock:
    +            # The call may have been evicted meanwhile and a newer call registered under the same key.
    +            lookup_key = (tool_name, formatted_tool_arg)
    +            if self._lookup_tool_id.get(lookup_key) == tool_id:

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest-inline:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:940446f9ac51d228c436053afc8b48001a9b1660e7168d5257e4361de4c1e794:inline-0 -->

    <sub><sub>!P2</sub></sub> Check call identity before removing a reused-ID lookup

    <!-- autotest-finding-meta prod_data_type=none finding_id=b2e15968-286e-4af2-afa3-5acff33bc3f2 prod_effect=static -->
    The lookup race remains when IDs are reused. ReAct's capture_plain_text_tool_usage() derives IDs from tool name plus input, so identical calls reuse an ID. If another thread evicts call A and registers an identical replacement while A's on_tool_call callback is finishing, this ID comparison still succeeds and deletes the replacement's lookup. Subsequent callbacks without IDs cannot resolve the replacement and lose its span links. Under the lock, also verify that the tracked object is still the resolved call.

                if self._tool_calls.get(tool_id) is tool_call and self._lookup_tool_id.get(lookup_key) == tool_id:
    

    <!-- datadog-autotest-feedback-legend:v1 -->
    React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
    <details><summary>What each reaction means</summary>

  • 👍 Useful: correct, and you're fixing it or will.

  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.

  • 😕 Unclear: you can't tell what it means or why it matters.

  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

  • </details>

    <sub>🤖 Bits Code Review</sub> <sub>· <a href="https://app.datadoghq.com/code/3f57c5b5-2ed5-4412-b440-ba0ba23c8767?referrer=autotest-pr-comment">Open Bits AI session</a></sub>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Nov 14, 2026 06:06 UTC
    Reviewer

    <img src="https://img.shields.io/badge/BITS%20CODE%20REVIEW-FAIL-CC0000?labelColor=632CA6&style=for-the-badge&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNjMuNTUsNzQuMzJhNTUuMiw1NS4yLDAsMCwxLTEwLTguMzJjLS4zMS0uMjMtLjI2LTEuMjUtLjI2LTEuMjVBNTUuODEsNTUuODEsMCwwLDAsNjguOTQsNzMuMWExMi43NCwxMi43NCwwLDAsMCw5LjgxLS44MywyNSwyNSwwLDAsMCw3LjUzLTYuNjRsLjM0LjU5YTE0LjkzLDE0LjkzLDAsMCwxLTEuMjksMy4wNiw4LDgsMCwwLDAsMi4yNC44MWw2LS45M2ExOC4xMiwxOC4xMiwwLDAsMCwyLTE0LjMxYy0uOTMtMy01Ljc5LTkuMS02LjE0LTkuNDMtMS4yMi0xLjE3LjIxLTUuNy0yLjIxLTEwLjY1Qzg0LjY1LDI5LjU0LDc4LDI0LjA5LDc1LjA5LDIxLjcyYy44NS42Miw2LjEsMi43NCw4LjU1LDUuNjkuMjMtLjMuMzItMS44OS41My0yLjI5LTIuMS0yLjc2LTIuMjYtNy42Ni0yLjI2LTlBMTQuODcsMTQuODcsMCwwLDAsODAuNjksMTFhOC4xNiw4LjE2LDAsMCwxLDIuNjUsNC41MywxOC41MSwxOC41MSwwLDAsMCwzLjgyLDguMzRjMy40Myw0LjI2LDYuNTIsNi40NSw4LjA4LDQuODgsMS44OC0xLjktMS44OS0xMC4zNy02LjcxLTE1LjEtNS42Mi01LjUyLTcuMDktNC44MS0xMC4zOS0zLjYzLTIuNjMuOTQtNCw4LjQtMTAuOTEsOC4yNi0xLjE2LS4xNC00LjE1LS4yMS01LjY0LS4yQzYyLjM2LDE3LDYzLDE2LjIxLDYzLDE2LjIxYTM1LjYxLDM1LjYxLDAsMCwwLTQuMjUsMi4wOW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EyNiwyNiwwLDAsMC0yLjg1LDEuMTMsNy4zMiw3LjMyLDAsMCwxLS43My0uNTVBNS41Myw1LjUzLDAsMCwxLDU1LjM0LDM5Ljc1Wm02MC4xMSwyNy44Mi0zMi41MSw1LjlhMTYsMTYsMCwwLDEtMy43NSwzLjMzLDExLjc1LDExLjc1LDAsMCwxLTkuMjkuODUsMjAsMjAsMCwwLDEtMy43MS0xLjE5bC03Ljk1LDEuMSw0LjgzLDQwLjIsNTUuNy0xMFpNNjUuODgsMTEzLjkybC0uNDYtNC4zNyw5LjA5LTEzLjg4LDEwLjMzLDMsOC44OC0xNC44NCwxMC42NSw3LDguMS0xNywyLjg3LDMwLjkxWiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg%3D%3D" alt="Bits Code Review: FAIL" height="36"/>

    The PR caps tool-call tracking at 1,000 entries and cleans stale lookups; the latest commit fixes the fork deadlock and lookup removal for different IDs. One P2 race remains: ReAct reuses IDs, allowing an evicted call’s callback to delete its replacement’s lookup and drop span links.

    <sub>Open Bits AI session</sub>

    <sub>🤖 Bits Code Review · Commit f9ac4f9</sub>

    <!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=FAIL ddrs_bucket=unknown session_id=3f57c5b5-2ed5-4412-b440-ba0ba23c8767 -->

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:940446f9ac51d228c436053afc8b48001a9b1660e7168d5257e4361de4c1e794:bundle -->

    mansur-akhmadi mansur-akhmadi commented on code on Nov 18, 2026 16:07 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -1030,12 +1054,16 @@ def on_tool_call(
             )
             if tool_call.tool_version is not None:
                 _annotate_llmobs_span_data(tool_span, tool_version=tool_call.tool_version)
    -        self._tool_calls[tool_id].tool_span_context = {
    +        tool_call.tool_span_context = {
                 "span_id": str(tool_span.span_id),
                 "trace_id": format_trace_id(tool_span.trace_id),
             }
    -        self._tool_calls[tool_id].tool_kind = tool_kind
    -        self._lookup_tool_id.pop((tool_name, formatted_tool_arg), None)
    +        tool_call.tool_kind = tool_kind
    +        with self._lock:
    +            # The call may have been evicted meanwhile and a newer call registered under the same key.
    +            lookup_key = (tool_name, formatted_tool_arg)
    +            if self._lookup_tool_id.get(lookup_key) == tool_id:

    Confirmed and fixed in 7cd39d4793. With a reused tool id the id comparison alone can delete the replacement's lookup, so on_tool_call now also requires self._tool_calls.get(tool_id) is tool_call before dropping it. test_link_tracker_tool_call_keeps_lookup_of_newer_call_with_reused_tool_id evicts the call and re-registers an identical one under the same id mid-resolution.

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Nov 18, 2026 16:10 UTC
    Reviewer

    <img src="https://img.shields.io/badge/BITS%20CODE%20REVIEW-PASS-1a7f37?labelColor=632CA6&style=for-the-badge&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNjMuNTUsNzQuMzJhNTUuMiw1NS4yLDAsMCwxLTEwLTguMzJjLS4zMS0uMjMtLjI2LTEuMjUtLjI2LTEuMjVBNTUuODEsNTUuODEsMCwwLDAsNjguOTQsNzMuMWExMi43NCwxMi43NCwwLDAsMCw5LjgxLS44MywyNSwyNSwwLDAsMCw3LjUzLTYuNjRsLjM0LjU5YTE0LjkzLDE0LjkzLDAsMCwxLTEuMjksMy4wNiw4LDgsMCwwLDAsMi4yNC44MWw2LS45M2ExOC4xMiwxOC4xMiwwLDAsMCwyLTE0LjMxYy0uOTMtMy01Ljc5LTkuMS02LjE0LTkuNDMtMS4yMi0xLjE3LjIxLTUuNy0yLjIxLTEwLjY1Qzg0LjY1LDI5LjU0LDc4LDI0LjA5LDc1LjA5LDIxLjcyYy44NS42Miw2LjEsMi43NCw4LjU1LDUuNjkuMjMtLjMuMzItM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CwwLDAsMC0uMzEtLjA3QzgwLjQ3LDM0LjU0LDgyLjQ0LDM0LjM0LDgzLjg1LDM1Wm0tNC42LDIxLjYzYy43Mi0uNTcsNC0xLjYyLDcuMDktMiwxLjYtLjE5LDMuODgtLjI5LDQuMzcsMCwxLC41MywxLDIuMTguMzEsMy43Mi0xLDIuMjItMi4zMyw0LjY3LTMuODgsNC44Ny0yLjUyLjM0LTQuOTEtMS03LjYzLTMuMDZBMi4yMywyLjIzLDAsMCwxLDc5LjI1LDU2LjYyWk01NS4zNCwzOS43NWM0LTIuNzMsOS4xNi0xLjY1LDguMy0uODMtMS42NSwxLjU2LjU0LDEuMS43OCw0YTUsNSwwLDAsMS0xLjEyLDRBMjUuNDksMjUuNDksMCwwLDAsNTguNyw0OGEyNiwyNiwwLDAsMC0yLjg1LDEuMTMsNy4zMiw3LjMyLDAsMCwxLS43My0uNTVBNS41Myw1LjUzLDAsMCwxLDU1LjM0LDM5Ljc1Wm02MC4xMSwyNy44Mi0zMi41MSw1LjlhMTYsMTYsMCwwLDEtMy43NSwzLjMzLDExLjc1LDExLjc1LDAsMCwxLTkuMjkuODUsMjAsMjAsMCwwLDEtMy43MS0xLjE5bC03Ljk1LDEuMSw0LjgzLDQwLjIsNTUuNy0xMFpNNjUuODgsMTEzLjkybC0uNDYtNC4zNyw5LjA5LTEzLjg4LDEwLjMzLDMsOC44OC0xNC44NCwxMC42NSw3LDguMS0xNywyLjg3LDMwLjkxWiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg%3D%3D" alt="Bits Code Review: PASS" height="36"/>

    <details>
    <summary>More details</summary>

    Tool-call tracking is capped at 1,000 entries with oldest-first eviction and stale-lookup cleanup; the earlier orphan-lookup race and fork deadlock are fixed. The latest change preserves replacement lookups even when tool IDs are reused, and no findings remain open.

    </details>
    Was this helpful? React 👍 or 👎

    <sub>Open Bits AI session</sub>

    <sub>🤖 Bits Code Review · Commit 7cd39d4</sub>

    <!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=PASS ddrs_bucket=unknown session_id=3f57c5b5-2ed5-4412-b440-ba0ba23c8767 -->

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:75855b53d74675a48ecc281f6909aa90e4dd69412cd94429535fd8435693cad5:bundle -->

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Nov 19, 2026 20:19 UTC
    Reviewer

    <img src="https://img.shields.io/badge/BITS%20CODE%20REVIEW-PASS-1a7f37?labelColor=632CA6&style=for-the-badge&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNjMuNTUsNzQuMzJhNTUuMiw1NS4yLDAsMCwxLTEwLTguMzJjLS4zMS0uMjMtLjI2LTEuMjUtLjI2LTEuMjVBNTUuODEsNTUuODEsMCwwLDAsNjguOTQsNzMuMWExMi43NCwxMi43NCwwLDAsMCw5LjgxLS44MywyNSwyNSwwLDAsMCw3LjUzLTYuNjRsLjM0LjU5YTE0LjkzLDE0LjkzLDAsMCwxLTEuMjksMy4wNiw4LDgsMCwwLDAsMi4yNC44MWw2LS45M2ExOC4xMiwxOC4xMiwwLDAsMCwyLTE0LjMxYy0uOTMtMy01Ljc5LTkuMS02LjE0LTkuNDMtMS4yMi0xLjE3LjIxLTUuNy0yLjIxLTEwLjY1Qzg0LjY1LDI5LjU0LDc4LDI0LjA5LDc1LjA5LDIxLjcyYy44NS42Miw2LjEsMi43NCw4LjU1LDUuNjkuMjMtLjMuMzItMS44OS41My0yLjI5LTIuMS0yLjc2LTIuMjYtNy42Ni0yLjI2LTlBMTQuODcsMTQuODcsMCwwLDAsODAuNjksMTFhOC4xNiw4LjE2LDAsMCwxLDIuNjUsNC41MywxOC41MSwxOC41MSwwLDAsMCwzLjgyLD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xLC41MywxLDIuMTguMzEsMy43Mi0xLDIuMjItMi4zMyw0LjY3LTMuODgsNC44Ny0yLjUyLjM0LTQuOTEtMS03LjYzLTMuMDZBMi4yMywyLjIzLDAsMCwxLDc5LjI1LDU2LjYyWk01NS4zNCwzOS43NWM0LTIuNzMsOS4xNi0xLjY1LDguMy0uODMtMS42NSwxLjU2LjU0LDEuMS43OCw0YTUsNSwwLDAsMS0xLjEyLDRBMjUuNDksMjUuNDksMCwwLDAsNTguNyw0OGEyNiwyNiwwLDAsMC0yLjg1LDEuMTMsNy4zMiw3LjMyLDAsMCwxLS43My0uNTVBNS41Myw1LjUzLDAsMCwxLDU1LjM0LDM5Ljc1Wm02MC4xMSwyNy44Mi0zMi41MSw1LjlhMTYsMTYsMCwwLDEtMy43NSwzLjMzLDExLjc1LDExLjc1LDAsMCwxLTkuMjkuODUsMjAsMjAsMCwwLDEtMy43MS0xLjE5bC03Ljk1LDEuMSw0LjgzLDQwLjIsNTUuNy0xMFpNNjUuODgsMTEzLjkybC0uNDYtNC4zNyw5LjA5LTEzLjg4LDEwLjMzLDMsOC44OC0xNC44NCwxMC42NSw3LDguMS0xNywyLjg3LDMwLjkxWiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg%3D%3D" alt="Bits Code Review: PASS" height="36"/>

    <details>
    <summary>More details</summary>

    Eviction intentionally drops span links for tool calls that outlive the 1,000-entry tracking window. Runtime validation remains unconfirmed because the focused tests stopped during native-extension compilation.

    </details>
    Was this helpful? React 👍 or 👎

    <sub>Open Bits AI session</sub>

    <sub>🤖 Bits Code Review · Commit cfd8110</sub>

    <!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=PASS ddrs_bucket=unknown session_id=1d654f98-a1e8-423d-a0ae-be8df07d561d -->

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:0722ce7091d1c4cf7ccbcda5538aceebd452e453fb978fa4f45377b49503e36d:bundle -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 26, 2026 17:49 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 75f2fa2d53

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 26, 2026 17:49 UTC
    Code Review
    tests/llmobs/test_utils.py:1
    @@ -829,3 +835,193 @@ def test_wire_none_and_empty(self):
         def test_normalize_after_wire_recovers_hex(self):
             wire = _trace_id_to_wire(self.HEX_TRACE_ID)
             assert _normalize_wire_trace_id_to_hex(wire) == self.HEX_TRACE_ID
    +
    +
    +def _llm_span_context(i):
    +    return {"span_id": str(i), "trace_id": format_trace_id(i)}
    +
    +
    +def test_link_tracker_bounds_tool_calls_never_executed():
    +    """Tool choices that are never executed nor fed back to an LLM must not accumulate forever."""
    +    tracker = LinkTracker()
    +    total = _MAX_TRACKED_TOOL_CALLS + 10
    +    for i in range(total):
    +        tracker.on_llm_tool_choice(f"call_{i}", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +
    +    assert len(tracker._tool_calls) == _MAX_TRACKED_TOOL_CALLS
    +    assert len(tracker._lookup_tool_id) == _MAX_TRACKED_TOOL_CALLS
    +    # Oldest entries are evicted first, newest are kept.
    +    assert "call_0" not in tracker._tool_calls
    +    assert ("extract", '{"i":0}') not in tracker._lookup_tool_id
    +    assert f"call_{total - 1}" in tracker._tool_calls
    +    assert tracker._lookup_tool_id[("extract", f'{{"i":{total - 1}}}')] == f"call_{total - 1}"
    +
    +
    +def test_link_tracker_bounds_tool_calls_executed_but_never_fed_back(tracer):
    +    tracker = LinkTracker()
    +    for i in range(_MAX_TRACKED_TOOL_CALLS + 10):
    +        args = f'{{"i":{i}}}'
    +        tracker.on_llm_tool_choice(f"call_{i}", "extract", args, _llm_span_context(i))
    +        with tracer.trace("tool") as tool_span:
    +            tracker.on_tool_call("extract", args, "function", tool_span)
    +
    +    assert len(tracker._tool_calls) == _MAX_TRACKED_TOOL_CALLS
    +    assert len(tracker._lookup_tool_id) == 0
    +
    +
    +def test_link_tracker_bounds_lookup_when_tool_id_is_reused():
    +    tracker = LinkTracker()
    +    for i in range(_MAX_TRACKED_TOOL_CALLS + 10):
    +        tracker.on_llm_tool_choice("call_reused", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +
    +    last_args = f'{{"i":{_MAX_TRACKED_TOOL_CALLS + 9}}}'
    +    assert list(tracker._tool_calls) == ["call_reused"]
    +    assert tracker._tool_calls["call_reused"].arguments == last_args
    +    assert tracker._lookup_tool_id == {("extract", last_args): "call_reused"}
    +
    +
    +def test_link_tracker_reregistered_tool_id_is_not_evicted_first():
    +    tracker = LinkTracker()
    +    for i in range(_MAX_TRACKED_TOOL_CALLS):
    +        tracker.on_llm_tool_choice(f"call_{i}", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +    tracker.on_llm_tool_choice("call_0", "extract", '{"i":"again"}', _llm_span_context(0))
    +    tracker.on_llm_tool_choice("call_new", "extract", '{"i":"new"}', _llm_span_context(1))
    +
    +    assert "call_0" in tracker._tool_calls
    +    assert "call_1" not in tracker._tool_calls
    +
    +
    +def test_link_tracker_forgets_lookup_when_tool_output_used_without_tool_span(tracer):
    +    """A tool run by uninstrumented code must not block tracking the same tool call later."""
    +    tracker = LinkTracker()
    +    args = '{"q":"x"}'
    +    tracker.on_llm_tool_choice("call_1", "search", args, _llm_span_context(1))
    +    with tracer.trace("llm") as llm_span:
    +        tracker.on_tool_call_output_used("call_1", llm_span)
    +    assert tracker._tool_calls == {}
    +    assert tracker._lookup_tool_id == {}
    +
    +    tracker.on_llm_tool_choice("call_2", "search", args, _llm_span_context(2))
    +    assert tracker._lookup_tool_id == {("search", args): "call_2"}
    +    assert "call_2" in tracker._tool_calls
    +
    +
    +def test_link_tracker_links_tool_round_trip(tracer):
    +    tracker = LinkTracker()
    +    args = '{"q":"x"}'
    +    tracker.on_llm_tool_choice("call_1", "search", args, _llm_span_context(1))
    +    with tracer.trace("tool") as tool_span:
    +        tracker.on_tool_call("search", args, "function", tool_span)
    +        tool_links = get_llmobs_span_links(tool_span)
    +    with tracer.trace("llm") as llm_span:
    +        tracker.on_tool_call_output_used("call_1", llm_span)
    +        llm_links = get_llmobs_span_links(llm_span)
    +
    +    assert [link["span_id"] for link in tool_links] == ["1"]
    +    assert [link["span_id"] for link in llm_links] == [str(tool_span.span_id)]
    +    assert tracker._tool_calls == {}
    +    assert tracker._lookup_tool_id == {}
    +
    +
    +def test_link_tracker_registration_is_atomic_with_eviction():
    +    """Eviction from another thread must not run between storing a tool call and its lookup entry."""
    +    tracker = LinkTracker()
    +    other_thread_progressed = threading.Event()
    +
    +    class _ContentionSignalingLock:
    +        def __init__(self, lock):
    +            self._lock = lock
    +
    +        def __enter__(self):
    +            if not self._lock.acquire(blocking=False):
    +                other_thread_progressed.set()
    +                self._lock.acquire()
    +
    +        def __exit__(self, *exc_info):
    +            self._lock.release()
    +
    +    def register_newer_calls():
    +        for i in range(_MAX_TRACKED_TOOL_CALLS):
    +            tracker.on_llm_tool_choice(f"call_{i}", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +        other_thread_progressed.set()
    +
    +    other_thread = threading.Thread(target=register_newer_calls)
    +
    +    class _InterleavingLookup(dict):
    +        def __setitem__(self, key, value):
    +            if value == "call_paused" and not other_thread.is_alive():
    +                # Let another thread register enough calls to evict this one before its lookup is stored.
    +                other_thread.start()
    +                assert other_thread_progressed.wait(timeout=10)
    +            super().__setitem__(key, value)
    +
    +    tracker._lock = _ContentionSignalingLock(tracker._lock)
    +    tracker._lookup_tool_id = _InterleavingLookup()
    +    tracker.on_llm_tool_choice("call_paused", "extract", '{"i":"paused"}', _llm_span_context(0))
    +    other_thread.join(timeout=10)
    +
    +    assert not other_thread.is_alive()
    +    assert len(tracker._tool_calls) == _MAX_TRACKED_TOOL_CALLS
    +    assert len(tracker._lookup_tool_id) == _MAX_TRACKED_TOOL_CALLS
    +    assert all(tool_id in tracker._tool_calls for tool_id in tracker._lookup_tool_id.values())
    +
    +
    +def test_link_tracker_lock_is_reset_in_fork_child():

    <sub><sub>!P1 Badge</sub></sub> Isolate the fork regression test in a subprocess

    This test forks the shared pytest worker directly, contrary to FS-14 in the architecture rules adopted by AGENTS.md. Consequently, it executes all registered ddtrace fork hooks against the worker's existing state; if a child hook stalls, the unbounded os.waitpid(pid, 0) can hang the suite before the lock-acquisition timeout helps. Use @pytest.mark.subprocess() and move the required imports into the test body so the regression test runs in an isolated, timeout-controlled process.

    AGENTS.md reference: AGENTS.md:L28-L30

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 26, 2026 17:49 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -995,18 +1006,31 @@ def on_llm_tool_choice(
             This is to avoid some issues with parsing tool calls from ReAct agents which format tool calls as plain text.
             """
             formatted_arguments = format_tool_call_arguments(arguments)
    -        if self._lookup_tool_id.get((tool_name, formatted_arguments)):
    -            return
    -
             tool_call = TrackedToolCall(
                 tool_id=tool_id,
                 tool_name=tool_name,
                 arguments=formatted_arguments,
                 llm_span_context=llm_span_context,
                 tool_version=tool_version,
             )
    -        self._tool_calls[tool_id] = tool_call
    -        self._lookup_tool_id[(tool_name, formatted_arguments)] = tool_id
    +        with self._lock:

    <sub><sub>!P1 Badge</sub></sub> Benchmark the new synchronization on span-finish callbacks

    With LLMObs enabled, on_llm_tool_choice, on_tool_call, and on_tool_call_output_used now acquire the same process-wide lock from synchronous span-finish callbacks, but the supplied validation reports only functional tests and lint results. PERF-4.1 and AGENTS.md require benchmark coverage for these performance-sensitive changes, and the existing benchmark scenarios do not exercise tool linking. Add representative before/after measurements covering concurrent callbacks and eviction at capacity so the synchronization overhead is validated before merging.

    AGENTS.md reference: AGENTS.md:L16-L18

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Nov 26, 2026 17:51 UTC
    Reviewer

    <img src="https://img.shields.io/badge/BITS%20CODE%20REVIEW-PASS-1a7f37?labelColor=632CA6&style=for-the-badge&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNjMuNTUsNzQuMzJhNTUuMiw1NS4yLDAsMCwxLTEwLTguMzJjLS4zMS0uMjMtLjI2LTEuMjUtLjI2LTEuMjVBNTUuODEsNTUuODEsMCwwLDAsNjguOTQsNzMuMWExMi43NCwxMi43NCwwLDAsMCw5LjgxLS44MywyNSwyNSwwLDAsMCw3LjUzLTYuNjRsLjM0LjU5YTE0LjkzLDE0LjkzLDAsMCwxLTEuMjksMy4wNiw4LDgsMCwwLDAsMi4yNC44MWw2LS45M2ExOC4xMiwxOC4xMiwwLDAsMCwyLTE0LjMxYy0uOTMtMy01Ljc5LTkuMS02LjE0LTkuNDMtMS4yMi0xLjE3LjIxLTUuNy0yLjIxLTEwLjY1Qzg0LjY1LDI5LjU0LDc4LDI0LjA5LDc1LjA5LDIxLjcyYy44NS42Miw2LjEsMi43NCw4LjU1LDUuNjkuMjMtLjMuMzItMS44OS41My0yLjI5LTIuMS0yLjc2LTIuMjYtNy42Ni0yLjI2LTlBMTQuODcsMTQuODcsMCwwLDAsODAuNjksMTFhOC4xNiw4LjE2LDAsMCwxLDIuNjUsNC41MywxOC41MSwxOC41MSwwLDAsMCwzLjgyLDguMzRjMy40Myw0LjI2L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sMy43Mi0xLDIuMjItMi4zMyw0LjY3LTMuODgsNC44Ny0yLjUyLjM0LTQuOTEtMS03LjYzLTMuMDZBMi4yMywyLjIzLDAsMCwxLDc5LjI1LDU2LjYyWk01NS4zNCwzOS43NWM0LTIuNzMsOS4xNi0xLjY1LDguMy0uODMtMS42NSwxLjU2LjU0LDEuMS43OCw0YTUsNSwwLDAsMS0xLjEyLDRBMjUuNDksMjUuNDksMCwwLDAsNTguNyw0OGEyNiwyNiwwLDAsMC0yLjg1LDEuMTMsNy4zMiw3LjMyLDAsMCwxLS43My0uNTVBNS41Myw1LjUzLDAsMCwxLDU1LjM0LDM5Ljc1Wm02MC4xMSwyNy44Mi0zMi41MSw1LjlhMTYsMTYsMCwwLDEtMy43NSwzLjMzLDExLjc1LDExLjc1LDAsMCwxLTkuMjkuODUsMjAsMjAsMCwwLDEtMy43MS0xLjE5bC03Ljk1LDEuMSw0LjgzLDQwLjIsNTUuNy0xMFpNNjUuODgsMTEzLjkybC0uNDYtNC4zNyw5LjA5LTEzLjg4LDEwLjMzLDMsOC44OC0xNC44NCwxMC42NSw3LDguMS0xNywyLjg3LDMwLjkxWiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg%3D%3D" alt="Bits Code Review: PASS" height="36"/>

    <details>
    <summary>More details</summary>

    No runtime tracker defect was identified. The specialist’s only candidate concerned fork-test isolation; no downstream failure was established, so it remained below the reporting threshold.

    </details>
    Was this helpful? React 👍 or 👎

    <sub>Open Bits AI session</sub>

    <sub>🤖 Bits Code Review · Commit 75f2fa2</sub>

    <!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=PASS ddrs_bucket=unknown session_id=826e7c9c-7dd7-4178-8a61-f86ff563bdd5 -->

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:64f49c7f68322a48d7160e79c19c5e27b07823bd54f9fa83c6b43c651751882a:bundle -->

    mansur-akhmadi mansur-akhmadi commented on code on Nov 26, 2026 18:29 UTC
    Code Review
    tests/llmobs/test_utils.py:1
    @@ -829,3 +835,193 @@ def test_wire_none_and_empty(self):
         def test_normalize_after_wire_recovers_hex(self):
             wire = _trace_id_to_wire(self.HEX_TRACE_ID)
             assert _normalize_wire_trace_id_to_hex(wire) == self.HEX_TRACE_ID
    +
    +
    +def _llm_span_context(i):
    +    return {"span_id": str(i), "trace_id": format_trace_id(i)}
    +
    +
    +def test_link_tracker_bounds_tool_calls_never_executed():
    +    """Tool choices that are never executed nor fed back to an LLM must not accumulate forever."""
    +    tracker = LinkTracker()
    +    total = _MAX_TRACKED_TOOL_CALLS + 10
    +    for i in range(total):
    +        tracker.on_llm_tool_choice(f"call_{i}", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +
    +    assert len(tracker._tool_calls) == _MAX_TRACKED_TOOL_CALLS
    +    assert len(tracker._lookup_tool_id) == _MAX_TRACKED_TOOL_CALLS
    +    # Oldest entries are evicted first, newest are kept.
    +    assert "call_0" not in tracker._tool_calls
    +    assert ("extract", '{"i":0}') not in tracker._lookup_tool_id
    +    assert f"call_{total - 1}" in tracker._tool_calls
    +    assert tracker._lookup_tool_id[("extract", f'{{"i":{total - 1}}}')] == f"call_{total - 1}"
    +
    +
    +def test_link_tracker_bounds_tool_calls_executed_but_never_fed_back(tracer):
    +    tracker = LinkTracker()
    +    for i in range(_MAX_TRACKED_TOOL_CALLS + 10):
    +        args = f'{{"i":{i}}}'
    +        tracker.on_llm_tool_choice(f"call_{i}", "extract", args, _llm_span_context(i))
    +        with tracer.trace("tool") as tool_span:
    +            tracker.on_tool_call("extract", args, "function", tool_span)
    +
    +    assert len(tracker._tool_calls) == _MAX_TRACKED_TOOL_CALLS
    +    assert len(tracker._lookup_tool_id) == 0
    +
    +
    +def test_link_tracker_bounds_lookup_when_tool_id_is_reused():
    +    tracker = LinkTracker()
    +    for i in range(_MAX_TRACKED_TOOL_CALLS + 10):
    +        tracker.on_llm_tool_choice("call_reused", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +
    +    last_args = f'{{"i":{_MAX_TRACKED_TOOL_CALLS + 9}}}'
    +    assert list(tracker._tool_calls) == ["call_reused"]
    +    assert tracker._tool_calls["call_reused"].arguments == last_args
    +    assert tracker._lookup_tool_id == {("extract", last_args): "call_reused"}
    +
    +
    +def test_link_tracker_reregistered_tool_id_is_not_evicted_first():
    +    tracker = LinkTracker()
    +    for i in range(_MAX_TRACKED_TOOL_CALLS):
    +        tracker.on_llm_tool_choice(f"call_{i}", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +    tracker.on_llm_tool_choice("call_0", "extract", '{"i":"again"}', _llm_span_context(0))
    +    tracker.on_llm_tool_choice("call_new", "extract", '{"i":"new"}', _llm_span_context(1))
    +
    +    assert "call_0" in tracker._tool_calls
    +    assert "call_1" not in tracker._tool_calls
    +
    +
    +def test_link_tracker_forgets_lookup_when_tool_output_used_without_tool_span(tracer):
    +    """A tool run by uninstrumented code must not block tracking the same tool call later."""
    +    tracker = LinkTracker()
    +    args = '{"q":"x"}'
    +    tracker.on_llm_tool_choice("call_1", "search", args, _llm_span_context(1))
    +    with tracer.trace("llm") as llm_span:
    +        tracker.on_tool_call_output_used("call_1", llm_span)
    +    assert tracker._tool_calls == {}
    +    assert tracker._lookup_tool_id == {}
    +
    +    tracker.on_llm_tool_choice("call_2", "search", args, _llm_span_context(2))
    +    assert tracker._lookup_tool_id == {("search", args): "call_2"}
    +    assert "call_2" in tracker._tool_calls
    +
    +
    +def test_link_tracker_links_tool_round_trip(tracer):
    +    tracker = LinkTracker()
    +    args = '{"q":"x"}'
    +    tracker.on_llm_tool_choice("call_1", "search", args, _llm_span_context(1))
    +    with tracer.trace("tool") as tool_span:
    +        tracker.on_tool_call("search", args, "function", tool_span)
    +        tool_links = get_llmobs_span_links(tool_span)
    +    with tracer.trace("llm") as llm_span:
    +        tracker.on_tool_call_output_used("call_1", llm_span)
    +        llm_links = get_llmobs_span_links(llm_span)
    +
    +    assert [link["span_id"] for link in tool_links] == ["1"]
    +    assert [link["span_id"] for link in llm_links] == [str(tool_span.span_id)]
    +    assert tracker._tool_calls == {}
    +    assert tracker._lookup_tool_id == {}
    +
    +
    +def test_link_tracker_registration_is_atomic_with_eviction():
    +    """Eviction from another thread must not run between storing a tool call and its lookup entry."""
    +    tracker = LinkTracker()
    +    other_thread_progressed = threading.Event()
    +
    +    class _ContentionSignalingLock:
    +        def __init__(self, lock):
    +            self._lock = lock
    +
    +        def __enter__(self):
    +            if not self._lock.acquire(blocking=False):
    +                other_thread_progressed.set()
    +                self._lock.acquire()
    +
    +        def __exit__(self, *exc_info):
    +            self._lock.release()
    +
    +    def register_newer_calls():
    +        for i in range(_MAX_TRACKED_TOOL_CALLS):
    +            tracker.on_llm_tool_choice(f"call_{i}", "extract", f'{{"i":{i}}}', _llm_span_context(i))
    +        other_thread_progressed.set()
    +
    +    other_thread = threading.Thread(target=register_newer_calls)
    +
    +    class _InterleavingLookup(dict):
    +        def __setitem__(self, key, value):
    +            if value == "call_paused" and not other_thread.is_alive():
    +                # Let another thread register enough calls to evict this one before its lookup is stored.
    +                other_thread.start()
    +                assert other_thread_progressed.wait(timeout=10)
    +            super().__setitem__(key, value)
    +
    +    tracker._lock = _ContentionSignalingLock(tracker._lock)
    +    tracker._lookup_tool_id = _InterleavingLookup()
    +    tracker.on_llm_tool_choice("call_paused", "extract", '{"i":"paused"}', _llm_span_context(0))
    +    other_thread.join(timeout=10)
    +
    +    assert not other_thread.is_alive()
    +    assert len(tracker._tool_calls) == _MAX_TRACKED_TOOL_CALLS
    +    assert len(tracker._lookup_tool_id) == _MAX_TRACKED_TOOL_CALLS
    +    assert all(tool_id in tracker._tool_calls for tool_id in tracker._lookup_tool_id.values())
    +
    +
    +def test_link_tracker_lock_is_reset_in_fork_child():

    Fixed in 5ec3295ee: the test runs under @pytest.mark.subprocess with its imports in the body (and PYTHONWARNINGS=ignore::DeprecationWarning, like the other fork tests in tests/llmobs). It still fails with a plain threading.Lock.

    mansur-akhmadi mansur-akhmadi commented on code on Nov 26, 2026 18:29 UTC
    Code Review
    ddtrace/llmobs/_utils.py:1
    @@ -995,18 +1006,31 @@ def on_llm_tool_choice(
             This is to avoid some issues with parsing tool calls from ReAct agents which format tool calls as plain text.
             """
             formatted_arguments = format_tool_call_arguments(arguments)
    -        if self._lookup_tool_id.get((tool_name, formatted_arguments)):
    -            return
    -
             tool_call = TrackedToolCall(
                 tool_id=tool_id,
                 tool_name=tool_name,
                 arguments=formatted_arguments,
                 llm_span_context=llm_span_context,
                 tool_version=tool_version,
             )
    -        self._tool_calls[tool_id] = tool_call
    -        self._lookup_tool_id[(tool_name, formatted_arguments)] = tool_id
    +        with self._lock:

    Nothing under benchmarks/ exercises LinkTracker, so I measured the tracker directly against its base-commit version and added the numbers to the description: about +0.5 µs per tool call (1.25 → 1.81 µs for choice + output used, 1.34 → 1.90 µs with 8 threads, 1.46 → 1.76 µs registering at capacity). It only runs for spans that carry tool calls.

    Assignees
    mansur-akhmadi mansur-akhmadi
    Labels
    risk: low confidence: 80.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 58.1% (MEDIUM) · Higher = larger blast radius
    58.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 80.5% · Lower = rushed or shallow review
    80.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 11.3% · Safe to merge
    11.3%