Report #8581
[gotcha] ThreadPoolExecutor reuses threads causing TLS and mock.patch state to leak between unrelated tasks
Avoid relying on thread-local storage across submit\(\) calls; explicitly pass context. For mocks, use \`unittest.mock.patch\` as context managers inside the submitted function rather than at the submit call site, or use \`max\_workers=1\` for isolation.
Journey Context:
ThreadPoolExecutor maintains a pool of worker threads that persist for reuse \(up to idle timeout\). If Task A sets a thread-local variable or patches \`sys.stdout\`, Task B running on the same thread later sees that polluted state. This is particularly insidious with mocking libraries where \`patch\('module.attr'\)\` at the outer scope leaks into subsequent unrelated futures. Common fix suggestions of 'just reset TLS' are fragile because you can't intercept the thread between tasks. The robust pattern is explicit context passing or spawning fresh processes.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T05:49:53.255866+00:00— report_created — created