← Back to Pull requests

fix(internal): start ddtrace threads eagerly instead of from application threads #22127

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 26, 2026 14:59 UTC
Author

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:

  • Trace writers start when create_trace_writer() or recreate() builds them, not on their first write. This includes the CI Visibility writer, whose recreate() now also stops the writer it replaces. CI Visibility also flushes and stops the writer it replaces when it configures its own.

  • A fork child rebuilds the tracer's writer in its fork hook, instead of on its first span. It first replaces the span aggregator lock, which another thread of the parent may have held at fork. Service locks are now fork-safe for the same reason, since the rebuild stops the inherited writer. A sync-mode writer recreated in a child no longer shuts down the exporter it inherited, which would resend the parent's stats. Native state is not built while the child fork hooks run: the writer builds its exporter, or buffer, on first use after them. A failed build is logged and retried on the next use, and a writer stopped before it builds its buffer, or a sync writer stopped before it builds its exporter, never builds it.

  • The data streams processor is created when ddtrace is imported, if data streams monitoring is enabled. Resetting the processor shuts down the one it replaces, and the exit hook of a processor already shut down no longer logs a warning.

  • SymDB debounces uploads with a new periodic.Debouncer, which the uploader configures at install time and leaves dormant when it is uninstalled. Module imports only touch it, and batches are sent without holding the lock that imports take. Scopes that imports in flight add after the uploader is uninstalled are dropped.

  • The telemetry dependency collector starts when the telemetry writer is created.

  • In a uWSGI master that forks its workers without the Python fork hooks, neither the writer nor the data streams processor starts in the master: a worker forked while a thread of the master holds the GIL hangs. Each worker starts them from the fork hooks that uWSGI runs after the fork, as it does for products.
  • Because writers now run from the start, stopping a periodic service right after a fork has to work too:

  • A fork stops every periodic thread, and ThreadRestartTimer restarts 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 a multiprocessing child and exits, lost its final flush. PeriodicService now stops its worker with PeriodicThread.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.

  • A CI Visibility writer that was never started sends what it holds when stopped, as one that was started does.
  • 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 from logging.config.dictConfig, for example a CloudWatch handler creating its log group. DD_TRACE_DEBUG=false did not avoid it: on a cold cache, the restart timer's log.debug still takes logging's lock to check the level. A release note is included.

    Behaviour that changes:

  • Trace writer threads, and the data streams processor when it is enabled, now run in every process that loads ddtrace, including pre-fork masters that never create a span. uWSGI masters that fork without the Python fork hooks are the exception: their workers start them.

  • A process that stops its tracer within about 100 ms of a fork now flushes its traces. Previously they could be lost.

  • Finishing a span after tracer.shutdown() no longer restarts the writer.

  • SymDB drops scopes from imports that finish after the uploader is uninstalled, for example by remote configuration. A later install collects anew from the loaded modules.
  • 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 holding logging._lock past the restart timer's tick. It hangs on main (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_writer and test_ci_visibility_writer_starts_when_recreated_not_on_write check 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.

  • SymDB: adding a scope starts no thread, batches are sent without holding the lock that imports take, and the uploader reuses one debouncer across installs and leaves it dormant on uninstall.
  • Tests for the review fixes, each failing without its fix:

  • a child forked while another thread holds the span aggregator lock, or the writer's service lock, completes its fork hook;

  • a sync-mode writer recreated in a fork child does not shut down the inherited exporter;

  • a sync-mode writer stopped before it builds its deferred exporter never builds it;

  • stopping a sync-mode writer does not wait for a send in flight on another thread;

  • CI Visibility stops the writer it replaces;

  • a reset of the data streams processor shuts down the one it replaces;

  • the exit hook of a data streams processor already shut down logs nothing;

  • a failed deferred exporter or buffer build does not raise and is retried;

  • a buffer writer stopped before its first use never builds its buffer, and stop() called from a signal handler during the build does not deadlock;

  • SymDB collects already-loaded modules when installed and drops scopes added after uninstall.
  • Tests updated for the eager design:

  • the post-fork writer tests and the agentless writer swap test;

  • the native writer test factory;

  • the avro and protobuf fixtures, which enable data streams monitoring at runtime and now create the processor;

  • MicroVM tests that rely on writers that were never started.
  • DummyWriter.stop() in tests/utils.py now 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 with scripts/run-tests on 3.14. Locally, with scripts/run-tests on 3.9 and 3.14, the tracer suite has only the failures that main has 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-configured is about 1 ms slower per fork (+8% to +12%), because each child now rebuilds its writer in the fork hook. rand-rand64bits is faster, and 643 other metrics are unchanged.

    Risks

  • Fork child setup. The writer is now rebuilt inside the child's fork hook rather than on its first span, which accounts for the fork-time regression above. Its native exporter, or the native trace buffer, is not built while the child fork hooks run (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.

  • Stopping a service right after a fork now restarts its worker on the stopping thread to run its shutdown callback, instead of leaving it to ThreadRestartTimer.

  • uWSGI. Workers of a master that forks without the Python fork hooks start their writer from the fork hooks that the product manager has uWSGI run, so they rely on ddtrace being loaded with ddtrace.auto or ddtrace-run, which uWSGI already requires.

  • Threads in more processes, as described under Customer impact.

  • SymDB timing. Uploads now happen 1 to 1.5 s after the last import, instead of exactly 1 s.
  • 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.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: gnufede Review duration: 6733m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    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.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #22127"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% 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: 46.7% · Lower = rushed or shallow review
    46.7%
    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: 27.7% · Safe to merge
    27.7%