You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
which seem specifically targetted at resolving the described issues.
What is the current expected state of support for the various forking models?
Either way, updating the docs to clarify the actual situation would be appreciated.
Thanks for opening this issue, I think it is an important topic.
Afaik, things should be working for tracing at this point. Metrics are a little more complicated and #2837 is definitely still valid. It would be great if we could clean up old issues/documentation and would definitely appreciate help on this if you have the time @PeterJCLaw.
@srikanthccv last worked on this, do you know if any of the linked bugs can be closed out now?
I think 4th linked issue can be closed; however, it's better to verify once before closing.
What does verification look like here? Given the nature of this as a forking issue I'd kinda assumed the failure mode was race conditions and the like -- timing based and hard to reproduce/be sure if fixed just from testing. Is there a known reproduction of the failure mode or something we can do to check that it's working as intended?
(Or is it a cased of code inspection?)
The verification can be pretty simple. If you run a simple gunicorn based application with multiple workers (Without following the special instructions mentioned in the docs), it should export the traces/metrics/logs. If they are not exported (to the collector, console etc.), then the issue still exists.
Hrm, ok. I'm currently running gunicorn with the default worker type and that does seem to work. My reading of gunicorns docs indicate that the master process doesn't actually load the application though -- only the workers do (after the fork happens), unless you use the --preload option (which I'm currently not doing).
I'll see if I can find some time to validate the behaviours under gunicorn & uwssgi.
Edit for clarity: my use of gunicorn without --preload works fine -- I get tracing reported even though I'm using BatchSpanProcessor.
My current setup is using gunicorn without calling --preload and that seems to work.
Not using --preload under gunicorn seems to be the default, though the open telemetry docs seem to imply that they're expecting the inverse -- that gunicorn will preload before forking.
I'm not sure how to validate that the desired batching is happening, though I can see that the traces are often not printed until several requests later which suggests that it is working.
Thank you, this confirms the above statement that traces and logs batch processors work all the time.
I'm not sure how to validate that the desired batching is happening, though I can see that the traces are often not printed until several requests later which suggests that it is working
They are emitted if the queue becomes full or batch timeout elapses. I think this is working fine.
Unfortunately while it looks like the BatchSpanProcessor does actually work fine, the PeriodicExportingMetricReader appears not to. I've not tested it under all the various configurations previously discussed, however I have observed it not working correctly in uWSGI's default mode (i.e: where it imports the WSGI app before forking). In that case the ticker thread only exists in the main process, presumably meaning that metrics are only collected from that main process. I'd guess this is due to PeriodicExportingMetricReader using the approach from #2242 rather then the enhanced approach introduced in #2277.
Edit: using uWSGI's --lazy-apps to delay the import does get PeriodicExportingMetricReader running in all the worker processes.
Hrm, the uWSGI side of this may be somewhat resolvable by users. Ish. Via https://stackoverflow.com/a/72601192 and unbit/uwsgi#2388 it seems that uWSGI has some extra options which can be used to enable os.register_at_fork to work -- specifically --py-call-osafterfork. There's also --enable-threads which seems to be needed to enable workers to have threads. Unfortunately in local testing I'm seeing that using those two options together results in uWSGI not serving any requests (at all); while using just --py-call-osafterfork seems to lock up one of the two workers I'm running with. Not sure yet if this is a uWSGI issue generally (definitely feels like it could be) or something to do with threads. I doubt it's open-telemetry specific. Posting here as hopefully useful to others hitting this.
+1 to updating docs here since BatchSpanProcessor is working well with Gunicorn. It cost me more than a few hours trying to get the post_fork hook to work (which didn't end up working) when it wasn't necessary.
It seems that BatchSpanProcessor works fine, but not OTLPSpanExporter (with --preload). Given test.py containing:
fromflaskimportFlaskfromopentelemetry.exporter.otlp.proto.http.trace_exporterimportOTLPSpanExporterfromopentelemetry.instrumentation.flaskimportFlaskInstrumentorfromopentelemetry.sdk.traceimportTracerProviderfromopentelemetry.sdk.trace.exportimportBatchSpanProcessor, SimpleSpanProcessor, ConsoleSpanExporter# BatchSpanProcessor works fine# exporter = ConsoleSpanExporter()# span_processor = BatchSpanProcessor(exporter)# But OTLPSpanExporter does notexporter=OTLPSpanExporter()
span_processor=SimpleSpanProcessor(exporter)
tracer_provider=TracerProvider()
tracer_provider.add_span_processor(span_processor)
app=Flask(__name__)
FlaskInstrumentor().instrument_app(app, tracer_provider=tracer_provider)
@app.route('/')defhello():
return'Hello!'
and running gunicorn --workers=2 --preload test:app, visiting http://127.0.0.1:8000 causes an error:
objc[37636]: +[NSCharacterSet initialize] may have been in progress in another thread when fork() was called.
objc[37636]: +[NSCharacterSet initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug.
[2024-10-14 13:50:45 +0200] [37634] [ERROR] Worker (pid:37636) was sent SIGKILL! Perhaps out of memory?
/Users/alex/.pyenv/versions/3.12.6/lib/python3.12/multiprocessing/popen_fork.py:66: DeprecationWarning: This process (pid=5221) is multi-threaded, use of fork() may lead to deadlocks in the child.
self.pid = os.fork()
I don't understand the technical details of the problem with fork(). But the fact that the Python warning says "use of fork() may lead to deadlocks in the child" makes me think that not sharing locks is important. I understand that BatchSpanProcessor also triggers the warning, but at least I see signs of the problem being addressed there.
Wanted to chime in and share the context, as I spent relatively more time in this area than other maintainers
PeriodicExportingMetricReader only starts a new thread, it doesn't create a fresh lock:
Either we overlooked it, or there were no sync variables other than the worker thread at the time fork hook patch, and later, some locks were introduced but never cleaned up in the fork hook. We should fix this.
I don't understand the technical details of the problem with fork(). But the fact that the Python warning says "use of fork() may lead to deadlocks in the child" makes me think that not sharing locks is important. I understand that BatchSpanProcessor also triggers the warning, but at least I see signs of the problem being addressed there.
Correct, we do the same for BatchLogProcessor as well
The following resource explains the issue in detail
A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources.
When fork() is called, only the calling thread is duplicated in the child process. Synchronization variables remain in the same state in the child as they were in the parent at the time fork() was called. Thus, for example, mutex locks may be held by threads that no longer exist in the child process, and any associated states may be inconsistent. The intention was that the parent process could have avoided this by explicit code that acquires and releases locks critical to the child via pthread_atfork(). In addition, any critical threads would have needed to be recreated and reinitialized to the proper state in the child (also via pthread_atfork()).
Although the changes from #2242 helped, they didn't fix the issue for users running uWSGI. Therefore, we introduced an additional workaround in #2277, using the PID to reset state. This approach solves the problem of logs and traces because they get pushed to the processor queue, allowing us to detect the child process via PID and then clean up. However, metrics are pulled (and exported without a queue), so PeriodicExportingMetricReader can’t clear its inconsistent state except via _at_fork_reinit
I'm a little confused as to the conclusion of this thread, is the following a fair summary?
PeriodicExportingMetricReader is not compatible with a fork / cooperative multiprocessing environment, like the one used by gunicorn w/ gevent.
I'm having a devil of a time getting PeriodicExportingMetricReader to work with gunicorn and gevent. Is there a working example to point to with this working? I think traces and logging works out of the box as indicated above in this thread.
While the batch exporters re-init themselves they don't re-init the underlying self._exporter (which in the case of e.g. the standard http OTLPLogExporter contains a long-lived requests.session(), which is unsafe to use post fork if it was used/in use pre-fork).
Keeping a requests.session object across a fork seems to be unsafe thanks to the underlying use of urllib3's connection pool (specifically in the case where you've used it at least once pre-fork).
Most likely OTLPLogExporter/OTLPSpanExporter/etc.. also need an _at_fork_reinit() style change to fix themselves post fork.
I just encountered similar issues when working with Celery.
We have added the instrumentation also to the Main Celery Process (because it consumes some custom events), so when process forks the workers end up with broken instrumentation:
[2026-02-12 10:45:47,755: ERROR/ForkPoolWorker-2] Failed to export metrics to otel-collector:4317, error code: StatusCode.DEADLINE_EXCEEDED
I know it's probably not a priority but it would be great to have some way to instrument both the parent and the forks.
In our production setting forked workers are being restarted (forked again) every X tasks so delaying the instrumentation in parent is not an option (I still have to confirm this since I am not sure how this celery forks happen).
Activity
aabmass commentedon May 11, 2023
Thanks for opening this issue, I think it is an important topic.
Afaik, things should be working for tracing at this point. Metrics are a little more complicated and #2837 is definitely still valid. It would be great if we could clean up old issues/documentation and would definitely appreciate help on this if you have the time @PeterJCLaw.
@srikanthccv last worked on this, do you know if any of the linked bugs can be closed out now?
srikanthccv commentedon May 11, 2023
PeterJCLaw commentedon May 11, 2023
Thanks for those additional details.
What does verification look like here? Given the nature of this as a forking issue I'd kinda assumed the failure mode was race conditions and the like -- timing based and hard to reproduce/be sure if fixed just from testing. Is there a known reproduction of the failure mode or something we can do to check that it's working as intended?
(Or is it a cased of code inspection?)
srikanthccv commentedon May 11, 2023
The verification can be pretty simple. If you run a simple gunicorn based application with multiple workers (Without following the special instructions mentioned in the docs), it should export the traces/metrics/logs. If they are not exported (to the collector, console etc.), then the issue still exists.
PeterJCLaw commentedon May 11, 2023
Hrm, ok. I'm currently running gunicorn with the default worker type and that does seem to work. My reading of gunicorns docs indicate that the master process doesn't actually load the application though -- only the workers do (after the fork happens), unless you use the
--preloadoption (which I'm currently not doing).I'll see if I can find some time to validate the behaviours under gunicorn & uwssgi.
Edit for clarity: my use of gunicorn without
--preloadworks fine -- I get tracing reported even though I'm usingBatchSpanProcessor.srikanthccv commentedon May 12, 2023
I am confused now. Is it working or not working with gunicorn?
PeterJCLaw commentedon May 13, 2023
My current setup is using gunicorn without calling
--preloadand that seems to work.Not using
--preloadunder gunicorn seems to be the default, though the open telemetry docs seem to imply that they're expecting the inverse -- that gunicorn will preload before forking.PeterJCLaw commentedon May 13, 2023
I've just tested a toy application under gunicorn and uWSGI, using both their
--preloadand--lazy-appsmodes (and not) respectively using https://gist.github.com/PeterJCLaw/5e6fd585d0c620496c82ca926ce50f67. All four configurations seem to work ok -- I get traces printed out to the console which seem reasonable.I'm not sure how to validate that the desired batching is happening, though I can see that the traces are often not printed until several requests later which suggests that it is working.
srikanthccv commentedon May 14, 2023
Thank you, this confirms the above statement that traces and logs batch processors work all the time.
They are emitted if the queue becomes full or batch timeout elapses. I think this is working fine.
PeterJCLaw commentedon Jun 6, 2023
Unfortunately while it looks like the
BatchSpanProcessordoes actually work fine, thePeriodicExportingMetricReaderappears not to. I've not tested it under all the various configurations previously discussed, however I have observed it not working correctly in uWSGI's default mode (i.e: where it imports the WSGI app before forking). In that case the ticker thread only exists in the main process, presumably meaning that metrics are only collected from that main process. I'd guess this is due toPeriodicExportingMetricReaderusing the approach from #2242 rather then the enhanced approach introduced in #2277.Edit: using uWSGI's
--lazy-appsto delay the import does getPeriodicExportingMetricReaderrunning in all the worker processes.PeterJCLaw commentedon Jun 6, 2023
Hrm, the uWSGI side of this may be somewhat resolvable by users. Ish. Via https://stackoverflow.com/a/72601192 and unbit/uwsgi#2388 it seems that uWSGI has some extra options which can be used to enable
os.register_at_forkto work -- specifically--py-call-osafterfork. There's also--enable-threadswhich seems to be needed to enable workers to have threads. Unfortunately in local testing I'm seeing that using those two options together results in uWSGI not serving any requests (at all); while using just--py-call-osafterforkseems to lock up one of the two workers I'm running with. Not sure yet if this is a uWSGI issue generally (definitely feels like it could be) or something to do with threads. I doubt it's open-telemetry specific. Posting here as hopefully useful to others hitting this.SharifiFaranak commentedon Jan 29, 2024
+1 to updating docs here since
BatchSpanProcessoris working well with Gunicorn. It cost me more than a few hours trying to get thepost_forkhook to work (which didn't end up working) when it wasn't necessary.alexmojaki commentedon Oct 14, 2024
It seems that
BatchSpanProcessorworks fine, but notOTLPSpanExporter(with--preload). Giventest.pycontaining:and running
gunicorn --workers=2 --preload test:app, visitinghttp://127.0.0.1:8000causes an error:alexmojaki commentedon Jan 8, 2025
Running this code:
causes a warning:
This is documented in https://docs.python.org/3/library/os.html#os.fork.
Is it though? #2242 made BatchSpanProcessor create a fresh lock:
opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py
Lines 231 to 241 in 29aad2e
PeriodicExportingMetricReader only starts a new thread, it doesn't create a fresh lock:
opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/export/__init__.py
Lines 503 to 509 in 29aad2e
I don't understand the technical details of the problem with
fork(). But the fact that the Python warning says "use of fork() may lead to deadlocks in the child" makes me think that not sharing locks is important. I understand that BatchSpanProcessor also triggers the warning, but at least I see signs of the problem being addressed there.srikanthccv commentedon Jan 10, 2025
Wanted to chime in and share the context, as I spent relatively more time in this area than other maintainers
Either we overlooked it, or there were no sync variables other than the worker thread at the time fork hook patch, and later, some locks were introduced but never cleaned up in the fork hook. We should fix this.
Correct, we do the same for BatchLogProcessor as well
opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/export/__init__.py
Lines 221 to 230 in 82279e4
The following resource explains the issue in detail
https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html
https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_atfork.html
So, to avoid the dead threads and inconsistent state, we are recreating all the sync variables in the child process. cpython standard lib modules also make use of the
atforkhandler to clean up the inconsistent state https://github.com/search?q=repo%3Apython%2Fcpython%20register_at_fork&type=codeAlthough the changes from #2242 helped, they didn't fix the issue for users running uWSGI. Therefore, we introduced an additional workaround in #2277, using the PID to reset state. This approach solves the problem of logs and traces because they get pushed to the processor queue, allowing us to detect the child process via PID and then clean up. However, metrics are pulled (and exported without a queue), so
PeriodicExportingMetricReadercan’t clear its inconsistent state except via_at_fork_reinitalexmojaki commentedon Jan 10, 2025
Could
PeriodicExportingMetricReadercheck the PID before acquiring a lock?srikanthccv commentedon Jan 11, 2025
No, as the worker thread that initiates the collection no longer exists in the child process
rodda-kyusu commentedon Mar 19, 2025
I'm a little confused as to the conclusion of this thread, is the following a fair summary?
PeriodicExportingMetricReaderis not compatible with a fork / cooperative multiprocessing environment, like the one used by gunicorn w/ gevent.I'm having a devil of a time getting
PeriodicExportingMetricReaderto work with gunicorn and gevent. Is there a working example to point to with this working? I think traces and logging works out of the box as indicated above in this thread.ZombieFoodDan commentedon May 13, 2025
While the batch exporters re-init themselves they don't re-init the underlying self._exporter (which in the case of e.g. the standard http OTLPLogExporter contains a long-lived requests.session(), which is unsafe to use post fork if it was used/in use pre-fork).
psf/requests#4323
Keeping a requests.session object across a fork seems to be unsafe thanks to the underlying use of urllib3's connection pool (specifically in the case where you've used it at least once pre-fork).
Most likely OTLPLogExporter/OTLPSpanExporter/etc.. also need an _at_fork_reinit() style change to fix themselves post fork.
drozdowsky commentedon Feb 12, 2026
I just encountered similar issues when working with Celery.
We have added the instrumentation also to the Main Celery Process (because it consumes some custom events), so when process forks the workers end up with broken instrumentation:
I know it's probably not a priority but it would be great to have some way to instrument both the parent and the forks.
In our production setting forked workers are being restarted (forked again) every X tasks so delaying the instrumentation in parent is not an option (I still have to confirm this since I am not sure how this celery forks happen).
ocelotl commentedon Jul 1, 2026
More related issues: #4994 #4215 #4759