TExcelTAD
Home › Release Engineering & CI/CD › A Model of a CI Job Graph

A Model of a CI Job Graph

Before the YAML, the idea. Every CI system (GitHub Actions, GitLab CI, Jenkins, Buildkite, CircleCI) does the same three things with your pipeline definition:

  1. expands matrices into concrete jobs (build × 3 operating systems × 2 versions = 6 jobs);
  2. orders jobs by their dependencies (needs) into a graph and runs everything whose dependencies have finished, in parallel;
  3. restores caches by computing a key from the inputs (OS, tool version, lockfile hash) and looking for an exact or prefix match.

The Git CI/CD lesson shows what a single runner does with one job. This lesson models the whole graph in JavaScript, so the GitHub Actions lessons that follow are just syntax for ideas you have already seen run.

The model

The pipeline below is written like a GitHub Actions workflow, as a JavaScript object. The model expands the matrix (including exclude and include), resolves needs (a job that needs a matrix job waits for all of its expansions), prints the execution stages, then shows what happens when one job fails:

js · try it yourself
const workflow = {
  lint:    { needs: [] },
  test:    { needs: ['lint'],
             matrix: { os: ['ubuntu', 'windows', 'macos'], node: [22, 24],
                       exclude: [{ os: 'macos', node: 22 }],
                       include: [{ os: 'ubuntu', node: 25, experimental: true }] } },
  build:   { needs: ['test'], matrix: { target: ['linux-x64', 'linux-arm64', 'windows-x64'] } },
  package: { needs: ['build'] },
  docs:    { needs: ['lint'] },
  release: { needs: ['package', 'docs'] },
};

function expand(name, job) {
  if (!job.matrix) return [{ id: name, job: name, vars: {} }];
  const { include = [], exclude = [], ...axes } = job.matrix;
  let combos = [{}];
  for (const [key, values] of Object.entries(axes)) {
    combos = combos.flatMap((c) => values.map((v) => ({ ...c, [key]: v })));
  }
  const matches = (c, pattern) => Object.entries(pattern).every(([k, v]) => c[k] === v);
  combos = combos.filter((c) => !exclude.some((e) => matches(c, e)));
  for (const extra of include) {
    // an include that matches no existing combination adds a new job
    const target = combos.find((c) => Object.keys(axes).every((k) => !(k in extra) || c[k] === extra[k])
                                      && Object.keys(axes).every((k) => k in extra));
    if (target) Object.assign(target, extra); else combos.push({ ...extra });
  }
  return combos.map((vars) => ({ id: `${name} (${Object.values(vars).join(', ')})`, job: name, vars }));
}

const jobs = Object.entries(workflow).flatMap(([name, job]) => expand(name, job));
console.log(`${Object.keys(workflow).length} job definitions -> ${jobs.length} jobs`);

function run(failing = new Set()) {
  const status = new Map();          // id -> 'success' | 'failure' | 'skipped'
  const jobDone = (name) => jobs.filter((j) => j.job === name).every((j) => status.has(j.id));
  const jobOk = (name) => jobs.filter((j) => j.job === name).every((j) => status.get(j.id) === 'success');
  let stage = 0;
  while (status.size < jobs.length) {
    const ready = jobs.filter((j) => !status.has(j.id) && workflow[j.job].needs.every(jobDone));
    stage++;
    const line = ready.map((j) => {
      const deps = workflow[j.job].needs;
      const result = !deps.every(jobOk) ? 'skipped' : failing.has(j.id) ? 'failure' : 'success';
      return [j, result];
    });
    for (const [j, result] of line) status.set(j.id, result);
    console.log(`  stage ${stage}: ` + line.map(([j, r]) => r === 'success' ? j.id : `${j.id} [${r}]`).join(' | '));
  }
}

console.log('all green:');
run();
console.log('one test job fails:');
run(new Set(['test (windows, 24)']));
6 job definitions -> 13 jobs
all green:
  stage 1: lint
  stage 2: test (ubuntu, 22) | test (ubuntu, 24) | test (windows, 22) | test (windows, 24) | test (macos, 24) | test (ubuntu, 25, true) | docs
  stage 3: build (linux-x64) | build (linux-arm64) | build (windows-x64)
  stage 4: package
  stage 5: release
