Skip to content

[build] Retry PyPI 502s when fetching pip dependencies - #65518

Closed
sai-miduthuri wants to merge 4 commits into
masterfrom
pip-retry-502
Closed

sai-miduthuri wants to merge 4 commits into
masterfrom
pip-retry-502

Conversation

@sai-miduthuri

@sai-miduthuri sai-miduthuri commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

rules_python's whl_library shells out to pip rather than using Bazel's downloader, so wheel fetches bypass Bazel's retry settings entirely — --experimental_repository_downloader_retries never sees them. The pip that rules_python pins (22.0.4) leaves 502 out of urllib3's status_forcelist:

status_forcelist=[500, 503, 520, 527],

so a transient files.pythonhosted.org 502 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 on ray-project/release: builds 104355 and 104354, both dying on whl_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 — pins pypi__pip 24.0 and pypi__pip_tools 7.4.1, declared before pip_install_dependencies() so rules_python's maybe() calls no-op and these win.
  • WORKSPACE — adds pypi__build, pypi__packaging, pypi__pyproject_hooks, which pip-tools 7.4.1 needs and rules_python does not provide.
  • thirdparty/patches/pip-retry-backoff-and-redial.patch (new) — two changes to pip's retry behaviour, applied to pypi__pip via patches/patch_args: a constant schedule jittered over 6–12s in place of the exponential one, and Connection: close so every attempt redials and re-draws a CDN node.
  • WORKSPACE — raises retries from the default 5 to 50 on pip_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, and WORKSPACE pip, plus open issues matching pip 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 in piptools/repositories/pypi.py, so //release:requirements_py310.update and //release:requirements_py310_test would fail to import. pip-tools 7.4.1 fixes that.

I checked whether BAR_TYPES was merely the first of many breaks. It is not. Of the 36 pip._internal symbols 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 the build_tracker branch.
  • DEV_PKGS — only in piptools/sync.py (pip-sync), which this compile path never imports.
  • BAR_TYPES — the only real blocker.

pip-tools 7.4.1 replaced its pep517 dependency with build + pyproject_hooks, and build needs packaging, hence the three added repositories. All five versions are the set rules_python itself 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 on pip_parse or pip_install_dependencies() exposes it, so shadowing the repository before pip_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), but whl_library puts the pypi__* repositories on PYTHONPATH, which precedes site-packages on sys.path, so pypi__pip shadows it and the interpreter's copy is never used. The failure tracebacks show this directly — they resolve setuptools/installer.py out of external/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 at rules_foreign_cc/foreign_cc/repositories.bzl:85. That is also a maybe(), so pinning rules_python explicitly before ray_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 the experimental_index_url path that fetches wheels through Bazel's downloader — where --experimental_repository_downloader_retries and 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 generated requirements.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 into self.urlopen on the same HTTPConnectionPool, 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:

result count served by
200 18 cache-pae2080021, …22, …23, …25, …26, …27
502 2 cache-pae2080020 — and only ever this node

The failures are also missing the shield hop the successes carry — cache-iad-kcgs7200167-IAD, cache-pae20800NN-PAE against a bare cache-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:

outcome when the bad node is drawn
keep-alive, as pip ships the draw happens once and every retry reuses that socket, so all 50 attempts fail
redial per attempt each attempt re-draws, so P(all 50 hit the bad node) ≈ 10⁻⁵⁰

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: close turns 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.org map to different POPs, and in the run above only 199.232.184.223 reached PAE, where the bad node lives, while the other five reached BFI and were clean on every request. So an /etc/hosts or --add-host pin 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, four 151.101.x.223 addresses, and 199.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_connection does iterate every getaddrinfo result, but only advances inside except 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 --retries alone 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:

retries=5:   [0, 0.5, 1, 2, 4]                       =    7.5s   (pip's default)
retries=9:   [0, 0.5, 1, 2, 4, 8, 16, 32, 64]        =  127.5s
retries=50:  ... saturating at 120s per sleep ...    = ~5050s    (~84 minutes)

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_factor is reachable from pip's command line. pip hardcodes backoff_factor=0.25 where it builds its urllib3.Retry (pip/_internal/network/session.py), and the urllib3 it vendors is 1.26.17, which implements exponential backoff only — Retry.backoff_jitter exists only in urllib3 2.x. --retries sets total and nothing else. Hence the patch, which subclasses urllib3.Retry and overrides get_backoff_time() to return random.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:

gap 1 gap 2 gap 3 total
stock pip 24.0 0.51s 1.00s 2.01s 3.5s
patched 9.39s 8.26s 6.48s 24.1s

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

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)). It is also passed as the rctx.execute timeout in _whl_library_impl, so it is a wall-clock bound on every generated whl_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:cli entrypoint rules_python's pip_compile.py uses, produces byte-identical pins. Only the generated header comment differs:

-# This file is autogenerated by pip-compile with python 3.10
-# To update, run:
+# This file is autogenerated by pip-compile with Python 3.10
+# by the following command:

so release/requirements_py310.txt will pick up a cosmetic header change the next time it is regenerated. release/ray_release/byod/requirements_byod_3.1{1,2}.txt carry similar headers but are not affected — the .update targets their headers reference no longer exist, and raydepsets generates from the .in files via uv 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:

  • A degraded POP, or a PyPI-wide incident. Redialling re-draws from the same pool, so if the pool is the problem all you get is ~10 minutes of trying.
  • sdist-only locked packages, whose setup_requires build 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_timeout with too 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

Command Result
Patch applies -p1 to pristine pip 24.0, py_compile, no line over 88 chars passed — regenerated from pristine rather than hand-edited, so hunk offsets are honest
Patched pip vs stock pip 24.0 against a local always-502 index, --retries=4 gaps of 9.39/8.26/6.48s vs 0.51/1.00/2.01s — see table above
Patched pip against a local always-502 index speaking HTTP/1.1 keep-alive, --retries=5 every attempt from a new source port (6 of 6 distinct); jittered 6–12s spacing preserved. Before the redial change the same test reused one port for all attempts
8 separate connections vs 1 kept-alive connection to a pinned Fastly address, reading x-served-by 7 distinct edge nodes vs the same node 6 times — the node is drawn per connection
20 fresh connections to 199.232.184.223, across two packages 18 × 200 from six distinct PAE nodes; 2 × 502, both from cache-pae2080020 and nothing else
Six addresses × 6 requests each, pinned with curl --resolve only 199.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/#49 constant 6.00–12.00s at every index, all draws distinct; Retry.sleep() routes through the override
bazel fetch @pypi__pip//:lib passed — fetched tree is pip 24.0 with status_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 in bazel/ray_deps_setup.bzl
bazel sync --only=py_deps_py310 + regenerated @py_deps_py310//:requirements.bzl 'extra_pip_args': ['--retries=50'], 'environment': {'PIP_RETRIES': '50'}, 'timeout': 1800, splatted into every whl_library by install_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) passed — rebuilt from scratch through the patched pip with --retries=50
bazel build //release:requirements_py310.update passed
pip-compile on identical inputs under both pip/pip-tools pairs byte-identical pins; header comment differs as shown above
bazel test //release:requirements_py310_test fails, pre-existing — see below
pre-commit run --files WORKSPACE release/BUILD.bazel thirdparty/patches/pip-retry-backoff-and-redial.patch passed
buildifier --mode=check --lint=warn WORKSPACE exit 0. Run directly because pre-commit's buildifier hook matches only BUILD/BUILD.bazel, so WORKSPACE is never linted by it

//release:requirements_py310_test fails locally both before and after this change, because release/requirements-doc.txt pins sphinx==8.2.3 and sphinx_design==0.7.0, both of which declare Requires-Python: >=3.11, while this lock targets Python 3.10. The checked-in lock still has the older sphinx==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.0 vs sphinx==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._internal usage 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.

@sai-miduthuri sai-miduthuri added the go add ONLY when ready to merge, run all tests label Aug 17, 2026
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]>

@elliot-barn elliot-barn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Can you add a timeout along side this?

Comment thread WORKSPACE
environment = {"PIP_RETRIES": "9"},
extra_pip_args = ["--retries=9"],
python_interpreter_target = python310,
requirements_lock = "//release:requirements_py310.txt",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can add a timeout = 1800, to pip_parse here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@elliot-barn elliot-barn Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed: even with 9 retries and the back off retries this won't exceed the 600s default

@sai-miduthuri sai-miduthuri Aug 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
elliot-barn added a commit that referenced this pull request Aug 17, 2026
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]>
@sai-miduthuri

Copy link
Copy Markdown
Contributor Author

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 is

Not a missing retry. files.pythonhosted.org is fronted by Fastly, and a single bad edge node — cache-pae2080020, in the PAE POP — was answering 502. Fastly selects the edge node per connection, while urllib3 deliberately drains a failed response in order to keep the socket alive and retries down that same connection. So every retry lands on the node that just failed, and no retry count helps.

Measured over 20 fresh connections to one address: 18 × 200 served by six distinct PAE nodes, 2 × 502 both from cache-pae2080020 and nothing else. The failures also lack the shield hop the successes carry — cache-iad-…-IAD, cache-pae20800NN-PAE against a bare cache-pae2080020 — so that edge node answers 502 without the request reaching the shield. Upstream: pypi/support#11876.

That reframed the fix from "retry for longer" to "retry somewhere else", which is what the last commit did: Connection: close, so each attempt redials and re-draws a node.

Why it still isn't enough

It only reaches one fetch path. In premerge 72103 with the redial in place, 142 jobs passed and the three reef jobs that died on whl_library 502s in both 72008 and 72031 all passed — zero whl_library failures anywhere. But four jobs still failed on exactly one thing: pip install inside Docker image builds, using the image's own pip at /opt/miniforge/…, version 25.2/25.3.

fetch path reached by this PR
rules_python whl_library → py_deps_py310 yes
pip install in Dockerfiles no
pip install -e during lint, and the pip its build_ext spawns no
Bazel downloader http_archive no
uv pip compile in raydepsets no

One path in five. The change patches a vendored third-party wheel from WORKSPACE — the full complexity and review cost is paid up front — and CI is still red afterwards.

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 substitute

Rejecting the bad address with iptables is client-agnostic and does cover the container builds this PR cannot. But it depends on a healthy alternative address existing at fetch time, and Fastly frequently returns a single A record. Across ten lookups in three minutes, two returned only the bad address, with no IPv6 route available as a fallback. In that state the rule is worse than no rule: it converts a ~10%-per-connection failure into a 100% one. The same limitation applies to /etc/hosts pinning and to NACLs; security groups cannot express a deny at all.

What would fix it

An index that is not the public CDN. Every client honours index configuration — whl_library through extra_pip_args, in-image pip through PIP_INDEX_URL or pip.conf, uv through UV_INDEX_URL — so one change covers every path above with no patching, and it takes the CDN out of the path rather than trying to route around its broken parts. That work is happening separately.

Leaving the branch in place for reference. The full measurements are in the description above.

elliot-barn added a commit that referenced this pull request Aug 19, 2026
## 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]>
elliot-barn added a commit that referenced this pull request Aug 19, 2026
## 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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants