diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index c7c064c..14623a2 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -97,6 +97,7 @@ cigen hash --pattern 'src/**/*.rs' --pattern Cargo.lock | `--base-dir ` | The project root that globs are relative to. Default `.`. | | `--output ` | Also write `name=` to `$GITHUB_OUTPUT`, when that's set. | | `--cache ` | Keep per-file hashes in this file, keyed by size and modification time, to hash faster next time. | +| `--matrix ` | The job's matrix entry (`${{ toJSON(matrix) }}`), for a job that runs GitHub's own matrix. Each entry gets its own hash. | Patterns that match no files hash to the word `empty`. diff --git a/docs/src/content/docs/jobs.md b/docs/src/content/docs/jobs.md index 53d51cc..697445b 100644 --- a/docs/src/content/docs/jobs.md +++ b/docs/src/content/docs/jobs.md @@ -121,3 +121,8 @@ keeps only letters, digits, `-` and `_`, the characters both GitHub and CircleCI value becomes `_`: `toolchain: ["1.90"]` gives `test-1_90`. Two combinations that would get the same name are an error, and so is a name that doesn't start with a letter. Today the values aren't passed into the job's steps, and a matrix job with `inputs` fails at its hash step. + +GitHub's own matrix also works, passed through the `github:` block (`github: { strategy: { matrix: … } }`), with +`${{ matrix.x }}` in the steps. Every entry runs the same job definition, so the generated hash step passes the entry +to `cigen hash --matrix`, and each entry gets its own hash and pass marker: an entry that failed never reuses another +entry's pass. diff --git a/internal_docs/DIRECTION.md b/internal_docs/DIRECTION.md index cf99918..885c8da 100644 --- a/internal_docs/DIRECTION.md +++ b/internal_docs/DIRECTION.md @@ -48,6 +48,12 @@ useful escape hatch. Designed December 2026; not built. Today each job checks its own marker after it starts (STATUS, "What works"). This replaces that with a plan made once, before any job starts. +A job that runs GitHub's own matrix (`github: { strategy }`) runs once per entry with one definition, so its pass +records must be per entry (STATUS known problem 23). The plan has one output per job, so until the planner can +enumerate a literal matrix it plans such a job as `run`, and each entry checks its own marker, keyed by +`cigen hash --matrix`. A matrix built by an expression (`fromJSON(...)`) can't be enumerated before the job starts and +always takes that path. + ### The planned workflow Every generated GitHub workflow with skippable jobs gets two extra jobs, `cigen_plan` first and `cigen_gate` last: diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 349598a..bd5bcc7 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -74,8 +74,10 @@ What the code does today, checked against the code in December 2026. Where cigen `src/plugin/`), with the config converted to protobuf in `src/orchestrator/convert.rs`: - `plugins/provider-github`: GitHub Actions workflows. Jobs with `inputs` get a skip flow: `cigen hash` computes the job hash, an exact-key `actions/cache` restore finds a marker, the remaining steps are skipped on a - hit, and a marker is recorded on success. Generated `cigen` commands pass `--config` only when the config isn't - `cigen.yml` or `.cigen/`, and the workflow header names the config and the `cigen generate` command. + hit, and a marker is recorded on success. A job with GitHub's own matrix (`github: { strategy }`) passes each + entry to `cigen hash --matrix`, so entries get separate keys. Generated `cigen` commands pass `--config` only + when the config isn't `cigen.yml` or `.cigen/`, and the workflow header names the config and the `cigen generate` + command. - Jobs with a skip flow get cigen from `cigen_install`. By default (`release`) a step downloads the release that generated the workflow (its version is baked in) for the runner's OS and architecture, checks it against the release's `.sha256`, and puts it on `PATH`; a checksum mismatch fails the job. `cigen_install: { job: }` @@ -124,6 +126,8 @@ What the code does today, checked against the code in December 2026. Where cigen files, `docs/**/*.md` includes `docs/a.md`, `*.md` matches at any depth, `/*.md` only at the root, `docs/*.md` only directly in `docs/`, a directory matches everything under it, and `hash --pattern` matches the same way. Each case changes a file and checks whether the hash changes. +- `tests/matrix_skip.rs`: a job with GitHub's own matrix runs its generated hash step once per entry: two entries get + different skip keys, and after one entry passes and another fails, the failed one runs again with unchanged inputs. - `tests/git_ownership.rs`: `cigen hash` in a checkout git treats as owned by another user (`GIT_TEST_ASSUME_DIFFERENT_OWNER`), at the repository root and in a subdirectory, matches the hash computed as its owner. @@ -199,6 +203,11 @@ What the code does today, checked against the code in December 2026. Where cigen 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. +23. Resolved (PR #51): a job running GitHub's own matrix through `github: { strategy }` gave every entry the + same hash and skip key, so an entry that failed reused the pass of one that succeeded (#43). The generated hash + step now passes `toJSON(matrix)` to `cigen hash --matrix`, which mixes the entry into the job's hash. The CircleCI + provider can't express a matrix or job parameters through its passthrough, and cigen's own `matrix:` gives each + combination its own job, so neither has the hole. ## Next diff --git a/plugins/provider-github/src/job.rs b/plugins/provider-github/src/job.rs index 72fd722..5bfb1c3 100644 --- a/plugins/provider-github/src/job.rs +++ b/plugins/provider-github/src/job.rs @@ -110,6 +110,7 @@ pub(crate) fn render_job( &job.id, &context.config_flag, &job.modules_digest, + job.extra.contains_key("strategy"), )) }; diff --git a/plugins/provider-github/src/skip.rs b/plugins/provider-github/src/skip.rs index b61277b..522304e 100644 --- a/plugins/provider-github/src/skip.rs +++ b/plugins/provider-github/src/skip.rs @@ -13,12 +13,25 @@ pub(crate) struct SkipFlow { /// `config_flag` is what `cigen hash` needs to find the config (empty for the default names). /// `modules_digest` is the digest of the job's module expansions when it was generated, so the /// hash covers the steps this workflow runs even if a different cigen computes it. -pub(crate) fn build_skip_flow(job_id: &str, config_flag: &str, modules_digest: &str) -> SkipFlow { +/// `matrix` is true for a job that runs GitHub's own matrix (a `strategy` in its `github:` +/// block): every entry runs the same definition, so the hash step passes the entry +/// (`toJSON(matrix)`) and each entry gets its own hash, skip key and pass marker. +pub(crate) fn build_skip_flow( + job_id: &str, + config_flag: &str, + modules_digest: &str, + matrix: bool, +) -> SkipFlow { let digest_arg = if modules_digest.is_empty() { String::new() } else { format!(" --modules-digest {modules_digest} \\\n") }; + let matrix_arg = if matrix { + " --matrix \"$CIGEN_MATRIX\" \\\n" + } else { + "" + }; let compute_script = format!( concat!( "set -euo pipefail\n", @@ -28,12 +41,14 @@ pub(crate) fn build_skip_flow(job_id: &str, config_flag: &str, modules_digest: & " --job {job_id}{config_flag} \\\n", " --base-dir . \\\n", "{digest_arg}", + "{matrix_arg}", " --output job_hash \\\n", " --cache .cigen/cache/file-hashes.json\n" ), job_id = job_id, config_flag = config_flag, - digest_arg = digest_arg + digest_arg = digest_arg, + matrix_arg = matrix_arg ); let mut compute_step = Mapping::new(); @@ -46,6 +61,15 @@ pub(crate) fn build_skip_flow(job_id: &str, config_flag: &str, modules_digest: & Value::String("compute_hash".into()), ); compute_step.insert(Value::String("run".into()), Value::String(compute_script)); + if matrix { + let mut env = Mapping::new(); + // In an environment variable, so the shell never parses the JSON. + env.insert( + Value::String("CIGEN_MATRIX".into()), + Value::String("${{ toJSON(matrix) }}".into()), + ); + compute_step.insert(Value::String("env".into()), Value::Mapping(env)); + } let mut cache_with = Mapping::new(); cache_with.insert( @@ -142,7 +166,7 @@ mod tests { #[test] fn skip_cache_key_is_a_github_expression_of_the_job_hash() { - let flow = build_skip_flow("clippy", "", ""); + let flow = build_skip_flow("clippy", "", "", false); let with = flow .restore_step .get(Value::String("with".into())) diff --git a/src/commands/hash.rs b/src/commands/hash.rs index a031825..0a129ea 100644 --- a/src/commands/hash.rs +++ b/src/commands/hash.rs @@ -1,3 +1,4 @@ +use super::matrix_entry::with_matrix_entry; use super::needs_hash; use anyhow::{Context, Result, bail}; use cigen::schema::CigenConfig; @@ -41,6 +42,11 @@ pub struct HashArgs { /// into the hash, so the hash covers the steps that config runs. #[arg(long = "modules-digest", requires = "job")] pub modules_digest: Option, + + /// The job's matrix entry as JSON (`${{ toJSON(matrix) }}`), for a job that runs GitHub's own + /// matrix. It goes into the hash, so each entry has its own hash and pass marker. + #[arg(long = "matrix", requires = "job")] + pub matrix: Option, } pub fn hash_command(args: HashArgs) -> Result<()> { @@ -130,7 +136,7 @@ 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( + let mut digest = job_digest( &config, &base_dir, job_id, @@ -138,7 +144,11 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { &mut file_hasher, &mut pattern_cache, &mut Vec::new(), - )?); + )?; + if let Some(entry) = &args.matrix { + digest = with_matrix_entry(&digest, entry)?; + } + let digest = hex::encode(digest); if let Some(name) = &args.output_name { write_github_output(name, &digest)?; diff --git a/src/commands/matrix_entry.rs b/src/commands/matrix_entry.rs new file mode 100644 index 0000000..83f3b4b --- /dev/null +++ b/src/commands/matrix_entry.rs @@ -0,0 +1,58 @@ +//! A job that runs GitHub's own matrix (`github: { strategy: { matrix } }`) runs once per entry, +//! with the same definition each time. Its generated hash step passes the entry +//! (`${{ toJSON(matrix) }}`) to `cigen hash --matrix`, and the entry goes into the job's hash, so +//! each entry has its own hash, skip key and pass marker. Otherwise an entry that failed could +//! reuse the pass of one that succeeded. + +use anyhow::{Context, Result}; +use sha2::{Digest, Sha256}; + +/// `digest` with the matrix entry mixed in. The entry is JSON, compared with its keys sorted, so +/// the same entry gives the same hash however GitHub orders it. +pub(super) fn with_matrix_entry(digest: &[u8], entry: &str) -> Result> { + let value: serde_json::Value = serde_json::from_str(entry).with_context(|| { + format!( + "`--matrix` must be the job's matrix entry as JSON (`${{{{ toJSON(matrix) }}}}`), got `{entry}`" + ) + })?; + let canonical = cigen::inputs::canonical_json(&value)?; + let mut hasher = Sha256::new(); + hasher.update(digest); + hasher.update(b"\0matrix\0"); + hasher.update(canonical.as_bytes()); + Ok(hasher.finalize().to_vec()) +} + +#[cfg(test)] +mod tests { + use super::with_matrix_entry; + + #[test] + fn each_entry_has_its_own_hash() { + let stable = with_matrix_entry(b"job", r#"{"rust": "stable", "os": "ubuntu-latest"}"#); + let nightly = with_matrix_entry(b"job", r#"{"rust": "nightly", "os": "ubuntu-latest"}"#); + assert_ne!(stable.unwrap(), nightly.unwrap()); + } + + #[test] + fn key_order_doesnt_matter() { + let one = with_matrix_entry(b"job", "{\n \"rust\": \"stable\",\n \"os\": \"x\"\n}"); + let other = with_matrix_entry(b"job", r#"{"os":"x","rust":"stable"}"#); + assert_eq!(one.unwrap(), other.unwrap()); + } + + #[test] + fn the_entry_changes_the_job_hash() { + assert_ne!( + with_matrix_entry(b"job", "null").unwrap(), + b"job".to_vec(), + "an entry is mixed in, never ignored" + ); + } + + #[test] + fn an_entry_that_isnt_json_is_an_error() { + let error = with_matrix_entry(b"job", "stable").unwrap_err().to_string(); + assert!(error.contains("toJSON(matrix)"), "{error}"); + } +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 558e145..4f64c32 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,5 +1,6 @@ mod generate; mod hash; +mod matrix_entry; mod needs_hash; pub mod report; mod validate; diff --git a/tests/matrix_skip.rs b/tests/matrix_skip.rs new file mode 100644 index 0000000..4ccba5c --- /dev/null +++ b/tests/matrix_skip.rs @@ -0,0 +1,156 @@ +//! A job that runs GitHub's own matrix (`github: { strategy: { matrix } }`) must give each entry +//! its own skip key. Otherwise an entry that failed reuses the pass of one that succeeded: a +//! false skip. mockci can't run a matrix yet, so this runs the generated hash step itself, once +//! per entry, as GitHub would, and plays the scenario out against a set of recorded passes. + +mod support; + +use serde_yaml::Value; +use std::collections::BTreeSet; +use std::process::Command; +use support::fixture_repo::FixtureRepo; + +const CONFIG: &str = "provider: github +workflows: + ci: + jobs: + test: + image: ubuntu-latest + inputs: ['src/**'] + github: + strategy: + fail-fast: false + matrix: + rust: [stable, nightly] + steps: + - run: cargo +${{ matrix.rust }} test + lint: + image: ubuntu-latest + inputs: ['src/**'] + steps: + - run: cargo clippy +"; + +/// GitHub's `toJSON(matrix)` for an entry: pretty-printed. +fn entry(rust: &str) -> String { + format!("{{\n \"rust\": \"{rust}\"\n}}") +} + +fn step<'a>(workflow: &'a Value, job: &str, name: &str) -> &'a Value { + workflow["jobs"][job]["steps"] + .as_sequence() + .expect("steps") + .iter() + .find(|step| step["name"].as_str() == Some(name)) + .unwrap_or_else(|| panic!("job `{job}` has no step `{name}`")) +} + +fn workflow(repo: &FixtureRepo) -> Value { + let text = std::fs::read_to_string(repo.path().join(".github/workflows/ci.yml")).unwrap(); + serde_yaml::from_str(&text).unwrap() +} + +/// Runs the job's generated "Compute source hash" step with bash, with `CIGEN_MATRIX` set the +/// way the step's `env` sets it on GitHub, and returns the skip key the restore step looks up. +fn skip_key(repo: &FixtureRepo, job: &str, matrix: Option<&str>) -> String { + let workflow = workflow(repo); + let compute = step(&workflow, job, "Compute source hash"); + let output = tempfile::NamedTempFile::new().unwrap(); + let cigen_dir = assert_cmd::cargo::cargo_bin("cigen") + .parent() + .unwrap() + .to_path_buf(); + let path = format!("{}:{}", cigen_dir.display(), std::env::var("PATH").unwrap()); + let mut command = Command::new("bash"); + command + .args(["-c", compute["run"].as_str().unwrap()]) + .current_dir(repo.path()) + .env("PATH", path) + .env("GITHUB_OUTPUT", output.path()); + for (name, _) in std::env::vars_os() { + if name.to_string_lossy().starts_with("GIT_") { + command.env_remove(name); + } + } + if let Some(matrix) = matrix { + assert_eq!( + compute["env"]["CIGEN_MATRIX"].as_str(), + Some("${{ toJSON(matrix) }}") + ); + command.env("CIGEN_MATRIX", matrix); + } + let result = command.output().unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + let outputs = std::fs::read_to_string(output.path()).unwrap(); + let hash = outputs + .lines() + .find_map(|line| line.strip_prefix("job_hash=")) + .expect("the hash step writes job_hash"); + let key = step(&workflow, job, "Restore skip cache")["with"]["key"] + .as_str() + .unwrap() + .replace("${{ runner.os }}", "Linux"); + key.replace("${{ steps.compute_hash.outputs.job_hash }}", hash) +} + +fn repo() -> FixtureRepo { + let repo = FixtureRepo::new(); + repo.write("cigen.yml", CONFIG) + .write("src/lib.rs", "pub fn f() {}\n") + .write("README.md", "readme\n"); + support::cigen() + .arg("generate") + .current_dir(repo.path()) + .assert() + .success(); + repo.commit("project"); + repo +} + +#[test] +fn each_matrix_entry_has_its_own_skip_key() { + let repo = repo(); + let stable = skip_key(&repo, "test", Some(&entry("stable"))); + let nightly = skip_key(&repo, "test", Some(&entry("nightly"))); + assert_ne!(stable, nightly); + // The same entry gives the same key, so an entry still skips its own unchanged run. + assert_eq!(stable, skip_key(&repo, "test", Some(&entry("stable")))); +} + +#[test] +fn an_entry_that_failed_runs_again_when_another_passed() { + let repo = repo(); + let mut passes = BTreeSet::new(); + + // Commit A: stable passes and records its marker; nightly fails and records nothing. + passes.insert(skip_key(&repo, "test", Some(&entry("stable")))); + + // Commit B changes nothing the job reads. + repo.write("README.md", "changed\n"); + repo.commit("docs"); + assert!( + !passes.contains(&skip_key(&repo, "test", Some(&entry("nightly")))), + "nightly failed on A, so it must run on B" + ); + assert!( + passes.contains(&skip_key(&repo, "test", Some(&entry("stable")))), + "stable passed on A with the same inputs, so it skips on B" + ); +} + +#[test] +fn a_job_without_a_github_matrix_hashes_as_before() { + let repo = repo(); + let workflow = workflow(&repo); + let compute = step(&workflow, "lint", "Compute source hash"); + assert!(compute.get("env").is_none()); + assert!(!compute["run"].as_str().unwrap().contains("--matrix")); + assert!( + !skip_key(&repo, "lint", None).is_empty(), + "lint still computes a key" + ); +}