From ccfda7b522cd3725b6a1a8a0926ba6bd3fe196f0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:33:08 +0700 Subject: [PATCH 1/2] feat(rust): treat in-repository local path packages as boundaries, not a repository-wide fallback Part of #131 (external dependency inputs, out-of-workspace Cargo.toml). As agreed in #91: a local path package that is not a workspace member but lives inside the repository (an excluded or vendored crate, or a [patch] target) no longer blocks every change. Its files stay unmodelled, so changing one keeps the full suite. Dependency edges now follow non-member packages until they reach members, so a -> vendor/bridge -> b still selects a when b changes. When such a package has a build script, or code that could read other crates' files (path literals, includes outside it, climbing out of its directory, running Cargo), the members that reach it depend on every workspace crate. Path packages outside the repository keep the repository-wide fallback, because they can change without the diff showing it. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- docs/using-diffci.md | 2 +- src/repo/adapters/rust.ts | 55 ++++++++++++++++++++++++++--- tests/repo/rust-adapter.test.ts | 45 +++++++++++++++++++++-- tests/repo/rust-integration.test.ts | 15 ++++++-- 4 files changed, 106 insertions(+), 11 deletions(-) diff --git a/docs/using-diffci.md b/docs/using-diffci.md index 19bbaf50..efba5e76 100644 --- a/docs/using-diffci.md +++ b/docs/using-diffci.md @@ -750,7 +750,7 @@ For supported languages and setup limits, see [What is included](../README.md#wh Maintainer: [@FredApps](https://github.com/FredApps). -Rust support is experimental. Cargo workspaces and single crates support conservative crate-level selection. Commands require verified plain `cargo test` evidence; wrappers and unmodeled execution contexts remain advisory. Metadata unions all features and target-platform dependencies, including dev-dependencies. Feature-conditional source stays crate-granular; required-feature test targets retain full validation. Locked registry and Git dependencies, including their build scripts and procedural macros, do not block selection: a `Cargo.lock` change keeps the full suite. A workspace crate with a build script, code that runs Cargo or rustc, or code that climbs out of its crate directory (`.parent()`, `.ancestors()`, `PathBuf::pop` or a formatted `..` path) is treated as depending on every workspace crate, so it runs for any Rust change while other crates still narrow. A literal path in Rust code that reaches another crate becomes a dependency on that crate. Only the crates plain `cargo test` covers (the root package, `default-members`, or every member of a virtual workspace) are test targets; other members stay sources whose changes reach their tested dependents. When dependency declarations request features, Cargo resolves features for each tested crate alone and with its dependents (`cargo tree`), and a selected command must give every package the features the full `cargo test` gives it. +Rust support is experimental. Cargo workspaces and single crates support conservative crate-level selection. Commands require verified plain `cargo test` evidence; wrappers and unmodeled execution contexts remain advisory. Metadata unions all features and target-platform dependencies, including dev-dependencies. Feature-conditional source stays crate-granular; required-feature test targets retain full validation. Locked registry and Git dependencies, including their build scripts and procedural macros, do not block selection: a `Cargo.lock` change keeps the full suite. A workspace crate with a build script, code that runs Cargo or rustc, or code that climbs out of its crate directory (`.parent()`, `.ancestors()`, `PathBuf::pop` or a formatted `..` path) is treated as depending on every workspace crate, so it runs for any Rust change while other crates still narrow. A literal path in Rust code that reaches another crate becomes a dependency on that crate. A local path package inside the repository that is not a workspace member (an excluded or vendored crate) is an unmodelled boundary: a change to it keeps the full suite, dependencies through it are followed, and a member that reaches one whose code could read other crates' files (a build script, path literals, includes, climbing out of its directory, running Cargo) depends on every workspace crate. A local path package outside the repository keeps the repository-wide fallback. Only the crates plain `cargo test` covers (the root package, `default-members`, or every member of a virtual workspace) are test targets; other members stay sources whose changes reach their tested dependents. When dependency declarations request features, Cargo resolves features for each tested crate alone and with its dependents (`cargo tree`), and a selected command must give every package the features the full `cargo test` gives it. | Reason | Meaning / next step | | --- | --- | diff --git a/src/repo/adapters/rust.ts b/src/repo/adapters/rust.ts index 76aa08e2..60f264ac 100644 --- a/src/repo/adapters/rust.ts +++ b/src/repo/adapters/rust.ts @@ -358,7 +358,16 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res // package outside the workspace appears, no member depends on these crates: they are fixtures or // excluded crates. Their files stay unmodelled, so changing one keeps the full suite (impact.ts) // without blocking changes elsewhere. Otherwise the repository-wide fallback stays. - const localDependencyOutside = metadata.packages.some(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null)); + // Local path packages that are not workspace members. Inside the repository they are unmodelled + // boundaries like fixture crates: a change to one keeps the full suite, and dependency edges + // through them are followed below. Outside the repository their changes are invisible to the diff. + const localNonMembers = metadata.packages.filter(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null)); + const localInside = new Map(); + for (const pkg of localNonMembers) { + const manifest = repositoryPath(root, pkg.manifest_path, known); + if (manifest && /(?:^|\/)Cargo\.toml$/.test(manifest) && manifest !== "Cargo.toml" && unmodeledManifests.includes(manifest)) localInside.set(pkg.id, manifest); + } + const localDependencyOutside = localNonMembers.some(pkg => !localInside.has(pkg.id)); const unmodeledBoundary = (file: string) => !localDependencyOutside && unmodeledManifests.some(manifest => under(file, manifest.slice(0, -"/Cargo.toml".length))); if (unmodeledManifests.length && localDependencyOutside) result.blockers.push(`Cargo manifests outside workspace membership require full validation: ${unmodeledManifests.join(", ")}`); @@ -444,21 +453,57 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res || metadata.workspace_members.some(id => !nodes.some(node => node.id === id))) { result.blockers.push("Cargo dependency resolution is missing or incomplete; full validation required"); } else { + // A member can depend on another member through packages outside the workspace (a local path + // package that itself depends on a member, or a `[patch]`ed crate). Follow dependencies through + // non-members until they reach members. An in-repository local package whose own code could + // read other crates' files (a build script, Cargo or program runs, climbing out of its + // directory, path literals or includes) makes the member depend on every workspace crate. + const byId = new Map(nodes.map(node => [node.id, node])); + const opaque = new Map(); + const opaqueLocal = (id: string) => { + const manifest = localInside.get(id); + if (!manifest) return false; + if (!opaque.has(id)) { + const directory = manifest.slice(0, -"/Cargo.toml".length); + const pkg = localNonMembers.find(candidate => candidate.id === id)!; + opaque.set(id, pkg.targets.some(target => target.kind.includes("custom-build")) + || context.files.filter(file => file.endsWith(".rs") && under(file, directory)).some(file => { + let scanned: ReturnType; + try { scanned = rustInputs(readFileSync(resolve(root, file), "utf8")); } catch { return true; } + return !scanned || scanned.compiles || scanned.navigates || scanned.documentation || scanned.paths.length > 0 + || scanned.inputs.some(input => { const path = repositoryPath(root, resolve(root, dirname(file), input.path), known); return !path || !under(path, directory); }); + })); + } + return opaque.get(id)!; + }; for (const node of nodes) { const anchor = anchors.get(node.id); if (!anchor) continue; - for (const dependency of node.dependencies) { + const reached = new Set(); + let everything = false; + const seen = new Set([node.id]); + const pending = [...node.dependencies]; + while (pending.length) { + const dependency = pending.pop()!; + if (seen.has(dependency)) continue; + seen.add(dependency); const target = anchors.get(dependency); - if (target && target !== anchor) result.edges.push({ from: anchor, to: target, kind: "import" }); + if (target) { reached.add(target); continue; } + if (opaqueLocal(dependency)) everything = true; + pending.push(...(byId.get(dependency)?.dependencies ?? [])); } + if (everything) for (const other of packages) reached.add(other.manifest); + reached.delete(anchor); + for (const target of reached) result.edges.push({ from: anchor, to: target, kind: "import" }); } } // Registry and Git dependencies are locked and immutable unless Cargo.lock changes, and a // Cargo.lock change keeps the full suite. Their build scripts and procedural macros run the same // code for the selected and the full invocation; anything they read from this repository outside // modelled Rust sources is a changed path that keeps the full suite. A local path dependency that - // is not a workspace member has no modelled ownership, so it still blocks the repository. - const localOutside = metadata.packages.filter(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null)); + // is not a workspace member and lives outside the repository can change without the diff showing it, + // so it still blocks the repository; one inside the repository is an unmodelled boundary (above). + const localOutside = localNonMembers.filter(pkg => !localInside.has(pkg.id)); if (localOutside.length) { result.blockers.push(`Local Cargo path dependencies outside the workspace require full validation: ${localOutside.map(pkg => pkg.name).sort().join(", ")}`); } diff --git a/tests/repo/rust-adapter.test.ts b/tests/repo/rust-adapter.test.ts index 9675ceba..81bf37fb 100644 --- a/tests/repo/rust-adapter.test.ts +++ b/tests/repo/rust-adapter.test.ts @@ -114,7 +114,7 @@ test("Rust detection is specific and missing root manifest falls back", () => { } finally { rmSync(root, { recursive: true, force: true }); } }); -test("an excluded nested Cargo package cannot silently become part of its parent, and blocks only if something depends on it", () => { +test("an excluded nested Cargo package cannot silently become part of its parent, and stays an unmodelled boundary", () => { const files = { "Cargo.toml": manifest("root"), "src/lib.rs": "", "excluded/Cargo.toml": manifest("excluded"), "excluded/src/lib.rs": "", "excluded/tests/api.rs": "" }; const root = fixture(files); @@ -127,7 +127,9 @@ test("an excluded nested Cargo package cannot silently become part of its parent assert.ok(!result.testFiles.includes("excluded/tests/api.rs")); const excluded = pkg(root, "excluded", "excluded"); const used = analyzeRustMetadata({ repoPath: root, files: Object.keys(files), profile: analyzeRepository({ repoPath: root }) }, metadata(root, [pkg(root, "", "root"), excluded], { workspace_members: [`path+${root}/#root@0.1.0`] })); - assert.ok(used.blockers.some(reason => reason.includes("Cargo manifests outside workspace membership") && reason.includes("excluded/Cargo.toml"))); + // Something depends on it: still no repository-wide blocker, and its files stay unmodelled. + assert.deepEqual(used.blockers, []); + assert.ok(!used.sourcePaths.includes("excluded/src/lib.rs")); } finally { rmSync(root, { recursive: true, force: true }); } }); @@ -360,6 +362,45 @@ test("registry dependencies narrow; local outside path dependencies, symlinked m } finally { rmSync(root, { recursive: true, force: true }); } }); +test("local path packages inside the repository are unmodelled boundaries; dependencies through them are followed", () => { + // a -> vendor/bridge (a local path package outside the workspace) -> b; c is independent. + const files: Record = { "Cargo.toml": '[workspace]\nmembers = ["a", "b", "c"]\nexclude = ["vendor"]\n', + "vendor/bridge/Cargo.toml": manifest("bridge"), "vendor/bridge/src/lib.rs": "pub fn bridge() -> u8 { b::value() }" }; + for (const name of ["a", "b", "c"]) Object.assign(files, { [`${name}/Cargo.toml`]: manifest(name), [`${name}/src/lib.rs`]: "pub fn value() -> u8 { 1 }" }); + const root = fixture(files); + try { + const context = { repoPath: root, files: Object.keys(files), profile: analyzeRepository({ repoPath: root }) }; + const [a, b, c] = ["a", "b", "c"].map(name => pkg(root, name, name)); + const bridge = pkg(root, "vendor/bridge", "bridge"); + const analyze = (bridgePackage: CargoPackage) => { + const packages = [a!, b!, c!, bridgePackage]; + return analyzeRustMetadata(context, metadata(root, packages, { workspace_members: [a!.id, b!.id, c!.id], + resolve: { nodes: [{ id: a!.id, dependencies: [bridgePackage.id] }, { id: bridgePackage.id, dependencies: [b!.id] }, { id: b!.id, dependencies: [] }, { id: c!.id, dependencies: [] }] } })); + }; + const result = analyze(bridge); + assert.deepEqual(result.blockers, []); + // The bridge's files are not modelled sources, so a change to one keeps the full suite. + assert.ok(!result.sourcePaths.includes("vendor/bridge/src/lib.rs")); + const tests = new Set(result.testFiles); + const graph = hydrateDependencyGraph({ nodes: result.sourcePaths.map(path => ({ path, isSource: true, isAsset: false, isTest: tests.has(path), isEntryPoint: false })), edges: result.edges } as unknown as DependencyGraph, root); + assert.deepEqual(graph.transitiveDependentsOf("b/src/lib.rs").filter(path => tests.has(path)), ["a/src/lib.rs"]); + assert.deepEqual(graph.transitiveDependentsOf("c/src/lib.rs").filter(path => tests.has(path)), []); + // A bridge whose code may read other crates' files (a build script, a path literal, climbing out + // of its directory, running Cargo) makes a depend on every workspace crate. + const opaque = (source: string, extraTargets: ReturnType[] = []) => { + writeFileSync(join(root, "vendor/bridge/src/lib.rs"), source); + const opaqueResult = analyze({ ...bridge, targets: [...bridge.targets, ...extraTargets] }); + assert.deepEqual(opaqueResult.blockers, []); + return opaqueResult.edges.filter(edge => edge.from === "a/Cargo.toml" && edge.to.endsWith("Cargo.toml")).map(edge => edge.to).sort(); + }; + assert.deepEqual(opaque("pub fn bridge() {}"), ["b/Cargo.toml"]); + assert.deepEqual(opaque("pub fn bridge() {}", [target(root, "vendor/bridge/build.rs", "build-script-build", "custom-build", false)]), ["b/Cargo.toml", "c/Cargo.toml"]); + assert.deepEqual(opaque('pub const DATA: &str = "../../c/src/lib.rs";'), ["b/Cargo.toml", "c/Cargo.toml"]); + assert.deepEqual(opaque('use std::path::Path;\npub fn up() { let _ = Path::new(env!("CARGO_MANIFEST_DIR")).parent(); }'), ["b/Cargo.toml", "c/Cargo.toml"]); + assert.deepEqual(opaque('pub fn run() { std::process::Command::new("cargo"); }'), ["b/Cargo.toml", "c/Cargo.toml"]); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + test("Cargo rejects symlink escapes and duplicate target source identities", (t) => { const files = { "Cargo.toml": manifest("root"), "src/lib.rs": "" }; const root = fixture(files); diff --git a/tests/repo/rust-integration.test.ts b/tests/repo/rust-integration.test.ts index 579d651d..5ed6b0c7 100644 --- a/tests/repo/rust-integration.test.ts +++ b/tests/repo/rust-integration.test.ts @@ -210,10 +210,19 @@ test("documentation stays full-suite when Rust code may read it, and excluded fi writeFileSync(join(root, "app/src/lib.rs"), '#[test] fn names() { assert_eq!("cmd", "cmd"); let _ = "doctor/visit"; }'); graph = await buildDependencyGraph({ repoPath: root }); assert.deepEqual(graph.profile.rustDocumentationReaders, []); - // A member that path-depends on the fixture keeps the repository-wide fallback. - output = metadata([{ id: "sample", name: "sample", manifest_path: join(root, "tests/fixtures/sample/Cargo.toml"), dependencies: [], features: {}, - targets: [{ name: "sample", kind: ["lib"], src_path: join(root, "tests/fixtures/sample/src/lib.rs"), test: true, doctest: true }] }]); + // A member that path-depends on the fixture inside the repository: the fixture stays an + // unmodelled boundary (its changes keep the full suite) and other changes still narrow. + const sample = (manifest: string) => [{ id: "sample", name: "sample", manifest_path: manifest, dependencies: [], features: {}, + targets: [{ name: "sample", kind: ["lib"], src_path: join(dirname(manifest), "src/lib.rs"), test: true, doctest: true }] }]; + output = metadata(sample(join(root, "tests/fixtures/sample/Cargo.toml"))); + graph = await buildDependencyGraph({ repoPath: root }); + assert.deepEqual(graph.adapterBlockers, []); + assert.equal(new ImpactAnalyzer().analyze(delta("core/src/lib.rs"), graph, graph.profile).fallbackRequired, false); + assert.equal(new ImpactAnalyzer().analyze(delta("tests/fixtures/sample/src/lib.rs"), graph, graph.profile).fallbackRequired, true); + // One outside the repository can change without the diff showing it: repository-wide fallback. + output = metadata(sample(join(dirname(root), "outside-sample/Cargo.toml"))); graph = await buildDependencyGraph({ repoPath: root }); assert.ok(graph.adapterBlockers?.some(reason => reason.startsWith("Cargo manifests outside workspace membership"))); + assert.ok(graph.adapterBlockers?.some(reason => reason.startsWith("Local Cargo path dependencies outside the workspace"))); } finally { rmSync(root, { recursive: true, force: true }); } }); From 6e6e5a2ac15016988c9dde909c2ebd61e6029cf0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:40:49 +0700 Subject: [PATCH 2/2] fix(rust): record readers and program runs of in-repo local packages A local path package inside the repository that is not a workspace member was scanned only to decide whether it was opaque. Its build scripts and documentation readers were never added to rustDocumentationReaders, and its program runs never set rustRunsPrograms, so a docs-only change could select no tests even when member tests call bridge code that reads the docs. Every such package is now scanned up front, reached or not. Unreadable or unscannable files count as readers and program runs. #[path] inputs resolve from the inline module base, as for members. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- docs/using-diffci.md | 2 +- src/repo/adapters/rust.ts | 59 +++++++++++++++++++++++---------- tests/repo/rust-adapter.test.ts | 59 +++++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 18 deletions(-) diff --git a/docs/using-diffci.md b/docs/using-diffci.md index 14969b54..39d52d33 100644 --- a/docs/using-diffci.md +++ b/docs/using-diffci.md @@ -753,7 +753,7 @@ For supported languages and setup limits, see [What is included](../README.md#wh Maintainer: [@FredApps](https://github.com/FredApps). -Rust support is experimental. Cargo workspaces and single crates support conservative crate-level selection. Commands require verified plain `cargo test` evidence; wrappers and unmodeled execution contexts remain advisory. Toolchain and cache actions (`dtolnay/rust-toolchain`, `actions-rust-lang/setup-rust-toolchain`, `Swatinem/rust-cache`, `actions/cache`), `rustup` steps (also chained with `&&`, with toolchain names from a matrix of plain words), `cargo build`/`check`/`clippy`/`fmt`/`doc` steps, `RUSTFLAGS`/`RUSTDOCFLAGS` set only to `-Dwarnings`, and `CARGO_TERM_*` settings count as ordinary CI. `cargo test --workspace` (or `--all`) counts as plain `cargo test` only when plain `cargo test` already tests every member: a single crate, or a virtual workspace without `default-members`. Metadata unions all features and target-platform dependencies, including dev-dependencies. Feature-conditional source stays crate-granular. A target with `required-features` keeps its package whole in a selected command (`-p name`, never `--test name`), so Cargo runs or skips it exactly as the full `cargo test` does. Locked registry and Git dependencies, including their build scripts and procedural macros, do not block selection: a `Cargo.lock` change keeps the full suite. A workspace crate with a build script, code that runs Cargo or rustc, or code that climbs out of its crate directory (`.parent()`, `.ancestors()`, `PathBuf::pop` or a formatted `..` path) is treated as depending on every workspace crate, so it runs for any Rust change while other crates still narrow. A literal path in Rust code that reaches another crate becomes a dependency on that crate. A local path package inside the repository that is not a workspace member (an excluded or vendored crate) is an unmodelled boundary: a change to it keeps the full suite, dependencies through it are followed, and a member that reaches one whose code could read other crates' files (a build script, path literals, includes, climbing out of its directory, running Cargo) depends on every workspace crate. A local path package outside the repository keeps the repository-wide fallback. Only the crates plain `cargo test` covers (the root package, `default-members`, or every member of a virtual workspace) are test targets; other members stay sources whose changes reach their tested dependents. In a Cargo-only repository, a Python helper script or a C/C++ source is confined to the crate that contains it (or its top-level directory outside every crate): a change that reaches that crate, or to the file itself, keeps the full suite, and other changes still narrow. JavaScript, Go, Java and other files that another engine could test, Python test files, files in a root package, and any repository whose Rust code starts external programs (other than Cargo, rustc or the package's own binaries) keep the repository-wide fallback. When dependency declarations request features, Cargo resolves features for each tested crate alone and with its dependents (`cargo tree`), and a selected command must give every package the features the full `cargo test` gives it. When the selected crates alone would build a shared dependency with fewer features, the command adds the tested crates of the smallest set Cargo resolved with the full run's features (it runs more tests than selected, and fewer than the full run); without such a set the plan stays advisory. +Rust support is experimental. Cargo workspaces and single crates support conservative crate-level selection. Commands require verified plain `cargo test` evidence; wrappers and unmodeled execution contexts remain advisory. Toolchain and cache actions (`dtolnay/rust-toolchain`, `actions-rust-lang/setup-rust-toolchain`, `Swatinem/rust-cache`, `actions/cache`), `rustup` steps (also chained with `&&`, with toolchain names from a matrix of plain words), `cargo build`/`check`/`clippy`/`fmt`/`doc` steps, `RUSTFLAGS`/`RUSTDOCFLAGS` set only to `-Dwarnings`, and `CARGO_TERM_*` settings count as ordinary CI. `cargo test --workspace` (or `--all`) counts as plain `cargo test` only when plain `cargo test` already tests every member: a single crate, or a virtual workspace without `default-members`. Metadata unions all features and target-platform dependencies, including dev-dependencies. Feature-conditional source stays crate-granular. A target with `required-features` keeps its package whole in a selected command (`-p name`, never `--test name`), so Cargo runs or skips it exactly as the full `cargo test` does. Locked registry and Git dependencies, including their build scripts and procedural macros, do not block selection: a `Cargo.lock` change keeps the full suite. A workspace crate with a build script, code that runs Cargo or rustc, or code that climbs out of its crate directory (`.parent()`, `.ancestors()`, `PathBuf::pop` or a formatted `..` path) is treated as depending on every workspace crate, so it runs for any Rust change while other crates still narrow. A literal path in Rust code that reaches another crate becomes a dependency on that crate. A local path package inside the repository that is not a workspace member (an excluded or vendored crate) is an unmodelled boundary: a change to it keeps the full suite, dependencies through it are followed, and a member that reaches one whose code could read other crates' files (a build script, path literals, includes, climbing out of its directory, running Cargo) depends on every workspace crate. Whether or not a member reaches it, such a package's build scripts and code that reads documentation make documentation changes keep the full suite, and code that runs other programs counts as Rust code that starts external programs. A local path package outside the repository keeps the repository-wide fallback. Only the crates plain `cargo test` covers (the root package, `default-members`, or every member of a virtual workspace) are test targets; other members stay sources whose changes reach their tested dependents. In a Cargo-only repository, a Python helper script or a C/C++ source is confined to the crate that contains it (or its top-level directory outside every crate): a change that reaches that crate, or to the file itself, keeps the full suite, and other changes still narrow. JavaScript, Go, Java and other files that another engine could test, Python test files, files in a root package, and any repository whose Rust code starts external programs (other than Cargo, rustc or the package's own binaries) keep the repository-wide fallback. When dependency declarations request features, Cargo resolves features for each tested crate alone and with its dependents (`cargo tree`), and a selected command must give every package the features the full `cargo test` gives it. When the selected crates alone would build a shared dependency with fewer features, the command adds the tested crates of the smallest set Cargo resolved with the full run's features (it runs more tests than selected, and fewer than the full run); without such a set the plan stays advisory. | Reason | Meaning / next step | | --- | --- | diff --git a/src/repo/adapters/rust.ts b/src/repo/adapters/rust.ts index 0ef4f925..9512e742 100644 --- a/src/repo/adapters/rust.ts +++ b/src/repo/adapters/rust.ts @@ -589,6 +589,46 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res const anchor = owner(file)?.manifest; if (anchor && anchor !== file) result.edges.push({ from: anchor, to: file, kind: "import" }, { from: file, to: anchor, kind: "import" }); } + // Every in-repository local package that is not a workspace member (a vendored or excluded + // "bridge" crate) is scanned up front, whether or not a member reaches it. Its build scripts and + // documentation readers count as readers, as members' do, so a docs change keeps the full suite; + // code that runs programs turns off crate scoping; and code that could read other crates' files + // makes the members that reach it depend on every workspace crate (below). What cannot be scanned + // counts as all three. + const bridgeOpaque = new Map(); + for (const [id, manifest] of localInside) { + const directory = manifest.slice(0, -"/Cargo.toml".length); + const pkg = localNonMembers.find(candidate => candidate.id === id)!; + const bridgeRoots = new Set(pkg.targets.map(target => resolvedPath(root, target.src_path))); + let isOpaque = false; + for (const target of pkg.targets.filter(target => target.kind.includes("custom-build"))) { + isOpaque = true; + (result.rustDocumentationReaders ??= []).push(repositoryPath(root, target.src_path, known) ?? manifest); + } + for (const file of context.files.filter(file => file.endsWith(".rs") && under(file, directory))) { + let scanned: ReturnType; + try { scanned = rustInputs(readFileSync(resolve(root, file), "utf8")); } catch { scanned = undefined; } + if (!scanned) { + isOpaque = true; + (result.rustDocumentationReaders ??= []).push(file); + result.rustRunsPrograms = true; + continue; + } + if (scanned.documentation) (result.rustDocumentationReaders ??= []).push(file); + if (scanned.runsPrograms) result.rustRunsPrograms = true; + // `#[path]` is relative to the file's directory, and inside inline modules to their names as + // well, which is only resolvable from a crate root or mod.rs (as for members, below). + const modRs = bridgeRoots.has(file) || /(?:^|\/)mod\.rs$/.test(file); + if (scanned.compiles || scanned.navigates || scanned.documentation || scanned.paths.length > 0 + || scanned.inputs.some(input => { + if (input.module?.length && !modRs) return true; + const base = input.module ? posix.join(dirname(file), ...input.module) : dirname(file); + const path = repositoryPath(root, resolve(root, base, input.path), known); + return !path || !under(path, directory); + })) isOpaque = true; + } + bridgeOpaque.set(id, isOpaque); + } // Cargo resolves all target platforms unless --filter-platform is supplied. // --all-features below unions optional dependencies too; cfg(feature) code // stays crate-granular and does not itself make the graph unsafe. @@ -606,23 +646,8 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res // read other crates' files (a build script, Cargo or program runs, climbing out of its // directory, path literals or includes) makes the member depend on every workspace crate. const byId = new Map(nodes.map(node => [node.id, node])); - const opaque = new Map(); - const opaqueLocal = (id: string) => { - const manifest = localInside.get(id); - if (!manifest) return false; - if (!opaque.has(id)) { - const directory = manifest.slice(0, -"/Cargo.toml".length); - const pkg = localNonMembers.find(candidate => candidate.id === id)!; - opaque.set(id, pkg.targets.some(target => target.kind.includes("custom-build")) - || context.files.filter(file => file.endsWith(".rs") && under(file, directory)).some(file => { - let scanned: ReturnType; - try { scanned = rustInputs(readFileSync(resolve(root, file), "utf8")); } catch { return true; } - return !scanned || scanned.compiles || scanned.navigates || scanned.documentation || scanned.paths.length > 0 - || scanned.inputs.some(input => { const path = repositoryPath(root, resolve(root, dirname(file), input.path), known); return !path || !under(path, directory); }); - })); - } - return opaque.get(id)!; - }; + const opaque = new Map([...localInside.keys()].map(id => [id, bridgeOpaque.get(id) === true])); + const opaqueLocal = (id: string) => opaque.get(id) === true; for (const node of nodes) { const anchor = anchors.get(node.id); if (!anchor) continue; diff --git a/tests/repo/rust-adapter.test.ts b/tests/repo/rust-adapter.test.ts index b38d383e..be0661bf 100644 --- a/tests/repo/rust-adapter.test.ts +++ b/tests/repo/rust-adapter.test.ts @@ -481,6 +481,65 @@ test("local path packages inside the repository are unmodelled boundaries; depen } finally { rmSync(root, { recursive: true, force: true }); } }); +test("local path packages inside the repository record their readers and program runs, reached or not", () => { + // a -> vendor/bridge -> b, and vendor/loose is reached by no member. Before 2026-11-18 a bridge was + // only scanned to decide whether it was opaque, so a docs change could select nothing even though + // a's tests call bridge code that reads the docs, and a bridge running `sh` kept crate scoping on. + const files: Record = { "Cargo.toml": '[workspace]\nmembers = ["a", "b"]\nexclude = ["vendor"]\n', + "vendor/bridge/Cargo.toml": manifest("bridge"), "vendor/bridge/src/lib.rs": "pub fn bridge() -> u8 { b::value() }", + "vendor/bridge/build.rs": "fn main() {}", + "vendor/loose/Cargo.toml": manifest("loose"), "vendor/loose/src/lib.rs": "pub fn loose() {}" }; + for (const name of ["a", "b"]) Object.assign(files, { [`${name}/Cargo.toml`]: manifest(name), [`${name}/src/lib.rs`]: "pub fn value() -> u8 { 1 }" }); + const root = fixture(files); + try { + const context = { repoPath: root, files: Object.keys(files), profile: analyzeRepository({ repoPath: root }) }; + const [a, b] = ["a", "b"].map(name => pkg(root, name, name)); + const bridge = pkg(root, "vendor/bridge", "bridge"); + const loose = pkg(root, "vendor/loose", "loose"); + const analyze = (bridgeSource: string, looseSource = "pub fn loose() {}", bridgeTargets: ReturnType[] = []) => { + writeFileSync(join(root, "vendor/bridge/src/lib.rs"), bridgeSource); + writeFileSync(join(root, "vendor/loose/src/lib.rs"), looseSource); + const bridgePackage = { ...bridge, targets: [...bridge.targets, ...bridgeTargets] }; + const result = analyzeRustMetadata(context, metadata(root, [a!, b!, bridgePackage, loose], { workspace_members: [a!.id, b!.id], + resolve: { nodes: [{ id: a!.id, dependencies: [bridgePackage.id] }, { id: bridgePackage.id, dependencies: [b!.id] }, { id: b!.id, dependencies: [] }, { id: loose.id, dependencies: [] }] } })); + assert.deepEqual(result.blockers, []); + return result; + }; + const plain = analyze("pub fn bridge() -> u8 { b::value() }"); + assert.deepEqual(plain.rustDocumentationReaders ?? [], []); + assert.equal(plain.rustRunsPrograms, false); + const docs = analyze('pub fn guide() -> String { std::fs::read_to_string("docs/guide.md").unwrap() }'); + assert.ok(docs.rustDocumentationReaders?.includes("vendor/bridge/src/lib.rs"), JSON.stringify(docs.rustDocumentationReaders)); + const build = analyze("pub fn bridge() {}", "pub fn loose() {}", [target(root, "vendor/bridge/build.rs", "build-script-build", "custom-build", false)]); + assert.ok(build.rustDocumentationReaders?.includes("vendor/bridge/build.rs"), JSON.stringify(build.rustDocumentationReaders)); + assert.equal(analyze('pub fn run() { std::process::Command::new("sh").arg("x.sh"); }').rustRunsPrograms, true); + // The same holds for a local package no member reaches: a member could still reach it later + // through a path no metadata shows, and the cost is only a full run for docs changes. + const looseDocs = analyze("pub fn bridge() {}", 'pub fn guide() -> String { std::fs::read_to_string("docs/guide.md").unwrap() }'); + assert.ok(looseDocs.rustDocumentationReaders?.includes("vendor/loose/src/lib.rs")); + assert.equal(analyze("pub fn bridge() {}", 'pub fn run() { std::process::Command::new("python3"); }').rustRunsPrograms, true); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + +test("a bridge with #[path] modules is opaque, wherever its module base resolves", () => { + // rustc reads `mod inner { #[path = "y.rs"] mod y; }` in util.rs (neither a crate root nor mod.rs) + // from a directory the scan does not model, so the bridge must make a depend on every crate. + const files: Record = { "Cargo.toml": '[workspace]\nmembers = ["a", "c"]\nexclude = ["vendor"]\n', + "vendor/bridge/Cargo.toml": manifest("bridge"), "vendor/bridge/src/lib.rs": "mod util;", + "vendor/bridge/src/util.rs": 'mod inner { #[path = "y.rs"] mod y; }' }; + for (const name of ["a", "c"]) Object.assign(files, { [`${name}/Cargo.toml`]: manifest(name), [`${name}/src/lib.rs`]: "pub fn value() -> u8 { 1 }" }); + const root = fixture(files); + try { + const context = { repoPath: root, files: Object.keys(files), profile: analyzeRepository({ repoPath: root }) }; + const [a, c] = ["a", "c"].map(name => pkg(root, name, name)); + const bridge = pkg(root, "vendor/bridge", "bridge"); + const result = analyzeRustMetadata(context, metadata(root, [a!, c!, bridge], { workspace_members: [a!.id, c!.id], + resolve: { nodes: [{ id: a!.id, dependencies: [bridge.id] }, { id: bridge.id, dependencies: [] }, { id: c!.id, dependencies: [] }] } })); + assert.deepEqual(result.blockers, []); + assert.deepEqual(result.edges.filter(edge => edge.from === "a/Cargo.toml" && edge.to.endsWith("Cargo.toml")).map(edge => edge.to).sort(), ["c/Cargo.toml"]); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + test("Cargo rejects symlink escapes and duplicate target source identities", (t) => { const files = { "Cargo.toml": manifest("root"), "src/lib.rs": "" }; const root = fixture(files);