Fix weakref bug preventing garbage collection of template-based models#14
Open
Fix weakref bug preventing garbage collection of template-based models#14
weakref bug preventing garbage collection of template-based models#14Conversation
7061ce4 to
d97b267
Compare
fiberleif
approved these changes
Apr 13, 2026
fiberleif
left a comment
There was a problem hiding this comment.
LGTM
nit: It looks like _connection_try_close is no longer used after the new static method _finalize_server. Do we want to remove it as well?
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Our template-based models rely on
RuleApplicationServer, which spins up parallel processes for template application. When the server is garbage-collected (for example, because one callsdelon the enclosing model), those processes should be terminated, and we tried to ensure this by usingweakref.finalizeto registerself.closeto be called. However, this has a fundamental bug:self.closecontains a reference toself, thus a reference toselfwill exist even after doingdelon the model, so the server can never be garbage collected; the processes are only killed when Python itself shuts down.This PR fixes the bug by moving the cleanup logic to a
staticmethodinstead. It also adds a test to verify the processes are cleaned up; before the bugfix commit the test does fail.For a minimal illustration of the bug, compare
with the fixed version relying on a static method
We did not find this issue before, as in most cases we load a single model, use it throughout some workflow, and then the script ends. The issue manifests itself when one uses a few models within one script, and calls
delin between in an attempt to free memory. With the changes here, this now works as expected (i.e. memory used by the model is recovered ondel).