fix(internal): start ddtrace threads eagerly instead of from application threads #22127
All Vouch review confidence checks passed
Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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.344
Real PR Conversation Timeline
1 comments
"Review active on #22127"
general
weight: 0.35
gnufede
Description
Starting a periodic thread takes the fork lock. When an application thread started one lazily while holding a lock of its own, it could deadlock against the thread restart timer, which holds the fork lock while it logs. For example, after a fork, a span finished inside logging.config.dictConfig started the trace writer while holding logging's lock, and a cold logger cache made the timer's log call wait for that lock.
Threads are now started where they are created for use, never on first use:
Because writers now run from the start, stopping a periodic service right after a fork has to work too:
ThreadRestartTimerrestarts them shortly after. A service stopped in that window was left for that restart to run its shutdown callback, so a process that exited before the timer ran, for example one that forks amultiprocessingchild and exits, lost its final flush.PeriodicServicenow stops its worker withPeriodicThread.shut_down(), which restarts a worker whose restart is pending right away, so that it runs its shutdown callback, and callers that join it wait for it.Customer impact
Forked processes, such as gunicorn workers (both sync and
UvicornWorker), no longer risk hanging at startup when the application finishes a span while configuring logging. The usual trigger is a logging handler that makes a traced call fromlogging.config.dictConfig, for example a CloudWatch handler creating its log group.DD_TRACE_DEBUG=falsedid not avoid it: on a cold cache, the restart timer'slog.debugstill takes logging's lock to check the level. A release note is included.Behaviour that changes:
tracer.shutdown()no longer restarts the writer.Testing
New tests:
test_span_finished_under_logging_lock_after_fork_does_not_deadlock: forks while a periodic thread is running, then, in the child, clears the logger caches and finishes a span while holdinglogging._lockpast the restart timer's tick. It hangs onmain(30 s timeout) and passes with this change.test_writer_is_rebuilt_in_children_forked_repeatedly_from_threads: forks repeatedly from two threads. Each child must have a running writer of its own, installed by the fork hook.test_periodic_service_stopped_before_its_restart_after_fork_shuts_down_promptly: stops a service right after a fork, with the restart timer slowed down, and checks that its shutdown callback runs.test_write_does_not_start_writerandtest_ci_visibility_writer_starts_when_recreated_not_on_writecheck that writes no longer start writers.periodic.Debouncer: the target runs once after the last touch, the debouncer is dormant without a target, and a touch while the target runs is not lost.Tests for the review fixes, each failing without its fix:
stop()called from a signal handler during the build does not deadlock;Tests updated for the eager design:
DummyWriter.stop()intests/utils.pynow flushes an inner writer that never started, which snapshot tests rely on.CI passed on
7ba0e2ac5f, including the flask, opentelemetry, profiling, profiling-uwsgi, CI Visibility integration and AWS Lambda suites that the first commit broke. After the review fixes, the tracer, internal, datastreams, CI Visibility, AWS Lambda, flask and opentelemetry suites were rerun locally withscripts/run-testson 3.14. Locally, withscripts/run-testson 3.9 and 3.14, thetracersuite has only the failures thatmainhas in the same environment, which come from stderr checks without a local agent. Lint passes, and the layering and import-cycle detectors report nothing new against the merge base.Benchmarks:
forktime-configuredis about 1 ms slower per fork (+8% to +12%), because each child now rebuilds its writer in the fork hook.rand-rand64bitsis faster, and 643 other metrics are unchanged.Risks
forksafe.in_child_hook()). It is built on the writer's first flush, or the buffer's first use, after them. A trace finished while the child fork hooks are still running is dropped with a debug log.ThreadRestartTimer.ddtrace.autoorddtrace-run, which uWSGI already requires.Additional Notes
This follows FS-8 in
docs/contributing-architecture.rst(start threads in the product lifecycle, not on first use). It removes the exception that rule listed for writers. The change was also checked against FS-2, FS-9, FS-10 and FS-14.Descriptor sweeps by process managers, such as Celery's
close_open_fds, are handled at the sweep site (#21855). Deferring native state while the child fork hooks run keeps this change correct with the current native fork handling and with the Python fork hooks proposed in #21974.The gevent variant of this deadlock (#21770) is handled separately in #21789.