From a5848ed09d87f769eb6b1ffb914c570c8ca1223a Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:32:50 -0500 Subject: [PATCH 1/2] Link extensions against a library shipped by another installed package A library artifact may name an installed Python package with python-package instead of a manifest. hatch-rs takes the library from that package's lib/ and headers from include/, links the consumer against it, and adds an rpath to the sibling package in bundled mode. In external mode the package is ignored and the library resolves as before, so a conda recipe builds unchanged. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- README.md | 21 ++++ hatch_rs/structs.py | 44 +++++++-- .../Cargo.lock | 14 +++ .../Cargo.toml | 21 ++++ .../package_link_project/__init__.py | 20 ++++ .../pyproject.toml | 54 +++++++++++ .../src/lib.rs | 12 +++ hatch_rs/tests/test_projects.py | 38 +++++++- hatch_rs/tests/test_structs.py | 95 +++++++++++++++++++ 9 files changed, 309 insertions(+), 10 deletions(-) create mode 100644 hatch_rs/tests/test_project_python_extension_package_library/Cargo.lock create mode 100644 hatch_rs/tests/test_project_python_extension_package_library/Cargo.toml create mode 100644 hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py create mode 100644 hatch_rs/tests/test_project_python_extension_package_library/pyproject.toml create mode 100644 hatch_rs/tests/test_project_python_extension_package_library/src/lib.rs diff --git a/README.md b/README.md index a1754c7..efdf01a 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,27 @@ library. Header, symbol, and validation-command checks still run against the external file, and the artifact manifest records it with role `external-library`. +A library that another installed wheel ships is declared with `python-package` +instead of `manifest`: hatch-rs locates that package in the build environment +(so the producer must be a build dependency) and takes the library from its +`lib/` and the headers from its `include/`. In `bundled` mode the extension +gets an rpath to the sibling package (`$ORIGIN/../fsspec_rs/lib` below), on +the assumption that both wheels install into one site-packages; on Windows +the consumer package imports the producer first so its `lib/` is on the DLL +search path. In `external` mode the package is ignored and the library is +resolved as above, which is what a conda recipe wants. + +```toml +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "fsspec" +python-package = "fsspec_rs" + +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "fsspec_kafka" +destination = "fsspec_kafka/{python_extension_name}" +links = ["fsspec"] +``` + ### ABI validation and artifact metadata `cdylib` artifacts can validate the copied C ABI library before the wheel is diff --git a/hatch_rs/structs.py b/hatch_rs/structs.py index 293fd27..3524927 100644 --- a/hatch_rs/structs.py +++ b/hatch_rs/structs.py @@ -5,6 +5,7 @@ from ctypes import CDLL from dataclasses import dataclass from glob import glob +from importlib.util import find_spec from json import dumps, loads from os import environ from os.path import relpath @@ -93,6 +94,7 @@ class ExternalLibrary: library_dir: Path include_dir: Path | None link_name: str + package: str | None = None WINDOWS_TARGETS = { @@ -650,6 +652,11 @@ class RustArtifactConfig(BaseModel): library_root: Path | None = Field( default=None, alias="library-root", description="Prefix with lib/ and include/ for this library in external mode." ) + python_package: str | None = Field( + default=None, + alias="python-package", + description="Installed Python package shipping this library under lib/ and include/; linked from there instead of built.", + ) import_library_destination: str | None = Field( default=None, alias="import-library-destination", @@ -736,6 +743,12 @@ def validate_header_symbol_prefix(self) -> RustArtifactConfig: raise ValueError(f"Artifact '{self.name}' must set expected-headers when using header-symbol-prefix.") return self + @model_validator(mode="after") + def validate_python_package(self) -> RustArtifactConfig: + if self.python_package is not None and (not self.name or self.manifest is not None or self.destination is not None): + raise ValueError(f"Artifact '{self.name}' with python-package must set name and no manifest or destination.") + return self + @dataclass(frozen=True) class PlannedArtifact: @@ -1171,9 +1184,10 @@ def generate(self): self._linked_names = self._linked_library_names(artifacts) self._external_libraries = {} for artifact in artifacts: - if artifact.name in self._linked_names and self._resolved_library_source in ("static", "direct"): + library = artifact.python_package is not None or artifact.name in self._linked_names + if library and self._resolved_library_source in ("static", "direct"): continue - if artifact.name in self._linked_names and self._resolved_library_source == "external": + if library and (artifact.python_package is not None or self._resolved_library_source == "external"): planned_artifact = self._plan_external_library(artifact, global_target=global_target) elif self._is_generated_artifact(artifact): planned_artifact = self._build_command_artifact_plan(artifact, global_target=global_target) @@ -1242,13 +1256,13 @@ def _library_env(self, artifact: RustArtifactConfig, resolved_target: ResolvedTa environment = {} for link in artifact.links: key = sub(r"[^A-Za-z0-9]", "_", link).upper() - if self._resolved_library_source == "bundled": - environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(self._bundled_library_dir(link, resolved_target)) - elif self._resolved_library_source == "external": - external = self._external_libraries[link] + external = self._external_libraries.get(link) + if external is not None: environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(external.library_dir) if external.include_dir is not None: environment[f"HATCH_RS_LIBRARY_{key}_INCLUDE_DIR"] = str(external.include_dir) + elif self._resolved_library_source == "bundled": + environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(self._bundled_library_dir(link, resolved_target)) return environment def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: ResolvedTarget) -> list[str]: @@ -1263,8 +1277,10 @@ def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: Res args.extend(("-C", f"link-arg=-Wl,-soname,{shared_library}")) if mode in ("static", "direct"): return args + origin = "$ORIGIN" if platform == "linux" else "@loader_path" for link in artifact.links: - if mode == "bundled": + external = self._external_libraries.get(link) + if external is None: library_dir = self._bundled_library_dir(link, resolved_target) link_name = f"{link}.dll" if platform == "win32" else link args.extend(("-L", f"native={library_dir}", "-l", f"dylib={link_name}")) @@ -1273,12 +1289,14 @@ def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: Res self._destination_directory(self._artifact_by_name(link), resolved_target), self._destination_directory(artifact, resolved_target), ) - origin = "$ORIGIN" if platform == "linux" else "@loader_path" rpath = origin if relative == "." else f"{origin}/{Path(relative).as_posix()}" args.extend(("-C", f"link-arg=-Wl,-rpath,{rpath}")) else: - external = self._external_libraries[link] args.extend(("-L", f"native={external.library_dir}", "-l", f"dylib={external.link_name}")) + if external.package is not None and platform in ("linux", "darwin"): + # both packages sit in one site-packages, so the rpath walks from the extension to the sibling package + relative = relpath(Path(*external.package.split(".")) / "lib", self._destination_directory(artifact, resolved_target)) + args.extend(("-C", f"link-arg=-Wl,-rpath,{origin}/{Path(relative).as_posix()}")) return args def _pkg_config_variable(self, artifact: RustArtifactConfig, variable: str) -> Path: @@ -1298,9 +1316,16 @@ def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: s name = self._artifact_name(artifact) label = self._artifact_label(artifact) root = environ.get("HATCH_RS_LIBRARY_ROOT") or (str(artifact.library_root) if artifact.library_root is not None else None) + package = artifact.python_package if self._resolved_library_source == "bundled" else None if root: prefix = _resolve_path(root, base=Path(self.path)) library_dir, include_dir = prefix / "lib", prefix / "include" + elif package: + spec = find_spec(package) + if spec is None or not spec.submodule_search_locations: + raise ValueError(f"Artifact '{label}' package '{package}' is not installed in the build environment.") + prefix = Path(next(iter(spec.submodule_search_locations))) + library_dir, include_dir = prefix / "lib", prefix / "include" elif artifact.pkg_config: library_dir = self._pkg_config_variable(artifact, "libdir") include_dir = self._pkg_config_variable(artifact, "includedir") @@ -1333,6 +1358,7 @@ def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: s library_dir=library_dir, include_dir=include_dir if include_dir.is_dir() else None, link_name=link_name, + package=package, ) def _plan_external_library(self, artifact: RustArtifactConfig, *, global_target: str | None) -> PlannedArtifact: diff --git a/hatch_rs/tests/test_project_python_extension_package_library/Cargo.lock b/hatch_rs/tests/test_project_python_extension_package_library/Cargo.lock new file mode 100644 index 0000000..835d156 --- /dev/null +++ b/hatch_rs/tests/test_project_python_extension_package_library/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "c_abi_library" +version = "0.1.0" + +[[package]] +name = "package_link_extension_py" +version = "0.1.0" +dependencies = [ + "c_abi_library", +] diff --git a/hatch_rs/tests/test_project_python_extension_package_library/Cargo.toml b/hatch_rs/tests/test_project_python_extension_package_library/Cargo.toml new file mode 100644 index 0000000..60a7d5e --- /dev/null +++ b/hatch_rs/tests/test_project_python_extension_package_library/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "package_link_extension_py" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +name = "package_link_extension" +path = "src/lib.rs" +crate-type = ["cdylib"] + +[dependencies] +c_abi_library = { path = "../test_project_python_extension_c_abi_library/rust", optional = true } + +[features] +default = ["capi"] +capi = [] +direct = ["dep:c_abi_library"] + +[profile.release] +panic = "abort" diff --git a/hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py b/hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py new file mode 100644 index 0000000..cd37750 --- /dev/null +++ b/hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from ctypes import CDLL, c_int +from pathlib import Path +from sys import platform + +# The producer package adds its lib/ directory to the DLL search path on Windows and, +# elsewhere, loads the library this extension links by its SONAME or install name. +import c_abi_bundle_project + +_PACKAGE_DIR = Path(__file__).resolve().parent +_EXTENSION_SUFFIX = ".pyd" if platform == "win32" else ".so" + +_EXTENSION = CDLL(str(_PACKAGE_DIR / f"package_link_extension{_EXTENSION_SUFFIX}")) +_EXTENSION.package_link_extension_library_answer.restype = c_int + + +def library_answer() -> int: + """The other package's library answer, reached through this extension.""" + return int(_EXTENSION.package_link_extension_library_answer()) diff --git a/hatch_rs/tests/test_project_python_extension_package_library/pyproject.toml b/hatch_rs/tests/test_project_python_extension_package_library/pyproject.toml new file mode 100644 index 0000000..1a70d03 --- /dev/null +++ b/hatch_rs/tests/test_project_python_extension_package_library/pyproject.toml @@ -0,0 +1,54 @@ +[build-system] +requires = ["hatchling>=1.20"] +build-backend = "hatchling.build" + +[project] +name = "hatch-rs-test-project-python-extension-package-library" +description = "Python extension linking a C ABI library shipped by another installed package" +version = "0.1.0" +requires-python = ">=3.9" +dependencies = [ + "hatchling>=1.20", + "hatch-rs", +] + +[tool.hatch.build] +artifacts = [ + "package_link_project/*.dll", + "package_link_project/*.dylib", + "package_link_project/*.pyd", + "package_link_project/*.so", + "package_link_project/lib/*.json", +] + +[tool.hatch.build.sources] +src = "/" + +[tool.hatch.build.targets.sdist] +packages = ["package_link_project"] + +[tool.hatch.build.targets.wheel] +packages = ["package_link_project"] + +[tool.hatch.build.hooks.hatch-rs] +verbose = true +path = "." +module = "package_link_project" +target-dir = "isolated" +artifact-manifest = true + +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "c_abi_library" +python-package = "c_abi_bundle_project" + +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "package_link_extension" +manifest = "Cargo.toml" +destination = "package_link_project/{python_extension_name}" +links = ["c_abi_library"] + +[tool.hatch.build.hooks.hatch-rs.artifacts.library-source-features] +bundled = ["capi"] +external = ["capi"] +static = ["direct"] +direct = ["direct"] diff --git a/hatch_rs/tests/test_project_python_extension_package_library/src/lib.rs b/hatch_rs/tests/test_project_python_extension_package_library/src/lib.rs new file mode 100644 index 0000000..142de8e --- /dev/null +++ b/hatch_rs/tests/test_project_python_extension_package_library/src/lib.rs @@ -0,0 +1,12 @@ +#[cfg(feature = "capi")] +extern "C" { + fn c_abi_library_answer() -> i32; +} + +#[cfg(feature = "direct")] +use c_abi_library::c_abi_library_answer; + +#[no_mangle] +pub extern "C" fn package_link_extension_library_answer() -> i32 { + unsafe { c_abi_library_answer() } +} diff --git a/hatch_rs/tests/test_projects.py b/hatch_rs/tests/test_projects.py index a493a6d..544a4f6 100644 --- a/hatch_rs/tests/test_projects.py +++ b/hatch_rs/tests/test_projects.py @@ -3,7 +3,7 @@ from os import environ, listdir, pathsep from os.path import dirname from pathlib import Path -from shutil import copy2, rmtree, which +from shutil import copy2, copytree, rmtree, which from subprocess import PIPE, STDOUT, check_call, run from sys import executable, modules, path, platform, version_info from zipfile import ZipFile @@ -337,6 +337,42 @@ def test_python_extension_links_external_c_abi_library(self, tmp_path): env["DYLD_LIBRARY_PATH" if platform == "darwin" else "LD_LIBRARY_PATH"] = str(prefix / "lib") _assert_c_abi_answers(env, shared=False) + def test_python_extension_links_library_from_installed_package(self, tmp_path): + """A second package links the library the first one ships, as fsspec-kafka does with fsspec-rs.""" + consumer_root = Path("hatch_rs/tests") / "test_project_python_extension_package_library" + consumer_package = consumer_root / "package_link_project" + rmtree(consumer_root / "dist", ignore_errors=True) + rmtree(consumer_package / "lib", ignore_errors=True) + for artifact in consumer_package.glob("package_link_extension*"): + artifact.unlink() + _clean_c_abi_project() + check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=C_ABI_PROJECT, env=_subprocess_env()) + + # the producer is importable in the build environment, as an installed build dependency would be + env = _subprocess_env() + env["PYTHONPATH"] = f"{C_ABI_PROJECT.resolve()}{pathsep}{env['PYTHONPATH']}" + check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=consumer_root, env=env) + + extension_name = "package_link_extension.pyd" if platform == "win32" else "package_link_extension.so" + assert (consumer_package / extension_name).exists() + assert list((consumer_package / "lib").iterdir()) == [consumer_package / "lib" / "hatch-rs-artifacts.json"] + records = loads((consumer_package / "lib" / "hatch-rs-artifacts.json").read_text())["artifacts"] + library = [record for record in records if record["name"] == "c_abi_library"] + assert [record["role"] for record in library] == ["external-library"] + assert Path(library[0]["source"]).is_relative_to(C_ABI_PACKAGE.resolve()) + assert "c_abi_library_answer" not in exported_symbols(consumer_package / extension_name) + + # install both packages side by side and call through to the producer's library + site = tmp_path / "site" + copytree(C_ABI_PACKAGE, site / "c_abi_bundle_project") + copytree(consumer_package, site / "package_link_project") + env["PYTHONPATH"] = str(site) + check_call([executable, "-c", "import package_link_project as m; assert m.library_answer() == 7"], cwd=tmp_path, env=env) + if platform != "win32": + # the rpath alone finds the sibling package's library, without the producer being imported first + code = f"from ctypes import CDLL; assert CDLL({str(site / 'package_link_project' / extension_name)!r}).package_link_extension_library_answer() == 7" + check_call([executable, "-c", code], cwd=tmp_path, env=env) + def test_python_extension_compiles_c_abi_library_in_direct_mode(self): _clean_c_abi_project() env = _subprocess_env() diff --git a/hatch_rs/tests/test_structs.py b/hatch_rs/tests/test_structs.py index 98cf75f..52d2302 100644 --- a/hatch_rs/tests/test_structs.py +++ b/hatch_rs/tests/test_structs.py @@ -1135,6 +1135,101 @@ def test_build_plan_external_mode_missing_library_fails_clearly(tmp_path, monkey _linked_plan(tmp_path, "x86_64-unknown-linux-gnu").generate() +def _package_plan(tmp_path, monkeypatch, target): + site = tmp_path / "site" + (site / "ffi_package" / "lib").mkdir(parents=True) + (site / "ffi_package" / "include").mkdir() + (site / "ffi_package" / "__init__.py").write_text("") + (site / "ffi_package" / "lib" / "libproject_ffi.so").write_bytes(b"") + (site / "ffi_package" / "lib" / "libproject_ffi.dylib").write_bytes(b"") + (site / "ffi_package" / "lib" / "project_ffi.dll").write_bytes(b"") + monkeypatch.syspath_prepend(str(site)) + return HatchRustBuildPlan( + module="project", + path=tmp_path, + target=target, + artifacts=[ + {"name": "project_ffi", "python-package": "ffi_package"}, + { + "name": "project_py", + "destination": "project/{python_extension_name}", + "links": ["project_ffi"], + "library-source-features": {"bundled": ["capi"], "external": ["capi"], "direct": ["direct"]}, + }, + ], + ) + + +def test_build_plan_links_library_from_installed_package(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + plan = _package_plan(tmp_path, monkeypatch, "x86_64-unknown-linux-gnu") + (extension,) = plan.generate() + + library_dir = tmp_path / "site" / "ffi_package" / "lib" + assert plan._artifact_plans[0].invocation is None + assert plan._artifact_plans[0].external_library.library == library_dir / "libproject_ffi.so" + assert "--features capi --no-default-features" in extension + args = plan._artifact_plans[1].invocation.args + assert f"native={library_dir}" in args + assert "dylib=project_ffi" in args + assert "link-arg=-Wl,-rpath,$ORIGIN/../ffi_package/lib" in args + env = plan._artifact_plans[1].invocation.env + assert env["HATCH_RS_LIBRARY_PROJECT_FFI_DIR"] == str(library_dir) + assert env["HATCH_RS_LIBRARY_PROJECT_FFI_INCLUDE_DIR"] == str(library_dir.parent / "include") + + +def test_build_plan_package_library_rpath_on_darwin(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + (extension,) = _package_plan(tmp_path, monkeypatch, "aarch64-apple-darwin").generate() + + assert "-C link-arg=-Wl,-rpath,@loader_path/../ffi_package/lib" in extension + + +def test_build_plan_package_library_external_mode_ignores_package(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HATCH_RS_LIBRARY_SOURCE", "external") + prefix = tmp_path / "prefix" + (prefix / "lib").mkdir(parents=True) + (prefix / "lib" / "libproject_ffi.so").write_bytes(b"") + monkeypatch.setenv("HATCH_RS_LIBRARY_ROOT", str(prefix)) + plan = _package_plan(tmp_path, monkeypatch, "x86_64-unknown-linux-gnu") + (extension,) = plan.generate() + + assert plan._artifact_plans[0].external_library.library == prefix / "lib" / "libproject_ffi.so" + assert "rpath" not in extension + + +def test_build_plan_package_library_direct_mode_skips_library(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HATCH_RS_LIBRARY_SOURCE", "direct") + (extension,) = _package_plan(tmp_path, monkeypatch, "x86_64-unknown-linux-gnu").generate() + + assert "--features direct --no-default-features" in extension + assert "-l dylib" not in extension + + +def test_build_plan_package_library_missing_package_fails_clearly(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + plan = HatchRustBuildPlan( + module="project", + path=tmp_path, + target="x86_64-unknown-linux-gnu", + artifacts=[{"name": "project_ffi", "python-package": "no_such_package_for_hatch_rs"}], + ) + with pytest.raises(ValueError, match="not installed"): + plan.generate() + + +def test_artifact_python_package_requires_name_without_manifest(): + with pytest.raises(ValueError, match="python-package"): + RustArtifactConfig(**{"python-package": "ffi_package"}) + with pytest.raises(ValueError, match="python-package"): + RustArtifactConfig(**{"name": "project_ffi", "python-package": "ffi_package", "manifest": "rust/Cargo.toml"}) + + def test_build_plan_rejects_unknown_library_source(tmp_path, monkeypatch): monkeypatch.setenv("HATCH_RS_LIBRARY_SOURCE", "vendored") with pytest.raises(ValueError, match="HATCH_RS_LIBRARY_SOURCE"): From 327b93b3b66efefc69763d041e500f06de61f8cc Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:36:15 -0500 Subject: [PATCH 2/2] Suppress the fixture's cross-package import for ty Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- .../package_link_project/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py b/hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py index cd37750..9f7467d 100644 --- a/hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py +++ b/hatch_rs/tests/test_project_python_extension_package_library/package_link_project/__init__.py @@ -6,7 +6,7 @@ # The producer package adds its lib/ directory to the DLL search path on Windows and, # elsewhere, loads the library this extension links by its SONAME or install name. -import c_abi_bundle_project +import c_abi_bundle_project # ty: ignore[import-not-found] _PACKAGE_DIR = Path(__file__).resolve().parent _EXTENSION_SUFFIX = ".pyd" if platform == "win32" else ".so"