Skip to content

instrumentation-threading breaks when Thread.run() is called without Thread.start() #4245

@dinmukhamedm

Description

@dinmukhamedm

Describe your environment

OS: MacOS 15
Python version: 3.13.9
Package version: 0.60b1 / main

What happened?

With ThreadingInstrumentor() enabled, if a thread is created and immediately run, the program will throw an exception.

Steps to Reproduce

from threading import Thread
from opentelemetry.instrumentation.threading import ThreadingInstrumentor

def main():
    ThreadingInstrumentor().instrument()
    t = Thread(target=lambda: print("Hello world!"))
    t.run()

if __name__ == "__main__":
    main()

Expected Result

Program prints out "Hello world!" and exits

Actual Result

Traceback (most recent call last):
  File "/Users/din/threading-repro/main.py", line 10, in <module>
    main()
    ~~~~^^
  File "/Users/din/threading-repro/main.py", line 7, in main
    t.run()
    ~~~~~^^
  File "/Users/din/threading-repro/.venv/lib/python3.13/site-packages/opentelemetry/instrumentation/threading/__init__.py", line 150, in __wrap_threading_run
    token = context.attach(instance._otel_context)
                           ^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Thread' object has no attribute '_otel_context'

Additional context

I know this isn't a completely valid way of using python threading.Threads, and that run() is a base method meant to behave somewhat like protected methods, i.e. can be overriden, but shouldn't be called directly. For example, attempting to join a thread like this will result in RuntimeError: cannot join thread before it is started.

However:

  • The repro is still a completely valid Python program and doesn't fail
  • The current instrumentation somehow breaks with frameworks like celery, maybe they run threads directly without starting them, and their framework works.

Would you like to implement a fix?

Yes

Tip

React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions