Repository navigation
[runtime_env] Expand env vars in uv package inputs - #65767
Conversation
Signed-off-by: Wang Zupeng <[email protected]>
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
⚠️ 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:
- The contents of
requirements.txtin the working directory change. - 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| 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) |
There was a problem hiding this comment.
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.
| 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) |
|
@edoakes Please take a look if you have time. |
|
@zupengwang could you please address the gemini review comments? |
Signed-off-by: Wang Zupeng <[email protected]>
|
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 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 ( |
edoakes
left a comment
There was a problem hiding this comment.
Looks good. Thanks for the contribution. Could you follow up to add a note to the docs page about this behavior?
## 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]>
Why are these changes needed?
RAY_RUNTIME_ENV_CREATE_WORKING_DIRis available while a runtime environment isbeing created, but uv package entries and
uv_pip_install_optionswere writtenand passed through literally. This made working-directory-relative requirements
fail for uv runtime environments.
Expand shell-style
$VARand${VAR}references using the per-installenvironment 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
/tmpdirectory.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
masterat7bbef5a7de29c97a44e682e21fa0d4f759f92937. Other historical attempts are alsoclosed.
Checks
bazel test //python/ray/tests/unit:test_runtime_env_uv --test_output=errorspython -m pytest -q python/ray/tests/test_runtime_env_uv.py::test_package_install_from_working_dir_requirements -s1 passed in 182.56spy_compile, andgit diff --checkThe focused integration test used a Ray 2.58.0 wheel with the exact patched
uv.pyoverlaid; the current-master source itself was covered by the exact-masterharness 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.