From a4ee8e726c2f97428fd8f380cce4df342e941179 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 15:03:38 +1300 Subject: [PATCH] Hash the jobs a job needs into its hash A job's hash covered its own inputs but not the jobs it needs. When test needs build and uses its artifact, a change to build's inputs alone made build run while test skipped on its unchanged hash: a false skip. hash_job's digest computation becomes job_digest (same place, same steps), which now ends with the whole digest of every job the job needs, in sorted order, transitively, through the small needs_hash module. A job it doesn't need stays out. A cycle (which the loader already rejects) is an error rather than a recursion. Tests: a mockci scenario where changing build's input makes test run, and a hash test for a two-step chain plus an unrelated job. STATUS 22 records it as resolved; the inputs and jobs docs say what the hash now covers. --- docs/src/content/docs/inputs.md | 3 ++ docs/src/content/docs/jobs.md | 3 +- internal_docs/STATUS.md | 13 +++-- src/commands/hash.rs | 93 +++++++++++++++++++++++---------- src/commands/mod.rs | 1 + src/commands/needs_hash.rs | 52 ++++++++++++++++++ tests/derived_inputs.rs | 54 +++++++++++++++++++ 7 files changed, 185 insertions(+), 34 deletions(-) create mode 100644 src/commands/needs_hash.rs diff --git a/docs/src/content/docs/inputs.md b/docs/src/content/docs/inputs.md index 530576e..62e3114 100644 --- a/docs/src/content/docs/inputs.md +++ b/docs/src/content/docs/inputs.md @@ -82,6 +82,9 @@ On top of the job's `inputs`, a job's hash covers: - **cigen's version**, the job's id and workflow, the **job's own definition**, and its **workflow's settings**. Changing a step reruns the job. +- **The jobs it `needs`**, each by its whole hash, and so the jobs those need too. A job usually uses what the jobs + before it made, so a change that reruns `build` also reruns the `test` that needs it. A job it doesn't need isn't in + its hash. - **Commands** the job uses, and the commands those use. - **Services** the job names. - **Top-level provider blocks** (`github:`, `circleci:`), which shape every generated job. diff --git a/docs/src/content/docs/jobs.md b/docs/src/content/docs/jobs.md index 251b343..4a8087d 100644 --- a/docs/src/content/docs/jobs.md +++ b/docs/src/content/docs/jobs.md @@ -65,7 +65,8 @@ To choose a GitHub runner for a container job, set `runs-on` in the job's `githu ## `needs` `needs` takes one job id or a list. Every id must be a job in the config, and a job can't need itself. Generated jobs -keep the dependencies. +keep the dependencies. A job's hash includes the hashes of the jobs it needs, so it runs again whenever one of them +would (see [inputs](/docs/inputs/)). ## Services diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 15850d0..8de1a8a 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -43,11 +43,12 @@ What the code does today, checked against the code in December 2026. Where cigen top level allows `$schema`. `tests/json_schema.rs` fails when they're stale (refresh with `CIGEN_UPDATE_GOLDEN=1 cargo test --test json_schema`) and checks every config in the repository against them. -- **Derived inputs** (`src/inputs.rs`): `cigen hash --job` adds, on top of a job's `inputs`, the commands it uses - (through other commands too), the services it names, the top-level provider blocks, every project file its steps - name (`sh scripts/check.sh`, `require('./x.js')`, every file of a local `uses: ./action`), and the root toolchain - pins, lockfiles and `package.json` `packageManager`, plus each module's resolved parameters, its steps for every - provider the config names, and the files it contributes. Each rule includes too much rather than too little. +- **Derived inputs** (`src/inputs.rs`, `src/commands/needs_hash.rs`): `cigen hash --job` adds, on top of a job's + `inputs`, the hashes of the jobs it `needs` (transitively, so a changed build reruns the tests that need it), the + commands it uses (through other commands too), the services it names, the top-level provider blocks, every project + file its steps name (`sh scripts/check.sh`, `require('./x.js')`, every file of a local `uses: ./action`), and the root + toolchain pins, lockfiles and `package.json` `packageManager`, plus each module's resolved parameters, its steps for + every provider the config names, and the files it contributes. Each rule includes too much rather than too little. - **Globs** (`src/pathspec.rs`): every glob cigen hashes (job and group `inputs`, module inputs, `hash --pattern`) is matched by `pathspec::list_files`, with gitignore's rules: a glob with no `/` matches at any depth (`*.md` is `**/*.md`), a leading `/` or `./` anchors it to the root, a glob with a `/` elsewhere starts at the root with `*` @@ -193,6 +194,8 @@ What the code does today, checked against the code in December 2026. Where cigen owned by another user, so git always failed ("detected dubious ownership") and the job hashed a different file list from the one computed anywhere else. cigen now passes git `-c safe.directory=` and fails with git's message on any other git error. +22. Resolved (PR #30): a job's hash didn't include the jobs it `needs`, so a change to `build`'s inputs alone left a + `test` that uses its artifact skipping. ## Next diff --git a/src/commands/hash.rs b/src/commands/hash.rs index 0159135..a031825 100644 --- a/src/commands/hash.rs +++ b/src/commands/hash.rs @@ -1,4 +1,6 @@ +use super::needs_hash; use anyhow::{Context, Result, bail}; +use cigen::schema::CigenConfig; use clap::Args; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -108,15 +110,13 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { }; let config = cigen::config::load(&config_path)?; - let job = config.jobs.get(job_id).with_context(|| { + config.jobs.get(job_id).with_context(|| { format!( "Job '{job_id}' not found in config at {}", config_path.display() ) })?; - let workflow_name = job.workflow.clone().unwrap_or_else(|| "ci".to_string()); - let cache_path = args .cache_path .as_ref() @@ -130,6 +130,46 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { let mut file_hasher = FileHasher::new(persistent_cache.as_mut()); let mut pattern_cache: BTreeMap> = BTreeMap::new(); + let digest = hex::encode(job_digest( + &config, + &base_dir, + job_id, + args.modules_digest.as_deref(), + &mut file_hasher, + &mut pattern_cache, + &mut Vec::new(), + )?); + + if let Some(name) = &args.output_name { + write_github_output(name, &digest)?; + } + + println!("{digest}"); + + if let Some(cache) = persistent_cache { + cache.save()?; + } + + Ok(()) +} + +/// The digest of `job_id`. `generated_modules` is `--modules-digest`, given for the job being +/// hashed; `chain` holds the jobs whose hashes are being computed, to catch a cycle in `needs`. +fn job_digest( + config: &CigenConfig, + base_dir: &Path, + job_id: &str, + generated_modules: Option<&str>, + file_hasher: &mut FileHasher<'_>, + pattern_cache: &mut BTreeMap>, + chain: &mut Vec, +) -> Result> { + let job = config + .jobs + .get(job_id) + .with_context(|| format!("job `{job_id}` isn't defined"))?; + let workflow_name = job.workflow.clone().unwrap_or_else(|| "ci".to_string()); + let mut entries: Vec = Vec::new(); for entry in &job.inputs { @@ -162,7 +202,7 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { // What the job depends on beyond its declared inputs: commands, services, provider blocks, // files its steps name and toolchain pins (see `cigen::inputs`). - let derived = cigen::inputs::derive(&config, job_id, &base_dir)?; + let derived = cigen::inputs::derive(config, job_id, base_dir)?; for (label, json) in &derived.config { final_hasher.update(b"\0derived\0"); final_hasher.update(label.as_bytes()); @@ -178,14 +218,14 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { } for pattern in &derived.patterns { - let digest = hash_pattern(pattern, &base_dir, &mut file_hasher, &mut pattern_cache)?; + let digest = hash_pattern(pattern, base_dir, file_hasher, pattern_cache)?; final_hasher.update(b"\0module-input\0"); final_hasher.update(pattern.as_bytes()); final_hasher.update([0u8]); final_hasher.update(&digest); } - if let Some(generated) = &args.modules_digest { - if *generated != derived.modules_digest { + if let Some(generated) = generated_modules { + if generated != derived.modules_digest { eprintln!( "warning: job `{job_id}`'s CI config was generated with modules digest {generated}, \ but this cigen expands its modules to {}. Regenerate the CI config with the cigen \ @@ -204,8 +244,7 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { for entry in entries { match entry { SourceEntry::Pattern(pattern) => { - let digest = - hash_pattern(&pattern, &base_dir, &mut file_hasher, &mut pattern_cache)?; + let digest = hash_pattern(&pattern, base_dir, file_hasher, pattern_cache)?; final_hasher.update(b"pattern\0"); final_hasher.update(pattern.as_bytes()); final_hasher.update([0u8]); @@ -215,13 +254,7 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { let patterns = config .input_group_patterns(&name) .with_context(|| format!("Job '{job_id}' uses `@{name}`"))?; - let digest = hash_group( - &name, - &patterns, - &base_dir, - &mut file_hasher, - &mut pattern_cache, - )?; + let digest = hash_group(&name, &patterns, base_dir, file_hasher, pattern_cache)?; final_hasher.update(b"group\0"); final_hasher.update(name.as_bytes()); final_hasher.update([0u8]); @@ -230,19 +263,23 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { } } - let digest = hex::encode(final_hasher.finalize()); - - if let Some(name) = &args.output_name { - write_github_output(name, &digest)?; - } - - println!("{digest}"); - - if let Some(cache) = persistent_cache { - cache.save()?; - } + // The jobs it needs, each by its whole hash (see `needs_hash`). + needs_hash::check_chain(chain, job_id)?; + chain.push(job_id.to_string()); + needs_hash::hash_needs(job_id, &job.needs, &mut final_hasher, &mut |need| { + job_digest( + config, + base_dir, + need, + None, + file_hasher, + pattern_cache, + chain, + ) + })?; + chain.pop(); - Ok(()) + Ok(final_hasher.finalize().to_vec()) } fn hash_group( diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 0d9b7aa..558e145 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,5 +1,6 @@ mod generate; mod hash; +mod needs_hash; pub mod report; mod validate; diff --git a/src/commands/needs_hash.rs b/src/commands/needs_hash.rs new file mode 100644 index 0000000..59bb46e --- /dev/null +++ b/src/commands/needs_hash.rs @@ -0,0 +1,52 @@ +//! The jobs a job `needs`, hashed into it. A job usually uses what the jobs before it made (an +//! artifact, an output), so a change that makes one of them run must make it run too: its hash +//! ends with the whole hash of every job it needs, which covers theirs in turn. + +use anyhow::{Result, bail}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; + +/// Adds the digest of each job `job_id` needs to `hasher`, in a fixed order. `digest_of` +/// computes a job's whole digest. +pub(super) fn hash_needs( + job_id: &str, + needs: &[String], + hasher: &mut Sha256, + digest_of: &mut dyn FnMut(&str) -> Result>, +) -> Result<()> { + let ordered: BTreeSet<&String> = needs.iter().collect(); + for need in ordered { + let digest = digest_of(need).map_err(|error| { + error.context(format!("hashing job `{need}`, which job `{job_id}` needs")) + })?; + hasher.update(b"\0needs\0"); + hasher.update(need.as_bytes()); + hasher.update([0u8]); + hasher.update(&digest); + } + Ok(()) +} + +/// The loader rejects cycles in `needs`; this keeps a bug there from recursing forever. +pub(super) fn check_chain(chain: &[String], job_id: &str) -> Result<()> { + if chain.iter().any(|job| job == job_id) { + bail!( + "job `{job_id}` needs itself: {} -> {job_id}", + chain.join(" -> ") + ); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_job_in_its_own_chain_is_a_cycle() { + let chain = vec!["test".to_string(), "build".to_string()]; + let error = check_chain(&chain, "test").unwrap_err().to_string(); + assert_eq!(error, "job `test` needs itself: test -> build -> test"); + assert!(check_chain(&chain, "lint").is_ok()); + } +} diff --git a/tests/derived_inputs.rs b/tests/derived_inputs.rs index cf1889a..ba229c7 100644 --- a/tests/derived_inputs.rs +++ b/tests/derived_inputs.rs @@ -211,3 +211,57 @@ fn local_actions_are_inputs() { }; assert_ne!(hash("echo one\n"), hash("echo two\n")); } + +#[test] +fn changing_a_job_this_job_needs_makes_it_run() { + // `test` uses what `build` makes. Its own inputs don't change, but `build`'s do. + let repo = FixtureRepo::new(); + repo.write(".cigen/config.yml", "provider: github\n") + .write( + ".cigen/workflows/ci/jobs/build.yml", + "image: rust:latest\ninputs: \"build/**\"\nsteps:\n - name: Build\n run: cat build/version\n", + ) + .write( + ".cigen/workflows/ci/jobs/test.yml", + "image: rust:latest\nneeds: [build]\ninputs: \"src/**\"\nsteps:\n - name: Run tests\n run: echo testing\n", + ) + .write("build/version", "1\n") + .write("src/lib.rs", "pub fn one() {}\n") + .generate(); + let mut sim = simulator(&repo); + let first = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + + repo.write("build/version", "2\n"); + let changed = repo.commit("change what build makes"); + let run = sim.run(WORKFLOW, &push(&changed)).unwrap(); + assert!(run.job("build").ran("Build"), "{run}"); + assert!( + tests_ran(&run), + "a job that needs a changed job runs: {run}" + ); +} + +/// `test` needs `check`, which needs `build`; `lint` is unrelated. Each declares its own inputs. +fn chain(build: &str, lint: &str) -> String { + let config = "provider: github\nworkflows:\n ci:\n jobs:\n build:\n inputs: \"build/**\"\n steps: [{ run: make }]\n check:\n needs: [build]\n inputs: \"check/**\"\n steps: [{ run: make check }]\n lint:\n inputs: \"lint/**\"\n steps: [{ run: make lint }]\n test:\n needs: [check]\n inputs: \"src/**\"\n steps: [{ run: make test }]\n"; + job_hash(&[ + ("cigen.yml", config), + ("build/version", build), + ("check/rules", "strict\n"), + ("lint/rules", lint), + ("src/lib.rs", "pub fn one() {}\n"), + ]) +} + +#[test] +fn a_job_hash_covers_the_jobs_it_needs_transitively_and_no_others() { + let base = chain("1\n", "a\n"); + assert_ne!(base, chain("2\n", "a\n"), "a change two jobs upstream"); + assert_eq!( + base, + chain("1\n", "b\n"), + "a change to a job it doesn't need" + ); +}