Skip to content

[runtime_env] Expand env vars in uv package inputs - #65767

Merged
edoakes merged 2 commits into
ray-project:masterfrom
zupengwang:fix-59343-uv-working-dir-env
Sep 4, 2026
Merged

edoakes merged 2 commits into
ray-project:masterfrom
zupengwang:fix-59343-uv-working-dir-env

Conversation

@zupengwang

Copy link
Copy Markdown
Contributor

Why are these changes needed?

RAY_RUNTIME_ENV_CREATE_WORKING_DIR is available while a runtime environment is
being created, but uv package entries and uv_pip_install_options were written
and passed through literally. This made working-directory-relative requirements
fail for uv runtime environments.

Expand shell-style $VAR and ${VAR} references using the per-install
environment passed to uv. Using that snapshot keeps requirements-file contents,
CLI options, and the uv subprocess environment consistent without consulting
mutable process-global environment state after async setup.

The existing unit test also now uses a pytest-scoped target directory instead of
the global /tmp directory.

Fixes #59343.

Duplicate-work check

I searched open PRs by issue number and semantic keywords and found no open
implementation. #62183 was approved but closed unmerged as stale, and the bug is
still present on current master at
7bbef5a7de29c97a44e682e21fa0d4f759f92937. Other historical attempts are also
closed.

Checks

  • Exact-master regression harness: failed before the patch, passed after it.
  • bazel test //python/ray/tests/unit:test_runtime_env_uv --test_output=errors
    • passed
  • python -m pytest -q python/ray/tests/test_runtime_env_uv.py::test_package_install_from_working_dir_requirements -s
    • 1 passed in 182.56s
  • Ray pre-commit ruff hooks, black, py_compile, and git diff --check
    • passed

The focused integration test used a Ray 2.58.0 wheel with the exact patched
uv.py overlaid; the current-master source itself was covered by the exact-master
harness and Bazel unit target.

AI assistance disclosure

AI assistance was used to research, implement, and test this change. I reviewed
every changed line, understand the implementation and its limitations, and
confirmed the test evidence above before submission.

@zupengwang
zupengwang requested a review from a team as a code owner August 28, 2026 15:58

@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 adds support for expanding environment variables (such as ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}) in uv package specs and installation options during runtime environment setup. The review feedback identifies a critical caching issue where using unexpanded variables in the cache key computation can lead to incorrect virtualenv reuse across different jobs. Additionally, a defensive type check is suggested for the expansion helper to handle non-string inputs gracefully.

"""Install required python packages via `uv`."""
virtualenv_path = virtualenv_utils.get_virtualenv_path(path)
python = virtualenv_utils.get_virtualenv_python(path)
uv_packages = [_expand_env_vars(package, pip_env) for package in uv_packages]

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.

high

⚠️ Critical Caching & Correctness Issue

Expanding environment variables (like RAY_RUNTIME_ENV_CREATE_WORKING_DIR or custom env_vars) during the installation phase (_install_uv_packages) introduces a major caching bug.

The Problem

