Skip to content

fix(profiling): respect frame limits during native stack collection - #19073

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 28 commits into
mainfrom
taegyunkim/prof-14213-propagate-max-frames
Sep 14, 2026
Merged

gh-worker-dd-mergequeue-cf854d[bot] merged 28 commits into
mainfrom
taegyunkim/prof-14213-propagate-max-frames

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Description

DD_PROFILING_MAX_FRAMES limits the number of frames reported in profiles, but the native Echion sampler previously walked plain Python thread stacks up to its 2,048-frame safety ceiling. With the default 64-frame limit, this could collect and materialize many frames that the exporter immediately discarded.

This PR propagates StackCollector.nframes into the native sampler and stops plain thread stack collection at that limit. It:

  • adds the internal native set_max_frames() entry point, preserving per-collector overrides and the existing zero/default behavior
  • rejects frame-limit updates while the native sampler is starting, running, or finishing
  • returns UnwindResult with explicit Unknown, NotTruncated, or Truncated status, and uses UnwindResult::Unknown() for unknown initialization
  • performs bounded lookahead after reaching the limit and calls mark_truncated() only after finding another reportable Python frame, avoiding false markers for terminal C/interpreter frames
  • documents that disabled detection always returns Unknown, while enabled detection can also remain unknown after a read failure, cycle, or exhausted probe budget
  • propagates an initial C-frame copy failure through Result<UnwindResult> and ThreadInfo::unwind() to abort the sample before task/greenlet discovery or rendering
  • leaves the existing 1,024-entry Echion frame cache unchanged

Asyncio-loop threads retain the existing 2,048-frame discovery depth because task stitching needs deeper physical frames to find the event-loop boundary and determine overlap. Greenlet logical stacks also retain their existing 2,048-frame discovery depth so this PR does not change parent-segment stitching. The configured reporting limit still applies to rendered profiles. Follow-up #19085 changes asyncio materialization separately.

Merged the latest origin/main at 33e9b69e96.

Testing

  • Rebuilt native extensions and native test binaries for CPython 3.14.5 and CPython 3.12.13 in a source-identical temporary checkout. Used the repository's editable-wheel build procedure and scripts/run-tests in its local CI execution mode because the Docker host filesystem was full.
  • Python 3.14 stack/GC tests: 75 passed, 6 skipped.
  • Python 3.12 stack/GC tests: 75 passed, 6 skipped.
  • Native sampling-cycle and unwind tests: 6 passed on each Python version, including disabled detection, bounded lookahead through ignored frames, and the Python 3.12 initial C-frame copy-error path.
  • Removed the native-frame disable override from the truncation tests. They now leave exporter headroom for injected native frames and separately assert the Python frame chain and conservative omission marker.
  • Full scripts/lint checks, C/C++ formatting, Reno lint, and git diff --check origin/main passed. Existing repository-wide lint warnings remain.
  • Five targeted Python 3.12 frame-limit tests passed.
  • Added a direct Python 3.12 native test that asserts frames_added == 2 and TruncationStatus::Truncated; all 23 standalone native CTests passed.
  • Strengthened the fork regression so the child samples a deep stack after restart and verifies its one-frame limit and omission marker.
  • Set the existing gevent stack test to nframes=1 while retaining exporter headroom; it still requires at least three recursive _fib frames, proving greenlet discovery retains its existing depth.
  • Targeted Python 3.12 results after these changes: standard profiling 5 passed, 1 skipped; gevent profiling 6 passed.
  • Validated this change as part of integration wheel 408cb68fc3a99557dff4cf595fed9f8321dc0ea2 in the isolated Python 3.13 Rapid Test Drive prof-14213-max-frames-v4. The service reached ready, its core CPU, memory, and wait workload checks returned HTTP 200, and the profiling backend received Python, native, and eBPF profiles.

CPU performance

Measured with dd-trace-doe at commit b68974823dacb76ef7728f64bbdc0acab79e1fc9. The experiment compared this PR with benchmark baseline 8e80a8b4e27d8009521ddac3a51c06329b175000, which was the exact main merge base when the experiment ran. It used Python 3.13, Flask gthread, four workers, 40 closed-loop clients, one-second sleeps inside generated stacks, tracing disabled, profiling enabled, and 60-second runs. Each version and stack depth was repeated three times.

The table reports the mean of DoE's top-level CPU metric, cpu / load_wall * 100, where cpu includes measured-load and shutdown/flush CPU:

