feat(toolchain): add the coverage hub to the deps of the executables
diff --git a/news/4415.fixed.md b/news/4415.fixed.md new file mode 100644 index 0000000..0218af6 --- /dev/null +++ b/news/4415.fixed.md
@@ -0,0 +1,4 @@ +(pypi) {obj}`pip.parse` with an `X.Y` {attr}`pip.parse.python_version` is no +longer ignored when the toolchains are only registered for `X.Y.Z` versions +that are not the default ones for the `X.Y` version. The interpreter of the +latest of them is used.
diff --git a/python/private/BUILD.bazel b/python/private/BUILD.bazel index ad3a2c2..8e46f60 100644 --- a/python/private/BUILD.bazel +++ b/python/private/BUILD.bazel
@@ -183,6 +183,21 @@ visibility = NOT_ACTUALLY_PUBLIC, ) +# The `coverage` package of the toolchains that are configured with +# `python.toolchain(configure_coverage_tool = True)`. It is only resolved when +# collecting coverage for the target config, so that it is not fetched for +# regular builds. +alias( + name = "toolchain_coverage_if_target_config", + actual = select({ + ":is_target_coverage_enabled": "@pythons_hub//:coverage", + "//conditions:default": "//python/private:sentinel", + }), + # Not actually public. Only public because it's an implicit dependency of + # rules built via py_binary_rule_builder() / py_test_rule_builder(). + visibility = NOT_ACTUALLY_PUBLIC, +) + config_setting( name = "is_target_coverage_enabled", flag_values = { @@ -732,6 +747,7 @@ ":py_internal", ":py_runtime_info", ":reexports", + ":sentinel_impl", "@bazel_skylib//lib:dicts", "@bazel_skylib//lib:paths", "@bazel_skylib//rules:common_settings",
diff --git a/python/private/py_executable.bzl b/python/private/py_executable.bzl index c14e74f..1d08683 100644 --- a/python/private/py_executable.bzl +++ b/python/private/py_executable.bzl
@@ -271,6 +271,10 @@ "_python_version_flag": lambda: attrb.Label( default = labels.PYTHON_VERSION, ), + "_toolchain_coverage": lambda: attrb.Label( + default = "//python/private:toolchain_coverage_if_target_config", + providers = [PyInfo], + ), "_uncachable_version_file": lambda: attrb.Label( default = "//python/private:uncachable_version_file", allow_files = True, @@ -928,14 +932,16 @@ The {obj}`--coverage` flag, which can also be set per target via `config_settings`, takes precedence over the `coverage_tool` of the Python - runtime, which is handled by the bootstrap. + runtime, which is handled by the bootstrap. If neither is set, then the + `coverage` package of the toolchains that are configured with + `python.toolchain(configure_coverage_tool = True)` is used. Args: ctx: {type}`ctx` the rule ctx. Returns: {type}`struct` with attributes: - * dep: {type}`Target | None` the `coverage` flag target to add to the + * dep: {type}`Target | None` the `coverage` target to add to the dependencies of the executable. * rcfiles: {type}`depset[File]` the files that may contain the `.coveragerc` files to merge. They are filtered when the bootstrap is @@ -943,6 +949,12 @@ """ target = ctx.attr._coverage_flag if ( + SentinelInfo in target and + not _maybe_get_runtime_from_ctx(ctx).coverage_tool + ): + target = ctx.attr._toolchain_coverage + + if ( not ctx.configuration.coverage_enabled or _is_tool_config(ctx) or SentinelInfo in target
diff --git a/python/private/py_runtime_rule.bzl b/python/private/py_runtime_rule.bzl index 21ecd2a..ee7aaa5 100644 --- a/python/private/py_runtime_rule.bzl +++ b/python/private/py_runtime_rule.bzl
@@ -21,6 +21,7 @@ load(":py_internal.bzl", "py_internal") load(":py_runtime_info.bzl", "DEFAULT_STUB_SHEBANG", "PyRuntimeInfo") load(":reexports.bzl", "BuiltinPyRuntimeInfo") +load(":sentinel_impl.bzl", "SentinelInfo") _py_builtins = py_internal _HAS_COVERAGE_FLAG = "//python/private:has_coverage_flag" @@ -61,7 +62,9 @@ Args: coverage_enabled: {type}`bool` whether the build is collecting coverage. coverage_tool: {type}`File | None` the runtime's coverage entry point. - has_coverage_flag: {type}`bool` whether `--coverage` is set to a target. + has_coverage_flag: {type}`bool` whether `--coverage` is set to a target + or the `coverage` package of the toolchain is added to the + dependencies of the executables. label: {type}`Label` the `py_runtime` being analyzed. Returns: @@ -183,7 +186,8 @@ coverage_enabled = ctx.configuration.coverage_enabled, coverage_tool = coverage_tool, has_coverage_flag = ( - ctx.attr._has_coverage_flag[0][BuildSettingInfo].value + ctx.attr._has_coverage_flag[0][BuildSettingInfo].value or + SentinelInfo not in ctx.attr._toolchain_coverage ), label = ctx.label, ) @@ -498,6 +502,11 @@ "_python_version_flag": attr.label( default = labels.PYTHON_VERSION, ), + # Whether the `coverage` package is added to the dependencies of + # the executables, see `python.toolchain.configure_coverage_tool`. + "_toolchain_coverage": attr.label( + default = "@pythons_hub//:has_coverage", + ), }, ), )
diff --git a/python/private/pypi/hub_builder.bzl b/python/private/pypi/hub_builder.bzl index df0c487..4498ece 100644 --- a/python/private/pypi/hub_builder.bzl +++ b/python/private/pypi/hub_builder.bzl
@@ -452,7 +452,22 @@ name = _host_interpreter_name(version_str) if name in available_interpreters: return name - return None + + if python_version != _major_minor_version(python_version): + return None + + # The toolchains may be pinned to `X.Y.Z` versions that are not the default + # one for the `X.Y` version, e.g. `3.12.3`. Use the latest one of them. + prefix = "python_{}_".format(python_version.replace(".", "_")) + suffix = "_host" + found, found_patch = None, -1 + for name in available_interpreters: + if not (name.startswith(prefix) and name.endswith(suffix)): + continue + patch = name[len(prefix):-len(suffix)] + if patch.isdigit() and int(patch) > found_patch: + found, found_patch = name, int(patch) + return found def _detect_interpreter(self, pip_attr, python_version, full_python_version): python_interpreter_target = pip_attr.python_interpreter_target
diff --git a/python/private/python.bzl b/python/private/python.bzl index 685d93b..3069c01 100644 --- a/python/private/python.bzl +++ b/python/private/python.bzl
@@ -264,6 +264,10 @@ # list[str] of the repo names for host compatible repos all_host_compatible_repo_names = [] + # list[str] of the full python versions that use the `coverage` package + # from the `rules_python_coverage` pip hub. + coverage_python_versions = [] + # Create the underlying python_repository repos that contain the # python runtimes and their toolchain implementation definitions. for i, toolchain_info in enumerate(py.toolchains): @@ -303,6 +307,9 @@ if not register_result.impl_repos: continue + if kwargs["register_coverage_tool"]: + coverage_python_versions.append(full_python_version) + host_platforms = {} for repo_name, (platform_name, platform_info) in register_result.impl_repos.items(): toolchain_impls.append(struct( @@ -462,6 +469,7 @@ toolchain_python_versions = toolchain_python_versions, toolchain_set_python_version_constraints = toolchain_set_python_version_constraints, host_compatible_repo_names = sorted(all_host_compatible_repo_names), + coverage_python_versions = coverage_python_versions, default_python_version = py.default_python_version, minor_mapping = py.config.minor_mapping, python_versions = list(py.config.default["tool_versions"].keys()), @@ -1261,12 +1269,17 @@ Whether or not to configure the default coverage tool provided by `rules_python` for the compatible toolchains. -The coverage tool is the `coverage` package from the `@rules_python_coverage` pip hub. See -{doc}`/coverage` for more details. +The `coverage` package is added to the dependencies of the {obj}`py_test` and {obj}`py_binary` +targets when coverage is collected, unless the {flag}`--coverage` flag or the +{attr}`py_runtime.coverage_tool` is set. It is locked per `X.Y` Python version, so it is used +for all of the `X.Y.Z` toolchains if this is set for any of them. See {doc}`/coverage` for +more details. :::{versionchanged} VERSION_NEXT_FEATURE -The coverage tool is the `coverage` package from the `@rules_python_coverage` pip hub, which -supports all of the platforms configured with {obj}`pip.default`. +The `coverage` package comes from a pip hub that is locked with a `uv.lock` file in +`rules_python`, which has the wheels for all of the platforms of the toolchains. It is +added to the dependencies of the executables instead of being the +{attr}`py_runtime.coverage_tool` of the toolchains. ::: """, ),
diff --git a/python/private/python_register_toolchains.bzl b/python/private/python_register_toolchains.bzl index 3e93c2c..6fed29b 100644 --- a/python/private/python_register_toolchains.bzl +++ b/python/private/python_register_toolchains.bzl
@@ -72,7 +72,8 @@ python_version: {type}`str` the Python version. register_toolchains: {type}`bool` Whether or not to register the downloaded toolchains. register_coverage_tool: {type}`bool` Whether or not to register the - downloaded coverage tool to the toolchains. + downloaded coverage tool to the toolchains. Only used with + WORKSPACE. set_python_version_constraint: {type}`bool` When set to `True`, `target_compatible_with` for the toolchains will include a version constraint. @@ -168,7 +169,11 @@ default = None, ), ) - if register_coverage_tool and coverage_tool == None: + + # NOTE: With bzlmod the `coverage` package from the + # `rules_python_coverage` pip hub is added to the dependencies of the + # executables instead, see `python.toolchain.configure_coverage_tool`. + if register_coverage_tool and coverage_tool == None and not bzlmod_toolchain_call: coverage_tool = coverage_dep( name = "{name}_{platform}_coverage".format( name = name,
diff --git a/python/private/pythons_hub.bzl b/python/private/pythons_hub.bzl index e2c06ed..dc27ecc 100644 --- a/python/private/pythons_hub.bzl +++ b/python/private/pythons_hub.bzl
@@ -20,6 +20,10 @@ load(":text_util.bzl", "render") load(":toolchains_repo.bzl", "toolchain_suites_content") +# The `coverage` package from the `rules_python_coverage` pip hub, which is +# configured in the `MODULE.bazel` file of `rules_python`. +_COVERAGE = Label("@rules_python_coverage//coverage") + def _have_same_length(*lists): if not lists: fail("expected at least one list") @@ -43,9 +47,63 @@ visibility = ["@rules_python//:__subpackages__"], ) +# The `coverage` package that is added to the dependencies of the executables +# when coverage is collected, see `python.toolchain.configure_coverage_tool`. +alias( + name = "coverage", + actual = {coverage}, + # Not actually public. Only public because it's an implicit dependency of + # the rules built via py_binary_rule_builder() / py_test_rule_builder(). + visibility = ["//visibility:public"], +) + +# Whether `:coverage` is set. Used by `py_runtime`, which cannot depend on +# `:coverage`, because it would be a dependency cycle. +alias( + name = "has_coverage", + actual = {has_coverage}, + # Not actually public. Only public because it's an implicit dependency of + # `py_runtime`. + visibility = ["//visibility:public"], +) + +filegroup(name = "_has_coverage") + {toolchains} """ +def _coverage_select(rctx, actual): + """Render a select that is `actual` if the Python version has `coverage`. + + The `rules_python_coverage` hub only has an entry per `X.Y` version, so + all of the `X.Y.Z` versions are matched if any of them is configured. + + Args: + rctx: {type}`repository_ctx` the repository ctx. + actual: {type}`str` the label to use for the configured versions. + + Returns: + {type}`str` the rendered label or `select`. + """ + sentinel = "@@{}//python/private:sentinel".format( + rctx.attr._rules_python_workspace.repo_name, + ) + conditions = {} + for python_version in rctx.attr.coverage_python_versions: + major_minor, _, _ = python_version.rpartition(".") + if major_minor in rctx.attr.minor_mapping: + python_version = major_minor + conditions["@@{}//python/config_settings:is_python_{}".format( + rctx.attr._rules_python_workspace.repo_name, + python_version, + )] = actual + if not conditions: + return render.str(sentinel) + + return render.select( + dict(sorted(conditions.items())) | {"//conditions:default": sentinel}, + ) + def _hub_build_file_content(rctx): # Verify a precondition. If these don't match, then something went wrong. if not _have_same_length( @@ -82,6 +140,8 @@ return _HUB_BUILD_FILE_TEMPLATE.format( toolchains = toolchain_suites_content(toolchains), + coverage = _coverage_select(rctx, str(_COVERAGE)), + has_coverage = _coverage_select(rctx, ":_has_coverage"), rules_python = rctx.attr._rules_python_workspace.repo_name, ) @@ -151,6 +211,9 @@ """, implementation = _hub_repo_impl, attrs = { + "coverage_python_versions": attr.string_list( + doc = "The Python versions in the `X.Y.Z` format that use the `coverage` package from the `rules_python_coverage` pip hub.", + ), "default_python_version": attr.string( doc = "Default Python version for the build in `X.Y` or `X.Y.Z` format.", mandatory = True,
diff --git a/tests/pypi/hub_builder/hub_builder_tests.bzl b/tests/pypi/hub_builder/hub_builder_tests.bzl index dd7cd65..5647797 100644 --- a/tests/pypi/hub_builder/hub_builder_tests.bzl +++ b/tests/pypi/hub_builder/hub_builder_tests.bzl
@@ -751,6 +751,57 @@ _tests.append(_test_skip_python_version_without_host_interpreter) +def _test_python_version_with_patch_version_host_interpreters(env): + # The toolchains can be pinned to patch versions that are not the default + # ones for the minor version. Then the minor version uses the interpreter + # of the latest of them instead of being skipped. + builder = hub_builder( + env, + available_interpreters = { + "python_3_15_10_host": "unit_test_interpreter_target_3_15_10", + "python_3_15_9_host": "unit_test_interpreter_target_3_15_9", + "python_3_16_1_host": "unit_test_interpreter_target_3_16_1", + }, + minor_mapping = { + "3.15": "3.15.19", + }, + ) + builder.pip_parse( + mocks.mctx( + mock_files = { + "requirements_3_15.txt": """ +simple==0.0.1 --hash=sha256:deadbeef +""", + }, + os_name = "linux", + arch_name = "amd64", + ), + _parse( + hub_name = "pypi", + python_version = "3.15", + requirements_lock = "requirements_3_15.txt", + ), + ) + pypi = builder.build() + + pypi.whl_map().contains_exactly({ + "simple": { + "pypi_315_simple": [ + whl_config_setting(version = "3.15"), + ], + }, + }) + pypi.whl_libraries().contains_exactly({ + "pypi_315_simple": { + "config_load": "@pypi//:config.bzl", + "dep_template": "@pypi//{name}:{target}", + "python_interpreter_target": "unit_test_interpreter_target_3_15_10", + "requirement": "simple==0.0.1 --hash=sha256:deadbeef", + }, + }) + +_tests.append(_test_python_version_with_patch_version_host_interpreters) + def _test_simple_with_markers(env): sub_tests = { ("osx", "aarch64"): "torch==2.4.1 --hash=sha256:deadbeef",