crates/nornir-graph/tests/rayon_free_law.rs
//! Guard test for the constellation's **rayon-free law** (ROOT LAW #0), scoped to
//! the whole `edda` workspace. edda had NO such guard; its siblings are
//! `skade/skade/tests/rayon_free_law.rs`, `znippy/tests/tests/rayon_free_law.rs`
//! and `znippy-zoomies/tests/rayon_free_law.rs`.
//!
//! # What the law says, and what this guard therefore checks
//!
//! ROOT LAW #0 is about what NORDISK code does: every CPU fan-out routes through the
//! `gatling` engine, and no first-party crate reaches for rayon. edda additionally
//! carries NO rayon at all any more — `nornir-graph`'s `cozo` backend runs on
//! `vendor/cozo-rayonfree`, a vendored fork with rayon removed at the source — so
//! there are two distinct claims here, and they need different guards.
//!
//! ## The claim that is easy to check blindly
//!
//! "No rayon in the tree." [`no_rayon_in_the_dependency_tree`] resolves the REAL
//! dependency graph under `--all-features`. That qualifier is the whole point: the
//! `cozo` backend is OFF BY DEFAULT, so `cargo tree -e normal` on the default
//! feature set is a single line — and it was a single line for the entire period
//! rayon was one `--features cozo` away. A guard that only looked at the default set
//! would have passed serenely throughout. That is the silent green this house hunts.
//!
//! **Scope, stated honestly.** That test covers `nornir-graph`, which is where the
//! rayon route was and where the vendored fork lives. It is NOT a claim about the
//! whole workspace: as of 2026-08-01 edda's lockfile still reaches rayon through
//! `typst-library`, `typst-utils`, `krilla`, `image`, `ravif`, `exr`,
//! `av-scenechange`, `dify`, `maybe-rayon` and `sysinfo` — the docs-rendering and
//! image stack pulled in by other members. None of that is first-party code, none of
//! it is reachable from `nornir-graph`, and clearing it is a different and much
//! larger job than this one. Saying so here beats letting a future reader infer from
//! a green test that edda is rayon-free end to end. It is not.
//!
//! ## The claim that matters more, and lasts longer
//!
//! "No first-party code CALLS rayon." That survives the fork being retired, and it
//! is what the law actually says. [`no_first_party_source_calls_rayon`] and
//! [`no_first_party_manifest_declares_rayon`] check it directly, and
//! [`every_member_is_classified`] keeps them honest about the word "first-party"
//! — a `vendor/*` member entering the workspace trips it, so whoever adds one has to
//! decide deliberately rather than discover later that the guard has quietly been
//! reading somebody else's code.
//!
//! # Calls versus comments
//!
//! Every "rayon" hit in edda's own source is a COMMENT forbidding it — 10 of them in
//! `crates/*/src` when this was written, in `nornir-fleet`, `nornir-bench` and
//! `nornir-graph`, plus this file's own vocabulary table. A naive `grep -r rayon`
//! guard would be permanently red on the very prose that enforces the law, and a
//! guard that cries wolf is weakened or ignored inside a week.
//!
//! So `//`-to-end-of-line is stripped from every source line before matching, `#`
//! likewise from manifests, and the iterator adaptors are matched as method CALLS
//! (`.par_iter(` — leading dot, trailing paren) so an identifier like `par_sorted` is
//! never a false positive. Both mechanisms are PROVED, not asserted:
//! [`the_token_scan_distinguishes_calls_from_commentary`] feeds the detector real
//! violations and real commentary and requires it to tell them apart.
//!
//! # The false-positive anchor
//!
//! A guard that has only ever seen clean input is unproven in the direction that
//! actually kills guards. `tests/fixtures/third_party_sample.rs.fixture` is a
//! stand-in for a third-party crate that uses rayon legitimately;
//! [`the_scan_sees_third_party_rayon_but_does_not_scan_it`] requires the detector to
//! FIRE on its contents while the first-party walk never collects it. That is what
//! makes "no first-party violations" a scoped measurement rather than an empty one.
//! The fixture is named `.rs.fixture` rather than `.rs` so it is excluded BY
//! CONSTRUCTION — no allowlist to rot.
//!
//! # What this guard deliberately does NOT check
//!
//! The siblings also enforce the **one-engine law** (no private `thread::spawn` /
//! `crossbeam` / `ThreadPoolBuilder` worker pools outside `gatling`). That half is
//! NOT ported here, and it is a measured decision rather than an oversight: 8 files
//! under `crates/*/src` use `std::thread::spawn` today (jera's agent and boot paths,
//! nornir-fleet's spinner and mock server, nornir-testmatrix's runner,
//! nornir-build-thing's progress reporter, nornir-bench's telemetry). Each is a
//! single long-lived I/O / supervisor / telemetry thread rather than a work-stealing
//! pool, so porting the sibling test would have meant porting an 8-entry allowlist
//! that asserts nothing. A real one-engine guard for edda is its own piece of work;
//! dressing this file up as one would be the same disease from the other end.
use std::path::{Path, PathBuf};
use std::process::Command;
// ───────────────────────── workspace discovery ─────────────────────────
/// The edda workspace root: walk up from this crate's manifest dir until a
/// `Cargo.toml` containing a `[workspace]` table turns up.
///
/// Panics rather than skipping if it is not found. A guard that quietly opts out
/// when it cannot locate its subject is a guard that always passes.
fn workspace_root() -> PathBuf {
let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
loop {
let manifest = dir.join("Cargo.toml");
if let Ok(text) = std::fs::read_to_string(&manifest) {
if text.lines().any(|l| l.trim() == "[workspace]") {
return dir;
}
}
assert!(
dir.pop(),
"walked to the filesystem root without finding a Cargo.toml containing \
`[workspace]` — this guard cannot run detached from the edda workspace, \
and must not pretend it passed"
);
}
}
/// Strip a `#`-to-end-of-line TOML comment. This is what lets a manifest discuss
/// rayon at length — as `crates/nornir-graph/Cargo.toml` does — without tripping
/// the manifest check.
fn strip_hash_comment(s: &str) -> &str {
match s.find('#') {
Some(i) => &s[..i],
None => s,
}
}
/// Strip a `//`-to-end-of-line comment so the token scan only sees live code. Every
/// rayon mention in edda's first-party source is prose forbidding it; commentary
/// about the law is not a violation of it.
fn strip_line_comment(line: &str) -> &str {
match line.find("//") {
Some(i) => &line[..i],
None => line,
}
}
/// Every workspace member directory, read from the root `Cargo.toml` `members`
/// array with `crates/*`-style globs expanded by directory listing — so a newly
/// added crate is covered automatically, with no carve-out to forget.
fn member_dirs() -> Vec<PathBuf> {
let root = workspace_root();
let manifest = std::fs::read_to_string(root.join("Cargo.toml")).expect("read root Cargo.toml");
let start = manifest
.find("members")
.expect("root Cargo.toml has a `members` list");
let open = manifest[start..].find('[').expect("members array opens") + start;
let close = manifest[open..].find(']').expect("members array closes") + open;
let mut dirs = Vec::new();
for raw in manifest[open + 1..close].split(',') {
let entry = strip_hash_comment(raw).trim().trim_matches('"').trim();
if entry.is_empty() {
continue;
}
match entry.strip_suffix("/*") {
Some(parent) => {
let base = root.join(parent);
let rd = std::fs::read_dir(&base)
.unwrap_or_else(|e| panic!("read member glob dir {base:?}: {e}"));
for e in rd.flatten() {
let p = e.path();
if p.join("Cargo.toml").is_file() {
dirs.push(p);
}
}
}
None => dirs.push(root.join(entry)),
}
}
dirs.sort();
dirs
}
/// The members this guard's scans actually read: the FIRST-PARTY ones, under
/// `crates/`.
///
/// `vendor/*` members are deliberately excluded. They are verbatim (or minimally
/// patched) copies of third-party crates, and ROOT LAW #0 governs what nordisk code
/// does — a vendored fork keeps its upstream's patterns. Scanning them would make
/// this guard red on somebody else's style choices, and a guard that cries wolf gets
/// weakened or ignored.
///
/// The exclusion is not a blanket amnesty. `vendor/cozo-rayonfree` exists precisely
/// to REMOVE rayon, and [`the_vendored_cozo_fork_stays_rayon_free`] plus
/// [`no_rayon_in_the_dependency_tree`] hold it to that — by dependency graph and by
/// manifest, which is stronger than a token scan would be.
/// [`every_member_is_classified`] makes sure a member cannot slip into neither bucket.
fn first_party_member_dirs() -> Vec<PathBuf> {
let crates = workspace_root().join("crates");
member_dirs().into_iter().filter(|d| d.starts_with(&crates)).collect()
}
/// The third-party members: `vendor/*`.
fn vendor_member_dirs() -> Vec<PathBuf> {
let vendor = workspace_root().join("vendor");
member_dirs().into_iter().filter(|d| d.starts_with(&vendor)).collect()
}
/// Recursively collect every `*.rs` path under `dir`.
fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(rd) = std::fs::read_dir(dir) else { return };
for entry in rd.flatten() {
let path = entry.path();
if path.is_dir() {
rs_files(&path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
out.push(path);
}
}
}
fn norm(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
// ───────────────────────── the token vocabulary ─────────────────────────
/// Tokens that can only appear when **rayon is actually being used**. Same list as
/// the three sibling guards, deliberately — the vocabulary is shared law, and a
/// token that trips skade must trip edda.
///
/// The adaptors are matched as method CALLS (leading dot, trailing paren) so a bare
/// identifier is never a false positive. `rayon::ThreadPool` and `ThreadPoolBuilder`
/// are here too: building a pool by hand is the same sin as calling into one.
const FORBIDDEN_RAYON: &[&str] = &[
"use rayon",
"rayon::",
"extern crate rayon",
".into_par_iter(",
".par_iter(",
".par_iter_mut(",
".par_bridge(",
".par_chunks(",
".par_sort(",
".par_sort_by(",
".par_sort_unstable(",
"ParallelIterator",
"IntoParallelIterator",
"ThreadPoolBuilder",
];
/// Does this line of source (comments already stripped) *use* rayon?
fn rayon_call_in(code: &str) -> Option<&'static str> {
FORBIDDEN_RAYON.iter().find(|t| code.contains(**t)).copied()
}
/// The ONE file the source scan skips: this one.
///
/// [`FORBIDDEN_RAYON`] is a literal table of every forbidden token and
/// [`the_token_scan_distinguishes_calls_from_commentary`] feeds the detector real
/// violations on purpose, so a guard that scanned itself would report 17 violations
/// against its own body and could never go green. (It did exactly that on first
/// run, which is a pleasant demonstration that the scanner works.) The three sibling
/// guards dodge this only by never looking at `tests/` at all; this one does look
/// there, so the exemption is explicit, is exactly one path suffix, and is asserted
/// to match exactly one file.
///
/// It costs nothing: the detector's correctness is not established by scanning this
/// file, it is established directly by
/// [`the_token_scan_distinguishes_calls_from_commentary`].
const SELF: &str = "/tests/rayon_free_law.rs";
// ───────────────────────── the first-party scans ─────────────────────────
/// Every first-party `.rs` file in the workspace.
fn first_party_rs_files() -> Vec<PathBuf> {
let mut files = Vec::new();
for dir in first_party_member_dirs() {
for sub in ["src", "tests", "benches", "examples"] {
rs_files(&dir.join(sub), &mut files);
}
}
files
}
/// Scan first-party source for live rayon usage. Returns one line per violation.
/// Shared by the check and by the calibration anchor, so the anchor tests the SAME
/// code path rather than a lookalike.
fn first_party_source_violations() -> Vec<String> {
let mut violations = Vec::new();
for file in first_party_rs_files() {
if norm(&file).ends_with(SELF) {
continue;
}
let text = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("read {file:?}: {e}"));
for (lineno, raw) in text.lines().enumerate() {
let code = strip_line_comment(raw);
if let Some(tok) = rayon_call_in(code) {
violations.push(format!(
"{}:{}: live `{tok}` — {}",
norm(&file),
lineno + 1,
code.trim()
));
}
}
}
violations
}
/// Every first-party manifest: the workspace root plus every member.
fn first_party_manifests() -> Vec<PathBuf> {
let mut m = vec![workspace_root().join("Cargo.toml")];
m.extend(first_party_member_dirs().into_iter().map(|d| d.join("Cargo.toml")));
m
}
/// Scan first-party manifests for a self-declared rayon dependency. Returns
/// `(violations, dependency_lines_examined)` — the second value is the anchor, so a
/// broken table parse cannot masquerade as compliance.
fn first_party_manifest_violations() -> (Vec<String>, usize) {
let mut offenders = Vec::new();
let mut dep_lines_seen = 0usize;
for manifest in first_party_manifests() {
let Ok(text) = std::fs::read_to_string(&manifest) else {
panic!("declared workspace member has no readable Cargo.toml: {manifest:?}")
};
let mut in_deps = false;
for raw in text.lines() {
let line = raw.trim();
if line.starts_with('[') {
// `[dependencies]`, `[dev-dependencies]`, `[build-dependencies]`,
// `[target.….dependencies]` — and the cargo-normalized
// `[dependencies.rayon]` table form.
in_deps = line.contains("dependencies]") || line.contains("dependencies.");
if let Some(name) = line
.strip_prefix('[')
.and_then(|l| l.strip_suffix(']'))
.and_then(|l| l.split("dependencies.").nth(1))
{
if name == "rayon" || name == "rayon-core" {
offenders.push(format!("{}: {line}", norm(&manifest)));
}
}
continue;
}
if !in_deps || line.is_empty() {
continue;
}
let code = strip_hash_comment(line);
let key = code.split('=').next().unwrap_or("").trim();
if key.is_empty() {
continue;
}
dep_lines_seen += 1;
if key == "rayon" || key == "rayon-core" {
offenders.push(format!("{}: {}", norm(&manifest), code.trim()));
}
}
}
(offenders, dep_lines_seen)
}
// ───────────────────────── 1. first-party source ─────────────────────────
/// No first-party `.rs` file may *use* rayon. Prose about rayon is fine — and edda
/// has a lot of it, all of it forbidding rayon.
#[test]
fn no_first_party_source_calls_rayon() {
let files = first_party_rs_files();
// Anchor: a mistyped path or a broken `members` parse would walk nothing at all
// and report a serene green. edda carried 243 `.rs` files under `crates/*/src`
// alone when this guard was written.
assert!(
files.len() > 200,
"only found {} .rs files across the workspace — the scan is not reaching the \
source tree, so a green here would mean nothing",
files.len()
);
// Anchor: the self-exemption must remove exactly one file, not silently swallow
// half the tree because someone loosened `SELF`.
let skipped = files.iter().filter(|f| norm(f).ends_with(SELF)).count();
assert_eq!(
skipped, 1,
"expected the scan to skip exactly one file (this one); it skipped {skipped}"
);
let violations = first_party_source_violations();
assert!(
violations.is_empty(),
"rayon-free law violated (ROOT LAW #0: nordisk code fans out through \
`gatling`, never rayon):\n{}",
violations.join("\n"),
);
}
/// The scan is only worth something if it can tell a rayon CALL from a comment
/// forbidding rayon. Prove both directions on the real predicate.
#[test]
fn the_token_scan_distinguishes_calls_from_commentary() {
for dirty in [
"use rayon::prelude::*;",
" let x = items.par_iter().map(f).collect();",
"fn f<I: ParallelIterator>(i: I) {}",
" let pool = ThreadPoolBuilder::new().build().unwrap();",
" rayon::spawn(move || work());",
] {
assert!(
rayon_call_in(strip_line_comment(dirty)).is_some(),
"the rayon detector failed to fire on a genuine call: {dirty:?} — every green \
it has ever reported would be worthless"
);
}
for clean in [
// real shapes taken from edda's own source
"//! - **fleet fan-out = jera** (ROOT LAW #0): no raw `thread::spawn`/rayon here.",
"/// 2. Export `RAYON_NUM_THREADS=1` for benchers that build a rayon pool from",
"// This module deliberately does not use rayon::prelude::*;",
"let n = par_sorted_len;",
] {
assert!(
rayon_call_in(strip_line_comment(clean)).is_none(),
"the rayon detector fired on commentary rather than a call: {clean:?} — a guard \
that is red on the prose enforcing the law gets ignored, which is worse than \
no guard"
);
}
}
// ───────────────────────── 2. first-party manifests ─────────────────────────
/// No first-party manifest may declare rayon as its own dependency.
///
/// This is the FIRST-PARTY half and it stays true even if the vendored fork is one
/// day retired and cozo's rayon comes back transitively — which is why it is a
/// separate check from [`no_rayon_in_the_dependency_tree`] rather than folded into
/// it. A transitive dependency is not a declaration.
#[test]
fn no_first_party_manifest_declares_rayon() {
let manifests = first_party_manifests();
assert!(
manifests.len() > 40,
"only found {} manifests — the member list is not being parsed",
manifests.len()
);
let (offenders, dep_lines_seen) = first_party_manifest_violations();
// Anchor: if the `[dependencies]` detection broke, not one line would ever be
// examined and the result would look exactly like compliance.
assert!(
dep_lines_seen > 100,
"examined only {dep_lines_seen} dependency lines across {} manifests — the \
`[dependencies]` detection is broken, so a green means nothing",
manifests.len()
);
assert!(
offenders.is_empty(),
"a first-party Cargo.toml declares a rayon dependency (ROOT LAW #0 forbids it; \
route CPU fan-out through `gatling`):\n{}",
offenders.join("\n"),
);
}
// ───────────────────────── 3. the scope itself ─────────────────────────
/// The scans above claim to cover FIRST-PARTY code. That claim rests on every
/// workspace member landing in a known bucket: `crates/*` is ours and is scanned,
/// `vendor/*` is somebody else's and is not.
///
/// A member in neither bucket trips this. That is the point — when the vendored cozo
/// fork was added as `vendor/cozo-rayonfree`, this test went red and FORCED the
/// exclusion to be written down deliberately, instead of the guard quietly starting
/// to scan third-party source (or quietly missing it). It will do the same for the
/// next one.
#[test]
fn every_member_is_classified() {
let root = workspace_root();
let all = member_dirs();
let first = first_party_member_dirs();
let vendored = vendor_member_dirs();
let unclassified: Vec<String> = all
.iter()
.filter(|d| !d.starts_with(root.join("crates")) && !d.starts_with(root.join("vendor")))
.map(|d| norm(d))
.collect();
assert!(
unclassified.is_empty(),
"workspace members in neither `crates/` (ours, scanned) nor `vendor/` \
(third-party, not scanned). Put them in a bucket deliberately — silently \
scanning third-party source is how a rayon guard becomes a false-positive \
machine, and silently skipping ours is how it becomes decorative:\n {}",
unclassified.join("\n ")
);
assert_eq!(
first.len() + vendored.len(),
all.len(),
"member classification does not partition the member list"
);
// Anchor: if the first-party bucket were empty, every scan above would be
// vacuously green.
assert!(
first.len() > 40,
"only {} first-party members — the scans would be reading almost nothing",
first.len()
);
// And the vendored members must genuinely be OUT of what the scans read.
let scanned = first_party_rs_files();
for v in &vendored {
assert!(
!scanned.iter().any(|f| f.starts_with(v)),
"the first-party source scan is reaching into the vendored member {} — \
it would go red on upstream's patterns, not ours",
norm(v)
);
}
}
// ───────────── 4. the calibration anchor: transitive rayon is FINE ─────────────
/// Resolve `nornir-graph`'s normal dependency graph with every feature on, one
/// package per line.
fn nornir_graph_tree_all_features() -> String {
let root = workspace_root();
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
let out = Command::new(&cargo)
.current_dir(&root)
.args([
"tree",
"-p",
"nornir-graph",
"--all-features",
"-e",
"normal",
"--prefix",
"none",
])
.output()
.unwrap_or_else(|e| panic!("could not run `{cargo} tree`: {e}"));
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
out.status.success(),
"`cargo tree -p nornir-graph --all-features` failed (status {:?}).\n\
--- stderr ---\n{stderr}\n--- stdout ---\n{stdout}",
out.status.code()
);
stdout
}
/// Is `pkg` a package in this tree output? Matches the package NAME at the start of
/// a line, so `rayon` never matches `rayon-core` and neither matches a crate that
/// merely contains the word.
fn tree_contains(tree: &str, pkg: &str) -> bool {
tree.lines()
.map(str::trim)
.any(|l| l == pkg || l.starts_with(&format!("{pkg} v")))
}
/// **The acceptance test for the vendored fork.** No rayon anywhere in
/// `nornir-graph`'s dependency graph, at ANY feature setting.
///
/// Deliberately not written as `cargo tree -i rayon`: that command prints
/// `package ID specification 'rayon' did not match any packages` and exits non-zero
/// whether rayon is genuinely absent or the name was fat-fingered — the two outcomes
/// are byte-identical, which is exactly the "check output, not exit code" trap. This
/// resolves the whole tree and reads the packages out of it, with anchors first.
#[test]
fn no_rayon_in_the_dependency_tree() {
let tree = nornir_graph_tree_all_features();
// ── Anchors, before the claim ──────────────────────────────────────────────
// A default-features resolve of this crate is a SINGLE line (it is a true leaf),
// so an accidental loss of `--all-features` would make the claim vacuous.
assert!(
tree.lines().filter(|l| !l.trim().is_empty()).count() > 50,
"the --all-features tree has only {} lines — that is not a resolved graph, and \
'no rayon in it' would be an empty measurement.\n{tree}",
tree.lines().count()
);
for expected in [
"nornir-graph",
// the optional backends, proving --all-features really switched them on
"petgraph",
"serde",
// a TRANSITIVE dependency of cozo, proving the resolve reached past the
// direct dependencies and into the Datalog engine itself
"smartstring",
] {
assert!(
tree_contains(&tree, expected),
"`{expected}` is missing from the --all-features tree, so --all-features did \
NOT switch the optional backends on and this test is measuring nothing. \
THIS is the failure mode the guard exists to avoid.\n{tree}"
);
}
// ── The claim ──────────────────────────────────────────────────────────────
for forbidden in ["rayon", "rayon-core"] {
assert!(
!tree_contains(&tree, forbidden),
"ROOT LAW #0 violated: `{forbidden}` is reachable from nornir-graph under \
--all-features.\n\
`cargo tree -p nornir-graph --all-features -i {forbidden}` will show who \
pulls it. Almost certainly cozo: `vendor/cozo-rayonfree` exists precisely \
to prevent this. Check that the `cozo` dependency line still points at the \
vendored path and has not been re-pointed at crates.io `cozo`, and that \
`graph-algo` has not been reinstated — `graph`/`graph_builder` declare \
rayon as a HARD dependency, so that feature can never be rayon-free.\n{tree}"
);
}
// ── Anchor, AFTER the claim: is it still the FORK doing the work? ──────────
// Deliberately last. Stock crates.io cozo 0.7.6 cannot be built rayon-free, so
// if this fires on its own, something else is now providing `cozo` and needs its
// own justification.
assert!(
tree_contains(&tree, "cozo-rayonfree"),
"the cozo backend is no longer the vendored fork. Stock cozo 0.7.6 declares \
rayon optional and then uses it unconditionally, so whatever is providing \
`cozo` now needs its own account of how it stays rayon-free.\n{tree}"
);
}
/// The vendored fork is the reason the tree above is clean. Pin the properties that
/// make it so, so a well-meaning "let us re-sync with upstream" cannot quietly undo
/// them.
#[test]
fn the_vendored_cozo_fork_stays_rayon_free() {
let dir = workspace_root().join("vendor/cozo-rayonfree");
assert!(
dir.join("Cargo.toml").is_file(),
"vendor/cozo-rayonfree is gone. If upstream cozo fixed its optional/unconditional \
rayon mismatch and nornir-graph depends on crates.io cozo again, delete this test \
along with the fork — do not leave it pointing at nothing."
);
let manifest = std::fs::read_to_string(dir.join("Cargo.toml")).expect("read fork manifest");
// (a) `graph-algo` must stay deleted: `graph` 0.3 and `graph_builder` declare
// rayon as a HARD dependency, so the feature cannot be reinstated AND kept
// rayon-free, no matter what the fork's own source does.
for line in manifest.lines() {
let code = strip_hash_comment(line).trim();
assert!(
!code.starts_with("graph-algo") && !code.contains("\"graph-algo\""),
"`graph-algo` is back in vendor/cozo-rayonfree/Cargo.toml — it pulls rayon \
unavoidably via `graph`/`graph_builder`:\n {code}"
);
}
// (b) no `graph` or `rayon` dependency table.
for forbidden in ["[dependencies.rayon]", "[dependencies.graph]"] {
assert!(
!manifest.contains(forbidden),
"vendor/cozo-rayonfree/Cargo.toml has reacquired `{forbidden}`"
);
}
// (c) the algos tree stays deleted — it held the unconditional
// `use rayon::prelude::*` in all_pairs_shortest_path.rs and
// shortest_path_dijkstra.rs.
assert!(
!dir.join("src/fixed_rule/algos").exists(),
"vendor/cozo-rayonfree/src/fixed_rule/algos/ is back; it carries unconditional \
rayon imports"
);
// Anchor: the fork must still BE cozo, or (a)-(c) are trivially true of an empty
// directory.
let mut files = Vec::new();
rs_files(&dir.join("src"), &mut files);
assert!(
files.len() > 50,
"vendor/cozo-rayonfree/src has only {} .rs files — that is not CozoDB, so the \
checks above are vacuous",
files.len()
);
assert!(
dir.join("src/query/eval.rs").is_file() && dir.join("src/lib.rs").is_file(),
"the two patched files (src/lib.rs, src/query/eval.rs) are missing from the fork"
);
}
/// Non-vacuity for [`tree_contains`]: it must answer TRUE for something present and
/// FALSE for something absent, or the anchor above proves nothing. Without this,
/// `tree_contains` could be `|_, _| true` and the rayon-is-present premise would
/// still "hold".
#[test]
fn the_tree_matcher_is_a_real_measurement() {
let tree = nornir_graph_tree_all_features();
assert!(
tree_contains(&tree, "petgraph"),
"the tree matcher cannot see `petgraph`, which IS in the --all-features tree.\n{tree}"
);
assert!(
tree_contains(&tree, "smartstring"),
"the tree matcher cannot see `smartstring`, a TRANSITIVE dependency of cozo — so \
it is not reading past the direct dependencies.\n{tree}"
);
assert!(
!tree_contains(&tree, "a-package-that-does-not-exist"),
"the tree matcher claims to see a package that cannot be there — it matches too \
loosely to mean anything.\n{tree}"
);
// Name matching must be exact-at-the-start, not a substring.
assert!(
!tree_contains("rayon-core v1.13.0", "rayon"),
"the matcher treats `rayon-core` as `rayon` — prefix matching is too loose"
);
assert!(
tree_contains("rayon-core v1.13.0", "rayon-core"),
"the matcher cannot match `rayon-core` by its own name"
);
}
// ───────────── the false-positive anchor: scoped, not blind ─────────────
/// **Proof that the first-party scan is SCOPED rather than simply lucky.**
///
/// Every other test here reports "no violations found". That is only meaningful if
/// the scan could have found some — and, just as importantly, if it correctly
/// declines to flag rayon that is not ours. Before the vendored fork landed, that
/// second half was demonstrated by cozo's own transitive rayon; now that edda has
/// none at all, the anchor needs a different vehicle or it silently disappears, and
/// a guard unproven against false positives is the kind that gets deleted the first
/// time it misfires.
///
/// The vehicle is `tests/fixtures/third_party_sample.rs.fixture`: a stand-in for a
/// third-party crate using rayon perfectly legitimately. This test requires BOTH
/// halves —
///
/// * the detector FIRES on its contents, so it can genuinely see rayon; and
/// * the first-party file walk never collected it, so the scan's verdict is scoped.
///
/// The fixture is excluded by CONSTRUCTION, not by an allowlist: the walk collects
/// `*.rs` and the fixture is `.rs.fixture`. There is no carve-out to rot.
#[test]
fn the_scan_sees_third_party_rayon_but_does_not_scan_it() {
let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/third_party_sample.rs.fixture");
let text = std::fs::read_to_string(&fixture).unwrap_or_else(|e| {
panic!("read the third-party fixture at {fixture:?}: {e} — without it this guard \
has never been shown a false-positive case")
});
// Half one: the detector really does fire on third-party rayon.
let hits: Vec<&'static str> = text
.lines()
.filter_map(|l| rayon_call_in(strip_line_comment(l)))
.collect();
assert!(
hits.len() >= 3,
"the detector found only {} rayon token(s) in a fixture that is full of them — \
it cannot see rayon, so every 'no violations' verdict it has given is worthless. \
Found: {hits:?}",
hits.len()
);
// Half two: and the first-party walk never went near it.
let collected = first_party_rs_files();
assert!(
!collected.iter().any(|f| f == &fixture),
"the first-party scan collected the third-party fixture — the scope is not \
holding, and this guard is now reading code that is not ours"
);
// Same story for the manifest side.
let fixture_manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/third_party_sample.Cargo.toml.fixture");
assert!(
std::fs::read_to_string(&fixture_manifest)
.expect("read the third-party manifest fixture")
.contains("rayon = \"1\""),
"the manifest fixture no longer declares rayon, so it cannot stand in for a \
third-party crate that does"
);
assert!(
!first_party_manifests().contains(&fixture_manifest),
"the manifest scan picked up the third-party fixture manifest — scope broken"
);
}