Repository navigation
[build] Retry PyPI 502s when fetching pip dependencies - #65518
sai-miduthuri wants to merge 4 commits into
Conversation
3513410 to
1cb0b66
Compare
rules_python's whl_library shells out to pip rather than using Bazel's downloader, so wheel fetches bypass Bazel's retry and mirroring settings entirely. The pip that rules_python pins (22.0.4) leaves 502 out of urllib3's status_forcelist, so a transient files.pythonhosted.org 502 fails a repository fetch on the first attempt with no retry at all, and one failed wheel takes down the build through the dependency cascade. pip 24.0 added 502 to that list upstream, so pin pip 24.0. pip 24 also drops pip._internal.cli.progress_bars.BAR_TYPES, which the pip-tools 6.6.0 that rules_python pins alongside it imports, so move pip-tools to 7.4.1 as well. 7.4.1 replaced pep517 with build + pyproject_hooks and needs packaging, none of which rules_python provides, so declare those three and wire them into _requirements_py310_deps. All five versions are the set rules_python itself pairs with pip 24.0 / pip-tools 7.4.1 upstream. Also raise the retry count from the default 5 (~8s of backoff) to 9 (~2 minutes) so a brief PyPI outage is ridden out instead of failing the build. --retries covers the pip invoked by whl_library, which runs with --isolated and so ignores PIP_* variables; PIP_RETRIES covers the separate, non-isolated pip that setuptools spawns for setup_requires when a locked package ships only an sdist. pip-compile output is unchanged by the pip-tools upgrade: compiling the same inputs under pip 22.0.4/pip-tools 6.6.0 and pip 24.0/pip-tools 7.4.1 produces byte-identical pins. Only the generated header comment differs, so release/requirements_py310.txt will pick up a cosmetic header change the next time it is regenerated. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: sai.miduthuri <[email protected]>
1cb0b66 to
0c65bef
Compare
elliot-barn
left a comment
There was a problem hiding this comment.
Looks good. Can you add a timeout along side this?
| environment = {"PIP_RETRIES": "9"}, | ||
| extra_pip_args = ["--retries=9"], | ||
| python_interpreter_target = python310, | ||
| requirements_lock = "//release:requirements_py310.txt", |
There was a problem hiding this comment.
can add a timeout = 1800, to pip_parse here
There was a problem hiding this comment.
Added in 6cf4d2e — thanks, this turned out to be load-bearing rather than just prudent.
Worth recording why: timeout is in common_attrs, which both pip_repository_attrs and whl_library_attrs merge in, and pip_repository.bzl:156 forwards it explicitly (# pass quiet and timeout args through to child repos. → "--timeout", str(rctx.attr.timeout)). So it bounds every generated whl_library, not just the parse step — which is the part that makes it matter here.
Without it the retry change is partly self-defeating: nine retries can spend ~2 minutes on backoff sleeps before the transfer makes progress, and a degraded PyPI is slow as well as flaky, so the 600s default can expire mid-retry and fail exactly the fetch the retries were meant to save.
Verified against the vendored copy Bazel actually resolves (rules_python-0.9.0 via the maybe() in rules_foreign_cc/foreign_cc/repositories.bzl) — byte-identical to the upstream 0.9.0 tag.
There was a problem hiding this comment.
As discussed: even with 9 retries and the back off retries this won't exceed the 600s default
There was a problem hiding this comment.
You were right — nine exponential retries top out at ~127s, so 600s was never going to bind.
Checking that turned up the underlying problem, though: raising --retries doesn't buy coverage, because pip's backoff is exponential and urllib3 caps each sleep at 120s, so 50 retries would run ~5050s. And neither the shape nor backoff_factor is reachable from pip's CLI. So 3ce017a patches pypi__pip to use a constant schedule jittered over 6–12s and raises the count to 50: 49 sleeps, 294–588s, bounded under 600s. Measured gaps against an always-502 index, the jitter rationale, and the rest are in the PR description.
I've kept the 1800s timeout, now justified by numbers rather than by "PyPI is slow": 588s of backoff worst case, plus up to pip's 15s socket timeout on each of 50 attempts. Happy to drop it back to the 600s default and halve the retry count to fit instead — your call.
There was a problem hiding this comment.
Follow-up: the retry count wasn't the binding constraint either. pip retries down the connection it already holds, and Fastly picks the edge node per connection, so all 50 attempts were hitting the same node — which is the bad-node failure mode in pypi/support#11876. Retrying harder was never going to help.
60d2365 sends Connection: close so each attempt redials and re-draws a node. Measured against files.pythonhosted.org: eight separate connections to one pinned address reached seven distinct edge nodes, while six requests over a single kept-alive socket all landed on the same one. Pinning a "good" address doesn't work — all four anycast addresses share a POP and a node pool. Full measurements are in the PR description.
Timeout is still 1800; the offer to size the retry budget to 600s instead stands.
pip_parse's timeout defaults to 600s and is forwarded to every generated whl_library, so it bounds each package's pip invocation rather than just the parse step. Nine retries can spend ~2 minutes on backoff sleeps before the transfer makes progress, and a degraded PyPI is slow as well as flaky, so the default can expire mid-retry and fail the fetch the retries were added to save. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: sai.miduthuri <[email protected]>
Premerge failures today were spread across four different pip surfaces, and three of them are ordinary pip/uv invocations inside CI image builds that had no retry configuration at all: - lint: clang_format -- `pip install -c python/requirements_compiled.txt clang-format` in the forge container, OSError / max retries exceeded. - wanda: wheel py3.11 -- `pip install cython setuptools` under the manylinux interpreters, retried and exhausted. - wanda: corebuild-py3.12, llm cpu tests -- uv, "Failed to download everett==3.1.0 / Request failed after 3 retries / 502 Bad Gateway". Set PIP_RETRIES and UV_HTTP_RETRIES on the five roots of the image graph so all 23 descendant images inherit them, at build time and at test time: - base.test.Dockerfile (ubuntu:jammy) -- root of oss-ci-base_test, and via base.build / base.ml the ancestor of most test images. - base.gpu.Dockerfile (nvidia/cuda) -- separate root for the gpu images. - forge.Dockerfile (ubuntu:22.04) -- runs the CI job commands themselves, so it also covers ad hoc pip installs in ci/ scripts. - manylinux.Dockerfile (quay.io/pypa/manylinux2014) -- the wheel builds. - windows.build.Dockerfile (rayproject/buildenv:windows). uv is included because its default is only 3 retries, which was observed being exhausted on a 502. Older uv releases ignore UV_HTTP_RETRIES rather than erroring, and pip needs >= 24.0 for 502 itself to be retryable. The Bazel whl_library surface is deliberately not addressed here: it runs pip with --isolated, so PIP_* never reaches it, and rules_python 0.9.0's vendored pip 22.0.4 omits 502 from urllib3's status_forcelist regardless of retry count. That needs the pip 24.0 pin in #65518. Signed-off-by: elliot-barn <[email protected]>
Nine retries only covered ~8 seconds of the ~2 minutes the previous commit claimed, because pip's schedule is exponential: raising the count mostly buys longer sleeps rather than more coverage. urllib3 caps a single sleep at 120s, so a 50-retry budget on the upstream schedule runs for ~5050s, which no fetch timeout can accommodate. Exponential backoff is also the wrong shape here -- it spends its early retries before an outage has plausibly cleared, and its late ones asleep in 2-minute blocks. Neither the shape of the schedule nor backoff_factor is reachable from pip's command line: pip hardcodes backoff_factor=0.25 where it builds its urllib3.Retry, and the urllib3 it vendors (1.26.17) has no jitter support at all, since Retry.backoff_jitter only exists in urllib3 2.x. So patch pip to override get_backoff_time() with a constant schedule jittered over 6-12s, and raise the retry count to 50. That makes the count buy wall-clock linearly: 50 retries is 49 sleeps, so 294-588s, ~440s typical, bounded under 600s. The jitter also spreads out the many wheel fetches Bazel runs in parallel, which on a fixed schedule would fail together, sleep for identical durations and re-converge on an already-degraded origin all at once. Measured against a local index that always returns 502, with --retries=4: stock pip 24.0 waits 0.5s, 1.0s, 2.0s, while the patched pip waits 9.4s, 8.3s, 6.5s. Both leave the first retry immediate, so a lone blip still costs nothing. The 1800s timeout stays and is now load-bearing for a concrete reason rather than a speculative one: the retry budget alone reaches 588s, and each of the 50 attempts can additionally burn pip's 15s socket timeout when the failure mode is a hang rather than a fast 502, so the 600s default cannot hold the schedule. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: sai.miduthuri <[email protected]>
The previous commit fixed when pip retries but not where the retries go. urllib3 drains a failed response specifically so the socket can go back to the pool, then recurses on the same connection pool, so all 50 attempts travel down one TCP connection. Fastly selects the edge node per connection, so every retry is pinned to the node that answered first. Against a single bad node -- the failure mode described in pypi/support#11876 -- no retry count helps at all, because the requests never go anywhere else. Send Connection: close so each attempt redials and re-draws a node. Measured against files.pythonhosted.org through the x-served-by header: eight separate connections to one pinned address reached seven distinct edge nodes, while six requests sent over a single kept-alive socket all landed on the same one. All four anycast addresses behind the name share a POP and a node pool, so pinning a "good" address does not avoid a bad node; only reconnecting does. Verified against a local always-502 index speaking HTTP/1.1 keep-alive: with --retries=5 every attempt now comes from a new source port, and the jittered 6-12s spacing is unchanged. The patch now covers both the schedule and the destination, so rename it to match. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: sai.miduthuri <[email protected]>
|
Closing this. The approach here does not fix the problem, and it should not land. Recording what the investigation established, since the diagnosis outlived the fix. What the root cause actually isNot a missing retry. Measured over 20 fresh connections to one address: 18 × That reframed the fix from "retry for longer" to "retry somewhere else", which is what the last commit did: Why it still isn't enoughIt only reaches one fetch path. In premerge 72103 with the redial in place, 142 jobs passed and the three
One path in five. The change patches a vendored third-party wheel from The image pips being newer than the 24.0 pinned here is the decisive part. They already retry 502s and still fail, so this was never a stale-pip problem that a version pin resolves: every pip retries in place. Covering the remaining paths would mean patching pip inside each image as well, which is the wrong thing for this repo to carry. Why the network-level alternatives are not a substituteRejecting the bad address with What would fix itAn index that is not the public CDN. Every client honours index configuration — Leaving the branch in place for reference. The full measurements are in the description above. |
## Description `files.pythonhosted.org` has been returning intermittent 502s (pypi/support#11895). The Read the Docs build installs `doc/requirements-doc.lock.txt` in a single pip invocation, so one failed wheel fetch fails the whole build. pip's default is 5 retries on an exponential backoff, which exhausts after roughly 8 seconds of sleeping — well short of the observed fault duration. This raises it to 10 for that build only. **Why a config file rather than `PIP_RETRIES`.** The install is `python.install`, run by Read the Docs rather than by us, so there is no command line of ours to add a flag to. Environment variables do not help either: each entry under `build.jobs` runs in its own shell, so an `export` in one does not reach the install step. pip reads `~/.config/pip/pip.conf` on every invocation in the build environment, including RTD's own, which makes it the one place that covers it. **Why only the retry count.** Every failure observed in this family is an immediate 502 response, not a hang, so raising `timeout` would only lengthen the worst case without making any individual fetch more likely to succeed. Worth setting expectations: this is a mitigation, not a fix. Measurements on a CI build of the same fault showed in-process retries have limited power against it — the client stays pinned to the same CDN edge across attempts — so this narrows the window rather than closing it. The structural fix is a caching index in front of PyPI, which is being wired up for CI in #65571 but cannot serve Read the Docs, since RTD builders run outside the network where that mirror lives. ## Related issues Upstream cause: pypi/support#11895. Not a duplicate: no open PR touches `.readthedocs.yaml`; #65571 and #65518 address the same upstream fault on the CI side and do not affect RTD builds. ## Testing - `.readthedocs.yaml` parses and the job keys are as intended: `post_checkout`, `pre_install`, `build`, with `python.install` untouched. - The `pre_install` snippet is valid shell (`bash -n`) and deliberately avoids the constructs the RTD job runner is documented in this file as mishandling: no `printf` with escape formats, no backslash escapes, no shell comments inside the block. - It `cat`s the file it writes, so the build log will show the effective config and confirm the step ran. - Not verified end to end: whether RTD's install step picks the config up in their environment. That is what the first build on this PR will show, and the failure mode if it does not is simply the status quo. AI assistance (Claude Code) was used for this change. Signed-off-by: elliot-barn <[email protected]>
## Description `files.pythonhosted.org` returns intermittent 502s (pypi/support#11895). Ray CI is hit disproportionately because a single job cold-fetches ~50 wheels concurrently, so it samples the fault dozens of times per job, and `rules_python` shells out to pip inside `whl_library`, where one 502 fails the repository rule and the build with it. **Retries do not fix this, which is why this PR contains none.** Measured on premerge build 72083: pip with `--retries=50` and a jittered 6-12s backoff exhausted on a single wheel with `too many 502 error responses`, while 47 of 62 *job-level* retries in the same build passed. urllib3 retries reuse the pooled connection and the already-resolved address, and anycast keeps every attempt on the same bad Fastly edge, so fifty in-process attempts are not fifty independent attempts. What fixes it is not asking that edge — i.e. a cache in front of PyPI, which fetches each `(package, version)` once and serves it from S3 afterwards. Four commits, in dependency order: 1. **Make the index an environment property.** Valueless `--repo_env` for `PIP_INDEX_URL`, `PIP_EXTRA_INDEX_URL`, `PIP_TRUSTED_HOST` and `RULES_PYTHON_PIP_ISOLATED` in `.bazelrc`, and those plus the `UV_*` equivalents forwarded into nested containers by `ci/ray_ci/container.py`. `RULES_PYTHON_PIP_ISOLATED` is load-bearing: `whl_library` runs pip with `--isolated`, which otherwise makes it ignore every `PIP_*` variable. The passthrough lives in the repo's `.bazelrc` rather than a generated one because every bazel invocation reads it, including the nested ones `ci/ray_ci:test_in_docker` spawns, which a `--config` flag on a step's command line never reaches. 2. **Stop the lock files overriding it.** 97 of the 99 files under `python/deplocks` opened with `--index-url https://pypi.org/simple`, and a requirements file's index URL beats both the environment and the command line. The `--extra-index-url` and `--find-links` entries for PyTorch, libtpu and PyG stay: those are not PyPI, so nothing else supplies them at install time. 3. **Resolve through the mirror when the job can reach it.** The forge image carries `ci/pypi_index_proxy.py` and a `profile.d` script that probes the mirror and picks a mode. ### Why a proxy and not just an index URL One `pip install` is two requests: the project page, governed by `--index-url`, and the artifact, governed by the URL written in that page's body. PyPI's simple index hands out **absolute** `files.pythonhosted.org` URLs, so pointing `--index-url` at a path-prefix byte cache mirrors the metadata request and leaves the multi-megabyte download on the origin that is returning the 502s. The proxy rewrites those file URLs so both hops transit the mirror. Wheels do not stream through the proxy process — clients fetch them straight from the mirror at the rewritten URLs — and the `#sha256=` fragments hash artifact content, not URLs, so hash verification is unaffected. ### Fail-open, deliberately The probe accepts a mode only after a real index fetch succeeds through it, and exports nothing otherwise, leaving pip and uv on public PyPI. That check hits the mirror rather than only the local process because `/healthz` never touches the mirror: a healthy proxy in front of an unreachable mirror answers every request with a 502, which is strictly worse than no proxy. Build 72083 exercised exactly that path — `mirror unreachable from this agent` — and the build continued. ## Related issues Upstream cause: pypi/support#11895. Not a duplicate: commits 1-2 are #65562 and commit 3 is #65563, opened as standalone reviewable units before the mirror existed. If reviewers prefer, land those two first and this rebases down to the single mirror commit. #65518 and #65538 raise pip/uv retry tolerance; they are complementary and deliberately excluded here, per the measurement above. ## Additional information **Depends on infrastructure:** the mirror is a per-VPC deployment in the Ray CI account, so `https://mirror.ci.ray.io` only resolves inside the Buildkite stack VPCs. `RAYCI_PYPI_MIRROR_URL` overrides the default for a fleet that runs its own. **Deliberately out of scope:** image builds still resolve from PyPI. The `pip` and `uv` invocations in `ci/docker/*.Dockerfile` run in a separate BuildKit context that cannot reach a proxy bound on the forge container's loopback, and a per-job address would change wanda's content-addressed cache key on every build and rebuild every image. That needs a build-reachable index, which is a follow-up. `ci/pypi_index_proxy.py` is vendored from a public gist, recorded at the top of the file along with the one local edit (the default mirror URL). ## Testing - `PYTHONPATH=.:release python -m pytest -q ci/ray_ci/test_linux_tester_container.py ci/ray_ci/test_container.py ci/ray_ci/test_tester.py ci/ray_ci/test_linux_container.py ci/ray_ci/test_windows_container.py` — 24 passed. - `bazel test //ci/raydepsets:test_cli` — passed, including `test_diff_lock_files_up_to_date`, the generated-equals-committed invariant for the deplock change. - Bazel 7.5.0: verified that a valueless `common --repo_env=NAME` reaches `rctx.os.environ` in a repository rule and reads unset when the variable is unset, and that `bazel info`/`query`/`version` do not reject the `common` lines. - `docker run --env NAME` with NAME unset leaves it absent in the container, not empty — which is what keeps the default path unchanged. - The mechanism as a whole ran on premerge 72083 (on a superset branch): the probe logged its verdict, fell back to PyPI because that fleet has no route to the mirror at the time, and the build proceeded. - `pre-commit run --files` over every changed file, shellcheck included. AI assistance (Claude Code) was used for this change. --------- Signed-off-by: elliot-barn <[email protected]> Signed-off-by: Elliot Barnwell <[email protected]>
…ject#65574) ## Description `files.pythonhosted.org` has been returning intermittent 502s (pypi/support#11895). The Read the Docs build installs `doc/requirements-doc.lock.txt` in a single pip invocation, so one failed wheel fetch fails the whole build. pip's default is 5 retries on an exponential backoff, which exhausts after roughly 8 seconds of sleeping — well short of the observed fault duration. This raises it to 10 for that build only. **Why a config file rather than `PIP_RETRIES`.** The install is `python.install`, run by Read the Docs rather than by us, so there is no command line of ours to add a flag to. Environment variables do not help either: each entry under `build.jobs` runs in its own shell, so an `export` in one does not reach the install step. pip reads `~/.config/pip/pip.conf` on every invocation in the build environment, including RTD's own, which makes it the one place that covers it. **Why only the retry count.** Every failure observed in this family is an immediate 502 response, not a hang, so raising `timeout` would only lengthen the worst case without making any individual fetch more likely to succeed. Worth setting expectations: this is a mitigation, not a fix. Measurements on a CI build of the same fault showed in-process retries have limited power against it — the client stays pinned to the same CDN edge across attempts — so this narrows the window rather than closing it. The structural fix is a caching index in front of PyPI, which is being wired up for CI in ray-project#65571 but cannot serve Read the Docs, since RTD builders run outside the network where that mirror lives. ## Related issues Upstream cause: pypi/support#11895. Not a duplicate: no open PR touches `.readthedocs.yaml`; ray-project#65571 and ray-project#65518 address the same upstream fault on the CI side and do not affect RTD builds. ## Testing - `.readthedocs.yaml` parses and the job keys are as intended: `post_checkout`, `pre_install`, `build`, with `python.install` untouched. - The `pre_install` snippet is valid shell (`bash -n`) and deliberately avoids the constructs the RTD job runner is documented in this file as mishandling: no `printf` with escape formats, no backslash escapes, no shell comments inside the block. - It `cat`s the file it writes, so the build log will show the effective config and confirm the step ran. - Not verified end to end: whether RTD's install step picks the config up in their environment. That is what the first build on this PR will show, and the failure mode if it does not is simply the status quo. AI assistance (Claude Code) was used for this change. Signed-off-by: elliot-barn <[email protected]>
## Description `files.pythonhosted.org` returns intermittent 502s (pypi/support#11895). Ray CI is hit disproportionately because a single job cold-fetches ~50 wheels concurrently, so it samples the fault dozens of times per job, and `rules_python` shells out to pip inside `whl_library`, where one 502 fails the repository rule and the build with it. **Retries do not fix this, which is why this PR contains none.** Measured on premerge build 72083: pip with `--retries=50` and a jittered 6-12s backoff exhausted on a single wheel with `too many 502 error responses`, while 47 of 62 *job-level* retries in the same build passed. urllib3 retries reuse the pooled connection and the already-resolved address, and anycast keeps every attempt on the same bad Fastly edge, so fifty in-process attempts are not fifty independent attempts. What fixes it is not asking that edge — i.e. a cache in front of PyPI, which fetches each `(package, version)` once and serves it from S3 afterwards. Four commits, in dependency order: 1. **Make the index an environment property.** Valueless `--repo_env` for `PIP_INDEX_URL`, `PIP_EXTRA_INDEX_URL`, `PIP_TRUSTED_HOST` and `RULES_PYTHON_PIP_ISOLATED` in `.bazelrc`, and those plus the `UV_*` equivalents forwarded into nested containers by `ci/ray_ci/container.py`. `RULES_PYTHON_PIP_ISOLATED` is load-bearing: `whl_library` runs pip with `--isolated`, which otherwise makes it ignore every `PIP_*` variable. The passthrough lives in the repo's `.bazelrc` rather than a generated one because every bazel invocation reads it, including the nested ones `ci/ray_ci:test_in_docker` spawns, which a `--config` flag on a step's command line never reaches. 2. **Stop the lock files overriding it.** 97 of the 99 files under `python/deplocks` opened with `--index-url https://pypi.org/simple`, and a requirements file's index URL beats both the environment and the command line. The `--extra-index-url` and `--find-links` entries for PyTorch, libtpu and PyG stay: those are not PyPI, so nothing else supplies them at install time. 3. **Resolve through the mirror when the job can reach it.** The forge image carries `ci/pypi_index_proxy.py` and a `profile.d` script that probes the mirror and picks a mode. ### Why a proxy and not just an index URL One `pip install` is two requests: the project page, governed by `--index-url`, and the artifact, governed by the URL written in that page's body. PyPI's simple index hands out **absolute** `files.pythonhosted.org` URLs, so pointing `--index-url` at a path-prefix byte cache mirrors the metadata request and leaves the multi-megabyte download on the origin that is returning the 502s. The proxy rewrites those file URLs so both hops transit the mirror. Wheels do not stream through the proxy process — clients fetch them straight from the mirror at the rewritten URLs — and the `#sha256=` fragments hash artifact content, not URLs, so hash verification is unaffected. ### Fail-open, deliberately The probe accepts a mode only after a real index fetch succeeds through it, and exports nothing otherwise, leaving pip and uv on public PyPI. That check hits the mirror rather than only the local process because `/healthz` never touches the mirror: a healthy proxy in front of an unreachable mirror answers every request with a 502, which is strictly worse than no proxy. Build 72083 exercised exactly that path — `mirror unreachable from this agent` — and the build continued. ## Related issues Upstream cause: pypi/support#11895. Not a duplicate: commits 1-2 are ray-project#65562 and commit 3 is ray-project#65563, opened as standalone reviewable units before the mirror existed. If reviewers prefer, land those two first and this rebases down to the single mirror commit. ray-project#65518 and ray-project#65538 raise pip/uv retry tolerance; they are complementary and deliberately excluded here, per the measurement above. ## Additional information **Depends on infrastructure:** the mirror is a per-VPC deployment in the Ray CI account, so `https://mirror.ci.ray.io` only resolves inside the Buildkite stack VPCs. `RAYCI_PYPI_MIRROR_URL` overrides the default for a fleet that runs its own. **Deliberately out of scope:** image builds still resolve from PyPI. The `pip` and `uv` invocations in `ci/docker/*.Dockerfile` run in a separate BuildKit context that cannot reach a proxy bound on the forge container's loopback, and a per-job address would change wanda's content-addressed cache key on every build and rebuild every image. That needs a build-reachable index, which is a follow-up. `ci/pypi_index_proxy.py` is vendored from a public gist, recorded at the top of the file along with the one local edit (the default mirror URL). ## Testing - `PYTHONPATH=.:release python -m pytest -q ci/ray_ci/test_linux_tester_container.py ci/ray_ci/test_container.py ci/ray_ci/test_tester.py ci/ray_ci/test_linux_container.py ci/ray_ci/test_windows_container.py` — 24 passed. - `bazel test //ci/raydepsets:test_cli` — passed, including `test_diff_lock_files_up_to_date`, the generated-equals-committed invariant for the deplock change. - Bazel 7.5.0: verified that a valueless `common --repo_env=NAME` reaches `rctx.os.environ` in a repository rule and reads unset when the variable is unset, and that `bazel info`/`query`/`version` do not reject the `common` lines. - `docker run --env NAME` with NAME unset leaves it absent in the container, not empty — which is what keeps the default path unchanged. - The mechanism as a whole ran on premerge 72083 (on a superset branch): the probe logged its verdict, fell back to PyPI because that fleet has no route to the mirror at the time, and the build proceeded. - `pre-commit run --files` over every changed file, shellcheck included. AI assistance (Claude Code) was used for this change. --------- Signed-off-by: elliot-barn <[email protected]> Signed-off-by: Elliot Barnwell <[email protected]>
Description
rules_python'swhl_libraryshells out to pip rather than using Bazel's downloader, so wheel fetches bypass Bazel's retry settings entirely —--experimental_repository_downloader_retriesnever sees them. The pip thatrules_pythonpins (22.0.4) leaves502out of urllib3'sstatus_forcelist:so a transient
files.pythonhosted.org502 fails a repository fetch on the first attempt with zero retries, and one failed wheel takes down the whole build through the dependency cascade. Recent examples onray-project/release: builds 104355 and 104354, both dying onwhl_library py_deps_py310_googleapis_common_protos failed: ... HTTP error 502.pip 24.0 added 502 to that list upstream. But making 502 retryable is not sufficient on its own, because pip retries down the connection it already holds and Fastly picks the edge node per connection, so every retry lands on the node that just failed. This PR therefore does three things: makes 502 retryable, makes the retry schedule usable, and makes the retries go somewhere else.
WORKSPACE— pinspypi__pip24.0 andpypi__pip_tools7.4.1, declared beforepip_install_dependencies()sorules_python'smaybe()calls no-op and these win.WORKSPACE— addspypi__build,pypi__packaging,pypi__pyproject_hooks, which pip-tools 7.4.1 needs andrules_pythondoes not provide.thirdparty/patches/pip-retry-backoff-and-redial.patch(new) — two changes to pip's retry behaviour, applied topypi__pipviapatches/patch_args: a constant schedule jittered over 6–12s in place of the exponential one, andConnection: closeso every attempt redials and re-draws a CDN node.WORKSPACE— raises retries from the default 5 to 50 onpip_parse, and the fetch timeout from 600s to 1800s so the schedule can actually be spent.release/BUILD.bazel— wires the three new repositories into_requirements_py310_deps.Every version pin is an unmodified upstream wheel. The one modification to a third-party dependency is the retry patch above, which touches a single pip file and is explained in detail below.
Related issues
No Ray issue. The upstream cause is tracked at pypi/support#11876 — a bad node in the CDN fronting
files.pythonhosted.org— which is what the redial half of this change is aimed at.I searched for prior art before opening this: open PRs matching
pypi__pip,status_forcelist,pip retries 502,whl_library 502, andWORKSPACE pip, plus open issues matchingpip 502 pythonhosted. The only open PRs touching pip dependencies are unrelated dependabot version bumps (#65465, #63734, #62380, #61887), so this is not duplicating work already in flight.Additional information
Why pip-tools moves too
pip 24 drops
pip._internal.cli.progress_bars.BAR_TYPES, which pip-tools 6.6.0 imports at module scope inpiptools/repositories/pypi.py, so//release:requirements_py310.updateand//release:requirements_py310_testwould fail to import. pip-tools 7.4.1 fixes that.I checked whether
BAR_TYPESwas merely the first of many breaks. It is not. Of the 36pip._internalsymbols pip-tools touches, only three flag on pip 24.0 and two are non-issues:req_tracker— pip-tools already gates this itself (if PIP_VERSION[:2] <= (22, 0)), so pip 24 correctly takes thebuild_trackerbranch.DEV_PKGS— only inpiptools/sync.py(pip-sync), which this compile path never imports.BAR_TYPES— the only real blocker.pip-tools 7.4.1 replaced its
pep517dependency withbuild+pyproject_hooks, andbuildneedspackaging, hence the three added repositories. All five versions are the setrules_pythonitself pairs with pip 24.0 / pip-tools 7.4.1 upstream, rather than an ad-hoc combination.Why an override rather than upgrading pip
pypi__pip's version is a hardcoded entry in rules_python's_RULE_DEPS(python/pip_install/repositories.bzl); no attribute onpip_parseorpip_install_dependencies()exposes it, so shadowing the repository beforepip_install_dependencies()runs is the only lever short of changing rules_python.Upgrading pip for the hermetic interpreter is not an alternative. The
python_register_toolchains()CPython build ships its own pip (also 22.0.4), butwhl_libraryputs thepypi__*repositories onPYTHONPATH, which precedessite-packagesonsys.path, sopypi__pipshadows it and the interpreter's copy is never used. The failure tracebacks show this directly — they resolvesetuptools/installer.pyout ofexternal/pypi__setuptools, not the interpreter's bundled setuptools.The underlying cause is that rules_python here is 0.9.0, from July 2022, which is where the pip 22.0.4 pin comes from. Ray never declares rules_python; it arrives transitively via
ray_deps_build_all()→rules_foreign_cc_dependencies(), pinned atrules_foreign_cc/foreign_cc/repositories.bzl:85. That is also amaybe(), so pinning rules_python explicitly beforeray_deps_build_all()would take precedence and is the real fix: a modern rules_python pins pip 24.0 itself, making all five entries here unnecessary, and adds theexperimental_index_urlpath that fetches wheels through Bazel's downloader — where--experimental_repository_downloader_retriesand downloader URL rewriting would finally apply to them, and where pip's own retry schedule stops governing a wheel download at all, so the patch goes away with it.That upgrade rewrites
whl_library, repository naming and the generatedrequirements.bzl, and interacts with the__PYTHON_RULES_MIGRATION_DO_NOT_USE_WILL_BREAK__tags already on Ray's Python targets, so it needs to be its own change. The WORKSPACE comment records this and says to delete the block as part of it.Why retrying in place cannot work
pip retries down the connection it already has, so every attempt reaches the same CDN node. urllib3's status-retry path calls
response.drain_conn()— whose docstring says "Unread data in the HTTPResponse connection blocks the connection from being released back to the pool" — then recurses intoself.urlopenon the sameHTTPConnectionPool, whose_get_conn()hands back the pooled connection. A 502 is a successful connect and a valid HTTP response, so nothing ever marks that socket bad.That is fatal here, because the failure is a single bad edge node (pypi/support#11876) and Fastly draws the node per connection. 20 fresh connections to one address, reading Fastly's
x-served-by:200cache-pae2080021,…22,…23,…25,…26,…27502cache-pae2080020— and only ever this nodeThe failures are also missing the shield hop the successes carry —
cache-iad-kcgs7200167-IAD, cache-pae20800NN-PAEagainst a barecache-pae2080020— so that edge node is answering 502 without the request reaching the shield at all.The node is therefore roughly a 1-in-10 draw, and the two behaviours diverge completely:
That is the observed CI failure in one line: a ~10% unhealthy-node rate becomes a certain build failure purely because pip pins itself to the first draw.
Connection: closeturns it back into a coin flip that retrying can actually resolve.Why not pin a "good" address instead. Address choice does matter — the addresses behind
files.pythonhosted.orgmap to different POPs, and in the run above only199.232.184.223reached PAE, where the bad node lives, while the other five reached BFI and were clean on every request. So an/etc/hostsor--add-hostpin would have dodged this particular incident. It is the more fragile lever, though: the DNS answer set rotates — three different sets inside an hour while investigating this (146.75.40.223, four151.101.x.223addresses, and199.232.184.223) — the address-to-POP mapping is Fastly's to change, and a pin has to be revisited whenever either moves. Redialling needs no knowledge of which address, POP or node is unhealthy.urllib3's own address failover substitutes for neither:
create_connectiondoes iterate everygetaddrinforesult, but only advances insideexcept socket.error, which a 502 never raises, so the first address in the list is used for every attempt.Why the retry schedule is patched, and why 50 retries
Raising
--retriesalone does not buy coverage, because pip's schedule is exponential and urllib3 caps a single sleep at 120s. Computed against the vendored urllib3 1.26.17:So the count mostly buys longer sleeps rather than more coverage, and at 50 the schedule runs for ~84 minutes — longer than any fetch timeout can accommodate. The shape is wrong for this failure mode in both directions: the early retries are spent before an outage has plausibly cleared, and the late ones sleep in 2-minute blocks, so only a small part of the budget lands inside the recovery window.
Neither the shape nor
backoff_factoris reachable from pip's command line. pip hardcodesbackoff_factor=0.25where it builds itsurllib3.Retry(pip/_internal/network/session.py), and the urllib3 it vendors is 1.26.17, which implements exponential backoff only —Retry.backoff_jitterexists only in urllib3 2.x.--retriessetstotaland nothing else. Hence the patch, which subclassesurllib3.Retryand overridesget_backoff_time()to returnrandom.uniform(6.0, 12.0)— equal jitter around a 12s nominal wait. It preserves urllib3's "no sleep before the first retry of a sequence" semantics, so a lone blip still recovers immediately at no cost.That makes the retry count buy wall-clock linearly: 50 retries is 49 sleeps, so 294–588s, ~440s typical, bounded under 600s.
The jitter is not cosmetic. Bazel fetches many wheels concurrently, each in its own pip process. On a fixed schedule they fail at the same instant, sleep for identical durations and re-converge on the origin together, so every retry round is a thundering herd against a service that is already degraded.
Measured against a local index that always returns 502, same interpreter,
--retries=4, gaps between requests as observed server-side:And simulated against pip's real vendored urllib3, 2000 draws per retry index: constant 6.00–12.00s at retry #2, #10 and #49 alike, where upstream gives 0.5s / 120s / 120s. All 2000 draws distinct. Over a full 50-retry budget, 500 trials span 408–480s (mean 441s) against upstream's flat 5048s.
Why the timeout is raised
timeoutis incommon_attrs, which bothpip_repository_attrsandwhl_library_attrsmerge in, andpip_repository.bzl:156forwards it explicitly (# pass quiet and timeout args through to child repos.→"--timeout", str(rctx.attr.timeout)). It is also passed as therctx.executetimeout in_whl_library_impl, so it is a wall-clock bound on every generatedwhl_library's pip invocation, not just on the parse step.The retry budget alone reaches 588s at worst, and each of the 50 attempts can additionally burn pip's 15s socket timeout when the failure mode is a hang rather than a fast 502. So the 600s default cannot hold the schedule, and 1800s covers the full backoff, the per-attempt timeouts, and a slow transfer afterwards.
Lock file impact
None in this PR. Compiling the same inputs under pip 22.0.4 / pip-tools 6.6.0 and pip 24.0 / pip-tools 7.4.1, through the same
piptools.scripts.compile:clientrypointrules_python'spip_compile.pyuses, produces byte-identical pins. Only the generated header comment differs:so
release/requirements_py310.txtwill pick up a cosmetic header change the next time it is regenerated.release/ray_release/byod/requirements_byod_3.1{1,2}.txtcarry similar headers but are not affected — the.updatetargets their headers reference no longer exist, and raydepsets generates from the.infiles viauv pip compile. The retry patch cannot affect lock output at all: it changes only how long pip waits between failed requests.Scope
This is a mitigation, not a complete fix, and the remaining gaps are worth naming.
It now covers the two failure modes that have actually been breaking builds: a transient 502, retryable at all only since the pip 24.0 pin, and a single bad CDN node, escapable only since the redial. What it still does not cover:
setup_requiresbuild dependencies are still fetched live from PyPI, unpinned and unhashed. Wheels-only locking would be the structural fix and is out of scope here.Both premerge runs on this branch walked into real outages, which is where several of the measurements above came from. 72008 (nine exponential retries, ~2 minutes of budget) lost 33 jobs. 72031 (fifty jittered retries, ~7 minutes, but still retrying in place) lost fewer and died the same way, on
async_timeoutwithtoo many 502 error responses. In both, the retries were demonstrably spent — urllib3 emits that message only when 502 is in the forcelist and the budget is exhausted, where pip 22.0.4 would have failed on the first response — and in 72031 the fetch sat silent for 410s beforehand, against a predicted 294–588s. 72031 is what prompted looking at where the retries were going rather than only how many there were.Tests run
-p1to pristine pip 24.0,py_compile, no line over 88 chars--retries=4--retries=5x-served-by199.232.184.223, across two packagescache-pae2080020and nothing elsecurl --resolve199.232.184.223(PAE) returned any 502; the other five (BFI) were 6/6 clean, TLS valid throughout_ConstantJitteredRetry.get_backoff_time()against pip's real vendored urllib3, 2000 draws at retry #2/#10/#49Retry.sleep()routes through the overridebazel fetch @pypi__pip//:libstatus_forcelist=[500, 502, 503, 520, 527]and Bazel applied the patch. Run against the previous commit; since then only the patch's contents and filename changed, and the label form matches the other//thirdparty/patches:entries already inbazel/ray_deps_setup.bzlbazel sync --only=py_deps_py310+ regenerated@py_deps_py310//:requirements.bzl'extra_pip_args': ['--retries=50'],'environment': {'PIP_RETRIES': '50'},'timeout': 1800, splatted into everywhl_librarybyinstall_deps()bazel fetch @py_deps_py310_pybuildkite//:pkg, with the repo deleted first to force a real pip run (this is the repo that 502'd in premerge 72008)--retries=50bazel build //release:requirements_py310.updatepip-compileon identical inputs under both pip/pip-tools pairsbazel test //release:requirements_py310_testpre-commit run --files WORKSPACE release/BUILD.bazel thirdparty/patches/pip-retry-backoff-and-redial.patchbuildifier --mode=check --lint=warn WORKSPACEBUILD/BUILD.bazel, soWORKSPACEis never linted by it//release:requirements_py310_testfails locally both before and after this change, becauserelease/requirements-doc.txtpinssphinx==8.2.3andsphinx_design==0.7.0, both of which declareRequires-Python: >=3.11, while this lock targets Python 3.10. The checked-in lock still has the oldersphinx==7.3.7/sphinx-design==0.5.0, so it is stale and cannot be regenerated at 3.10 under any pip-tools version. The reported symptom differs between versions only because pip-tools 6.6.0 uses pip's legacy resolver and 7.4.1 uses the backtracking resolver, so they name a different first-unsatisfiable pin (sphinx_design==0.7.0vssphinx==8.2.3). This looks like a genuine pre-existing inconsistency worth fixing separately; it is out of scope here.AI assistance
This change was developed with AI assistance (Claude Code). The investigation — identifying the missing 502 in the forcelist, pinning the pip 24.0 boundary, auditing pip-tools'
pip._internalusage to size the upgrade, establishing that the backoff shape is unreachable from pip's CLI, working out that retries were pinned to a single CDN node and measuring the node diversity that fixes it, and confirming lock output is unchanged — was AI-assisted and then verified with the commands above.