Skip to content

BUG: Hold the graph weakly in cached edge and degree views - #8892

Merged
rossbar merged 2 commits into
networkx:mainfrom
MridulS:weakref-view-backrefs
Sep 17, 2026
Merged

rossbar merged 2 commits into
networkx:mainfrom
MridulS:weakref-view-backrefs

Conversation

@MridulS

@MridulS MridulS commented Sep 2, 2026

Copy link
Copy Markdown
Member

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 weakref to avoid depending on the cyclic garbage collector in CPython to clean up networkx graphs. A quick example to show the cyclic issue

>>> import gc, weakref, networkx as nx
>>> gc.disable()
>>> G = nx.DiGraph([(0, 1)])
>>> r = weakref.ref(G)
>>> G.number_of_edges()
>>> del G
>>> print(r() is None)

will lead to False on main branch and True after this change.

A claude generated minimal reproduction which kind of matches our issues in task graphs that holds arrays in graph nodes.

import gc, resource, sys, numpy as np, networkx as nx
mb = (1 << 20) if sys.platform == "darwin" else 1024
state, resident = [], []
for i in range(40):
    G = nx.path_graph(5)                                # a small task graph...
    G.graph["payload"] = np.full(30_000_000 // 8, 1.0)  # ...carrying 30 MB (untracked: invisible to the GC counters)
    G.number_of_edges()                                 # any view read: G is now in a cycle with its cached view
    state.extend([i] for i in range(4000))              # surviving allocations (a growing accumulator); the young sweeps they trigger promote G
    for _ in range(100_000): tmp = [0]                  # the rest of the work allocates and discards -> nets to zero on the GC counters
    resident.append(sum(isinstance(o, nx.Graph) for o in gc.get_objects()) - 1)
print("dead graphs resident, every 5th iteration:", resident[::5], "| final:", resident[-1])
print("automatic gen-2 sweeps:", gc.get_stats()[2]["collections"], "| peak RSS: %d MB" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / mb))
dead graphs resident, every 5th iteration final gen-2 sweeps peak RSS
main, 3.13 (= 3.14.5+) [0, 5, 5, 5, 5, 5, 5, 10] 9 0 415 MB
main, 3.12 [0, 3, 2, 4, 7, 9, 0, 3] 5 2 448 MB
this PR [0, 0, 0, 0, 0, 0, 0, 0] 0 0 95 MB

#3011 and #5614 should also have some more context.

Comment thread networkx/classes/reportviews.py Resolved
Comment thread networkx/classes/reportviews.py Resolved

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

Comment thread networkx/classes/reportviews.py Resolved
Comment thread networkx/classes/reportviews.py Resolved
self._weight = weight

@classmethod
def _from_view(cls, view, nbunch, weight):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused by this one... wasn't this already working on 2afe173 ? Which case gives the ReferenceError?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@dschult dschult added this to the 3.7 milestone Sep 3, 2026

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment on lines +238 to +243
try:
single = nbunch in adj
except TypeError:
single = False
if single: # if nbunch is a single node
return iter([nbunch])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+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).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It wouldn't have that's why we need the _from_view bit.

self._weight = weight

@classmethod
def _from_view(cls, view, nbunch, weight):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused by this one... wasn't this already working on 2afe173 ? Which case gives the ReferenceError?

@dschult

dschult commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Gemini suggests using weakref.finalize to allow us to convert to a list/dict/whatever we think best when the original graph is being collected.

nodes/edges/degree views can store the data as a list. DataViews probably need to store a dict.
But: storing it locally on the view still keeps a reference to the potentially large array hanging off a node.

Yet another option.

[Edit: degree is actually easier than the others -- just store a dict with integer values and no refs]

@MridulS

MridulS commented Sep 7, 2026

Copy link
Copy Markdown
Member Author

Gemini suggests using weakref.finalize to allow us to convert to a list/dict/whatever we think best when the original graph is being collected.
nodes/edges/degree views can store the data as a list. DataViews probably need to store a dict.
But: storing it locally on the view still keeps a reference to the potentially large array hanging off a node.

Maayybe, but I would push this to follow up issue/PR to maybe discuss this a bit more?

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_iter from 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/_pred dict. 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 graph G can 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"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's give the receiver of this more info. Something like:

Suggested change
"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."

@dschult

dschult commented Sep 17, 2026

Copy link
Copy Markdown
Member

Other info from my explorations:

properties vs cached_properties vs no properties:
The performance of the views doesn't matter for almost all cases. I checked with benchmark style cases and also with pytest timings of the tests in various subpackages of nx. This difference between 7.1s and 7.25s and 7.5s seems minor. I could create specially designed situations where it mattered percentage wise, but the time is short. For example,

G = nx.path_graph(1000)
for node in G:
    edges = list(G.edges(node))

views vs copies:
Another approach I explored a little is to replace views with code that copies the data. I might not have found the best way to do this, but I decided it is unlikely to make this a performant option.

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's give this a try!

@rossbar
rossbar merged commit 083e472 into networkx:main Sep 17, 2026
43 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

3 participants