Stack depth Baseline CPU PR CPU Difference Relative change
64 12.1% 11.4% -0.7 pp -6.0%
256 16.6% 11.5% -5.1 pp -30.7%
768 33.1% 13.1% -20.0 pp -60.4%

All 18 runs completed with zero request errors and produced 180 profile payloads. DoE classifies three repetitions as low confidence, so these results demonstrate the expected depth-dependent direction and magnitude rather than a general production-overhead claim. Per-run CPU ranges were 11.9-12.3% versus 11.0-11.6% at depth 64, 16.3-16.9% versus 10.9-12.1% at depth 256, and 32.1-34.0% versus 12.6-13.7% at depth 768.

CI follow-up

  • Renamed the inconclusive truncation state from Unchecked to Unknown, which covers both skipped detection and detection that could not reach a conclusion.
  • Explicitly discarded the new Result<void> return value in the remaining thread-unwind fuzz harness, fixing clang-tidy's nodiscard diagnostic.
  • Kept the release-note wording change in a separate commit from the main merge. Reno rejects the combined add/modify history produced when that note is edited inside the merge itself.
  • Re-ran the full profiling clang-tidy wrapper with LLVM 18, full scripts/lint checks, and the six native sampling-cycle/unwind tests.
  • scripts/docs/build.sh passed Reno lint and the warnings-as-errors HTML build using READTHEDOCS=1. The local Sphinx spelling stage was skipped because the machine lacks its dictionary setup; repository-wide codespell checks passed.

Risks

Plain thread stacks stop unwinding at the configured limit. The omitted-frame count is deliberately conservative: an early-truncation marker records at least one deeper reportable Python frame, rather than walking and counting the entire omitted portion.

Asyncio discovery retains its existing safety ceiling. An unreadable initial C frame now aborts the sample rather than continuing without a physical stack. No public API changes.

Additional Notes

  • JIRA: PROF-14213
  • Asyncio follow-up: perf(profiling): bound asyncio task stack collection #19085
  • Release note: releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml: "Stack collection now honors configured frame limits, reducing profiler CPU and memory overhead for deep Python call stacks."

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

No remaining files require a CODEOWNERS review.

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

There are 1 circular imports that already exist on the base branch and have not been changed by this PR.

ddtrace.errortracking._handled_exceptions.bytecode_injector -> ddtrace.errortracking._handled_exceptions.callbacks -> ddtrace.errortracking._handled_exceptions.collector -> ddtrace.errortracking._handled_exceptions.bytecode_reporting -> ddtrace.errortracking._handled_exceptions.bytecode_injector

@taegyunkim taegyunkim added the Profiling Continous Profling label Jul 15, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from b4d7e00 to 890dd4e Compare July 15, 2026 16:06
@datadog-prod-us1-4

datadog-prod-us1-4 Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 75d3783 | Docs | View more details | Give us feedback!

@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from 890dd4e to 891f2f9 Compare July 15, 2026 16:27
@taegyunkim
taegyunkim changed the base branch from main to taegyunkim/prof-14213-backend-max-frames July 15, 2026 16:27
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from 891f2f9 to 32b532a Compare July 15, 2026 17:45
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from 32b532a to ecdbdab Compare July 15, 2026 20:02
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jul 16, 2026
## Description

Aligns profiling frame-limit configuration with the backend's [600-location limit](https://datadoghq.atlassian.net/wiki/spaces/PROF/pages/5307007274/Profiling+Libraries+Frame+Truncation+Behaviors).

- raises the native exporter cap from 512 to 599 captured frames
- reserves the 600th backend location for the synthetic `<N frames omitted>` indicator on truncated stacks
- clamps `DD_PROFILING_MAX_FRAMES` to 599 in `ddtrace.internal.settings.profiling`
- preserves configured values from 513 through 599 instead of reducing them to 512 in the native exporter
- ensures collectors receive the same effective configured limit

