-
Notifications
You must be signed in to change notification settings - Fork 283
fix(task_manager): reinitialize consumer threads after os.fork() #1654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pyg410
wants to merge
3
commits into
langfuse:v2-stable
Choose a base branch
from
pyg410:taskmanager-fork-safety
base: v2-stable
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡
os.register_at_forkhas no public unregister API in CPython, so eachTaskManager.__init__permanently appends a freshlambda(closing over a newWeakMethod) to the process-global at-fork list — and the entries are never reclaimed even after theTaskManageris GC'd. TheWeakMethodcorrectly prevents the manager itself from being pinned, but the lambda+WeakMethod wrapper pair is not collectible, so in long-lived processes that build/tear down many Langfuse clients (e.g. pytest-xdist with per-test setup, notebook kernels that re-instantiate, multi-tenant handlers that recycle per tenant) the list grows without bound and each subsequentfork()walks O(N) dead no-op callbacks. Nit / follow-up only — the primary--preloadbug is correctly fixed; a cleaner pattern is a module-levelWeakSetofTaskManagerinstances with a single process-global at-fork callback that iterates live members.Extended reasoning...
What this is
os.register_at_forkin CPython has no public unregister API — once anafter_in_childcallback is added to_PyOS_BeforeFork's arrays inModules/posixmodule.c, it lives there for the lifetime of the interpreter. This PR callsos.register_at_fork(...)unconditionally on every__init__, registering a fresh lambda that closes over a newWeakMethod:The
WeakMethodwas added (correctly) in response to the Greptile P1 review comment to prevent theTaskManageritself — along with its threads, queues,MediaManager, andFernLangfuseclient — from being pinned in memory. That part is fine. However, the lambda object and theWeakMethodit captures in its closure are themselves strong-referenced from the at-fork registry, and they are not collectible.Step-by-step proof
Langfuse()→TaskManager.__init__runs → entry Add license #1 (lambda+WeakMethod) appended to the global list.TaskManageris GC'd. TheWeakMethodresolves toNone. ✅ Heavy resources are freed.Langfuse()again → entry Improvements langchain integration #2 appended. Entry Add license #1 is still there, now dead.Noneand do nothing; one is live.fork()after this iterates all N entries. Memory cost: N × (lambda + WeakMethod + closure cell) ≈ a few hundred bytes per dead entry, never reclaimed.Why the existing fix doesn't prevent it
The
WeakMethodcorrectly addresses Greptile's P1 (the bound method had pinnedself). But the wrapper — the lambda plus its capturedWeakMethod— is whatregister_at_forkactually holds, and that wrapper has no weakref-aware path. CPython exposes no API to remove a registered callback. So the residual leak is structural: the WeakMethod choice only weakens what the wrapper points at, not the wrapper itself.Practical impact (and why this is a nit, not a blocker)
I want to explicitly address the refutation: the practical impact is small in the typical deployment.
--preload) creates one client in the master and forks workers once. The accumulation here is zero.pytestdoes not fork between tests; Jupyter kernels do not fork; multi-tenant request handlers typically do not fork per tenant. So the combination of "create manyTaskManagers + fork repeatedly" is uncommon.Where this does matter is the pathological-but-real cases (e.g.
pytest-xdistrunners that re-instantiate clients in workers that themselves fork, long-running task workers using Celery's prefork pool with per-job client setup as the user@georgieementioned). In those, the leak is bounded only by process lifetime andfork()cost grows linearly in N.Suggested follow-up (not blocking)
Move from per-instance registration to a module-level singleton:
That bounds the at-fork list at exactly one entry, regardless of how many clients are created — and the
WeakSetkeeps the rest of the GC story correct. This is a non-trivial refactor (touches state that has to be coordinated across all instances) and is reasonable to defer; the current PR's primary fix is solid.