Repository navigation
BUG: Hold the graph weakly in cached edge and degree views - #8892
Conversation
rossbar
left a comment
There was a problem hiding this comment.
Thanks @MridulS for (re-re-)starting the discussion. The motivating example is compelling and I think I understand the issue more directly (or at least see the downsides) more clearly than I did the first time this was brought up.
The weakref approach strikes me as the right way to go about this, but I'm not very confident that there isn't some legitimate use-case we might be breaking with it (for example - the effect on pickling never occurred to me!)
I'm do think resolving the cases where memory remains claimed unnecessarily is worthwhile - this would be very frustrating and hard to identify for the users who ran into it. I'm tentatively in favor of this but certainly would like to hear the perspectives of folks who have a better grasp of the object model than I do!
| self._weight = weight | ||
|
|
||
| @classmethod | ||
| def _from_view(cls, view, nbunch, weight): |
There was a problem hiding this comment.
this method is to avoid using the graph object as we don't need it and it prevents the ReferenceError.
self._graph is a weakref property, so if the graph has already been released by something like G.copy().degree(weight="w") the copy dies the moment degree returns.
There was a problem hiding this comment.
I'm confused by this one... wasn't this already working on 2afe173 ? Which case gives the ReferenceError?
There was a problem hiding this comment.
Actually no, 2afe173 wasn't enough as something like this was failing
nx.path_graph(4).edges([0,1])as the weakref would have eagerly deref as soon as the edges method is called.
There was a problem hiding this comment.
I see - this is a bit more nuanced than I thought! In the initial pass I had thought there was no way to hit the ReferenceError; however, the nbunch branch on the view will hit it...
This actually makes me more leery about the change as I do think this has the potential to be disruptive.
There was a problem hiding this comment.
This actually makes me more leery about the change as I do think this has the potential to be disruptive.
We will never know until we release it 🙃 I can already draft a revert-this-change PR if that's any better.
rossbar
left a comment
There was a problem hiding this comment.
The latest commit confused me a bit - I thought some of the cases that were brought up previously were handled fine with weakref directly without having to add the extra abstractions (e.g. _from_view).
| try: | ||
| single = nbunch in adj | ||
| except TypeError: | ||
| single = False | ||
| if single: # if nbunch is a single node | ||
| return iter([nbunch]) |
There was a problem hiding this comment.
Why the extra defense here? Can't we stick with the orginal elif? The fn is private so I don't think we need extra input validation.
There was a problem hiding this comment.
The original elif was elif nbunch in self and by moving this to reportviews we can't really reference the graph object by itself (its just a normal method now) and adj is just a dict, so if something like nbunch=[0, 1] pops up we need to defend against the TypeError.
| finally: | ||
| gc.enable() | ||
|
|
||
| def test_views_of_temporary_graphs(self): |
There was a problem hiding this comment.
+1 for this test, as I think this is the primary concern. Would this test have passed on 2afe173 ? My understanding is that it would/will (and local testing seems to indicate that's the case).
There was a problem hiding this comment.
It wouldn't have that's why we need the _from_view bit.
| self._weight = weight | ||
|
|
||
| @classmethod | ||
| def _from_view(cls, view, nbunch, weight): |
There was a problem hiding this comment.
I'm confused by this one... wasn't this already working on 2afe173 ? Which case gives the ReferenceError?
|
Gemini suggests using nodes/edges/degree views can store the data as a list. DataViews probably need to store a dict. Yet another option. [Edit: degree is actually easier than the others -- just store a dict with integer values and no refs] |
Maayybe, but I would push this to follow up issue/PR to maybe discuss this a bit more? |
dschult
left a comment
There was a problem hiding this comment.
I dived into edge/degree views, properties and circular references some this week. Here's an attempt at a summary.
While this PR is motivated by circular references and garbage collection, it has some other nice features:
- This PR creates some really helpful tests for this kind of investigation. The tests for circular references really helps track what is going on (and why that might be a problem). The test that cached views survive deepcopy/pickle is really helpful when messing with these views. And the test that deepcopy/pickle doesn't mess up the
__call__feature of views is a different take on the same issue. Any time we touch this code those are headaches we wrestle with and now they have tests which take on the issues. - This PR also centralizes the view creation process inside a view's
__call__method to a private method_from_view. This means as we fiddle with the details we aren't having to change the same code in many places. I'm not sure the name is right (maybe_view_from_view?) because it doesn't indicate what is coming from the view, but it made my experiments much easier to manage. - moving
nbunch_iterfrom a graph class method to a private utility function (that is used for the graph classes method -- but is stored elsewhere to help avoid circular imports and just mentally separate that logic/concept from the rest of the class.
The idea we've been most focused on is changing the view's attribute _graph to a weakref based property. This avoids a circular reference back to the graph object so garbage collection is not delayed until the cyclic garbage collector is run. Currently essentially all graphs are kept in memory when the regular garbage collector is run. This is a compelling reason for this solution.
It took me way too long to wrap my head around another aspect of this: This PR doesn't allow the entire graph object to be deleted. It keeps the dict structure needed for this view. The other dict structures can then be "collected". So, if you have large data stored as node attributes, the EdgeView keeps the _adj dict around, but allows the _node attributes to be collected.
The danger/worry as I understand it is that a graph object might be collected before the view is used leading to unclear exceptions about a graph no longer existing when it seems like it should exist. Here are two patterns I know of where this is a potential surprise:
nx.path_graph(N).edges(): This is included in this PR's tests. Trouble is avoided by referencing the_adj/_succ/_preddict. The graph itself can be collected, but the adj dict stays around. Note that if we had the years-ago discussed generator feature of optionally returning the nodes/edges this might be avoided.for u,v in G.edges: <some code that reassigns G = new_version_of_G>: This case should also work with this PR. The graphGcan be collected, but the dict is not collected until the view is released.
The second idiom here is not directly tested, but I think the tests of the first idiom are sufficient to avoid trouble with both surprises.
I think the approach in this PR is solid and can be merged. I think the exception message should have some info about how to avoid the exception (suggestion below). But I approve the PR in any case. After merging this we should still have on our "list" to re-explore the view system and the generator nodes/edges system.
In the exception message, I suggested that folks to create an issue if they run into this exception and have concerns/questions. Is that warranted there?
| G = self._graph_ref() | ||
| if G is None: | ||
| raise ReferenceError( | ||
| "the graph this view was created from no longer exists" |
There was a problem hiding this comment.
Let's give the receiver of this more info. Something like:
| "the graph this view was created from no longer exists" | |
| "The graph this view was created from no longer exists." | |
| "To avoid this you can wrap the view in a list or dict," | |
| "or keep a reference to the graph until the view is finished" | |
| " being used. Please create an issue on our Github site with" | |
| "questions/comments. We want to avoid this exception." |
|
Other info from my explorations: properties vs cached_properties vs no properties: G = nx.path_graph(1000)
for node in G:
edges = list(G.edges(node))views vs copies: |
We ran into #7697 in one of our services too!
This was raised in #6235 too and unsetting the cached_property was the solution in the dowstream package, but I want to bring this up again and just wanted to understand if we can just use something like
weakrefto avoid depending on the cyclic garbage collector in CPython to clean up networkx graphs. A quick example to show the cyclic issuewill lead to
Falseon main branch andTrueafter this change.A claude generated minimal reproduction which kind of matches our issues in task graphs that holds arrays in graph nodes.
main, 3.13 (= 3.14.5+)[0, 5, 5, 5, 5, 5, 5, 10]main, 3.12[0, 3, 2, 4, 7, 9, 0, 3][0, 0, 0, 0, 0, 0, 0, 0]#3011 and #5614 should also have some more context.