fix(llmobs): bound tool call tracking used for span links #21665
<!-- 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
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-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>
</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>
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 -->
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.
<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 -->
<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 -->
<!-- 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
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-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>
</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-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>
</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>
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 -->
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.
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.
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.
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-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>
</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>
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 -->
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.
<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 -->
<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 -->
<!-- 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
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>
<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 -->
<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 -->
<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 -->
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.
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.
mansur-akhmadi
Description
Fixes #21664
LinkTrackerkept 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_callsand_lookup_tool_idfor the life of the process.Changes, all in
ddtrace/llmobs/_utils.py:_tool_callsis now anOrderedDictcapped at_MAX_TRACKED_TOOL_CALLS(1000). When it's full, the oldest entry is evicted along with its lookup entry. This follows the boundedOrderedDict+popitem(last=False)pattern used by the promptHotCache.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 madeon_llm_tool_choiceskip every later identical tool call.on_tool_callwrites to the tool call it looked up rather than indexing_tool_callsagain, since an entry can now be evicted between the two reads._tool_callsand_lookup_tool_idtogether under oneforksafe.Lock(reset in a forked child), andon_tool_calldrops 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:The first three fail on main.
tests/llmobs/test_utils.py,tests/contrib/openai/test_openai_llmobs.py,tests/contrib/langgraph/test_langgraph_llmobs.pyandtests/contrib/openai_agentspass.scripts/lintstyle, typing, spelling, security and suitespec checks pass on the changed files.After rebasing on current main (with
ddtrace.llmobsnow type-checked, #21998):tests/llmobs/test_utils.py85 passed, mypy 1.15.0 reports no errors inddtrace/llmobs/_utils.py, ruff check and format are clean.Fork:
test_link_tracker_lock_is_reset_in_fork_childruns under@pytest.mark.subprocessand fails with a plainthreading.Lock(the child cannot take a lock held at fork time).Performance: no scenario under
benchmarks/exercisesLinkTracker, 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_spansin 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.