diff --git a/news/pypi-index-order.fixed.md b/news/pypi-index-order.fixed.md new file mode 100644 index 0000000000..c0bd1da7f5 --- /dev/null +++ b/news/pypi-index-order.fixed.md @@ -0,0 +1,3 @@ +(pypi) With extra index URLs, the first index that has a package is now +picked in the declared order, not in the order of cached results +([#4581](https://github.com/bazel-contrib/rules_python/issues/4581)). diff --git a/python/private/pypi/simpleapi_download.bzl b/python/private/pypi/simpleapi_download.bzl index b5f7032b0a..77fc7ade07 100644 --- a/python/private/pypi/simpleapi_download.bzl +++ b/python/private/pypi/simpleapi_download.bzl @@ -170,7 +170,11 @@ def _get_dist_urls(ctx, *, default_index, index_urls, index_url_overrides, sourc results[index_url] = download.wait() found_on_index = {} - for index_url, result in results.items(): + + # Walk the indexes in the declared order. The `results` dict has cache hits + # inserted before downloads, so its order depends on what is cached. + for index_url in index_urls: + result = results[index_url] for pkg in sources: if pkg in found_on_index: # We have already found the package, skip searching for it in diff --git a/tests/pypi/simpleapi_download/simpleapi_download_tests.bzl b/tests/pypi/simpleapi_download/simpleapi_download_tests.bzl index dfa33ebe65..b269f2e2b8 100644 --- a/tests/pypi/simpleapi_download/simpleapi_download_tests.bzl +++ b/tests/pypi/simpleapi_download/simpleapi_download_tests.bzl @@ -90,6 +90,40 @@ def _test_simple(env): _tests.append(_test_simple) +def _test_index_order_does_not_depend_on_cache(env): + """The first index in the declared order wins, even if a later one is cached.""" + + def read_simpleapi(ctx, url, versions, attr, cache, get_auth, block, parse_index): + _ = ctx, attr, cache, get_auth, versions, block # buildifier: disable=unused-variable + if parse_index: + result = struct(success = True, output = {"foo": "/foo/"}) + + # The default index is a cache hit and the extra index is a download + return result if "main" in url else struct(wait = lambda: result) + + return struct( + output = struct(sdists = {}, whls = {}, hashes_by_version = {}), + success = True, + ) + + contents = simpleapi_download( + ctx = mocks.mctx(), + attr = struct( + index_url_overrides = {}, + index_url = "https://main.com", + extra_index_urls = ["https://extra.com"], + sources = {"foo": None}, + envsubst = [], + ), + cache = pypi_cache(), + parallel_download = True, + read_simpleapi = read_simpleapi, + ) + + env.expect.that_str(contents["foo"].index_url).equals("https://extra.com/foo/") + +_tests.append(_test_index_order_does_not_depend_on_cache) + def _test_index_overrides(env): calls = [] fails = []