fix(test-optimization): start the attempt timeout when a socket is free #11476
<!-- codex-pull-request-review-summary -->
<!-- codex-review-state:v1 {"code_review":{"commit_sha":"089e6455992eff49b6b7e3d24075641c5a25f9d9","has_any_findings":false,"has_unresolved_findings":false,"status":"completed"},"security_review":{"commit_sha":"089e6455992eff49b6b7e3d24075641c5a25f9d9","has_any_findings":null,"has_unresolved_findings":null,"status":"completed"}} -->
<!-- codex-security-review:v1 {"blockingSeverityThreshold":"P0","headSha":"089e6455992eff49b6b7e3d24075641c5a25f9d9","mergeGateEnabled":false,"pullRequestNumber":11476,"repository":"DataDog/dd-trace-js","status":"completed"} -->
<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-27T09:05:39.894569Z">2026-11-27T09:05:39.894569Z</relative-time> | 089e645 | Manual request |
| 🔒 Security Review | ✅ Completed <relative-time datetime="2026-11-27T09:08:10.556689Z">2026-11-27T09:08:10.556689Z</relative-time> | 089e645 | Manual request |
<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>
Overall package size
Self size: 9.62 MB
Deduped: 10.42 MB
No deduping: 10.42 MB
<details><summary>Dependency sizes</summary>
| name | version | self size | total size |
|------|---------|-----------|------------|
| import-in-the-middle | 3.7.0 | 180.06 kB | 580.71 kB |
| opentracing | 0.14.7 | 194.81 kB | 194.81 kB |
| dc-polyfill | 0.1.11 | 25.74 kB | 25.74 kB |
</details>
<sub>🤖 This report was automatically generated by heaviest-objects-in-the-universe<sub>
<sub><sub>!P2 Badge</sub></sub> Track socket capacity per origin rather than per agent
In agentless mode, trace, coverage, log, and screenshot uploads share the same protocol-specific agent but use different intake hosts (agentless/index.js). Node's maxSockets applies per origin, whereas this single counter imposes a limit across all origins. Consequently, 16 outstanding trace uploads now block coverage and logs even when their hosts have no occupied sockets; during finalization, those unrelated payloads can expire without being sent. Comparing the parent and this commit with a stub transport confirms that a coverage request following 16 trace requests is newly withheld. Key the accounting by the agent's connection-pool name so requests wait only when their actual socket pool is full.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
<sub><sub>!P2 Badge</sub></sub> Drain synchronous socket handoffs without recursive re-entry
When many requests are waiting and the common transport's buffer has insufficient remaining space for their bodies, transport.writable can still be true, but each attempt synchronously invokes its callback with ERR_DD_REQUEST_BUFFER_FULL (exporters/common/request.js). That callback calls releaseSocketSlot() again, so this synchronous next() recursively dispatches another waiter before the previous attempt can schedule its backpressure retry. A reproduction with 10,000 queued 1 KiB payloads overflowed the stack after roughly 1,160 dispatches, throwing RangeError out of the response callback and leaving requests stranded. Make the drain re-entrancy-safe so synchronous transport failures are processed iteratively rather than adding a stack frame per waiter.
AGENTS.md reference: AGENTS.md:L104-L106
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: 33a7cdaa46
<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
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
</details>
Codecov Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 99.16%. Comparing base (
0b16c04) to head (089e645).<details><summary>Additional details and impacted files</summary>
@@ Coverage Diff @@
## master #11476 +/- ##
=======================================
Coverage 99.16% 99.16%
=======================================
Files 1142 1142
Lines 189752 189849 +97
Branches 86 86
=======================================
+ Hits 188168 188265 +97
Misses 1584 1584
| Flag | Coverage Δ | |
|---|---|---|
| ai-guard | 63.86% <100.00%> (-0.02%) | :arrow_down: |
| apm-capabilities | 55.09% <100.00%> (+0.02%) | :arrow_up: |
| apm-integrations | 81.92% <100.00%> (-0.01%) | :arrow_down: |
| appsec | 59.66% <100.00%> (+0.09%) | :arrow_up: |
| debugger | 70.90% <100.00%> (-0.02%) | :arrow_down: |
| instrumentation | 59.95% <100.00%> (+0.05%) | :arrow_up: |
| llmobs | 82.54% <100.00%> (-0.02%) | :arrow_down: |
| master-coverage | 99.16% <100.00%> (?) | |
| openfeature | 68.10% <100.00%> (-0.02%) | :arrow_down: |
| platform | 67.51% <100.00%> (+<0.01%) | :arrow_up: |
| profiling | 66.55% <100.00%> (-0.02%) | :arrow_down: |
| serverless | 66.99% <100.00%> (-0.01%) | :arrow_down: |
| test-optimization | 82.06% <97.05%> (+0.02%) | :arrow_up: |
Flags with carried forward coverage won't be shown. Click here to find out more.
</details>
:umbrella: View full report in Codecov by Harness.
:loudspeaker: Have feedback on the report? Share it here.
<details><summary> :rocket: New features to boost your workflow: </summary>
</details>
Fixed in 089e645599: slots are now keyed by agent and origin, using the endpoint key from retry.js, so a full test-cycle pool no longer holds back coverage, logs or API uploads. Covered by limits each origin to its own agent sockets.
_🤖 Addressed by Claude Code_
Fixed in 089e645599: a release during the handoff now only frees the socket, and the running loop hands it on, so synchronous transport failures are processed iteratively. Covered by hands a free socket on without recursion when woken attempts fail synchronously, which queues 10,001 requests and overflowed the stack before this change.
_🤖 Addressed by Claude Code_
<!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
<!-- datadog-autotest-inline:v1:prod -->
<!-- datadog-autotest-delivery:v1:prod:3b59038e2e2969efee79c4143641b3e2ab0fd3f0334596fdb411232bd9cb0153:inline-0 -->
<sub><sub>!P1</sub></sub> Prevent recursive socket handoff under transport backpressure
<!-- autotest-finding-meta prod_data_type=none finding_id=8fddc098-5405-40b4-9851-7bd32bd015dc prod_effect=static -->
When the common transport has some buffer capacity but insufficient room for the next payload, writable remains true and its callback synchronously returns ERR_DD_REQUEST_BUFFER_FULL. That callback releases another slot, recursively entering this drain. A focused harness with 16 slots and 3,000 waiting 1-KiB requests reproduced a stack overflow before the successful request completed. Make the drain non-reentrant so transport backpressure cannot crash the test process; the suggested guard drained the same queue successfully.
* @param {SocketSlots & { draining?: boolean }} slots
*/
function releaseSocketSlot (slots) {
slots.active--
if (slots.draining) return
slots.draining = true
try {
// A woken request can settle or wait for exporter backpressure instead, leaving the socket to the next one.
while (slots.active < slots.limit && slots.waiting.size > 0) {
const [next] = slots.waiting
slots.waiting.delete(next)
next()
}
} finally {
slots.draining = false
}
}
<!-- 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/ffee78fa-1073-41cd-a31b-27e9536ec856?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:3b59038e2e2969efee79c4143641b3e2ab0fd3f0334596fdb411232bd9cb0153:inline-1 -->
<sub><sub>!P2</sub></sub> Track socket slots separately for each destination pool
<!-- autotest-finding-meta prod_data_type=none finding_id=c3ca5686-8fa1-447f-93cb-a0e9e723ed1d prod_effect=static -->
In agentless mode, trace and coverage writers share one HTTPS agent across different intake hosts. Node applies maxSockets separately to each origin, but this counter imposes 16 slots across the entire agent. The reviewer's base/head harness confirmed that 16 outstanding trace requests now block coverage despite its destination having no occupied sockets. A slow trace intake can therefore make healthy coverage uploads miss final-flush deadlines. Key the accounting by the agent's destination pool; this requires changes to both pool lookup and request-option handling.
<!-- 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/ffee78fa-1073-41cd-a31b-27e9536ec856?referrer=autotest-pr-comment">Open Bits AI session</a></sub>
Socket handoff can recurse through synchronous buffer-full callbacks until the test process overflows its stack. The agent-wide counter also makes independent intake hosts contend for one shared socket limit.
<sub>Open Bits AI session</sub>
<sub>🤖 Bits Code Review · Commit 33a7cda</sub>
<!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=FAIL ddrs_bucket=unknown session_id=ffee78fa-1073-41cd-a31b-27e9536ec856 -->
<!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
<!-- datadog-autotest:v1:prod -->
<!-- datadog-autotest-delivery:v1:prod:3b59038e2e2969efee79c4143641b3e2ab0fd3f0334596fdb411232bd9cb0153:bundle -->
Already fixed in 089e645599, after the reviewed commit: releaseSocketSlot sets a draining flag (reset in finally), so a release inside the handoff only frees the socket and the running loop hands it on. Covered by hands a free socket on without recursion when woken attempts fail synchronously (10,001 waiting requests).
_🤖 Addressed by Claude Code_
Already fixed in 089e645599, after the reviewed commit: slots are keyed by agent and origin, using the endpoint key from retry.js, so 16 outstanding test-cycle requests no longer block coverage. Covered by limits each origin to its own agent sockets.
_🤖 Addressed by Claude Code_
/datadog autotest review
@codex review
<details>
<summary>More details</summary>
Attempt timeouts now start when a destination’s socket slot becomes available, while final-flush deadlines still bound queued requests. The update fixes both earlier issues—recursive handoff causing stack overflow and contention between independent intake hosts—and leaves no reportable findings in static review.
</details>
Was this helpful? React 👍 or 👎
<sub>Open Bits AI session</sub>
<sub>🤖 Bits Code Review · Commit 089e645</sub>
<!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=PASS ddrs_bucket=unknown session_id=ffee78fa-1073-41cd-a31b-27e9536ec856 -->
<!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
<!-- datadog-autotest:v1:prod -->
<!-- datadog-autotest-delivery:v1:prod:f52d87423caa37d977e3136eb5e8ed630801afdc33bf08c04b844605ae438f5a:bundle -->
<!-- codex-review-receipt:v1 -->
Codex Review: Didn't find any major issues. Keep it up!
Reviewed commit: 089e645599
<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
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
</details>
<a target='_blank' href='https://app.datadoghq.com/ci/pipeline-executions?query=ci_level%3Ajob+%40git.commit.sha%3A089e6455992eff49b6b7e3d24075641c5a25f9d9&referrer=pr-comment&start=1795768177000'><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/pipelines-ok.svg"/><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/pipelines-ok-light.svg" alt="Pipelines" align="center" /></picture></a> <a target='_blank' href='https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest+%40git.commit.sha%3A61de1dabe14d866bd601f0c663e43822014f62cd&referrer=pr-comment&start=1795768177000'><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/tests-ok.svg"/><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/tests-ok-light.svg" alt="Tests" align="center" /></picture></a>
<details><summary><b>🎉 All green!</b></summary>
🧪 All tests passed
❄️ No new flaky tests detected
</details>
🔄 Datadog retried 1 test - 1 passed on retry <a href="https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest+%40git.commit.sha%3A61de1dabe14d866bd601f0c663e43822014f62cd+%40test.is_retry%3Atrue+AND+%28%40test.retry_reason%3Aauto_test_retry+OR+%28-%40test.retry_reason%3A%2A+AND+-%40test.is_new%3Atrue%29%29&referrer=pr-comment" title="View in Datadog"><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/datadog_icon.svg" alt="View in Datadog" align="center" /></a>
🎯 Code Coverage (<a target='_blank' href='https://app.datadoghq.com/ci/code-coverage/github.com%2Fdatadog%2Fdd-trace-js/pull-requests/11476'>details</a>)<br>• <strong><span title="Percentage of modified executable lines covered by tests in this PR">Patch Coverage</span></strong>: 100.00%<br>• <strong><span title="Percentage of all executable lines covered by tests in the entire codebase">Overall Coverage</span></strong>: 98.57% <span title="Change in overall coverage compared to the base branch">(-0.03%)</span><br>
<sub>
This comment will be updated automatically if new data arrives. <br />
🔗 Commit SHA: 089e645 | <a href="https://docs.datadoghq.com/integrations/guide/source-code-integration/#pr-comments">Docs</a> | <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzExNDc2?referrer=pr-comment">View more details</a> | Give us <a href="https://dd.enterprise.slack.com/archives/C07E3U2QRMM">feedback</a>!
</sub>
<!-- codex-review-receipt:v1 -->
🛡️ Codex Security Review · _Automatically triggered_
Security review completed. No security issues were found in this pull request.
Reviewed commit: 089e645599
_Only the user who started this review can view the report in Codex._
<details> <summary>ℹ️ About Codex security reviews in GitHub</summary>
<br/>
This is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found.
</details>
<details>
<summary>More details</summary>
Socket accounting is scoped per agent and origin, and iterative handoff preserves queue progress when waiting attempts fail synchronously. Full-suite verification remains unavailable because dependencies are absent.
</details>
Was this helpful? React 👍 or 👎
<sub>Open Bits AI session</sub>
<sub>🤖 Bits Code Review · Commit 089e645</sub>
<!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=PASS ddrs_bucket=unknown session_id=0cb279d4-26ba-4834-969b-0345696ab418 -->
<!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
<!-- datadog-autotest:v1:prod -->
<!-- datadog-autotest-delivery:v1:prod:97c1c7b23280cd0d0e8674283c3bb6a1393cbeea296e1b7403f6c6d4ec5f7e13:bundle -->
Benchmarks
Benchmark execution time: 2026-11-27 09:13:21
Comparing candidate commit 089e6455992eff49b6b7e3d24075641c5a25f9d9 in PR branch juan-fernandez/test-optimization-socket-slots with baseline commit 0b16c0414adcd14c65b8e23c1049f8a06e3a7823 in branch master.
Found 0 performance improvements and 0 performance regressions! Performance is the same for 2479 metrics, 8 unstable metrics.
<details>
<summary><h3>Explanation</h3></summary>
This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:
🟩 = significantly better candidate vs. baseline
🟥 = significantly worse candidate vs. baseline
We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.
If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.
Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.
<details>
<summary><h4>More details about the CI and significant changes</h4></summary>
You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.
CIs of the difference of means are often centered around 0%, because often changes are not that big:
---------------------------------(------|---^--------)-------------------------------->
-0.6% 0% 0.3% +1.2%
| | |
lower bound of the CI --' | |
sample mean (center of the CI) -------------' |
upper bound of the CI ----------------------'
As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).
For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:
----------------------------------------|---------|---(---------^---------)---------->
0% 1% 1.3% 2.2% 3.1%
| | | |
significant impact threshold --------------' | | |
lower bound of CI --------------' | |
sample mean (center of the CI) --------------------------' |
upper bound of CI ----------------------------------'
</details>
</details>
<details>
<summary><h3>Unstable benchmarks</h3></summary>
These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.
scenario:appsec-appsec-enabled-20
max_rss_usage [-80.137MB; +30.164MB] or [-34.724%; +13.070%]scenario:appsec-iast-no-vulnerability-iast-enabled-default-config-24
max_rss_usage [-50.707MB; +72.994MB] or [-15.143%; +21.798%]scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-20
max_rss_usage [-40.764MB; +30.033MB] or [-11.429%; +8.421%]scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-26
max_rss_usage [-27.229MB; +21.552MB] or [-9.001%; +7.124%]scenario:encoders-0.4-immediate-flush-24
max_rss_usage [-6.771MB; +2.487MB] or [-8.072%; +2.965%]scenario:openfeature-initialization-configuration-20
max_rss_usage [-7.364MB; +3.228MB] or [-9.288%; +4.071%]scenario:openfeature-initialization-error-20
max_rss_usage [-4745.124KB; +4773.124KB] or [-6.154%; +6.190%]scenario:openfeature-scale-full-26
max_rss_usage [-38.202MB; +18.882MB] or [-17.557%; +8.678%]</details>
Approved these changes.
Approved these changes.
szegedi
juan-fernandez
<!-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -->
<!-- Please make sure your changes are properly tested -->
<!-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -->
<!--
PR title guidance:
use test: cover retries, not fix: cover retries.
such as fix(http, tests): handle retries.
- Tests: test(scope): description
- Benchmarks: bench(scope): description
- Documentation: docs(scope): description
- CI and workflows: ci(scope): description
- Build tooling: build(scope): description
- Maintenance: chore(scope): description
use test(http): cover retries, not fix(test): cover retries.
chore(eslint), chore(scripts), ci(release), ci(workflows), and test(integration-tests).
-->
What does this PR do?
<!-- A brief description of the change being made with this pull request. -->
Test Optimization requests sent through an agent with a socket limit wait in the request layer until one of the sockets for their origin is free. Their attempt timeout starts then, not when the attempt is created.
ERR_DD_TEST_OPTIMIZATION_BACKPRESSURE_TIMEOUT.Motivation
<!-- What inspired you to submit this pull request? -->
The payload agent has 16 sockets, and each attempt has a 15-second timeout. When that timeout also counts the wait for a socket, a payload near the end of a long queue can send its whole body, time out before the intake answers, and be uploaded again by the retry.
Additional Notes
<!-- Anything else we should know when reviewing? -->
Synthetic replay of 187 payloads of about 2 MiB, sent in worker-sized messages to an intake that answers after 8 seconds (Node 24, one trial per row):
| Arrival rate | Duplicate uploads,
master| This PR | Final flush,master| This PR || --- | ---: | ---: | ---: | ---: |
| 25 MiB/s | 31 | 0 | 48.5 s | 33.6 s |
| As fast as possible | 15 | 0 | 30.6 s | 16.2 s |
Dropped payloads are the same on both (123 and 155). #11441 makes this reachable at lower latencies, because its compressed queue holds more payloads.
request.spec.jscovers the socket limit, the timeout start, the handoff past a request that reached its deadline, and the final-flush error. Theci-visibilityandexportersspecs pass withscripts/mocha-parallel-files.js, andnpm run type:check:cipasses.🤖 Generated with Claude Code