From 7933efc761fc411d0bc8a6711adefb33e7ab573e Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Thu, 3 Dec 2026 14:22:25 -0600 Subject: [PATCH] Add Dispatcher.should_run and the cache helpers its rules use should_run asks a wrapper's own rule, set with nxapi._utils.should_run, as can_run does. NetworkX asks it only on the automatic path, so a rule there moves a call to NetworkX without declining a backend graph or a call that names this backend. A rule reads a fact from the NetworkX graph through remembered, which keeps it in the graph's __networkx_cache__ until NetworkX empties it. It keeps nothing while cache_converted_graphs is off or in NetworkX's test mode, where an edit in place needs no clearing, or for a view, whose cache NetworkX keeps when the graph under it changes. The rebuild verdict in can_run now goes through it: a view converted before its graph gained a second edge attribute was answered from the stale conversion without that attribute, and is now left to NetworkX. has_reusable_conversion says whether NetworkX will give a call a cached conversion, from the key NetworkX's own conversion code makes for that call. It says no for a view, whose cached conversion may be stale; in NetworkX's test mode, which converts afresh; and if the private names it reads have changed. --- graphblas_algorithms/interface.py | 34 +- graphblas_algorithms/nxapi/_cache.py | 118 +++++ graphblas_algorithms/nxapi/_utils.py | 14 + graphblas_algorithms/tests/test_dispatch.py | 2 +- graphblas_algorithms/tests/test_should_run.py | 411 ++++++++++++++++++ 5 files changed, 566 insertions(+), 13 deletions(-) create mode 100644 graphblas_algorithms/nxapi/_cache.py create mode 100644 graphblas_algorithms/tests/test_should_run.py diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..ec5ebed 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -2,6 +2,7 @@ from collections import namedtuple from . import nxapi +from .nxapi._cache import remembered ####### # NOTE: Remember to run `python scripts/maketree.py` when adding or removing algorithms @@ -190,20 +191,13 @@ def _unrebuildable(graph, weight, preserve_edge_attrs, *, keeps_node_data=True): def _rebuild_refusal(graph, preserve_edge_attrs): - """`_unrebuildable`'s reason for `graph`, remembered in the graph's `__networkx_cache__`. + """`_unrebuildable`'s reason for `graph`, read once per version of the graph.""" + preserve = bool(preserve_edge_attrs) - The memo follows NetworkX's own cached conversions: NetworkX empties that cache whenever the - graph is mutated, and with `cache_converted_graphs` off, or no cache, it scans each time. - """ - import networkx as nx + def reason(graph): + return _unrebuildable(_materialize_virtual_adjacency(graph), None, preserve)[1] - cache = getattr(graph, "__networkx_cache__", None) if nx.config.cache_converted_graphs else None - memo = {} if cache is None else cache.setdefault("graphblas_rebuild", {}) - key = bool(preserve_edge_attrs) - if key not in memo: - graph = _materialize_virtual_adjacency(graph) - memo[key] = _unrebuildable(graph, None, preserve_edge_attrs)[1] - return memo[key] + return remembered(graph, ("rebuild", preserve), reason) def _materialize_virtual_adjacency(graph): @@ -591,6 +585,22 @@ def can_run(name, args, kwargs): return reason return True + @staticmethod + def should_run(name, args, kwargs): + """True if serving `name` here should be faster than NetworkX, else the reason not. + + NetworkX asks only where it would convert a graph to call this backend, after `can_run` + said yes. A wrapper's own rule is its `_should_run` attribute, set with + `nxapi._utils.should_run`. + """ + hook = getattr(getattr(Dispatcher, name, None), "_should_run", None) + if hook is None: + return True + bound = _bound_args(name, args, kwargs) + if bound is None or (reason := hook(bound)) is None: + return True + return reason + @staticmethod def on_start_tests(items): """Mark the tests in NetworkX's suite that this backend cannot pass; the table is empty. diff --git a/graphblas_algorithms/nxapi/_cache.py b/graphblas_algorithms/nxapi/_cache.py new file mode 100644 index 0000000..9a341cf --- /dev/null +++ b/graphblas_algorithms/nxapi/_cache.py @@ -0,0 +1,118 @@ +"""What this backend keeps in a NetworkX graph's `__networkx_cache__`, and reads from it. + +NetworkX owns that cache. It keeps its conversions there and empties it when the graph changes +through its methods; after an edit to the data in place, the caller clears it. A fact kept here +lives and dies with those conversions. +""" + + +def _in_networkx_test_mode(): + """True in NetworkX's test mode, and where this NetworkX no longer says: the safe answer. + + That mode converts afresh for every call that names no backend, so a test may edit a graph's + data in place between calls without clearing its cache. + """ + try: + from networkx.utils.backends import _dispatchable + + return bool(_dispatchable._is_testing) + except Exception: + return True + + +def remembered(graph, key, compute): + """`compute(graph)`, kept in the graph's `__networkx_cache__` until NetworkX empties it. + + For a rule that reads a fact from a NetworkX graph before every call, so that it reads the + graph once per version. Nothing is kept while `cache_converted_graphs` is off, when an edit + in place needs no clearing; in NetworkX's test mode, for the same reason; for a graph without + a cache; or for a view, since NetworkX does not empty a view's cache when the graph under it + changes. + """ + import networkx as nx + + cache = getattr(graph, "__networkx_cache__", None) if nx.config.cache_converted_graphs else None + # NetworkX's views hold their graph as `_graph`. + if cache is None or hasattr(graph, "_graph") or _in_networkx_test_mode(): + return compute(graph) + memo = cache.setdefault("graphblas_facts", {}) + if key not in memo: + memo[key] = compute(graph) + return memo[key] + + +# What NetworkX's `_convert_graph` builds its cache key from. +_KEY_ARGUMENTS = ( + "edge_attrs", + "node_attrs", + "preserve_edge_attrs", + "preserve_node_attrs", + "preserve_graph_attrs", +) + + +class _CacheKeys: + """A stand-in for a dispatched function that records the cache key of each graph converted. + + NetworkX's `_convert_arguments` reads the call's arguments into what each graph's conversion + must carry; run on this, it records the key of each graph argument where NetworkX would + convert it, by the argument's name. + """ + + def __init__(self, func): + self._func = func + self.recorded = {} + + def __getattr__(self, attr): + return getattr(self._func, attr) + + def _convert_graph(self, backend_name, graph, **kwargs): + from networkx.utils.backends import _get_cache_key + + key = _get_cache_key(**{name: kwargs[name] for name in _KEY_ARGUMENTS}) + self.recorded[kwargs["graph_name"]] = key + return graph + + +def has_reusable_conversion(name, bound, graph_name="G"): + """True if NetworkX will give this call of `name` a cached conversion of `bound[graph_name]`. + + `bound` holds the call's arguments by name, as a `can_run` or `should_run` hook gets them. + The key is the one NetworkX's own code makes for this call, and the search is its own, so + a conversion cached for other attributes counts only where NetworkX would use it. False + where it cannot be sure: for a view, whose cached conversions NetworkX keeps when the graph + under it changes, so that one may be stale; in NetworkX's test mode, which converts afresh + for a call that names no backend; or if NetworkX's private names used here have changed. + """ + import networkx as nx + + graph = bound.get(graph_name) + cache = getattr(graph, "__networkx_cache__", None) + if not cache or not nx.config.cache_converted_graphs or _in_networkx_test_mode(): + return False + try: + # NetworkX's views hold their graph as `_graph`. + if hasattr(graph, "_graph"): + return False + return _cached_for(name, bound, graph_name, cache) + except Exception: + return False + + +def _cached_for(name, bound, graph_name, cache): + """`has_reusable_conversion`'s search, through NetworkX's private names.""" + from networkx.utils import backends + + # The registry holds a function wrapping the dispatchable object. + func = backends._registered_algorithms[name].__wrapped__ + if not isinstance(func, backends._dispatchable): + return False + keys = _CacheKeys(func) + backends._dispatchable._convert_arguments( + keys, "graphblas", (), dict(bound), use_cache=True, mutations=None + ) + if graph_name not in keys.recorded: + return False # not converted: a backend graph already + converted = dict(cache.get("backends", {}).get("graphblas", {})) # the search may write to it + _key, found = backends._get_from_cache(converted, keys.recorded[graph_name]) + return found is not None and found != backends.FAILED_TO_CONVERT diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index 72f728b..b3fe7a9 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -147,6 +147,20 @@ def decorator(func): return decorator +def should_run(hook): + """Give the decorated wrapper `hook` as its rule in `Dispatcher.should_run`. + + `hook(bound)` gets the arguments as `can_run`'s hook does, and returns the reason NetworkX + should serve the call itself, as the faster of the two, or None to serve it here. + """ + + def decorator(func): + func._should_run = hook + return func + + return decorator + + def check_nodelist(G, nodelist, *, null_graph=True): """Refuse what NetworkX's `to_scipy_sparse_array` refuses, in the order it checks. diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 1765e78..fd74a43 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -647,4 +647,4 @@ def test_the_rebuild_verdict_is_not_kept_while_networkx_caches_no_conversions(mo monkeypatch.setattr(nx.config, "cache_converted_graphs", False) G = two_edge_attributes() assert isinstance(Dispatcher.can_run("k_truss", (G, 2), {}), str) - assert "graphblas_rebuild" not in G.__networkx_cache__ + assert "graphblas_facts" not in G.__networkx_cache__ diff --git a/graphblas_algorithms/tests/test_should_run.py b/graphblas_algorithms/tests/test_should_run.py new file mode 100644 index 0000000..131f314 --- /dev/null +++ b/graphblas_algorithms/tests/test_should_run.py @@ -0,0 +1,411 @@ +"""`should_run`, and what its rules read from a NetworkX graph's `__networkx_cache__`. + +NetworkX asks `should_run` only where it would convert a NetworkX graph for a call that names +no backend. A backend graph is served as it is and `backend="graphblas"` is served whatever +`should_run` says, so a rule there moves only the automatic call to NetworkX. +""" + +import warnings + +import networkx as nx +import pytest +from networkx.utils import backends +from networkx.utils.backends import _registered_algorithms + +from graphblas_algorithms.classes import Graph +from graphblas_algorithms.interface import Dispatcher, _bound_args, _rebuild_refusal +from graphblas_algorithms.nxapi._cache import has_reusable_conversion, remembered +from graphblas_algorithms.tests._dispatched import CALLS, call_args, dispatcher_functions + + +@pytest.fixture(autouse=True) +def _quiet_cache_warning(): + """NetworkX warns whenever a cached conversion is used, and using one is the point here.""" + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", message="Note: conversions to backend graphs are saved to cache" + ) + yield + + +@pytest.fixture +def calls(monkeypatch): + """The names `should_run` is asked about and the graphs converted, in order.""" + seen = {"should_run": [], "converted": []} + should_run = Dispatcher.should_run + convert_from_nx = Dispatcher.convert_from_nx + + def asked(name, args, kwargs): + seen["should_run"].append(name) + return should_run(name, args, kwargs) + + def converted(graph, *args, **kwargs): + seen["converted"].append(graph) + return convert_from_nx(graph, *args, **kwargs) + + monkeypatch.setattr(Dispatcher, "should_run", staticmethod(asked)) + monkeypatch.setattr(Dispatcher, "convert_from_nx", staticmethod(converted)) + return seen + + +@pytest.fixture +def rule(monkeypatch): + """A rule on `bellman_ford_path_length`: graphs whose weights differ go to NetworkX. + + It reads the fact through `remembered`, as a rule should; the list holds each read. + """ + reads = [] + + def weights_differ(G): + reads.append(G) + return len({data.get("weight", 1) for *_edge, data in G.edges(data=True)}) > 1 + + def hook(bound): + if remembered(bound["G"], "test: weights differ", weights_differ): + return "the weights differ" + return None + + monkeypatch.setattr(Dispatcher.bellman_ford_path_length, "_should_run", hook, raising=False) + return reads + + +def ring(): + """A 5-cycle of weight 1.0: from 0 to 2 is 2.0 through 1, and 3.0 the other way.""" + G = nx.cycle_graph(5) + nx.set_edge_attributes(G, 1.0, "weight") + return G + + +def bellman_ford(G, **kwargs): + return nx.bellman_ford_path_length(G, 0, 2, **kwargs) + + +def test_should_run_is_asked_only_on_the_automatic_path(calls, backend_priority): + G = ring() + native = Graph.from_networkx(G, weight="weight") + assert bellman_ford(native) == 2.0 + assert calls == {"should_run": [], "converted": []} + assert bellman_ford(G, backend="graphblas") == 2.0 + assert calls == {"should_run": [], "converted": [G]} + H = ring() + with backend_priority("algos"): + assert bellman_ford(H) == 2.0 + assert calls == {"should_run": ["bellman_ford_path_length"], "converted": [G, H]} + + +def test_a_declining_rule_moves_only_the_automatic_call(calls, backend_priority, monkeypatch): + def hook(bound): + return "declined by the hook" + + monkeypatch.setattr(Dispatcher.bellman_ford_path_length, "_should_run", hook, raising=False) + G = ring() + with backend_priority("algos"): + assert bellman_ford(G) == 2.0 + assert calls == {"should_run": ["bellman_ford_path_length"], "converted": []} + assert bellman_ford(G, backend="graphblas") == 2.0 + assert bellman_ford(Graph.from_networkx(G, weight="weight")) == 2.0 + assert calls == {"should_run": ["bellman_ford_path_length"], "converted": [G]} + + +def test_a_hook_gets_the_arguments_by_name_with_defaults(monkeypatch): + seen = [] + + def hook(bound): + seen.append(dict(bound)) + return "declined by the hook" if bound["nodes"] is None else None + + monkeypatch.setattr(Dispatcher.triangles, "_should_run", hook, raising=False) + G = nx.path_graph(3) + assert Dispatcher.should_run("triangles", (G, [0]), {}) is True + assert Dispatcher.should_run("triangles", (G,), {}) == "declined by the hook" + # A keyword NetworkX does not declare, this backend's `chunksize`, is left out of the binding. + assert Dispatcher.should_run("triangles", (G,), {"chunksize": 2}) == "declined by the hook" + assert seen == [{"G": G, "nodes": [0]}, {"G": G, "nodes": None}, {"G": G, "nodes": None}] + # Arguments that do not bind are NetworkX's to refuse; no rule acts on a guess. + assert Dispatcher.should_run("triangles", (G, None, None), {}) is True + assert len(seen) == 3 + + +def test_a_name_without_a_rule_is_served(): + assert Dispatcher.should_run("triangles", (nx.path_graph(3),), {}) is True + assert Dispatcher.should_run("no_such_name", (nx.path_graph(3),), {}) is True + + +def test_the_rule_reads_the_graph_once_per_version(rule, calls, backend_priority): + G = ring() + with backend_priority("algos"): + assert bellman_ford(G) == 2.0 + assert bellman_ford(G) == 2.0 + assert rule == [G] + G.add_edge(0, 1, weight=5.0) # NetworkX empties the cache: a new version + assert bellman_ford(G) == 3.0 + assert rule == [G, G] + assert calls["converted"] == [G] # the second call reused it, the third went to NetworkX + + +def test_remembered_keeps_a_value_until_networkx_empties_the_cache(): + G = ring() + reads = [] + + def count(graph): + reads.append(graph) + return len(reads) + + assert remembered(G, "count", count) == 1 + assert remembered(G, "count", count) == 1 + assert remembered(G, "another", count) == 2 + G.__networkx_cache__.clear() + assert remembered(G, "count", count) == 3 + G.add_node(9) + assert remembered(G, "count", count) == 4 + assert remembered(G, "count", count) == 4 + + +def test_remembered_keeps_nothing_without_a_cache(): + reads = [] + G = ring() + G.__networkx_cache__ = None + assert remembered(G, "count", lambda g: reads.append(g) or len(reads)) == 1 + assert remembered(G, "count", lambda g: reads.append(g) or len(reads)) == 2 + del G.__networkx_cache__ + assert remembered(G, "count", lambda g: reads.append(g) or len(reads)) == 3 + + +def test_a_view_is_read_afresh_since_networkx_keeps_its_cache_when_its_graph_changes(): + G = ring() + V = G.subgraph([0, 1, 2]) + assert remembered(V, "edges", nx.number_of_edges) == 2 + G.add_edge(0, 2) + assert V.__networkx_cache__ is not None + assert remembered(V, "edges", nx.number_of_edges) == 3 + assert "graphblas_facts" not in V.__networkx_cache__ + + +def test_remembered_keeps_nothing_in_networkx_s_test_mode(monkeypatch): + """That mode converts afresh for each call, so its tests may edit data in place between them.""" + monkeypatch.setattr(backends._dispatchable, "_is_testing", True) + G = ring() + reads = [] + assert remembered(G, "count", lambda g: reads.append(g) or len(reads)) == 1 + assert remembered(G, "count", lambda g: reads.append(g) or len(reads)) == 2 + assert "graphblas_facts" not in G.__networkx_cache__ + assert _rebuild_refusal(G, True) is None + G[0][1]["colour"] = "red" # in place, with no clearing + assert isinstance(_rebuild_refusal(G, True), str) + + +def test_a_rule_is_read_afresh_while_networkx_caches_no_conversions( + rule, calls, backend_priority, monkeypatch +): + monkeypatch.setattr(nx.config, "cache_converted_graphs", False) + G = ring() + with backend_priority("algos"): + assert bellman_ford(G) == 2.0 + assert bellman_ford(G) == 2.0 + assert calls["converted"] == [G, G] + G[0][1]["weight"] = 5.0 # in place, which needs no clearing with caching off + assert bellman_ford(G) == bellman_ford(G, backend="networkx") == 3.0 + assert rule == [G, G, G] + assert calls["converted"] == [G, G] # NetworkX answered the third + assert "graphblas_facts" not in G.__networkx_cache__ + + +def test_a_rule_follows_an_in_place_edit_once_the_cache_is_cleared(rule, calls, backend_priority): + G = ring() + with backend_priority("algos"): + assert bellman_ford(G) == 2.0 + G[0][1]["weight"] = 5.0 # in place: one weight now differs + G.__networkx_cache__.clear() # as NetworkX asks after an edit in place + assert bellman_ford(G) == bellman_ford(G, backend="networkx") == 3.0 + assert rule == [G, G] + assert calls["converted"] == [G] # NetworkX answered the second + assert bellman_ford(G, backend="graphblas") == 3.0 # converted afresh, after the edit + assert calls["converted"] == [G, G] + assert calls["should_run"] == ["bellman_ford_path_length"] * 2 + + +def test_a_view_s_rebuild_verdict_follows_its_graph(backend_priority): + """NetworkX keeps a view's cache, conversions included, when the graph under it changes.""" + G = ring() + V = G.subgraph([0, 1, 2]) + with backend_priority("generators"): + nx.k_truss(V, 2) # converts V, and keeps the conversion in V's cache + G.add_edge(0, 1, weight=1.0, colour="red") + assert isinstance(Dispatcher.can_run("k_truss", (V, 2), {}), str) + with backend_priority("generators"): + got = nx.k_truss(V, 2) + assert isinstance(got, nx.Graph) # NetworkX's answer, which keeps the colour + assert sorted(got.edges(data=True)) == sorted(nx.k_truss(V, 2).edges(data=True)) + + +def test_the_rebuild_verdict_is_kept_for_each_way_of_asking(): + """A name that asks for every edge attribute may carry one; one that asks for none cannot. + + NetworkX before 3.7 asks for none on `reverse`, and for all on `k_truss`. + """ + G = nx.Graph([(0, 1, {"cost": 2.0}), (1, 2, {"cost": 3.0})]) + assert _rebuild_refusal(G, True) is None + assert isinstance(_rebuild_refusal(G, False), str) + assert _rebuild_refusal(G, True) is None + + +# Calls that make NetworkX convert `G` and look it up in the cache: before the call, nothing, +# or one of these conversions. +_PRIMERS = { + "nothing": None, + "weight": lambda G: nx.adjacency_matrix(G, backend="graphblas"), + "no data": lambda G: nx.adjacency_matrix(G, weight=None, backend="graphblas"), + "another attribute": lambda G: nx.adjacency_matrix(G, weight="other", backend="graphblas"), + "the call itself": "the call itself", +} +_VARIANTS = ({}, {"weight": None}, {"weight": "cost"}) + + +@pytest.fixture +def lookups(monkeypatch): + """What NetworkX's own cache search returns, call by call.""" + found = [] + search = backends._get_from_cache + + def recorded(cache, key, **kwargs): + rv = search(cache, key, **kwargs) + found.append(rv[1]) + return rv + + monkeypatch.setattr(backends, "_get_from_cache", recorded) + return found + + +@pytest.mark.parametrize("name", sorted(dispatcher_functions())) +def test_has_reusable_conversion_says_what_networkx_then_does(name, lookups): + kind, args = CALLS[name] + func = _registered_algorithms[name] + graph_name = next(iter(func.graphs)) + parameters = func.__wrapped__.__signature__.parameters + for kwargs in _VARIANTS: + if kwargs and "weight" not in parameters: + continue + for primer in _PRIMERS.values(): + G, built = call_args(kind, args) + try: + if primer == "the call itself": + func(G, *built, backend="graphblas", **kwargs) + elif primer is not None: + primer(G) + except Exception: + pass + said = has_reusable_conversion(name, _bound_args(name, (G, *built), kwargs), graph_name) + lookups.clear() + try: + func(G, *built, backend="graphblas", **kwargs) + except Exception: + pass + # NetworkX converts the graphs in order, so its first search is for this graph. + reused = bool(lookups) and lookups[0] is not None and not isinstance(lookups[0], str) + assert said == reused, (kwargs, primer) + + +def test_no_conversion_is_reusable_while_networkx_caches_none(monkeypatch, calls): + G = ring() + nx.adjacency_matrix(G, backend="graphblas") + bound = _bound_args("adjacency_matrix", (G,), {}) + assert has_reusable_conversion("adjacency_matrix", bound) + monkeypatch.setattr(nx.config, "cache_converted_graphs", False) + assert not has_reusable_conversion("adjacency_matrix", bound) + nx.adjacency_matrix(G, backend="graphblas") + assert calls["converted"] == [G, G] # the cached one was there, and NetworkX did not use it + + +def test_no_conversion_is_reusable_in_networkx_s_test_mode(monkeypatch): + """Its test mode converts afresh for every call that names no backend.""" + G = ring() + nx.adjacency_matrix(G, backend="graphblas") + bound = _bound_args("adjacency_matrix", (G,), {}) + assert has_reusable_conversion("adjacency_matrix", bound) + monkeypatch.setattr(backends._dispatchable, "_is_testing", True) + assert not has_reusable_conversion("adjacency_matrix", bound) + + +def directed_ring(): + G = nx.cycle_graph(5, create_using=nx.DiGraph) + nx.set_edge_attributes(G, 1.0, "weight") + return G + + +# Each kind of view NetworkX makes: a subgraph filters its graph's nodes and edges, and the other +# two read its adjacency in another direction or as another class. None has its cache emptied +# with its graph's. +_VIEWS = { + "subgraph": (ring, lambda G: G.subgraph([0, 1, 2])), + "reverse": (directed_ring, lambda G: G.reverse(copy=False)), + "to_undirected": (directed_ring, lambda G: G.to_undirected(as_view=True)), +} + + +@pytest.mark.parametrize("kind", sorted(_VIEWS)) +def test_a_view_s_conversion_is_not_reusable_since_networkx_keeps_it_when_its_graph_changes(kind): + make, view = _VIEWS[kind] + G = make() + V = view(G) + for graph in (G, V): + nx.adjacency_matrix(graph, backend="graphblas") + assert V.__networkx_cache__["backends"]["graphblas"] + bound = _bound_args("adjacency_matrix", (G,), {}) + assert has_reusable_conversion("adjacency_matrix", bound) + assert not has_reusable_conversion("adjacency_matrix", {**bound, "G": V}) + G.add_edge(0, 2) # NetworkX empties G's cache, and keeps V's + assert V.__networkx_cache__["backends"]["graphblas"] + assert not has_reusable_conversion("adjacency_matrix", {**bound, "G": V}) + + +def test_a_failed_conversion_is_not_reusable_and_the_search_leaves_the_cache_alone(): + G = nx.Graph([(0, 1, {"weight": "heavy"}), (1, 2, {"weight": "light"})]) + with pytest.raises(NotImplementedError): + nx.adjacency_matrix(G, backend="graphblas") + converted = G.__networkx_cache__["backends"]["graphblas"] + before = dict(converted) + # NetworkX's search would note the failure under this name's key too (it carries all data). + for name, args in [("k_truss", (G, 2)), ("adjacency_matrix", (G,))]: + assert not has_reusable_conversion(name, _bound_args(name, args, {})) + assert converted == before + + +def test_a_backend_graph_or_an_unknown_name_has_no_reusable_conversion(): + G = ring() + nx.adjacency_matrix(G, backend="graphblas") + native = Graph.from_networkx(G, weight="weight") + assert not has_reusable_conversion("adjacency_matrix", {"G": native, "weight": "weight"}) + assert not has_reusable_conversion("no_such_name", {"G": G}) + assert not has_reusable_conversion("adjacency_matrix", {"G": None, "weight": "weight"}) + + +# NetworkX's private names that `has_reusable_conversion` and `remembered` read, each removed or +# changed in shape as a later NetworkX might. +_CHANGED_PRIVATES = { + "registry": (backends, "_registered_algorithms", None), + "search": (backends, "_get_from_cache", None), + "search's shape": (backends, "_get_from_cache", lambda cache, key: None), + "key": (backends, "_get_cache_key", None), + "failure marker": (backends, "FAILED_TO_CONVERT", None), + "test mode": (backends._dispatchable, "_is_testing", None), + "conversion code": (backends._dispatchable, "_convert_arguments", None), + "conversion code's shape": (backends._dispatchable, "_convert_arguments", lambda self: None), +} + + +@pytest.mark.parametrize("change", sorted(_CHANGED_PRIVATES)) +def test_a_changed_private_name_gives_the_answers_that_claim_nothing(change, monkeypatch): + G, H = ring(), ring() # before the change, which NetworkX's own dispatch may need + nx.adjacency_matrix(G, backend="graphblas") + bound = _bound_args("adjacency_matrix", (G,), {}) + assert has_reusable_conversion("adjacency_matrix", bound) + owner, attr, replacement = _CHANGED_PRIVATES[change] + if replacement is None: + monkeypatch.delattr(owner, attr) + else: + monkeypatch.setattr(owner, attr, replacement) + assert not has_reusable_conversion("adjacency_matrix", bound) + reads = [] + remembered(H, "count", lambda g: reads.append(g) or len(reads)) + remembered(H, "count", lambda g: reads.append(g) or len(reads)) + assert len(reads) == (2 if change == "test mode" else 1)