JIRA: [PROF-14213](https://datadoghq.atlassian.net/browse/PROF-14213?atlOrigin=eyJpIjoiNWFmMTNkMDg2MmJjNDVlZTlkN2JlNGZkMjg3ZWZiYzEiLCJwIjoiaiJ9)

## Testing

- Added configuration tests covering the default, values below the maximum captured-frame limit, the exact 599-frame limit, and values at or above the 600-location backend limit.
- Ran `TestMaxFramesConfig` on Python 3.9, all 6 tests passed. The editable install also rebuilt the native extension successfully.
- Completed a clean Python 3.14 native build for the initial change.
- Ran `scripts/lint checks`, targeted formatting, spelling, and `git diff --check`. Broad lint checks reported only existing repository warnings.

## Risks

Configurations between 513 and 599 can now retain more frames than before. This matches the backend contract but can slightly increase per-sample work for users who explicitly configure values in that range.

Values of 600 and above are now clamped to 599 at configuration load instead of reaching individual collectors unchanged. This leaves one location for the omitted-frame indicator so truncated samples remain within the backend's 600-location cap.

## Additional Notes

This PR is the base of stacked #19073 and #19085, which propagate the limit into Echion and bound task-aware stack collection.

[PROF-14213]: https://datadoghq.atlassian.net/browse/PROF-14213?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiaiJ9


Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
Base automatically changed from taegyunkim/prof-14213-backend-max-frames to main July 16, 2026 20:54
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from 67ae55e to c0a7c8f Compare July 16, 2026 21:17
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from c0a7c8f to dd6bece Compare July 16, 2026 21:45
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 228 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 228 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=133)
ddtrace.profiling.collector.pytorch -×-> ddtrace.trace  (product:profiling -> product:tracing, score=131)
ddtrace.llmobs._integrations.google_adk -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=131)
ddtrace.llmobs._telemetry -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=131)
ddtrace.internal.ci_visibility.git_client -×-> ddtrace.trace  (product:ci_visibility -> product:tracing, score=131)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

Comment thread tests/profiling/collector/test_stack.py Resolved
@taegyunkim taegyunkim changed the title perf(profiling): honor configured maximum frame count perf(profiling): bound native stack collection by configured frame limit Sep 9, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from 56fd6a4 to b8284b1 Compare September 9, 2026 19:09
@taegyunkim taegyunkim changed the title perf(profiling): bound native stack collection by configured frame limit perf(profiling): respect frame limits during native stack collection Sep 9, 2026
@taegyunkim taegyunkim changed the title perf(profiling): respect frame limits during native stack collection fix(profiling): respect frame limits during native stack collection Sep 10, 2026
@vlad-scherbich

vlad-scherbich commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

I checked your tests — they're pretty comprehensive, but for a change this size I don't think they covered all edge cases. Two of the five new Python tests would still pass if the unwind change were reverted. Specifically:

The set is not complete. Two of five new Python tests would still pass if the unwind change were reverted.

  • No native assert of Truncated or frames_added == max. Break the status assignment and only the sampling integration test can catch it.
  • test_exact_native_frame_limit_is_not_truncated only rules out “always mark truncated at exact fill.” It does not prove we stopped early.
  • test_native_frame_limit is setter/getter only. It does not walk a stack.
  • Fork restart never samples, so the child could ignore 32 and still pass.
  • Greenlets still walk 2048. Unmentioned and untested.

@taegyunkim

Copy link
Copy Markdown
Contributor Author

@vlad-scherbich Thanks for flagging these. I addressed the substantive coverage gaps in 5ebada27ed:

  • Added a direct native test that asserts the unwind stops at the configured limit with frames_added == 2 and TruncationStatus::Truncated.
  • Strengthened the fork test so the child samples a deep stack after restart, then verifies the one-frame limit and omission marker in its profile.
  • Greenlet logical stacks intentionally retain their existing 2,048-frame discovery depth in this PR. I documented that scope and set the existing gevent test to nframes=1 with exporter headroom; it still requires at least three recursive _fib frames, proving discovery exceeded the plain-stack limit.

The exact-limit test and setter/getter test remain intentionally focused on separate contracts: avoiding a false marker at exact fill, and preserving zero/default plus large-value configuration. test_collect_truncate remains the early-unwind integration regression because its exporter budget is 64 while the sampler limit is five.

Validation: all 23 Python 3.12 standalone native CTests passed, standard targeted profiling had 5 passed and 1 skipped, gevent targeted profiling had 6 passed, and full lint passed.

@KowalskiThomas KowalskiThomas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall LGTM; just one minor concern on release notes.

@taegyunkim

Copy link
Copy Markdown
Contributor Author

Thank you both for reviews

@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot merged commit 9379ddd into main Sep 14, 2026
492 checks passed
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot deleted the taegyunkim/prof-14213-propagate-max-frames branch September 14, 2026 19:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Profiling Continous Profling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants