← Back to Pull requests

perf(test-optimization): reduce startup overhead and clean up temporary artifacts #11538

Closed
unknown closed this pull request without merging on Nov 30, 2026 20:06 UTC
View on GitHub
unknown unknown commented on Nov 30, 2026 08:49 UTC
Author

What does this PR do?

Reduces Test Optimization startup overhead (time, memory, module loading, and subprocess churn) and cleans up temporary files left behind during Test Optimization runs:

1. Skip loading dd-trace when ci/init.js does not initialize and avoid plugin subscribe/unsubscribe churn (ci/init.js):
- Return early with a lightweight no-op stub ({ init () {}, use () {} }) before require('../packages/dd-trace') when running inside package managers (npm/yarn/pnpm, supporting both POSIX and Windows bin/ paths), when DD_CIVISIBILITY_ENABLED=false, when agentless without DD_API_KEY, or when Vitest worker init is skipped.
- Lazily require packages/dd-trace/src/log on the package-manager skip path only when debug logging is enabled.
- Disable fs and child_process plugins (tracer.use('fs', false), tracer.use('child_process', false)) before tracer.init(baseOptions) so those plugins are never subscribed and immediately unsubscribed during initialization.

2. Deduplicate startup git subprocesses and skip redundant work when unshallowing is disabled (packages/dd-trace/src/plugins/util/git.js, packages/dd-trace/src/plugins/util/test.js, packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js):
- getGitRemoteName(): run git remote first and short-circuit immediately when there is a single remote (eliminating redundant rev-parse / branch / config lookups).
- getGitMetadata(): combine the three HEAD queries (git show author/committer, git show --format=%B, git rev-parse HEAD) into a single git show -s --no-show-signature --format=%H%x00%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI%x00%B invocation while preserving untrimmed commit message formatting.
- getTestEnvironmentMetadata() & checkShaDiscrepancies(): reuse the SHA and repository URL already extracted by getGitMetadata() instead of spawning getGitInformationDiscrepancy() again.
- sendGitMetadata(): check DD_CIVISIBILITY_GIT_UNSHALLOW_ENABLED before isShallowRepository(), avoiding redundant isShallowRepository(), getLatestCommits(), duplicate /search_commits requests, and duplicate git rev-list invocations on shallow clones when unshallowing is disabled.

3. Stream GitHub Actions _diag logs lazily and skip redundant worker filesystem reads (packages/dd-trace/src/plugins/util/ci.js, packages/dd-trace/src/plugins/util/test.js, packages/dd-trace/src/plugins/ci_plugin.js):
- Lazily expand diagnostic directory candidates (expandDiagnosticDirCandidates generator) so directory scanning stops as soon as Worker_.log files are found.
- Stream Worker_
.log in 64 KB chunks with 4 KB overlap (readJobIDFromWorkerLog), stopping as soon as the job ID matches and handling per-file read errors safely instead of reading entire multi-MB log files into memory.
- Skip getJobIDFromDiagFile() and getGitHubEventPayload() filesystem reads in worker processes (skipFilesystemReads: shouldSkipGitMetadataExtraction), while propagating CI_JOB_ID and CI_JOB_URL from the main process's testEnvironmentMetadata onto worker traces in CIPlugin._prepareWorkerTrace().

4. Clean up temporary Test Optimization artifacts and make cache writes atomic (packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js, packages/dd-trace/src/plugins/util/git.js, packages/dd-trace/src/ci-visibility/test-optimization-cache.js):
- Remove generated .pack and companion .idx files after upload (both on success and failure) in generateAndUploadPackFiles(), and execute git pack-objects without cachedExec so .cache files are not left behind or served stale after cleanup.
- Write DD_EXPERIMENTAL_TEST_OPT_SETTINGS_CACHE atomically via a temp sibling + renameSync (cleaning up the temp file on failure), and register an exit cleanup handler for auto-generated cache paths while never deleting user-configured cache files.

Motivation

Test Optimization runs via NODE_OPTIONS=-r dd-trace/ci/init, which executes in every spawned Node.js process (including package managers, helper scripts, test runners, and worker processes). Avoiding unnecessary module loading, redundant git subprocesses, full-file diagnostic log reads, and leftover temp artifacts significantly reduces startup latency, memory footprint, and disk clutter across CI runs.

Additional Notes

Performance & Memory Benchmarks (master vs. this PR)

Measured back-to-back on Node v24.14.1 (darwin-arm64), 20 fresh Node.js subprocess runs per workload (reporting median):

| Workload | Metric | Baseline (master) | Candidate (PR) | Delta |
| --- | --- | ---: | ---: | ---: |
| ci/init skipped (package manager bin/npm) | Wall time | 60.08 ms | 31.57 ms | -47.5% |
| | Peak RSS / Heap used | 68.75 MB / 12.43 MB | 48.87 MB / 5.22 MB | -28.9% / -58.0% |
| | Modules loaded | 187 | 14 | -92.5% |
| ci/init skipped (DD_CIVISIBILITY_ENABLED=false) | Wall time | 61.05 ms | 30.88 ms | -49.4% |
| | Peak RSS / Heap used | 68.80 MB / 12.44 MB | 50.02 MB / 4.92 MB | -27.3% / -60.5% |
| | Modules loaded | 186 | 13 | -93.0% |
| ci/init active (agentless) | Wall time (median / p95) | 86.24 ms / 89.44 ms | 85.23 ms / 86.72 ms | -1.2% / -3.0% |
| | Peak RSS / Heap used | 78.37 MB / 12.93 MB | 77.52 MB / 12.49 MB | -1.1% / -3.4% |
| | child_process sub/unsub events | 4,431 | 0 | -100% |
| getTestEnvironmentMetadata() main process (this repo) | Inner time / Wall time | 155.57 ms / 197.54 ms | 65.48 ms / 106.37 ms | -57.9% / -46.2% |
| | Heap delta | 0.85 MB | 0.65 MB | -23.5% |
| | git subprocess spawns | 14 | 5 | -64.3% |
| Worker getTestEnvironmentMetadata() in GHA (5 MB Worker_.log + 100 KB event.json) | Inner time / Wall time | 63.57 ms / 106.58 ms | 3.95 ms / 46.02 ms | -93.8% / -56.8% |
| | Peak RSS / Heap delta | 80.73 MB / 0.56 MB | 63.21 MB / 0.25 MB | -21.7% / -55.4% |
| Main process getJobIDFromDiagFile() in GHA (5 MB Worker_
.log) | Inner time / Wall time | 40.95 ms / 81.64 ms | 0.53 ms / 40.66 ms | -98.7% / -50.2% |
| | Peak RSS / Heap delta | 78.55 MB / 5.07 MB | 59.91 MB / 0.11 MB | -23.7% / -97.8% |
| Hygiene (shallow clone, DD_CIVISIBILITY_GIT_UNSHALLOW_ENABLED=false) | HTTP calls / leftover pack files | 3 / 2 | 2 / 0 | -1 HTTP call, 0 leftover files |
| Hygiene (auto-generated test-optimization-cache) | Leftover temp cache file after exit | yes | no | cleaned up |

Validation


  • Ran all packages/dd-trace/test/ci-visibility/*/.spec.js, packages/dd-trace/test/plugins/util/*.spec.js, packages/dd-trace/test/proxy.spec.js, packages/dd-trace/test/plugin_manager.spec.js, and packages/datadog-instrumentations/test/nyc.spec.js on 7.0.0-pre (Node v24.14.1) — all passed.

  • Validated all added/modified Test Optimization specs under 5.0.0 (v5 compatibility) — all passed.

  • Ran npm run lint, npm run type:check:ci, and npm run lint:editorconfig — all passed.
  • Made with Cursor

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: juan-fernandez Review duration: 677m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #11538"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 60.5% · Lower = rushed or shallow review
    60.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: 20.5% · Safe to merge
    20.5%