Skip to content

[core] Reuse installed py_modules wheels across source URIs - #66570

Open
laysfire wants to merge 4 commits into
ray-project:masterfrom
laysfire:reuse_installed_py_modules_wheels
Open

laysfire wants to merge 4 commits into
ray-project:masterfrom
laysfire:reuse_installed_py_modules_wheels

Conversation

@laysfire

Copy link
Copy Markdown
Contributor

Description

When two py_modules URIs reference the same wheel filename, they share a local installation directory but have separate URI cache entries. Setting up the second URI passes the existing installation directory to pip as if it were a wheel. Installation fails, and cleanup deletes the directory still referenced by the first environment.

This PR:

  • Normalizes wheel cache keys by filename and deduplicates matching entries.
  • Reuses existing installations, with a file lock covering the existence check, download, and installation.
  • Resolves the original source URI when a download is needed.

Related issues

Additional information

@laysfire
laysfire requested a review from a team as a code owner September 29, 2026 06:28

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes the installation of wheel packages in py_modules by using the wheel filename as a cache key, preventing duplicate downloads and installations of the same wheel from different URIs. It introduces concurrency control using _AsyncFileLock and skips installation if the wheel is already present. Unit tests have been added to verify these caching and reuse behaviors. Feedback on the changes suggests adding a safety check is_whl_uri(source_uri) in _get_source_uri_for_whl before parsing URIs to avoid potential ValueError crashes on invalid or local paths.

Comment on lines +233 to +235
for source_uri in runtime_env.py_modules():
if parse_uri(source_uri)[1] == wheel_filename:
return source_uri

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Calling parse_uri directly on all entries in runtime_env.py_modules() can raise a ValueError if any entry is a raw local path or an invalid URI (which is common before normalization or in certain test/validation contexts).

To prevent potential crashes and avoid unnecessary parsing of non-wheel URIs, we should check is_whl_uri(source_uri) first, matching the pattern already established in get_uris.

Suggested change
for source_uri in runtime_env.py_modules():
if parse_uri(source_uri)[1] == wheel_filename:
return source_uri
for source_uri in runtime_env.py_modules():
if is_whl_uri(source_uri) and parse_uri(source_uri)[1] == wheel_filename:
return source_uri

@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Sep 29, 2026

@stantheman0128 stantheman0128 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I checked the root cause against master and it matches the description. For a remote wheel, download_and_unpack_package returns the existing local directory if it is already there. create then passes that path to install_wheel_package as wheel_uri, and the finally block in install_wheel_package removes wheel_uri, which is the directory the first environment is still using. Keying the URI by filename fixes this. Since create_for_plugin_if_needed and the agent's uris_parser both go through get_uris, the two environments now share one URI cache entry and one reference count.

Two comments:

  1. With the filename as the key, two different builds that share a filename (say, a wheel rebuilt and uploaded to a new path without a version bump) will reuse whichever one was installed on that node first, and the only sign of it is an INFO log. I think that's a reasonable trade-off, and it matches what get_uri_for_package already assumes about wheel filenames. It is still a behavior change for that case, so a sentence in the PR description or a comment on get_uris would help anyone who runs into it.

  2. The three new tests call get_uris and create directly, so none of them runs the sequence from the bug: two runtime envs listing the same wheel filename under different URIs, set up one after the other on the same node. A test that calls create_for_plugin_if_needed twice with a shared URICache could cover it. The download and install stubs from test_py_modules_plugin_downloads_whl_from_runtime_env_uri should mostly carry over; with a call counter on the install stub, the test can check that install ran once and that both contexts end up with the same directory in PYTHONPATH. On master the install stub would be called twice, so this would also catch a regression in the cache key.

I used an AI assistant to help trace the code paths and checked each point above against master myself.

Sparks0219 pushed a commit that referenced this pull request Oct 20, 2026
## What broke