Ray computes the cache key (URI) for the uv plugin on the client side using the unexpanded uv spec (e.g., ["-r ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}/requirements.txt"]). Because this string is constant, the computed URI (e.g., uv://<hash>) will be identical across different jobs/tasks, even if:

  1. The contents of requirements.txt in the working directory change.
  2. Different tasks use different working directories with different requirements.

When this happens, Ray's URICache will see the same URI and reuse the cached virtualenv from a previous run, completely ignoring the new requirements or local wheels.

How to Reproduce

If you run the following two tasks in the same Ray session, the second task will incorrectly reuse the virtualenv from the first task (containing requests==2.32.3) instead of installing requests==2.32.2:

@ray.remote(runtime_env={
    "working_dir": "dir_with_requests_2_32_3",
    "uv": ["-r ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}/requirements.txt"]
})
def f1():
    import requests
    return requests.__version__

@ray.remote(runtime_env={
    "working_dir": "dir_with_requests_2_32_2",
    "uv": ["-r ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}/requirements.txt"]
})
def f2():
    import requests
    return requests.__version__

Proposed Solution

To fix this, we must mix the values of any referenced environment variables (including RAY_RUNTIME_ENV_CREATE_WORKING_DIR and custom env_vars) into the uv spec before hashing it in get_uri.

Since get_uri is not in the current diff, you can update it in python/ray/_private/runtime_env/uv.py as follows:

def get_uri(runtime_env: Dict) -> Optional[str]:
    """Return `"uv://<hashed_dependencies>"`, or None if no GC required."""
    uv = runtime_env.get("uv")
    if uv is not None:
        uv_dict = uv if isinstance(uv, dict) else dict(packages=uv)
        
        # Extract all referenced env vars from the uv spec and mix their values into the hash
        referenced_vars = set()
        for value in uv_dict.values():
            if isinstance(value, list):
                for item in value:
                    for match in _ENV_VAR_PATTERN.finditer(str(item)):
                        name = match.group(1)
                        if name.startswith("{"):
                            name = name[1:-1]
                        referenced_vars.add(name)
            elif isinstance(value, str):
                for match in _ENV_VAR_PATTERN.finditer(value):
                    name = match.group(1)
                    if name.startswith("{"):
                        name = name[1:-1]
                    referenced_vars.add(name)
        
        # Mix the values of these env vars into the uv_dict for hashing
        env_vars = runtime_env.get("env_vars") or {}
        mixed_env = {}
        for var in referenced_vars:
            if var == "RAY_RUNTIME_ENV_CREATE_WORKING_DIR":
                # Use the working_dir URI/path as the unique identifier
                mixed_env[var] = runtime_env.get("working_dir")
            elif var in env_vars:
                mixed_env[var] = env_vars[var]
            elif var in os.environ:
                mixed_env[var] = os.environ[var]
        
        if mixed_env:
            # Create a copy to avoid mutating the original runtime_env
            uv_dict = {**uv_dict, "_expanded_env_vars": mixed_env}

        uri = "uv://" + _get_uv_hash(uv_dict=uv_dict)
    else:
        uri = None
    return uri

Comment on lines +27 to +36
def _expand_env_vars(value: str, env: Mapping[str, str]) -> str:
"""Expand shell-style variables using a per-install environment snapshot."""

def replace(match: re.Match) -> str:
name = match.group(1)
if name.startswith("{"):
name = name[1:-1]
return env.get(name, match.group(0))

return _ENV_VAR_PATTERN.sub(replace, value)

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

Add a defensive type check to handle cases where value is not a string at runtime. Since Python does not enforce type hints at runtime, passing a non-string value (e.g., if the user-supplied configuration is malformed) would cause re.sub to raise a TypeError.

Suggested change
def _expand_env_vars(value: str, env: Mapping[str, str]) -> str:
"""Expand shell-style variables using a per-install environment snapshot."""
def replace(match: re.Match) -> str:
name = match.group(1)
if name.startswith("{"):
name = name[1:-1]
return env.get(name, match.group(0))
return _ENV_VAR_PATTERN.sub(replace, value)
def _expand_env_vars(value: str, env: Mapping[str, str]) -> str:
"""Expand shell-style variables using a per-install environment snapshot."""
if not isinstance(value, str):
return value
def replace(match: re.Match) -> str:
name = match.group(1)
if name.startswith("{"):
name = name[1:-1]
return env.get(name, match.group(0))
return _ENV_VAR_PATTERN.sub(replace, value)

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

Kunchd commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

@edoakes Please take a look if you have time.

@edoakes edoakes added the go add ONLY when ready to merge, run all tests label Sep 3, 2026
@edoakes

edoakes commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

@zupengwang could you please address the gemini review comments?

@zupengwang

Copy link
Copy Markdown
Contributor Author

Thanks for the nudge — I addressed both Gemini comments locally.

The cache concern was valid: the old URI hashed the unexpanded UV spec, so two working directories could reuse the same virtualenv. The fix now mixes only referenced runtime-env values into the key, using the content-addressed working-dir URI rather than the node-local unpack path. Unreferenced env vars keep the existing key.

For the defensive-type comment, I added fail-fast validation for non-string entries in dict-form uv["packages"] instead of silently passing malformed values through _expand_env_vars.

I added URI tests for list/dict forms, package/install-option expansion, brace/plain variables, unused variables, and invalid package types, plus a same-session integration regression with two working directories. Focused tests pass (7 passed; integration 1 passed).

@edoakes edoakes 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. Thanks for the contribution. Could you follow up to add a note to the docs page about this behavior?

@edoakes
edoakes merged commit 2cf41a6 into ray-project:master Sep 4, 2026
6 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Why are these changes needed?

`RAY_RUNTIME_ENV_CREATE_WORKING_DIR` is available while a runtime
environment is
being created, but uv package entries and `uv_pip_install_options` were
written
and passed through literally. This made working-directory-relative
requirements
fail for uv runtime environments.

Expand shell-style `$VAR` and `${VAR}` references using the per-install
environment passed to uv. Using that snapshot keeps requirements-file
contents,
CLI options, and the uv subprocess environment consistent without
consulting
mutable process-global environment state after async setup.

The existing unit test also now uses a pytest-scoped target directory
instead of
the global `/tmp` directory.

Fixes ray-project#59343.

## Duplicate-work check

I searched open PRs by issue number and semantic keywords and found no
open
implementation. ray-project#62183 was approved but closed unmerged as stale, and
the bug is
still present on current `master` at
`7bbef5a7de29c97a44e682e21fa0d4f759f92937`. Other historical attempts
are also
closed.

## Checks

- Exact-master regression harness: failed before the patch, passed after
it.
- `bazel test //python/ray/tests/unit:test_runtime_env_uv
--test_output=errors`
  - passed
- `python -m pytest -q
python/ray/tests/test_runtime_env_uv.py::test_package_install_from_working_dir_requirements
-s`
  - `1 passed in 182.56s`
- Ray pre-commit ruff hooks, black, `py_compile`, and `git diff --check`
  - passed

The focused integration test used a Ray 2.58.0 wheel with the exact
patched
`uv.py` overlaid; the current-master source itself was covered by the
exact-master
harness and Bazel unit target.

## AI assistance disclosure

AI assistance was used to research, implement, and test this change. I
reviewed
every changed line, understand the implementation and its limitations,
and
confirmed the test evidence above before submission.

---------

Signed-off-by: Wang Zupeng <[email protected]>
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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RuntimeEnv] RAY_RUNTIME_ENV_CREATE_WORKING_DIR isn't propagated when using 'ray job submit'

3 participants