Skip to content

BUG: Make argmap._lazy_compile thread-safe - #8659

Merged
MridulS merged 1 commit into
networkx:mainfrom
MridulS:gh8658
Jun 7, 2026
Merged

MridulS merged 1 commit into
networkx:mainfrom
MridulS:gh8658

Conversation

@MridulS

@MridulS MridulS commented May 21, 2026

Copy link
Copy Markdown
Member

fixes #8658

This adds a class level lock while moving over the code to the compiled version.

Disclaimer: Claude was used to create the following MRE, it is still stochastic but I was able to get it to fail pretty quickly.

"""Minimal reproducer for gh-8658: argmap lazy-compile race on free-threaded Python.

Run on a free-threaded build (the GIL hides the race)::

    pixi run -e test-base-py314t python argmap_gh8658_repro.py

Unpatched, this prints stochastic failures such as
``NameError: name 'argmap__not_implemented_for_107' is not defined`` (the same
symptom reported from ``nx.Graph`` / ``nx.is_connected`` on an HPC cluster).
With the fix it prints OK.

Why it triggers: the first call to an argmap-decorated function compiles a
specialized version and swaps it into the wrapper. When many threads race that
first call, one could observe the new ``__code__`` before the mangled names it
references were published into ``__globals__`` -- or two compilations could
collide on a name. Every wrapper here shares a name but returns a distinct
value, so a mis-binding shows up as a wrong result, not only a crash.
"""

import sys
import threading

from networkx.utils import not_implemented_for

if hasattr(sys, "_is_gil_enabled") and sys._is_gil_enabled():
    print("warning: GIL is enabled; run with python3.14t to expose the race")

N = 64
errors = []


def make(seed):
    # @not_implemented_for is the argmap decorator seen in the gh-8658 traceback.
    @not_implemented_for("directed")
    def f(G, _seed=seed):
        return _seed

    return f


# Fresh wrappers => each one's first call exercises the lazy compile.
wrappers = [make(s) for s in range(N)]
barrier = threading.Barrier(N)
G = __import__("networkx").Graph()


def worker(start):
    barrier.wait()  # release all threads onto the cold wrappers at once
    try:
        for i in range(N):
            idx = (start + i) % N
            if wrappers[idx](G) != idx:
                raise AssertionError(f"wrong result from wrapper {idx}")
    except Exception as e:  # NameError or wrong-result AssertionError
        errors.append(repr(e))


threads = [threading.Thread(target=worker, args=(i,)) for i in range(N)]
for t in threads:
    t.start()
for t in threads:
    t.join()

if errors:
    print(f"FAILED: {len(errors)} thread(s) errored, e.g. {errors[0]}")
    sys.exit(1)
print("OK: no errors")

@dschult

dschult commented May 22, 2026

Copy link
Copy Markdown
Member

This looks very promising!! -- Thanks @mridul!!

Of course, when I run the test on a vanilla clone of the repo using a recent mamba environment that has nothing to do with threading, I don't get any error even after running it many times. So I have a question about how we can/will test threading based bugs and suggestions. What is the current CI setup for this? Do we have a freethreaded CI run? Should we?

@rossbar

rossbar commented May 22, 2026

Copy link
Copy Markdown
Contributor

That's what we get for diving down into the dunders 🙃 - no thread-safety guarantees down there!

Of course, when I run the test on a vanilla clone of the repo using a recent mamba environment that has nothing to do with threading, I don't get any error even after running it many times.

Interesting - the reproducer works every time on my machine - here's what I'm doing:

  1. copy the example from the OP into a file ttest.py
  2. python3.14t -m venv test-env
  3. source test-env/bin/activate
  4. pip install networkx # Installs v3.6.1
  5. python ttest.py

I wonder if there's a relationship between N in the test vs. the number of cpus on the host machine?

So I have a question about how we can/will test threading based bugs and suggestions

Great question - I'd like to understand the full chain that results in this exception better. The good news is I'd expect that the thread-safety guarantees of Python itself are good enough for all code where we're not explicitly injecting into/overriding the object model, which should be the vast majority of the library.

What is the current CI setup for this? Do we have a freethreaded CI run? Should we?

We do - they are the runs with python-3.14t. Of course, we don't have any explicit tests for threading in the test suite.

@rossbar

rossbar commented May 22, 2026

Copy link
Copy Markdown
Contributor

I wonder if there's a relationship between N in the test vs. the number of cpus on the host machine?

To answer my own question - there sure seems to be, at least on my machine! I tried on my m2 (10 cores) with varying values for N:

N  | % fails
------------
2  | 0
4  | 0
8  | 10%
16 | 50%
32 | 100%

Whether this result generalizes (and how it maps to CI, where threading/num_cpu detection is even weirder) - who knows!

One easy thing to try: add the test first (without the fix) in it's own PR and twist the knobs on the parameters until we get it reliably failing on main. Ad-hoc is better than nothing!

func.__code__ = real_func.__code__
func.__globals__.update(real_func.__globals__)
func.__dict__.update(real_func.__dict__)
with argmap._compile_lock:

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.

Should we call this "lazy compile lock"?

Also, is it possible that the compile acquires the lock and causes a deadlock? I guess no but that's what also motivates my first question.

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.

Also, is it possible that the compile acquires the lock and causes a deadlock? I guess no but that's what also motivates my first question.

I am not a 100% sure honestly, this seemed like the easiest lock to put in to make the MRE happy. But I think for now we should try to get this merged and we can iterate on this in the future.

@rossbar rossbar added this to the 3.7 milestone May 26, 2026
@rossbar

rossbar commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

One easy thing to try: add the test first (without the fix) in it's own PR and twist the knobs on the parameters until we get it reliably failing on main. Ad-hoc is better than nothing!

I went ahead and tried this over in #8676 - as we can see from the action logs this test doesn't fail as-is on CI for the 314t jobs; at least not reliably. FTR the test still fails locally every time for me on various (up to 16CPU/32thread) systems; so it's something to do with how threading behaves on the cloud (which doesn't surprise me).

IMO the fix should go in for v3.7, regardless of test behavior in the action runners! I'm going to experiment a little more - some obvious things to try:

  1. What happens if we bump the number of threads to something absurd
  2. What about incorporating threadpoolctl (or similar)

@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've successfully gotten the error to occur locally (and consistently) on main. And the error does not occur locally consistently on this PR branch. I agree with the approach of merging this even if we don't see a difference on CI (passes on main and this branch).

My understanding is that we will next look for an example that breaks on CI. But that's really more about finding tests for future troubles than this PR anyway.

I approve this PR

@MridulS
MridulS merged commit e187ba2 into networkx:main Jun 7, 2026
44 of 45 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.

Stochastic exceptions involving argmap

4 participants