Since 2.57, `JobSubmissionClient.submit_job()` raises before it uploads
anything when `py_modules` contains an imported module, which the
[runtime_env API
reference](https://docs.ray.io/en/latest/ray-core/handling-dependencies.html#runtime-environments-api-ref)
lists as a supported entry:

```python
import my_module
from ray.job_submission import JobSubmissionClient

client = JobSubmissionClient("http://127.0.0.1:8265")
client.submit_job(entrypoint="python main.py", runtime_env={"py_modules": [my_module]})
```

```
  File ".../ray/dashboard/modules/job/sdk.py", line 221, in submit_job
    runtime_env = copy.deepcopy(runtime_env or {})
TypeError: cannot pickle 'module' object
```

Expected: the module's directory is uploaded and the job runs, as on
2.56.1. A user upgrading from 2.56.1 hit this and is pinned there.

| `py_modules` entry | 2.56.1 | 2.57.0, 2.58.0, master |
|---|---|---|
| module object, Python SDK | works | `TypeError` at submit |
| path string, Python SDK | works | works |
| path string, `ray job submit --runtime-env-json` | works | works |

## Why

#63990 (the fix for #46625) made `submit_job` deep-copy `runtime_env`,
so that uploading stops rewriting the caller's dict with `gcs://` URIs.
Module objects can't be deep-copied, so the copy itself raises. Nothing
in CI passes a module object through `submit_job`, so it went unnoticed.

## The fix

Copy shallowly: `dict(runtime_env or {})`.

- That is enough for #46625. `upload_working_dir_if_needed` and
`upload_py_modules_if_needed` only rebind top-level keys
(`runtime_env["py_modules"] = py_modules_uris`, a new list) and never
mutate a value in place, so the caller's dict and list are left alone.
- A `RuntimeEnv` argument becomes a plain dict before upload and is
rebuilt by the existing `RuntimeEnv(**runtime_env)` right after.
`RuntimeEnv` validation rejects module objects, so only a plain dict can
carry one.

## Not a duplicate

No open issue or PR covers this. The open PRs in the area don't touch
the submission path: #64621 changes CLI stack traces (`cli.py`,
`cli_utils.py`), #66570 changes how nodes install `py_modules` wheels,
and #65933 and #66279 change how nodes download packages. Nothing on
#63990 mentions module objects.

## Testing

`test_submit_job_with_module_object_in_py_modules` runs the real upload
path behind a fake HTTP layer and checks that the module's directory is
zipped with its parent (`my_module/__init__.py`), that the job request
carries a `gcs://` URI, and that the caller's dict still holds the
module. Against the unmodified `sdk.py` it fails with `TypeError: cannot
pickle 'module' object`.

```
$ python -m pytest -v python/ray/dashboard/modules/job/tests/test_sdk.py
110 passed in 141.93s

$ python -m pytest -v python/ray/dashboard/modules/job/tests/test_http_job_server.py
1 failed, 63 passed in 348.11s
```

The one failure, `test_submit_job[conda_yaml]`, times out because conda
isn't installed on the test machine; it times out the same way with the
unmodified `sdk.py`.

End to end on a local cluster, `submit_job(runtime_env={"py_modules":
[my_module]})` now succeeds and the driver imports the module; the same
script raises the `TypeError` with the 2.58.0 wheel. Pre-commit passes
on both changed files.

AI assistance was used for this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 25, 2026
@laysfire

laysfire commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

unstale

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 2036b1c. Configure here.

uri,
module_dir,
)
return get_directory_size_bytes(module_dir)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Partial wheel installs treated as complete

Medium Severity

The reuse path treats any existing install directory as a finished wheel. After a crash or agent restart during install_wheel_package, that leftover directory is cached as success, so later setups skip install and workers import from an incomplete package.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2036b1c. Configure here.

seen_wheel_filenames.add(wheel_filename)
uri = f"{Protocol.GCS.value}://{wheel_filename}"
uris.append(uri)
return uris

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Shared wheel cache key double-counted

Low Severity

Different runtime envs that share a wheel filename now share one URI cache key, but setup is still locked per serialized env. Two cache misses can both finish create and both add the same URI, inflating _total_size_bytes and evicting other unused packages early.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2036b1c. Configure here.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 2, 2026
@laysfire

Copy link
Copy Markdown
Contributor Author

@martinlhw Could you help review this?

@laysfire

Copy link
Copy Markdown
Contributor Author

@karticam Could you help review this?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community core Issues that should be addressed in Ray Core unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants