Skip to content
5 changes: 4 additions & 1 deletion crates/turborepo-lockfiles/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ use rayon::prelude::*;
use rustc_hash::{FxBuildHasher, FxHashSet};
use serde::Serialize;
use turbopath::RelativeUnixPathBuf;
pub use uv::{Error as UvLockError, PrunedUvLock, UvPackageKey, uv_prune_lock};
pub use uv::{
Error as UvLockError, PrunedUvLock, UvPackageKey, changed_package_names as uv_changed_packages,
uv_prune_lock,
};
pub use yarn1::{Yarn1Lockfile, yarn_subgraph};

// The closure walk visits every edge of every workspace's dependency closure,
Expand Down
55 changes: 54 additions & 1 deletion crates/turborepo-lockfiles/src/uv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! `uv workspace metadata`. This module does not resolve uv dependencies; it
//! only removes `[[package]]` tables that metadata determined are unreachable.

use std::collections::HashSet;
use std::collections::{BTreeMap, HashSet};

#[derive(Debug, thiserror::Error)]
pub enum Error {
Expand Down Expand Up @@ -36,6 +36,44 @@ pub struct PrunedUvLock {
pub lockfile: String,
}

/// Return package names whose complete lockfile tables changed.
///
/// Dependency ownership remains metadata-derived; this only identifies which
/// pinned package records changed between two lockfiles.
pub fn changed_package_names(previous: &str, current: &str) -> Result<HashSet<String>, Error> {
fn packages(contents: &str) -> Result<BTreeMap<String, Vec<String>>, Error> {
let document: toml_edit::DocumentMut = contents.parse().map_err(Box::new)?;
let packages = document
.get("package")
.and_then(|item| item.as_array_of_tables())
.ok_or(Error::MalformedPackageArray)?;
let mut by_name = BTreeMap::<String, Vec<String>>::new();
for package in packages {
let name = package
.get("name")
.and_then(|item| item.as_str())
.ok_or(Error::MissingPackageName)?;
by_name
.entry(name.to_string())
.or_default()
.push(package.to_string());
}
for entries in by_name.values_mut() {
entries.sort();
}
Ok(by_name)
}

let previous = packages(previous)?;
let current = packages(current)?;
Ok(previous
.keys()
.chain(current.keys())
.filter(|name| previous.get(*name) != current.get(*name))
.cloned()
.collect())
}

/// Filter a uv.lock to package identities and workspace members selected by
/// `uv workspace metadata`.
pub fn uv_prune_lock(
Expand Down Expand Up @@ -121,6 +159,21 @@ version = "2.0.0"
source = { registry = "https://pypi.org/simple" }
"#;

#[test]
fn detects_changed_package_tables_by_name() {
let current = LOCK.replace("sha256:abc", "sha256:def");
assert_eq!(
changed_package_names(LOCK, &current).unwrap(),
HashSet::from(["dep".to_string()])
);
}

#[test]
fn ignores_non_package_lockfile_changes() {
let current = LOCK.replace("revision = 3", "revision = 4");
assert!(changed_package_names(LOCK, &current).unwrap().is_empty());
}

#[test]
fn filters_packages_and_manifest_members() {
let kept = HashSet::from([
Expand Down
21 changes: 14 additions & 7 deletions crates/turborepo-repository/src/change_mapper/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub use package::{
GlobalDepsPackageChangeMapper, PackageChangeMapper, PackageMapping,
};
use tracing::debug;
use turbopath::{AbsoluteSystemPath, AnchoredSystemPathBuf};
use turbopath::{AbsoluteSystemPath, AnchoredSystemPath, AnchoredSystemPathBuf};
use wax::Program;

use crate::package_graph::{
Expand All @@ -38,9 +38,12 @@ pub enum LockfileContents {
/// previous lockfile (i.e. `git status`, or perhaps a lockfile that was
/// deleted or otherwise inaccessible with the information we have)
UnknownChange,
/// We know the lockfile changed and have the contents of the previous
/// lockfile
Changed(Vec<u8>),
/// We know the lockfile changed and have its repository-relative path and
/// the contents of the previous lockfile.
Changed {
path: AnchoredSystemPathBuf,
previous_contents: Vec<u8>,
},
}

#[derive(Debug, PartialEq, Eq, Hash, Clone)]
Expand Down Expand Up @@ -160,10 +163,13 @@ impl<'a, PD: PackageChangeMapper> ChangeMapper<'a, PD> {

PackageChanges::Some(mut changed_pkgs) => {
match lockfile_contents {
LockfileContents::Changed(previous_lockfile_contents) => {
LockfileContents::Changed {
path,
previous_contents,
} => {
// if we run into issues, don't error, just assume all packages have changed
let Ok(lockfile_changes) =
self.get_changed_packages_from_lockfile(&previous_lockfile_contents)
self.get_changed_packages_from_lockfile(&path, &previous_contents)
else {
debug!(
"unable to determine lockfile changes, assuming all packages \
Expand Down Expand Up @@ -318,10 +324,11 @@ impl<'a, PD: PackageChangeMapper> ChangeMapper<'a, PD> {

fn get_changed_packages_from_lockfile(
&self,
path: &AnchoredSystemPath,
lockfile_content: &[u8],
) -> Result<Vec<ExternalDependencyChange>, ChangeMapError> {
self.pkg_graph
.changed_packages_from_lockfile_contents(lockfile_content)
.changed_packages_from_lockfile_contents(path, lockfile_content)
.map_err(Into::into)
}

Expand Down
6 changes: 5 additions & 1 deletion crates/turborepo-repository/src/package_graph/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ fn resolution_data(
}

impl PackageGraph {
pub fn changed_packages_from_lockfile_contents(
pub(super) fn changed_javascript_packages_from_lockfile_contents(
&self,
previous_lockfile_contents: &[u8],
) -> Result<Vec<ExternalDependencyChange>, ChangedPackagesError> {
Expand Down Expand Up @@ -379,4 +379,8 @@ pub enum ChangedPackagesError {
PackageManager(#[from] crate::package_manager::Error),
#[error("Yarn config error: {0}")]
Yarnrc(#[from] crate::package_manager::yarnrc::Error),
#[error("uv lockfile error: {0}")]
Uv(#[from] turborepo_lockfiles::UvLockError),
#[error("Lockfile content is not UTF-8")]
NonUtf8Lockfile,
}
83 changes: 80 additions & 3 deletions crates/turborepo-repository/src/package_graph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ use crate::{
external_resolution::{
ExternalDeclarations, ExternalPackageIdentity, ExternalResolutionData,
ExternalResolutionDomainId, ExternalResolutionGeneration, ExternalResolutionStatus,
JAVASCRIPT_RESOLUTION_DOMAIN, PackageExternalDeclarations, PackageResolutionState,
JAVASCRIPT_RESOLUTION_DOMAIN, PYTHON_RESOLUTION_DOMAIN, PackageExternalDeclarations,
PackageResolutionState,
},
knowledge::{RelationshipKnowledge, RepositoryKnowledge},
package_json::PackageJson,
Expand Down Expand Up @@ -1029,6 +1030,73 @@ impl PackageGraph {
self.lockfile.as_deref()
}

pub fn changed_packages_from_lockfile_contents(
&self,
path: &AnchoredSystemPath,
previous_contents: &[u8],
) -> Result<Vec<ExternalDependencyChange>, ChangedPackagesError> {
if path.as_str() != "uv.lock" {
return self.changed_javascript_packages_from_lockfile_contents(previous_contents);
}

let previous = std::str::from_utf8(previous_contents)
.map_err(|_| ChangedPackagesError::NonUtf8Lockfile)?;
let current = self
.repo_root()
.join_component("uv.lock")
.read_to_string()
.map_err(crate::package_manager::Error::Io)?;
let changed_names = turborepo_lockfiles::uv_changed_packages(previous, &current)?;
if changed_names.is_empty() {
return Ok(Vec::new());
}

let resolution = self
.external_resolution
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let domain = resolution
.generation
.as_deref()
.and_then(|generation| generation.domain(&PYTHON_RESOLUTION_DOMAIN))
.ok_or(ChangedPackagesError::ResolutionUnavailable)?;
let ExternalResolutionData::Resolved { packages, .. } = domain.data() else {
return Err(ChangedPackagesError::ResolutionUnavailable);
};

let mut changes = Vec::new();
for resolution in packages {
let added = resolution
.identities()
.iter()
.filter(|identity| {
changed_names.contains(identity.display_name())
|| changed_names.contains(identity.key())
})
.map(|identity| turborepo_lockfiles::Package {
key: identity.key().to_string(),
version: identity.version().to_string(),
})
.collect::<Vec<_>>();
if added.is_empty() {
continue;
}
let name = PackageName::from(resolution.package());
let context = self
.package_task_context(&name)
.ok_or(ChangedPackagesError::ResolutionUnavailable)?;
changes.push(ExternalDependencyChange {
package: WorkspacePackage {
name,
path: context.directory().to_owned(),
},
added,
removed: Vec::new(),
});
}
Ok(changes)
}

pub fn external_resolution_status(&self) -> ExternalResolutionStatus {
self.external_resolution
.lock()
Expand Down Expand Up @@ -1850,7 +1918,10 @@ mod test {
mapper
.changed_packages(
HashSet::new(),
LockfileContents::Changed(b"invalid lockfile".to_vec()),
LockfileContents::Changed {
path: AnchoredSystemPathBuf::from_raw("package-lock.json").unwrap(),
previous_contents: b"invalid lockfile".to_vec(),
},
)
.unwrap(),
PackageChanges::All(AllPackageChangeReason::LockfileChangeDetectionFailed)
Expand All @@ -1874,7 +1945,13 @@ mod test {
let mapper = ChangeMapper::new(&dep_graph, Vec::new(), detector);
assert_eq!(
mapper
.changed_packages(HashSet::new(), LockfileContents::Changed(previous_contents),)
.changed_packages(
HashSet::new(),
LockfileContents::Changed {
path: AnchoredSystemPathBuf::from_raw(lockfile).unwrap(),
previous_contents,
},
)
.unwrap(),
PackageChanges::All(AllPackageChangeReason::LockfileChangeDetectionFailed)
);
Expand Down
8 changes: 7 additions & 1 deletion crates/turborepo-scope/src/change_detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,13 @@
};

debug!("lockfile changed, have the previous content");
LockfileContents::Changed(content)
LockfileContents::Changed {
path: self

Check failure on line 127 in crates/turborepo-scope/src/change_detector.rs

View workflow job for this annotation

GitHub Actions / Rust clippy

used `expect()` on a `Result` value
.turbo_root
.anchor(&lockfile_path)
.expect("lockfile should be in repo"),
Comment thread
vercel[bot] marked this conversation as resolved.
Resolved
previous_contents: content,
}
}
}

Expand Down
5 changes: 4 additions & 1 deletion crates/turborepo/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,10 @@ the shared repository graph.
- **Discovery** invokes `uv workspace metadata --frozen --offline` once and uses
its member list and resolution graph as authoritative. Turborepo parses each
returned `pyproject.toml` only for task/tool declarations and dependency-kind
labels. Discovery also probes uv and the Python interpreter selected by
labels. For git-range affectedness, `uv.lock` package tables are diffed
mechanically and changed package names are intersected with these
metadata-derived closures; unrelated workspace packages remain unaffected.
Discovery also probes uv and the Python interpreter selected by
`uv python find` for cache identity. Missing identities and repository-local
uv executables fail closed to uncached tasks. Names are PEP 503-normalized.
Dependencies become internal graph edges only when
Expand Down
60 changes: 52 additions & 8 deletions crates/turborepo/tests/uv_workspace_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,28 +528,72 @@ fn test_uv_flag_disabled_hints_at_opt_in() {
}

#[test]
fn test_uv_lock_change_affects_all_packages() {
fn test_uv_lock_metadata_only_change_affects_no_packages() {
let tempdir = tempfile::tempdir().unwrap();
setup_uv_pure_workspace(tempdir.path());

let base = dry_run_tasks(
tempdir.path(),
&["build", "--filter=[HEAD]", "--log-order", "grouped"],
);
assert_eq!(task_ids(&base), Vec::<String>::new());

let lock_path = tempdir.path().join("uv.lock");
let mut contents = fs::read_to_string(&lock_path).unwrap();
contents.push_str("\n# turbo-test lockfile perturbation\n");
fs::write(&lock_path, contents).unwrap();

let json = dry_run_tasks(
tempdir.path(),
&["build", "--filter=[HEAD]", "--log-order", "grouped"],
);
assert_eq!(task_ids(&json), Vec::<String>::new());
}

#[test]
fn test_uv_lock_change_only_affects_dependency_closure() {
if !uv_available() {
return;
}
let tempdir = tempfile::tempdir().unwrap();
setup_uv_pure_workspace(tempdir.path());
append_manifest(
tempdir.path(),
"packages/py-app/pyproject.toml",
"\n[dependency-groups]\ndev = [\"ruff==0.12.0\"]\n",
);
let lock = std::process::Command::new("uv")
.arg("lock")
.current_dir(tempdir.path())
.output()
.expect("uv lock runs");
assert_command_success(&lock, "initial uv lock");
let add = std::process::Command::new("git")
.args(["add", "."])
.current_dir(tempdir.path())
.output()
.expect("git add runs");
assert_command_success(&add, "git add");
let commit = std::process::Command::new("git")
.args(["commit", "-m", "add ruff"])
.current_dir(tempdir.path())
.output()
.expect("git commit runs");
assert_command_success(&commit, "git commit");

let manifest = tempdir.path().join("packages/py-app/pyproject.toml");
let contents = fs::read_to_string(&manifest)
.unwrap()
.replace("ruff==0.12.0", "ruff==0.12.1");
fs::write(manifest, contents).unwrap();
let lock = std::process::Command::new("uv")
.arg("lock")
.current_dir(tempdir.path())
.output()
.expect("uv lock runs");
assert_command_success(&lock, "updated uv lock");

let json = dry_run_tasks(
tempdir.path(),
&["build", "--filter=[HEAD]", "--log-order", "grouped"],
);
let ids = task_ids(&json);
assert!(ids.contains(&"py-app#build".to_string()), "ids: {ids:?}");
assert!(ids.contains(&"py-lib#build".to_string()), "ids: {ids:?}");
assert!(!ids.contains(&"py-lib#build".to_string()), "ids: {ids:?}");
}

#[test]
Expand Down
5 changes: 4 additions & 1 deletion packages/turbo-repository/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,10 @@ impl Workspace {
let git = SCM::new(workspace_root);
let anchored_path = workspace_root.resolve(lockfile_path);
match git.previous_content(Some(from_commit), &anchored_path) {
Ok(contents) => LockfileContents::Changed(contents),
Ok(previous_contents) => LockfileContents::Changed {
path: lockfile_path.to_owned(),
previous_contents,
},
Err(e) => {
debug!("{e}");
LockfileContents::UnknownChange
Expand Down
Loading