Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/src/content/docs/inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion docs/src/content/docs/jobs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 8 additions & 5 deletions internal_docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `*`
Expand Down Expand Up @@ -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=<repository root>` 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

Expand Down
93 changes: 65 additions & 28 deletions src/commands/hash.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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()
Expand All @@ -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<String, Vec<u8>> = 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<String, Vec<u8>>,
chain: &mut Vec<String>,
) -> Result<Vec<u8>> {
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<SourceEntry> = Vec::new();

for entry in &job.inputs {
Expand Down Expand Up @@ -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());
Expand All @@ -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 \
Expand All @@ -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]);
Expand All @@ -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]);
Expand All @@ -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(
Expand Down
1 change: 1 addition & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod generate;
mod hash;
mod needs_hash;
pub mod report;
mod validate;

Expand Down
52 changes: 52 additions & 0 deletions src/commands/needs_hash.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<u8>>,
) -> 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());
}
}
54 changes: 54 additions & 0 deletions tests/derived_inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
);
}
Loading