From 4c7dc975aab11ef2418c190cd220cf35e2061011 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Tue, 1 Dec 2026 23:44:59 -0600 Subject: [PATCH 1/7] macOS wheels: share the bundled libomp with other OpenMP users delocate copies libomp into suitesparse_graphblas/.dylibs/, gives the copy the install name /DLC/suitesparse_graphblas/.dylibs/libomp.dylib, and links libgraphblas to it by path. A process that already has an LLVM OpenMP runtime, such as conda-forge's NumPy (whose OpenBLAS uses llvm-openmp) or numba's omp threading layer, then loads a second one, and libomp aborts with "OMP: Error #15" when GraphBLAS starts it. With KMP_DUPLICATE_LIB_OK=TRUE the two runtimes deadlock instead. Loading the bundled copy privately can't avoid this. libomp registers itself per process, whatever its file name, install name or dlopen mode, and dyld binds the weak symbols of both copies to whichever was loaded first, so a second copy can crash the process even if it is never started. conda-forge's libomp has the install name @rpath/libomp.dylib, which is also what numba and conda-forge's OpenBLAS link, and dyld resolves @rpath/libomp.dylib to an already-loaded image with that install name before it searches any LC_RPATH. So the new script continuous_integration/share_libomp.py, run after delocate in the macOS repair command, gives the bundled copy that install name and links libgraphblas to @rpath/libomp.dylib, with an LC_RPATH of @loader_path. GraphBLAS then uses a libomp that is already loaded, or loads its own, which libraries loaded later share: one runtime, whatever the order. The file stays at suitesparse_graphblas/.dylibs/libomp.dylib, where python-graphblas looks for it. The script fails if the wheel is not laid out as it expects, and changes nothing on a second run. A libomp loaded before GraphBLAS must be LLVM 19 or newer, which has __kmpc_dispatch_deinit; with an older one, importing suitesparse_graphblas now fails with "Symbol not found: ___kmpc_dispatch_deinit" instead of aborting or crashing later. Wheels that load their own libomp by path still start a second runtime, as before. test_bundled_libomp_is_shared loads a copy of the bundled libomp before GraphBLAS, runs a parallel GraphBLAS operation, and checks that the copy is the only libomp in the process. It fails with the 10.5.2.0 wheel (two libomp images) and passes once that wheel is repaired. The README says what to expect. --- .github/workflows/wheels.yml | 10 ++ README.md | 9 + continuous_integration/share_libomp.py | 173 ++++++++++++++++++++ suitesparse_graphblas/tests/test_package.py | 62 +++++++ 4 files changed, 254 insertions(+) create mode 100644 continuous_integration/share_libomp.py diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index e13369f..5c9a541 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -241,6 +241,16 @@ jobs: # see https://github.com/adang1345/delvewheel/issues/33 CIBW_REPAIR_WHEEL_COMMAND_WINDOWS: "delvewheel repair --add-path \"C:\\GraphBLAS\\bin\" --no-mangle \"libgomp-1.dll;libgcc_s_seh-1.dll\" -w {dest_dir} {wheel}" + # macOS: cibuildwheel's default (delocate), then share_libomp.py, which links the libomp + # that delocate bundled as @rpath/libomp.dylib. GraphBLAS then uses an LLVM OpenMP + # runtime already in the process (e.g., from conda-forge's NumPy or numba) instead of + # starting a second one, which aborts ("OMP: Error #15"). It must run last: delocate + # would undo it. The repair runs in the build venv, where `python` is the Python + # being built for and has delocate. + CIBW_REPAIR_WHEEL_COMMAND_MACOS: >- + delocate-wheel --require-archs {delocate_archs} -w {dest_dir} -v {wheel} && + python {project}/continuous_integration/share_libomp.py {dest_dir} + # make cibuildwheel install test dependencies from pyproject.toml CIBW_TEST_EXTRAS: "test" diff --git a/README.md b/README.md index 5334701..2e487d2 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,15 @@ or conda install -c conda-forge python-suitesparse-graphblas ``` +### OpenMP on macOS +The macOS wheels bundle LLVM's OpenMP runtime (`libomp`) and share it with the other libraries +in the process that use `@rpath/libomp.dylib`, such as conda-forge's packages and numba: +whichever loads first serves them all. A `libomp` loaded before this package must be from +LLVM 19 or newer, or importing it fails with "Symbol not found: ___kmpc_dispatch_deinit". +Packages whose wheels load their own `libomp` by path still start a second OpenMP runtime, +which can abort with "OMP: Error #15" (or hang, with `KMP_DUPLICATE_LIB_OK=TRUE`). In a conda +environment, prefer conda-forge's `python-suitesparse-graphblas`. + ### In the browser (Pyodide) PyPI also has WebAssembly wheels for [Pyodide](https://pyodide.org) 314 (Python 3.14) and 0.29.4 or later (Python 3.13), the `pyemscripten` platform of diff --git a/continuous_integration/share_libomp.py b/continuous_integration/share_libomp.py new file mode 100644 index 0000000..574cc35 --- /dev/null +++ b/continuous_integration/share_libomp.py @@ -0,0 +1,173 @@ +"""Make the libomp in a delocated macOS wheel shareable: link it as @rpath/libomp.dylib. + +Usage: python share_libomp.py WHEEL_OR_DIRECTORY (a directory must hold exactly one wheel) + +It runs after delocate-wheel (see CIBW_REPAIR_WHEEL_COMMAND_MACOS in wheels.yml). delocate +copies libomp into suitesparse_graphblas/.dylibs/, gives the copy an install name of its own +(/DLC/suitesparse_graphblas/.dylibs/libomp.dylib) and links libgraphblas to it by path. A +process that already has an LLVM OpenMP runtime (conda-forge's OpenBLAS, numba's omp layer) +then gets a second one, and libomp aborts with "OMP: Error #15" (with KMP_DUPLICATE_LIB_OK=TRUE, +the two deadlock). Loading the copy privately can't avoid that: libomp registers itself per +process whatever its file or install name, and dyld binds both copies' weak symbols to the one +loaded first. + +conda-forge's libomp has the install name @rpath/libomp.dylib, which is also what numba's omp +layer and conda-forge's OpenBLAS link, and dyld resolves @rpath/libomp.dylib to an already-loaded +image with that install name before it searches LC_RPATHs. So the copy gets that install name, +and libgraphblas links @rpath/libomp.dylib with an LC_RPATH that reaches the copy: GraphBLAS +uses a libomp that is already loaded, or else loads the copy, which libraries loaded later then +share. One runtime either way. The file stays where it is: python-graphblas looks for it there. + +An @rpath/libomp.dylib loaded before GraphBLAS must be LLVM 19 or newer, which has +__kmpc_dispatch_deinit; otherwise importing suitesparse_graphblas fails with "Symbol not found". +""" + +import os +import re +import subprocess +import sys +from pathlib import Path + +from delocate.wheeltools import InWheelCtx + +OMP = Path("suitesparse_graphblas/.dylibs/libomp.dylib") +SHARED = "@rpath/libomp.dylib" +# libomp, libiomp5, libgomp: a wheel holding any other one isn't the layout this script knows +OPENMP = re.compile(r"lib[gi]?omp[\d.]") +LINKS = { + "LC_LOAD_DYLIB", + "LC_LOAD_WEAK_DYLIB", + "LC_LOAD_UPWARD_DYLIB", + "LC_LAZY_LOAD_DYLIB", + "LC_REEXPORT_DYLIB", +} + + +def fail(message): + sys.exit(f"share_libomp: {message}") + + +def run(*args): + # otool, install_name_tool and codesign come from PATH, as they do for delocate + proc = subprocess.run(args, capture_output=True, text=True) + if proc.returncode: + fail(f"{' '.join(map(str, args))} failed:\n{proc.stderr}") + return proc.stdout + + +def load_commands(path): + """[(command, install name or rpath)] for the load commands of a Mach-O file.""" + pattern = r"cmd (LC_\w+)\n +cmdsize \d+\n +(?:name|path) (.*) \(offset \d+\)" + return re.findall(pattern, run("otool", "-l", path)) + + +def install_ids(path): + return [name for cmd, name in load_commands(path) if cmd == "LC_ID_DYLIB"] + + +def rpaths(path): + # conda-forge's libraries have "@loader_path/", which is the same as "@loader_path" + return [name.rstrip("/") for cmd, name in load_commands(path) if cmd == "LC_RPATH"] + + +def machos(): + # InWheelCtx has changed into the unpacked wheel, so paths are relative to its root + return sorted(p for p in Path().rglob("*") if p.suffix in {".so", ".dylib"} and p.is_file()) + + +def omp_users(): + """{Mach-O file: its links to OpenMP runtimes}, for the files that have any.""" + users = {} + for path in machos(): + links = [n for c, n in load_commands(path) if c in LINKS and OPENMP.match(n.split("/")[-1])] + if links: + users[path] = links + return users + + +def rpath_to_omp(path): + rel = os.path.relpath(OMP.parent, path.parent) + return "@loader_path" if rel == "." else f"@loader_path/{rel}" + + +def share(): + """Link the bundled libomp as @rpath/libomp.dylib in the unpacked wheel; return what changed.""" + if not OMP.is_file(): + fail(f"no {OMP} in the wheel; did delocate bundle libomp?") + others = [p for p in machos() if OPENMP.match(p.name) and p != OMP] + if others: + fail(f"OpenMP runtimes other than {OMP} in the wheel: {others}") + changed = [] + if install_ids(OMP) != [SHARED]: + run("install_name_tool", "-id", SHARED, OMP) + changed.append(OMP) + for path, links in omp_users().items(): + args = [] + for link in links: + if link == SHARED: + continue + # delocate links the copy relative to the file that uses it + target = link.removeprefix("@loader_path/") + if target == link or Path(os.path.normpath(path.parent / target)) != OMP: + fail(f"{path} links {link}, which is not {OMP}") + args += ["-change", link, SHARED] + if rpath_to_omp(path) not in rpaths(path): + args += ["-add_rpath", rpath_to_omp(path)] + if args: + run("install_name_tool", *args, path) + changed.append(path) + for path in changed: + # install_name_tool invalidates the signature, and arm64 won't load unsigned code + run("codesign", "--force", "--sign", "-", path) + return changed + + +def check(): + """Fail unless the unpacked wheel shares libomp as intended; return the files that link it.""" + if install_ids(OMP) != [SHARED]: + fail(f"{OMP} has install name {install_ids(OMP)}, not {SHARED}") + users = omp_users() + if not users: + fail(f"nothing in the wheel links {OMP}") + for path, links in users.items(): + if links != [SHARED]: + fail(f"{path} links {links}, not [{SHARED!r}]") + found = rpaths(path) + if rpath_to_omp(path) not in found: + fail(f"{path} has rpaths {found}, without {rpath_to_omp(path)}") + # dyld searches them in order, so one outside the wheel could find another libomp first + outside = [r for r in found if r != "@loader_path" and not r.startswith("@loader_path/")] + if outside: + fail(f"{path} has rpaths outside the wheel: {outside}") + for path in machos(): + # x86_64 linkers don't sign, and unsigned code runs there; code with a bad signature doesn't + proc = subprocess.run(["codesign", "--verify", path], capture_output=True, text=True) + if proc.returncode and "code object is not signed at all" not in proc.stderr: + fail(f"bad signature: {proc.stderr}") + return sorted(users) + + +def main(arg): + wheel = Path(arg) + if wheel.is_dir(): + wheels = sorted(wheel.glob("*.whl")) + if len(wheels) != 1: + fail(f"expected one wheel in {arg}, found {[w.name for w in wheels]}") + [wheel] = wheels + wheel = wheel.resolve() # InWheelCtx changes directory + with InWheelCtx(wheel) as ctx: + changed = share() + users = check() + if changed: + # Write the wheel (with a new RECORD) on leaving the block; on an error, don't + ctx.out_wheel = str(wheel) + print( + f"share_libomp: {wheel.name}: {', '.join(map(str, users))} link {SHARED}; " + f"changed: {', '.join(map(str, changed)) or 'nothing'}" + ) + + +if __name__ == "__main__": + if len(sys.argv) != 2: + fail("usage: python share_libomp.py WHEEL_OR_DIRECTORY") + main(sys.argv[1]) diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index 8d513aa..bf7a376 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -1,6 +1,11 @@ import importlib +import json import os +import shutil +import subprocess import sys +import textwrap +from pathlib import Path import pytest @@ -52,6 +57,63 @@ def test_openmp(): assert val_ptr[0], "libgraphblas was built without OpenMP" +# Load a libomp from elsewhere before GraphBLAS, as another package would, use GraphBLAS in +# parallel, then print the libomp images in the process. +_SHARED_LIBOMP_SCRIPT = textwrap.dedent(""" + import ctypes + import json + import os + import sys + + ctypes.CDLL(sys.argv[1]) + + import numpy as np + + import suitesparse_graphblas as ssgb + from suitesparse_graphblas import lib, vector + + ssgb.initialize() + n = 2**20 + v = vector.vector_new(lib.GrB_INT64, n) + # A permutation, so the build sorts n indices, in parallel + indices = np.arange(n, dtype=np.uint64) * 7919 % n + vector.vector_build_int64(v, indices, np.ones(n, np.int64), n, lib.GrB_PLUS_INT64) + assert vector.vector_nvals(v) == n + + libsystem = ctypes.CDLL("/usr/lib/libSystem.B.dylib") + libsystem._dyld_image_count.restype = ctypes.c_uint32 + libsystem._dyld_get_image_name.argtypes = [ctypes.c_uint32] + libsystem._dyld_get_image_name.restype = ctypes.c_char_p + images = map(libsystem._dyld_get_image_name, range(libsystem._dyld_image_count())) + print(json.dumps([os.fsdecode(p) for p in images if os.path.basename(p) == b"libomp.dylib"])) + """) + +_bundled_libomp = Path(suitesparse_graphblas.__file__).parent / ".dylibs" / "libomp.dylib" + + +@pytest.mark.skipif( + sys.platform != "darwin" or not _bundled_libomp.exists(), + reason="only the macOS wheels bundle libomp", +) +def test_bundled_libomp_is_shared(tmp_path): + # Two LLVM OpenMP runtimes in one process abort ("OMP: Error #15") or deadlock, so the + # wheels link the libomp they bundle as @rpath/libomp.dylib, the install name of the one + # that conda-forge's OpenBLAS and numba load (see continuous_integration/share_libomp.py). + # dyld then uses such a libomp if one is already loaded instead of loading the bundled one. + # A copy of the bundled libomp, loaded first, stands in for it. + copy = tmp_path / "libomp.dylib" + shutil.copyfile(_bundled_libomp, copy) + proc = subprocess.run( + [sys.executable, "-W", "error", "-c", _SHARED_LIBOMP_SCRIPT, str(copy)], + capture_output=True, + text=True, + timeout=60, + ) + assert proc.returncode == 0, proc.stderr + images = json.loads(proc.stdout.splitlines()[-1]) + assert len(images) == 1 and os.path.samefile(images[0], copy), images + + def test_libgraphblas_version_matches_the_loaded_library(): """The GraphBLAS this extension was compiled against must be the one it loads. From 4a2d4ebe4136e9459033b224587692335836b612 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 00:05:40 -0600 Subject: [PATCH 2/7] Explain the ImportError when an older libomp is already loaded The macOS wheels now use an LLVM OpenMP runtime that another package already loaded as @rpath/libomp.dylib. If that runtime is older than LLVM 19, it lacks __kmpc_dispatch_deinit, which libgraphblas calls, and dyld refuses to load libgraphblas ("Symbol not found: ___kmpc_dispatch_deinit"). The same setups used to abort or crash. When the import fails with dyld's "Symbol not found" for an OpenMP function, raise an ImportError, chained to dyld's, that says what happened and what to do: update that libomp (in conda, llvm-openmp>=19), or in a conda environment use conda-forge's python-suitesparse-graphblas. Importing suitesparse_graphblas first helps only if the package that loaded the old libomp is not NumPy: suitesparse_graphblas imports NumPy (through utils) before _graphblas, and conda-forge's NumPy loads conda's libomp. dyld's error comes out of `from . import utils`, which imports _graphblas, so the try covers both imports. Their order stays, so NumPy's libomp, if it has one, is still loaded first. test_old_libomp_error checks the message against what dyld printed with conda-forge's llvm-openmp 18.1.8 loaded first. A test with a real old libomp would have to download one. --- suitesparse_graphblas/__init__.py | 37 +++++++++++++++++++-- suitesparse_graphblas/tests/test_package.py | 18 ++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 2e5935b..ba9f0d8 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -5,8 +5,41 @@ import struct as _struct from . import exceptions as ex -from . import utils -from ._graphblas import ffi, lib + + +def _old_libomp_error(error): + """A clearer ImportError than `error` if a loaded libomp lacks what GraphBLAS needs, or None. + + The macOS wheels share an LLVM OpenMP runtime that is already loaded (see the README), and + dyld then fails to load libgraphblas if that runtime lacks an OpenMP function it calls. + """ + import re + + text = str(error) + missing = re.search(r"Symbol not found: _(__kmpc_\w+|omp_\w+)", text) + if not missing: + return None + where = re.search(r"Expected in:\s+(?:<[^>]*>\s+)?(.+)", text) + loaded = f" ({where[1].strip()})" if where else "" + return ImportError( + f"Another package already loaded an LLVM OpenMP runtime (libomp) older than LLVM 19" + f"{loaded}, which lacks {missing[1]} and so can't serve this build of " + "SuiteSparse:GraphBLAS. Update that libomp (in conda: llvm-openmp>=19), or in a conda " + "environment install conda-forge's python-suitesparse-graphblas instead. If the package " + "that loaded it isn't NumPy (which suitesparse_graphblas imports first), importing " + "suitesparse_graphblas before that package also works." + ) + + +try: + # utils imports NumPy, then _graphblas, which loads libgraphblas and with it libomp + from . import utils + from ._graphblas import ffi, lib +except ImportError as exc: # pragma: no cover (an import that fails) + error = _old_libomp_error(exc) + if error is None: + raise + raise error from exc _is_osx_arm64 = platform.machine() == "arm64" _is_ppc64le = platform.machine() == "ppc64le" diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index bf7a376..e7cdd67 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -114,6 +114,24 @@ def test_bundled_libomp_is_shared(tmp_path): assert len(images) == 1 and os.path.samefile(images[0], copy), images +def test_old_libomp_error(): + # What dyld said when conda-forge's llvm-openmp 18.1.8 was loaded first (paths shortened) + dyld = ( + "dlopen(/sp/suitesparse_graphblas/_graphblas.abi3.so, 0x0002): " + "Symbol not found: ___kmpc_dispatch_deinit\n" + " Referenced from: " + "/sp/suitesparse_graphblas/.dylibs/libgraphblas.10.5.2.dylib\n" + " Expected in: <6D0D0290-7DDA-3EB4-965D-E9009788F2B9> /env/lib/libomp.dylib" + ) + error = suitesparse_graphblas._old_libomp_error(ImportError(dyld)) + assert isinstance(error, ImportError) + assert "older than LLVM 19 (/env/lib/libomp.dylib), which lacks __kmpc_dispatch_deinit" in ( + str(error) + ) + assert "llvm-openmp>=19" in str(error) + assert suitesparse_graphblas._old_libomp_error(ImportError("No module named 'cffi'")) is None + + def test_libgraphblas_version_matches_the_loaded_library(): """The GraphBLAS this extension was compiled against must be the one it loads. From 5ec0fcff06cda0f43c8950929ede3ddeb1b4b647 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 00:05:55 -0600 Subject: [PATCH 3/7] share_libomp.py: Apple's tools, one rpath, known OpenMP imports - Run /usr/bin/otool, install_name_tool, codesign and nm, not whichever comes first on PATH: a conda environment can put cctools-port's first. - Require each file that links libomp to have exactly one LC_RPATH, the one that reaches the bundled copy. When no libomp is loaded yet, dyld tries a file's LC_RPATHs in order, so another one could load some other libomp. delocate removes absolute ones today; this keeps it so. - Fail if libgraphblas imports an OpenMP function other than the 23 that 10.5.2 and 10.5.3 import. A libomp that is already loaded must export all of them, and the newest, __kmpc_dispatch_deinit, is what makes the minimum LLVM 19. A new one may raise that minimum, so it needs a look, and then the README and the ImportError message may need an update. - Write the repaired wheel to a temporary file and replace the original only once it is complete, so that a failure while zipping can't leave a truncated wheel behind. --- continuous_integration/share_libomp.py | 77 +++++++++++++++++++++----- 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/continuous_integration/share_libomp.py b/continuous_integration/share_libomp.py index 574cc35..f11b5e4 100644 --- a/continuous_integration/share_libomp.py +++ b/continuous_integration/share_libomp.py @@ -20,6 +20,8 @@ An @rpath/libomp.dylib loaded before GraphBLAS must be LLVM 19 or newer, which has __kmpc_dispatch_deinit; otherwise importing suitesparse_graphblas fails with "Symbol not found". +That minimum comes from the OpenMP functions that libgraphblas calls, so the script fails if it +calls one that isn't in OPENMP_IMPORTS. """ import os @@ -41,6 +43,39 @@ "LC_LAZY_LOAD_DYLIB", "LC_REEXPORT_DYLIB", } +# What libgraphblas imports from libomp (10.5.2 and 10.5.3). __kmpc_dispatch_deinit is the +# newest, from LLVM 19. If it imports another one, the oldest libomp it can share may be newer: +# check, then update this list, the README and the ImportError message in __init__.py. +OPENMP_IMPORTS = { + "__kmpc_dispatch_deinit", + "__kmpc_dispatch_init_4", + "__kmpc_dispatch_init_8", + "__kmpc_dispatch_init_8u", + "__kmpc_dispatch_next_4", + "__kmpc_dispatch_next_8", + "__kmpc_dispatch_next_8u", + "__kmpc_end_reduce_nowait", + "__kmpc_flush", + "__kmpc_for_static_fini", + "__kmpc_for_static_init_4", + "__kmpc_for_static_init_8", + "__kmpc_for_static_init_8u", + "__kmpc_fork_call", + "__kmpc_global_thread_num", + "__kmpc_push_num_threads", + "__kmpc_reduce_nowait", + "omp_destroy_lock", + "omp_get_max_threads", + "omp_get_wtime", + "omp_init_lock", + "omp_set_lock", + "omp_unset_lock", +} +# Apple's tools, not whichever come first on PATH (a conda env can have cctools-port's) +CODESIGN = "/usr/bin/codesign" +INSTALL_NAME_TOOL = "/usr/bin/install_name_tool" +NM = "/usr/bin/nm" +OTOOL = "/usr/bin/otool" def fail(message): @@ -48,7 +83,6 @@ def fail(message): def run(*args): - # otool, install_name_tool and codesign come from PATH, as they do for delocate proc = subprocess.run(args, capture_output=True, text=True) if proc.returncode: fail(f"{' '.join(map(str, args))} failed:\n{proc.stderr}") @@ -58,7 +92,7 @@ def run(*args): def load_commands(path): """[(command, install name or rpath)] for the load commands of a Mach-O file.""" pattern = r"cmd (LC_\w+)\n +cmdsize \d+\n +(?:name|path) (.*) \(offset \d+\)" - return re.findall(pattern, run("otool", "-l", path)) + return re.findall(pattern, run(OTOOL, "-l", path)) def install_ids(path): @@ -85,6 +119,12 @@ def omp_users(): return users +def openmp_imports(path): + # nm -u lists undefined symbols with C's leading underscore + names = (line.removeprefix("_") for line in run(NM, "-u", path).split()) + return {name for name in names if name.startswith(("__kmpc_", "omp_"))} + + def rpath_to_omp(path): rel = os.path.relpath(OMP.parent, path.parent) return "@loader_path" if rel == "." else f"@loader_path/{rel}" @@ -99,7 +139,7 @@ def share(): fail(f"OpenMP runtimes other than {OMP} in the wheel: {others}") changed = [] if install_ids(OMP) != [SHARED]: - run("install_name_tool", "-id", SHARED, OMP) + run(INSTALL_NAME_TOOL, "-id", SHARED, OMP) changed.append(OMP) for path, links in omp_users().items(): args = [] @@ -114,11 +154,11 @@ def share(): if rpath_to_omp(path) not in rpaths(path): args += ["-add_rpath", rpath_to_omp(path)] if args: - run("install_name_tool", *args, path) + run(INSTALL_NAME_TOOL, *args, path) changed.append(path) for path in changed: # install_name_tool invalidates the signature, and arm64 won't load unsigned code - run("codesign", "--force", "--sign", "-", path) + run(CODESIGN, "--force", "--sign", "-", path) return changed @@ -132,16 +172,18 @@ def check(): for path, links in users.items(): if links != [SHARED]: fail(f"{path} links {links}, not [{SHARED!r}]") - found = rpaths(path) - if rpath_to_omp(path) not in found: - fail(f"{path} has rpaths {found}, without {rpath_to_omp(path)}") - # dyld searches them in order, so one outside the wheel could find another libomp first - outside = [r for r in found if r != "@loader_path" and not r.startswith("@loader_path/")] - if outside: - fail(f"{path} has rpaths outside the wheel: {outside}") + # dyld searches them in order, so another one could find another libomp first + if rpaths(path) != [rpath_to_omp(path)]: + fail(f"{path} has rpaths {rpaths(path)}, not just {rpath_to_omp(path)!r}") + new = openmp_imports(path) - OPENMP_IMPORTS + if new: + fail( + f"{path} imports OpenMP functions it didn't before: {sorted(new)}. The oldest " + "libomp it can share may be newer now; see OPENMP_IMPORTS" + ) for path in machos(): # x86_64 linkers don't sign, and unsigned code runs there; code with a bad signature doesn't - proc = subprocess.run(["codesign", "--verify", path], capture_output=True, text=True) + proc = subprocess.run([CODESIGN, "--verify", path], capture_output=True, text=True) if proc.returncode and "code object is not signed at all" not in proc.stderr: fail(f"bad signature: {proc.stderr}") return sorted(users) @@ -155,12 +197,17 @@ def main(arg): fail(f"expected one wheel in {arg}, found {[w.name for w in wheels]}") [wheel] = wheels wheel = wheel.resolve() # InWheelCtx changes directory + # Not *.whl, so that cibuildwheel can't take it for the repaired wheel + tmp = wheel.with_suffix(".whl.tmp") with InWheelCtx(wheel) as ctx: changed = share() users = check() if changed: - # Write the wheel (with a new RECORD) on leaving the block; on an error, don't - ctx.out_wheel = str(wheel) + # Write it (with a new RECORD) on leaving the block; on an error, don't + ctx.out_wheel = str(tmp) + if changed: + # Only now, so that an error while writing can't leave a truncated wheel + os.replace(tmp, wheel) print( f"share_libomp: {wheel.name}: {', '.join(map(str, users))} link {SHARED}; " f"changed: {', '.join(map(str, changed)) or 'nothing'}" From 26682f845a9c3f638653d803b9da999a4418aa75 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 00:09:41 -0600 Subject: [PATCH 4/7] Test that libraries loaded later share the bundled libomp too test_bundled_libomp_is_shared covered a libomp loaded before GraphBLAS. Run it also with nothing loaded first: after GraphBLAS has loaded its own copy and run in parallel, a dlopen of @rpath/libomp.dylib, as a library that links it would do, must get GraphBLAS's copy (dladdr on omp_get_max_threads says which file), and the process must still have one libomp. dyld finds it as "already-loaded-by-rpath", the same lookup it does for a library's @rpath dependency. With 10.5.2.0's layout the dlopen finds no libomp, or the interpreter's own (conda), and the test fails. Use ctypes.CDLL(None) to reach dyld's functions instead of naming libSystem's path. --- suitesparse_graphblas/tests/test_package.py | 64 +++++++++++++++------ 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index e7cdd67..ee2c432 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -57,15 +57,17 @@ def test_openmp(): assert val_ptr[0], "libgraphblas was built without OpenMP" -# Load a libomp from elsewhere before GraphBLAS, as another package would, use GraphBLAS in -# parallel, then print the libomp images in the process. +# Optionally load a libomp first, as another package would, use GraphBLAS in parallel, then ask +# dyld for @rpath/libomp.dylib, as a library loaded later would. Print the file that request got +# (or why it failed) and the libomp images in the process. _SHARED_LIBOMP_SCRIPT = textwrap.dedent(""" import ctypes import json import os import sys - ctypes.CDLL(sys.argv[1]) + if sys.argv[1]: + ctypes.CDLL(sys.argv[1]) import numpy as np @@ -80,12 +82,33 @@ def test_openmp(): vector.vector_build_int64(v, indices, np.ones(n, np.int64), n, lib.GrB_PLUS_INT64) assert vector.vector_nvals(v) == n - libsystem = ctypes.CDLL("/usr/lib/libSystem.B.dylib") - libsystem._dyld_image_count.restype = ctypes.c_uint32 - libsystem._dyld_get_image_name.argtypes = [ctypes.c_uint32] - libsystem._dyld_get_image_name.restype = ctypes.c_char_p - images = map(libsystem._dyld_get_image_name, range(libsystem._dyld_image_count())) - print(json.dumps([os.fsdecode(p) for p in images if os.path.basename(p) == b"libomp.dylib"])) + + class DlInfo(ctypes.Structure): + _fields_ = [ + ("fname", ctypes.c_char_p), + ("fbase", ctypes.c_void_p), + ("sname", ctypes.c_char_p), + ("saddr", ctypes.c_void_p), + ] + + + libc = ctypes.CDLL(None) + libc.dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(DlInfo)] + try: + later = ctypes.CDLL("@rpath/libomp.dylib") + except OSError as exc: + later = str(exc) + else: + info = DlInfo() + address = ctypes.cast(later.omp_get_max_threads, ctypes.c_void_p) + assert libc.dladdr(address, ctypes.byref(info)) + later = os.fsdecode(info.fname) + libc._dyld_image_count.restype = ctypes.c_uint32 + libc._dyld_get_image_name.argtypes = [ctypes.c_uint32] + libc._dyld_get_image_name.restype = ctypes.c_char_p + images = map(libc._dyld_get_image_name, range(libc._dyld_image_count())) + images = [os.fsdecode(p) for p in images if os.path.basename(p) == b"libomp.dylib"] + print(json.dumps({"images": images, "later": later})) """) _bundled_libomp = Path(suitesparse_graphblas.__file__).parent / ".dylibs" / "libomp.dylib" @@ -95,23 +118,30 @@ def test_openmp(): sys.platform != "darwin" or not _bundled_libomp.exists(), reason="only the macOS wheels bundle libomp", ) -def test_bundled_libomp_is_shared(tmp_path): +@pytest.mark.parametrize("first", ["other", "graphblas"]) +def test_bundled_libomp_is_shared(first, tmp_path): # Two LLVM OpenMP runtimes in one process abort ("OMP: Error #15") or deadlock, so the # wheels link the libomp they bundle as @rpath/libomp.dylib, the install name of the one # that conda-forge's OpenBLAS and numba load (see continuous_integration/share_libomp.py). - # dyld then uses such a libomp if one is already loaded instead of loading the bundled one. - # A copy of the bundled libomp, loaded first, stands in for it. - copy = tmp_path / "libomp.dylib" - shutil.copyfile(_bundled_libomp, copy) + # dyld then gives every library that links @rpath/libomp.dylib the one loaded first: a libomp + # already loaded when GraphBLAS loads (here a copy of the bundled one stands in for it), or + # else GraphBLAS's copy, also for libraries loaded later (here a dlopen stands in for them). + preload = "" + expected = _bundled_libomp + if first == "other": + preload = expected = tmp_path / "libomp.dylib" + shutil.copyfile(_bundled_libomp, expected) proc = subprocess.run( - [sys.executable, "-W", "error", "-c", _SHARED_LIBOMP_SCRIPT, str(copy)], + [sys.executable, "-W", "error", "-c", _SHARED_LIBOMP_SCRIPT, str(preload)], capture_output=True, text=True, timeout=60, ) assert proc.returncode == 0, proc.stderr - images = json.loads(proc.stdout.splitlines()[-1]) - assert len(images) == 1 and os.path.samefile(images[0], copy), images + result = json.loads(proc.stdout.splitlines()[-1]) + images, later = result["images"], result["later"] + assert len(images) == 1 and os.path.samefile(images[0], expected), result + assert os.path.exists(later) and os.path.samefile(later, expected), result def test_old_libomp_error(): From 4f24852b2b05050af1c0842c4960f3edbc106a07 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 00:10:57 -0600 Subject: [PATCH 5/7] wheels.yml: say why the bundled llvm-openmp should be the newest Libraries loaded after GraphBLAS that link @rpath/libomp.dylib now get the libomp the wheel bundles. One that needs a function this libomp lacks fails to load, so take the newest llvm-openmp at each release. --- .github/workflows/wheels.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 5c9a541..bc4b9c8 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -164,6 +164,7 @@ jobs: run: | brew fetch --retry coreutils && brew install coreutils prefix="$RUNNER_TEMP/libomp" + # The newest at each release: libraries loaded after GraphBLAS share it, and fail if it's too old micromamba create --yes --prefix "$prefix" --override-channels --channel conda-forge "llvm-openmp=23.1.6" # The build string (the pin is on the version only) and the minimum macOS it supports micromamba list --prefix "$prefix" From cbd3747153456b60c1558e71f57b2ed295fcb1ee Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 00:10:59 -0600 Subject: [PATCH 6/7] README: which libraries share the macOS libomp, and what to do Say what to do when an older libomp loaded first makes the import fail: update it, or import suitesparse_graphblas first, which cannot help when it came with NumPy because suitesparse_graphblas imports NumPy first. Say which cases still give two runtimes: Homebrew's libomp (the xgboost and lightgbm wheels) shares only if suitesparse_graphblas loads first, and the copies in the scikit-learn wheel and recent PyTorch wheels, linked by path, never do. --- README.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 2e487d2..5e333e1 100644 --- a/README.md +++ b/README.md @@ -28,12 +28,17 @@ conda install -c conda-forge python-suitesparse-graphblas ``` ### OpenMP on macOS -The macOS wheels bundle LLVM's OpenMP runtime (`libomp`) and share it with the other libraries -in the process that use `@rpath/libomp.dylib`, such as conda-forge's packages and numba: -whichever loads first serves them all. A `libomp` loaded before this package must be from -LLVM 19 or newer, or importing it fails with "Symbol not found: ___kmpc_dispatch_deinit". -Packages whose wheels load their own `libomp` by path still start a second OpenMP runtime, -which can abort with "OMP: Error #15" (or hang, with `KMP_DUPLICATE_LIB_OK=TRUE`). In a conda +The macOS wheels bundle LLVM's OpenMP runtime (`libomp`) as `@rpath/libomp.dylib`, the name that +conda-forge's packages and numba link theirs by, so these libraries share one runtime: whichever +of them loads first serves them all. If that is a `libomp` older than LLVM 19, which lacks +`__kmpc_dispatch_deinit`, importing this package fails. Update it (in conda: `llvm-openmp>=19`), +or, unless it came with NumPy (which this package imports first), import this package before the +one that loads it. + +Libraries that load a `libomp` under another name don't share it, and two OpenMP runtimes in one +process can abort with "OMP: Error #15" (or hang, with `KMP_DUPLICATE_LIB_OK=TRUE`). Homebrew's +`libomp`, which the xgboost and lightgbm wheels use, shares only if this package loads first; the +copies bundled in the scikit-learn wheel and recent PyTorch wheels never do. In a conda environment, prefer conda-forge's `python-suitesparse-graphblas`. ### In the browser (Pyodide) From e7484273399dd8c30fab60c97789cc48d598b046 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 00:13:52 -0600 Subject: [PATCH 7/7] Test: accept a libomp that NumPy loaded before GraphBLAS With nothing preloaded, test_bundled_libomp_is_shared[graphblas] required the bundled libomp to be the process's only one. But with conda-forge's NumPy, OpenBLAS loads conda's libomp before GraphBLAS does, GraphBLAS then shares it, and the test failed although that is the intended behavior. Check instead that there is one libomp and that a later request for @rpath/libomp.dylib gets it. The original 10.5.2.0 wheel still fails both cases; a repaired one passes both, with PyPI's NumPy and with conda-forge's. --- suitesparse_graphblas/tests/test_package.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index ee2c432..adc3aa3 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -126,8 +126,7 @@ def test_bundled_libomp_is_shared(first, tmp_path): # dyld then gives every library that links @rpath/libomp.dylib the one loaded first: a libomp # already loaded when GraphBLAS loads (here a copy of the bundled one stands in for it), or # else GraphBLAS's copy, also for libraries loaded later (here a dlopen stands in for them). - preload = "" - expected = _bundled_libomp + preload = expected = "" if first == "other": preload = expected = tmp_path / "libomp.dylib" shutil.copyfile(_bundled_libomp, expected) @@ -140,7 +139,11 @@ def test_bundled_libomp_is_shared(first, tmp_path): assert proc.returncode == 0, proc.stderr result = json.loads(proc.stdout.splitlines()[-1]) images, later = result["images"], result["later"] - assert len(images) == 1 and os.path.samefile(images[0], expected), result + assert len(images) == 1, result + # With nothing preloaded, the libomp is usually the bundled one, but NumPy may have loaded + # another first (conda-forge's does, through OpenBLAS), which GraphBLAS then shares + expected = expected or images[0] + assert os.path.samefile(images[0], expected), result assert os.path.exists(later) and os.path.samefile(later, expected), result