Skip to content

77 cache stamp - #181

Open
eriknw wants to merge 1 commit into
python-graphblas:20-wiener-efficiencyfrom
eriknw:77-cache-stamp
Open

eriknw wants to merge 1 commit into
python-graphblas:20-wiener-efficiencyfrom
eriknw:77-cache-stamp

Conversation

@eriknw

@eriknw eriknw commented Dec 4, 2026

Copy link
Copy Markdown
Member

Graph(A) uses A without copying it, and G.matrix hands it out, so an entry added to the matrix or removed from it after a call left the graph's cached properties as they were. On a path 0 - 1 - 2 with node 3 alone, nx.degree_centrality(G) after A[2, 3] = A[3, 2] = 1 still gave node 3 nothing; a self-loop added after nx.triangles left has_self_edges False; and on a DiGraph, nx.ancestors(D, 0) stayed set() after the edge (2, 0) was added, read from the cached transpose. Now the cache notices such a change and empties itself, says what it holds, and can be emptied by hand.

  • The snapshot. A graph's cache is one object: its matrix, read once; that matrix's GraphBLAS handle and number of entries; and the properties computed from it. get_property, get_properties, _cacheit, _cache and cache_info compare the handle and the count with the graph's matrix first, and when either differs they make a new snapshot and put it in place with one assignment. A lookup pays one check. The snapshot holds its matrix, so the handle cannot be freed and given to a new matrix while it is compared. Here the allocator gave a freed handle to the next matrix in 50 tries out of 50, and a test puts a matrix with as many entries where a freed one was. A handle keeps its dtype for its life. The count is read by one GrB_Matrix_nvals call into a buffer the snapshot holds: 85 ns, against 196 ns for python-graphblas's _nvals and 719 ns for nvals, which records each call.

  • Threads.

    • Each getter is given its call's snapshot instead of the graph. It reads the matrix and the dict from that snapshot and asks it for the properties it needs, so a value lands only in the dict of the matrix it was computed from.

    • The stamp and the dict are one object for a reason. Held as two attributes, two threads reading while a third replaced the matrix could leave the dict stamped for the new matrix but filled from the old one, still served after the threads had joined. A getter whose nested call emptied the cache raised KeyError: 'has_self_edges'.

    • Code that reads the matrix and caches from it outside a getter takes one snapshot for both: checked_sum_type, whose absolute sum a writer could otherwise cache under the next matrix, and is_acyclic.

    • Threads that only read a graph share its cache, and each store into it can hand the GIL to another thread, so a reader can find the cache part filled by another call. A getter therefore reads only keys it has found or stored itself. is_iso used to read the key that get_iso_value stores second, and two readers alone could raise KeyError: 'is_iso'; it now stores its own answer, and so does has_self_edges after asking for diag. cache_info counts from a copy of the cache, since a reader may store into it meanwhile.

    • Probes, 40-60 s each, Graph and DiGraph. No value was wrong once the threads had joined, and no call raised:

      • two readers and a writer, the writer replacing the matrix with fresh copies, or putting back one of three matrices, while the readers ask for every property, degree_centrality, checked_sum_type and is_acyclic;
      • four readers and no writer, each asking iso_value and is_iso of a new graph, 60000 rounds.

      The writer runs had the faults listed under "Not here" taken out, since those appear without threads too.

    • The function given to _cacheit reads the graph itself, so its value is kept only if the graph still has the snapshot the call started with. A matrix that is replaced and then put back while the function runs is not seen.

    • An algorithm that reads two properties in two separate calls can get them from two different matrices if another thread replaces the matrix in between. degree_centrality of a Graph does this: it reads the degrees, has_self_edges and diag separately. The answer can then be wrong for that one call, but nothing wrong is cached.

    • A snapshot finishes its matrix (wait()) once, so threads only read it. A converted graph's matrix is finished before the graph is handed out.

  • A lock instead. A per-graph lock held over each call's check and getter was tried and dropped, for two reasons:

    • It cost more on every timing below: a cached get_property took 0.37 us against the snapshot's 0.31, and is_regular +2.00 us against +1.06.
    • Getters under it still read the graph's matrix partway through a call. With a writer replacing the matrix, single calls returned values that matched no matrix. When a matrix was put back, wrong values were still served after the threads joined: 3 for Graph and 16 for DiGraph in 45 s.
  • What it does not see. A change that keeps the number of entries: new values for entries the matrix already holds, or one entry added and another removed between two calls. After such a change, call G.clear_cache(), as the docstrings say.

  • G.clear_cache() puts in a new snapshot of the graph's matrix. G.cache_info() gives the bytes each cached property holds, by key, as GraphBLAS counts them. These count 0:

    • the matrix itself;
    • a value already counted under another key (offdiag is A when there are no self-loops, and U- is U+).

    A cached graph (the structure twin a weight=None call makes) counts its matrix and its own cache.

  • Finished as stored. A Matrix, Vector or Scalar is wait()ed as it enters the cache. The getters store values again on every call, filling one key from another (such as count_rowwise+ from count_rowwise- when there are no self-loops). A value its key already holds is left as it is and not waited for again.

  • Columns of an undirected graph. <op>_columnwise<+/-> now uses the getter of <op>_rowwise<+/-> and is cached under the row key. Before, asking for the columnwise key first gave it a getter of its own, and both vectors were computed and kept: equal, but two objects. A DiGraph's columns are its own, as before.

  • Symmetry. Graph's docstring now says that A must hold each edge in both directions. This is not checked, and the cache assumes it: has_self_edges is read from a cached triangle's size (2 * U+.nvals > A.nvals).

  • Pickling and copying. The snapshot's handle and buffer do not pickle. __getstate__ keeps the matrix and the properties of one snapshot, and __setstate__ puts them in a snapshot of the copy's own matrix, so a copy keeps the cache. Without these hooks, pickle and copy.deepcopy of a graph failed, and so did a deep copy of a NetworkX graph holding a cached conversion. A graph pickled by an earlier release still loads, with its cache: __setstate__ takes the properties from its _cache dict. So does a NetworkX graph pickled with a cached conversion to one, which NetworkX keeps by default.

  • Cost. Indicative: one bench slot, load 4.0, JIT on, 4 threads.

    • Setup: a native undirected graph of 1M edges (100000 nodes, 1999790 entries). The base, this change and the lock were interleaved over four rounds of fresh processes. Each timing is the median of 15 repeats of a loop on a warm cache.
    • A check costs 0.13 us.
    • degree_centrality (three checks): 30.58 us against 29.70, +0.88 us or +3.0%. The base's own rounds spread 1.09 us.
    • number_of_isolates (two checks): 8.31 us against 7.80, +0.51 or +6.5%, spread 0.19.
    • is_regular (three checks): 35.28 us against 34.21, +1.06 or +3.1%, spread 0.23.
    • A cached get_property alone: 0.31 us against 0.14.
    • Each of these calls makes three or four more Python calls than on the base: its checks and one store of a value already held.
  • Tests (tests/test_cache.py, 57 tests; 52 fail on the base).

    • For Graph and DiGraph, after an added edge, an added self-loop and a removed edge, read through get_property and through get_properties, each compared with a fresh graph's: degrees, has_self_edges, offdiag, diag, the triangles, a reduction and the transpose.
    • degree_centrality and ancestors through dispatch after each change, and _cache read directly.
    • What empties the cache: a replaced matrix, a new handle behind the same matrix, and a matrix placed where a freed one was.
    • Thread interleavings played out on one thread:
      • another thread's work runs while a check drops the old cache;
      • a matrix is replaced between a getter's check and its nested call;
      • a matrix is replaced while _cacheit computes, then put back;
      • a matrix is replaced while checked_sum_type reads properties, and between is_acyclic's cache and its loop;
      • a matrix is put back just before, or replaced just after, a pickled graph's check;
      • a reader stores a property while cache_info counts the graph or its cached twin.
    • Readers sharing a cache: for Graph and DiGraph, with values stored iso or not and with or without self-loops, every state another call leaves the cache in between two of its stores, for every property asked first. Each state is asked for every property, 13248 pairs in all, and none raises. Where no fault listed under "Not here" applies, each answer equals a fresh graph's.
    • The structure twin after a change, clear_cache after new values, and a property whose value is None.
    • cache_info: after a change, for a Scalar, and for a cached graph.
    • wait: on each stored value, on none in a warm call, once per snapshot for the matrix, and for a converted graph's matrix.
    • The columnwise key, and pickle and deepcopy before and after a change.
    • A Graph, and a NetworkX graph holding a conversion, pickled before the cache was a snapshot.
    • Mutants: 34, covering the check, the snapshot, clear_cache, cache_info, the pickling hooks, the waits, the held-value test, the columnwise getter, is_iso, checked_sum_type and is_acyclic as they were, and cache_info over the live dict. 33 fail the suite in NetworkX 3.7 (Python 3.14 and 3.13) and 3.6.1. They include one where a getter's nested calls check the graph again instead of using their call's snapshot. The 34th, has_self_edges leaving its key to diag again, passes: get_diag stores has_self_edges whenever it is missing, so the change there only follows the rule.
  • NetworkX's tests through the backend.

    • The modules that read the cache: BFS, boundary, betweenness, degree, group and Katz centrality, clustering, partition quality, components, cores, cuts, DAGs, distance measures, efficiency, isolates, isomorphism, PageRank, link prediction, reciprocity, regularity, shortest paths, s-metric, tournaments, tree recognition and triads. Same outcomes before and after: 1984 passed in 3.7 on Python 3.14 and 3.13, and 1418 in 3.6.1.
    • These tests make 144544 checks over 21428 conversions in 3.7, and 134419 over 19361 in 3.6.1. None finds a change.
    • NetworkX's whole suite also gives the same outcomes before and after: 9128 passed, 60 skipped and 742 xfailed in 3.7, and 6815 passed, 78 skipped and 2 xfailed in 3.6.1.
  • Not here:

    • a memory budget for the cache;
    • a table of its properties;
    • triangles counted from L- alone;
    • three inference faults that show up on one thread and on the base, each left to a change of its own:
      • a DiGraph infers has_self_edges from total_degrees+, whose sum is always twice the number of entries, so the inference says False (79 self edges #177);
      • recip_degrees+ and recip_degrees- come out FP64 or INT64 depending on which property was asked for first (80 cache inference #180);
      • has_negative_diagonal reads a missing min_element- as 0, so a negative edge off the diagonal can make it True (80 cache inference #180).

Stacked on #121.

Graph(A) uses A without copying it, so an entry added to A or removed
from it left every cached property computed from the old matrix:
degrees, the triangle matrices, has_self_edges, the transpose. A
graph's cache is now a snapshot: the matrix read once, its GraphBLAS
handle and number of entries, and the properties computed from it.
get_property, get_properties, _cacheit and _cache take the current
snapshot and make a new one, put in place with one store, when the
matrix was replaced or its number of entries changed. A getter is
given the snapshot in place of the graph and asks it for the
properties it needs, so a value lands only in the cache of the matrix
it was computed from, even while other threads replace the matrix.
checked_sum_type and is_acyclic, which cache outside the getters,
take one snapshot for the matrix and the cache too.

Threads that only read a graph share its cache and can find it part
filled by another call, so is_iso and has_self_edges now store the
answer they return rather than leave it to the call they make.

A change that keeps the number of entries, such as new values for
existing ones, is not seen and needs clear_cache(), which is now
public, as is cache_info(), the bytes each cached property holds.

A value is finished with wait() as it is stored, and the matrix once
per snapshot, so that threads sharing a graph only read them. An
undirected graph's columnwise reduction is now its rowwise one, cached
under one key; asked for first, it used to be computed and kept a
second time. Graph's docstring says that A must be symmetric, which
the cache assumes. Pickling and copying keep the cache, and a graph
pickled by an earlier release still loads.
@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.24561% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.05%. Comparing base (5b54ace) to head (06eda8c).

Additional details and impacted files
@@                   Coverage Diff                    @@
##           20-wiener-efficiency     #181      +/-   ##
========================================================
+ Coverage                 92.88%   94.05%   +1.17%     
========================================================
  Files                       182      183       +1     
  Lines                     11227    11750     +523     
  Branches                   1274     1313      +39     
========================================================
+ Hits                      10428    11052     +624     
+ Misses                      546      470      -76     
+ Partials                    253      228      -25     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant