Skip to content

Commit 42920fc

Browse files
leosvelperezFrozenPandaz
authored andcommitted
fix(core): make runtime cache key deterministic (#34390)
## Current Behavior Runtime cache keys could be nondeterministic because the order of environment variables varied, leading to inconsistent cache hits across runs. ## Expected Behavior Runtime cache keys are deterministic regardless of the insertion order of env variables, improving cache stability. (cherry picked from commit f43d202)
1 parent 7c80acc commit 42920fc

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

packages/nx/src/native/tasks/hashers/hash_runtime.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pub fn hash_runtime(
1818
env: &HashMap<String, String>,
1919
cache: Arc<DashMap<String, String>>,
2020
) -> anyhow::Result<String> {
21-
let cache_key = format!("{}-{:?}", command, env);
21+
let cache_key = runtime_cache_key(command, env);
2222

2323
if let Some(cache_results) = cache.get(&cache_key) {
2424
return Ok(cache_results.clone());
@@ -47,6 +47,12 @@ pub fn hash_runtime(
4747
Ok(hash_result)
4848
}
4949

50+
fn runtime_cache_key(command: &str, env: &HashMap<String, String>) -> String {
51+
let mut entries: Vec<_> = env.iter().collect();
52+
entries.sort_by(|(a, _), (b, _)| a.cmp(b));
53+
format!("{}-{:?}", command, entries)
54+
}
55+
5056
#[cfg(target_os = "windows")]
5157
pub fn create_command_builder() -> Command {
5258
let comspec = std::env::var("COMSPEC");
@@ -84,4 +90,21 @@ mod tests {
8490
let result = hash_runtime(workspace_root, command, &env, Arc::clone(&cache)).unwrap();
8591
assert_eq!(result, "10571312846059850300");
8692
}
93+
94+
#[test]
95+
fn runtime_cache_key_is_deterministic() {
96+
let command = "echo runtime";
97+
let mut env_a = HashMap::new();
98+
env_a.insert("B".to_string(), "2".to_string());
99+
env_a.insert("A".to_string(), "1".to_string());
100+
101+
let mut env_b = HashMap::new();
102+
env_b.insert("A".to_string(), "1".to_string());
103+
env_b.insert("B".to_string(), "2".to_string());
104+
105+
let key_a = runtime_cache_key(command, &env_a);
106+
let key_b = runtime_cache_key(command, &env_b);
107+
108+
assert_eq!(key_a, key_b);
109+
}
87110
}

0 commit comments

Comments
 (0)