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
1 change: 1 addition & 0 deletions docs/src/content/docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ cigen hash --pattern 'src/**/*.rs' --pattern Cargo.lock
| `--base-dir <dir>` | The project root that globs are relative to. Default `.`. |
| `--output <name>` | Also write `name=<hash>` to `$GITHUB_OUTPUT`, when that's set. |
| `--cache <file>` | Keep per-file hashes in this file, keyed by size and modification time, to hash faster next time. |
| `--matrix <json>` | 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`.

Expand Down
5 changes: 5 additions & 0 deletions docs/src/content/docs/jobs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 6 additions & 0 deletions internal_docs/DIRECTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
13 changes: 11 additions & 2 deletions internal_docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <id> }`
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions plugins/provider-github/src/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ pub(crate) fn render_job(
&job.id,
&context.config_flag,
&job.modules_digest,
job.extra.contains_key("strategy"),
))
};

Expand Down
30 changes: 27 additions & 3 deletions plugins/provider-github/src/skip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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();
Expand All @@ -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(
Expand Down Expand Up @@ -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()))
Expand Down
14 changes: 12 additions & 2 deletions src/commands/hash.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::matrix_entry::with_matrix_entry;
use super::needs_hash;
use anyhow::{Context, Result, bail};
use cigen::schema::CigenConfig;
Expand Down Expand Up @@ -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<String>,

/// 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<String>,
}

pub fn hash_command(args: HashArgs) -> Result<()> {
Expand Down Expand Up @@ -130,15 +136,19 @@ 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(
let mut digest = job_digest(
&config,
&base_dir,
job_id,
args.modules_digest.as_deref(),
&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)?;
Expand Down
58 changes: 58 additions & 0 deletions src/commands/matrix_entry.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<u8>> {
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}");
}
}
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 matrix_entry;
mod needs_hash;
pub mod report;
mod validate;
Expand Down
Loading
Loading