one test job fails:
  stage 1: lint
  stage 2: test (ubuntu, 22) | test (ubuntu, 24) | test (windows, 22) | test (windows, 24) [failure] | test (macos, 24) | test (ubuntu, 25, true) | docs
  stage 3: build (linux-x64) [skipped] | build (linux-arm64) [skipped] | build (windows-x64) [skipped]
  stage 4: package [skipped]
  stage 5: release [skipped]

What the model shows about every CI system:

  • The matrix multiplies cost. Six job definitions became thirteen jobs. exclude removed macOS on Node 22; include added one extra combination (ubuntu, Node 25) that no axis produced.
  • needs on a matrix job waits for all of it. build couldn't start until every test combination finished.
  • Independent jobs run in parallel. docs ran next to the tests because it only needs lint.
  • Failure skips dependents, not siblings. One failing test job skipped build, package and release, but docs still ran and the other test jobs finished. (GitHub Actions additionally cancels in-progress matrix jobs on failure unless fail-fast: false; the model lets them finish.)

Cache keys

A cache is only useful if a key changes exactly when the cached content would change. The usual recipe: OS + tool version + a hash of the lockfile. On a miss, a restore key (a prefix) brings back the newest older cache, which is usually better than nothing; the job then updates it and saves under the new key:

js · try it yourself
async function sha256(text) {
  const bytes = new TextEncoder().encode(text);
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}

// What the cache server already holds, oldest first.
const stored = [];

async function cacheStep(runner, lockfile) {
  const key = `npm-${runner}-${(await sha256(lockfile)).slice(0, 12)}`;
  const restoreKeys = [`npm-${runner}-`];
  let result;
  if (stored.includes(key)) {
    result = 'exact hit, nothing to install';
  } else {
    const prefix = restoreKeys.find((p) => stored.some((k) => k.startsWith(p)));
    const fallback = prefix && stored.filter((k) => k.startsWith(prefix)).at(-1);
    result = fallback ? `partial hit from ${fallback}, install the difference, save` : 'miss, full install, save';
    stored.push(key);
  }
  console.log(`${key}  ${result}`);
}

const lockV1 = '{ "lodash": "4.17.21", "chalk": "5.3.0" }';
const lockV2 = '{ "lodash": "4.18.1", "chalk": "5.3.0" }';
await cacheStep('Linux', lockV1);     // first run ever
await cacheStep('Linux', lockV1);     // nothing changed
await cacheStep('Windows', lockV1);   // other OS: separate cache
await cacheStep('Linux', lockV2);     // a dependency was updated
await cacheStep('Linux', lockV2);
npm-Linux-a2041500622e  miss, full install, save
npm-Linux-a2041500622e  exact hit, nothing to install
npm-Windows-a2041500622e  miss, full install, save
npm-Linux-7a55283a0456  partial hit from npm-Linux-a2041500622e, install the difference, save
npm-Linux-7a55283a0456  exact hit, nothing to install

The same key structure appears in the real actions/cache step in Caching & Artifacts: key: npm-${{ runner.os }}-${{ hashFiles('**/package-lock.json') }} with restore-keys: npm-${{ runner.os }}-. Two rules follow from the model: never put something in the key that changes every run (a timestamp, the commit SHA) or the cache never hits, and always include everything the cached content depends on (OS, tool version) or a cache from the wrong environment gets restored.

Test yourself

A matrix has os: [ubuntu, windows, macos] and node: [22, 24] with one exclude. How many jobs?

  1. 5
  2. 6
  3. 7
  4. 3

Job build has needs: [test] and test is a matrix of 5 jobs. When does build start?

  1. After the first test job succeeds
  2. After all 5 test jobs succeed
  3. Immediately
  4. After any test job finishes

Why is key: deps-${{ github.sha }} a bad cache key?

  1. SHAs are secret
  2. It changes on every commit, so the exact key never hits
  3. It's too short
  4. Caches can't use variables