local-ci 0.20.0

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Recomputable dynamic dispatch. Digests bind data; hosts authenticate transport.
use super::{digest, MAX_TASKS};
use crate::dag::{ExecutionTask, JobNode, NodeKind, OutputAggregation, TaskVariant};
use crate::expr::{Ctx, PortableStage, Status};
use crate::frozen::FrozenPlan;
use crate::job_evaluate::{self, Decision};
use crate::source_execute::{EvaluationSource, VerifiedEvaluationSource};
use crate::task::TaskInputs;
use anyhow::{ensure, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};

pub const DISPATCH_VERSION: u32 = 1;
const MAX_FACT_BYTES: usize = 1024 * 1024;
const MAX_DERIVED_BYTES: usize = 8 * 1024 * 1024;

/// Explicit host-authorized portable facts, never inferred from a worker.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortableFacts {
    pub schema_version: u32,
    pub github: Map<String, Value>,
    pub vars: Map<String, Value>,
    pub inputs: Map<String, Value>,
}
impl PortableFacts {
    pub(crate) fn validate(&self) -> Result<()> {
        ensure!(
            self.schema_version == DISPATCH_VERSION,
            "unsupported portable facts version"
        );
        ensure!(
            serde_json::to_vec(self)?.len() <= MAX_FACT_BYTES,
            "portable facts exceed byte bound"
        );
        let mut keys = std::collections::BTreeSet::new();
        for key in self.github.keys() {
            ensure!(
                keys.insert(key.to_ascii_lowercase()),
                "duplicate case-insensitive github fact"
            );
            ensure!(
                key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'),
                "invalid github fact key"
            );
            crate::expr::validate_portable(&format!("github.{key}"), true, PortableStage::Matrix)?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunnerRequirement {
    pub job: String,
    pub original: Option<Value>,
    pub evaluated: Option<Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DerivedDispatch {
    schema_version: u32,
    plan_digest: String,
    origin: String,
    task: String,
    index: usize,
    inputs_digest: String,
    evaluation_digest: String,
    expansion_digest: String,
}
impl DerivedDispatch {
    pub fn task_id(&self) -> &str {
        &self.task
    }
    pub fn origin(&self) -> &str {
        &self.origin
    }
    pub fn index(&self) -> usize {
        self.index
    }
    pub fn from_json(text: &str) -> Result<Self> {
        ensure!(text.len() <= MAX_FACT_BYTES, "dispatch exceeds byte bound");
        Ok(serde_json::from_str(text)?)
    }
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct EvaluationContext {
    pub source: EvaluationSource,
    pub facts: PortableFacts,
}
impl EvaluationContext {
    pub fn new(
        plan: &FrozenPlan,
        source: &VerifiedEvaluationSource,
        facts: PortableFacts,
    ) -> Result<Self> {
        facts.validate()?;
        ensure!(
            source.record().plan_digest() == plan.digest,
            "evaluation source plan mismatch"
        );
        Ok(Self {
            source: source.record().clone(),
            facts,
        })
    }
    pub fn contexts(&self, plan: &FrozenPlan, task: &ExecutionTask) -> Result<Map<String, Value>> {
        let wf = plan
            .workflows
            .iter()
            .find(|w| w.file == task.workflow)
            .context("missing evaluation workflow")?;
        let mut github: Map<String, Value> = self
            .facts
            .github
            .iter()
            .map(|(key, value)| (key.to_ascii_lowercase(), value.clone()))
            .collect();
        // These facts are actually present in the selected source plan.
        github.insert("workflow".into(), Value::String(wf.name.clone()));
        github.insert("event_name".into(), Value::String(wf.event.clone()));
        if task.jobs.len() == 1 {
            github.insert("job".into(), Value::String(task.jobs[0].clone()));
        }
        Ok([
            ("github".into(), Value::Object(github)),
            ("vars".into(), Value::Object(self.facts.vars.clone())),
            ("inputs".into(), Value::Object(self.facts.inputs.clone())),
        ]
        .into_iter()
        .collect())
    }
    pub fn requirement(
        &self,
        task: &ExecutionTask,
        job: &str,
        contexts: &Map<String, Value>,
    ) -> Result<RunnerRequirement> {
        let wf = self
            .source
            .workflows()
            .iter()
            .find(|w| w.workflow() == task.workflow)
            .context("missing source workflow")?;
        let source = wf
            .jobs()
            .iter()
            .find(|j| j.job() == job)
            .context("missing source job")?;
        let original = source.runs_on().cloned();
        let mut contexts = contexts.clone();
        if let Some(github) = contexts.get_mut("github").and_then(Value::as_object_mut) {
            github.insert("job".into(), Value::String(job.into()));
        }
        let evaluated = original
            .as_ref()
            .map(|value| {
                job_evaluate::validate_strings(value, &contexts, PortableStage::RunsOn)?;
                job_evaluate::eval_strings(
                    value,
                    &Ctx::new(&contexts, Status::Success)
                        .with_output_limit(job_evaluate::PORTABLE_OUTPUT_BYTES),
                )
            })
            .transpose()?;
        Ok(RunnerRequirement {
            job: job.into(),
            original,
            evaluated,
        })
    }
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct Selection {
    pub task: ExecutionTask,
    pub display: String,
    pub matrix: Value,
    pub strategy: Value,
    pub requirement: RunnerRequirement,
}
impl Selection {
    pub fn worker_evaluation(
        &self,
        github: Value,
        runner: Value,
        needs: &Map<String, Value>,
        facts: &PortableFacts,
    ) -> job_evaluate::JobEvaluation {
        let mut github = github;
        if let Some(object) = github.as_object_mut() {
            object.extend(
                facts
                    .github
                    .iter()
                    .filter(|(key, _)| {
                        !matches!(
                            key.to_ascii_lowercase().as_str(),
                            "workflow" | "job" | "event_name"
                        )
                    })
                    .map(|(key, value)| (key.to_ascii_lowercase(), value.clone())),
            );
        }
        let contexts = [
            ("github".into(), github),
            ("runner".into(), runner),
            ("needs".into(), Value::Object(needs.clone())),
            ("matrix".into(), self.matrix.clone()),
            ("strategy".into(), self.strategy.clone()),
            ("vars".into(), Value::Object(facts.vars.clone())),
            ("inputs".into(), Value::Object(facts.inputs.clone())),
            ("env".into(), json!({})),
        ]
        .into_iter()
        .collect();
        job_evaluate::JobEvaluation {
            budget_exceeded: false,
            entries: vec![job_evaluate::EvaluatedEntry {
                display: self.display.clone(),
                decision: Decision::Run(contexts),
            }],
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct Expansion {
    pub group: JobNode,
    pub selections: Vec<Selection>,
    pub dispatches: Vec<DerivedDispatch>,
    pub inputs: TaskInputs,
}
pub(crate) enum Derivation {
    Expanded(Box<Expansion>),
    Skipped(String),
    Failed(String),
}

fn ensure_expansion_budget(bytes: usize, limit: usize) -> Result<()> {
    ensure!(bytes <= limit, "expansion evaluated byte budget exceeded");
    Ok(())
}

pub(crate) fn derive(
    plan: &FrozenPlan,
    evaluation: &EvaluationContext,
    origin: &ExecutionTask,
    inputs: &TaskInputs,
    limit: usize,
    byte_limit: usize,
) -> Result<Derivation> {
    ensure!(
        origin.dynamic_matrix
            && origin.jobs.len() == 1
            && origin.variant.is_none()
            && origin.shard.is_none(),
        "not a supported dynamic origin"
    );
    ensure!(
        inputs.schema_version == crate::wire::WIRE_SCHEMA_VERSION,
        "invalid task inputs version"
    );
    let wf = plan
        .workflows
        .iter()
        .find(|w| w.file == origin.workflow)
        .context("missing workflow")?;
    let spec = wf.job(&origin.jobs[0]).context("missing dynamic job")?;
    ensure!(
        spec.needs.iter().all(|n| inputs.needs.contains_key(n)),
        "missing dynamic needs"
    );
    let source_job = evaluation
        .source
        .workflows()
        .iter()
        .find(|w| w.workflow() == origin.workflow)
        .and_then(|w| w.jobs().iter().find(|j| j.job() == origin.jobs[0]))
        .context("missing source scheduling job")?;
    // Bound copied data before Cartesian construction, including duplicated
    // needs/requirements, rather than relying only on a member-count bound.
    let per_member = serde_json::to_vec(&(origin, inputs, &evaluation.facts, source_job))?
        .len()
        .max(1);
    let byte_limit = byte_limit.min(MAX_DERIVED_BYTES);
    let limit = limit.min(byte_limit / per_member);
    let contexts = evaluation.contexts(plan, origin)?;
    let ancestor_failed = spec
        .needs
        .iter()
        .any(|n| inputs.needs[n].failed_or_ancestor_failed());
    let evaluated = job_evaluate::evaluate_portable(
        &spec.to_job(),
        &contexts,
        &inputs.context(),
        ancestor_failed,
        inputs.run_cancelled,
        limit.min(MAX_TASKS),
    );
    let input_bytes = crate::expr::serialized_size(inputs, MAX_DERIVED_BYTES)?;
    let mut charged = input_bytes
        .checked_add(4096)
        .context("expansion byte budget exhausted")?;
    let mut selections = Vec::new();
    for (index, entry) in evaluated.entries.into_iter().enumerate() {
        let cm = match entry.decision {
            Decision::Run(cm) => cm,
            Decision::Skip(reason) => return Ok(Derivation::Skipped(reason)),
            Decision::Error(reason) => return Ok(Derivation::Failed(reason)),
        };
        // Count actual evaluated data before cloning into variant/matrix/label
        // and before duplicating authoritative inputs into Ready phase/outbox.
        let requirement = match evaluation.requirement(origin, &origin.jobs[0], &cm) {
            Ok(requirement) => requirement,
            Err(error) => return Ok(Derivation::Failed(format!("runs-on: {error:#}"))),
        };
        let evaluated_bytes = crate::expr::serialized_size(
            &(
                origin,
                &cm["matrix"],
                &cm["matrix"],
                &entry.display,
                &entry.display,
                &cm["strategy"],
                &requirement,
            ),
            byte_limit,
        )?;
        charged = charged
            .checked_add(evaluated_bytes)
            .and_then(|n| {
                input_bytes
                    .checked_mul(2)
                    .and_then(|inputs| n.checked_add(inputs))
            })
            .and_then(|n| {
                origin
                    .id
                    .len()
                    .checked_mul(8)
                    .and_then(|ids| n.checked_add(ids))
            })
            .and_then(|n| n.checked_add(4096))
            .context("expansion byte budget exhausted")?;
        ensure_expansion_budget(charged, byte_limit)?;
        let mut task = origin.clone();
        task.id = member_id(&origin.id, index);
        ensure!(
            !plan.tasks.iter().any(|t| t.id == task.id),
            "derived member collides with frozen task"
        );
        task.nodes = vec![task.id.clone()];
        task.dynamic_matrix = false;
        task.variant = Some(TaskVariant {
            group: origin.nodes[0].clone(),
            index,
            values: cm["matrix"]
                .as_object()
                .context("missing derived matrix")?
                .clone(),
            label: entry.display.clone(),
        });
        selections.push(Selection {
            task,
            display: entry.display,
            matrix: cm["matrix"].clone(),
            strategy: cm["strategy"].clone(),
            requirement,
        });
    }
    ensure!(!selections.is_empty(), "empty derived evaluation");
    let group = JobNode {
        id: origin.nodes[0].clone(),
        workflow: origin.workflow.clone(),
        job: origin.jobs[0].clone(),
        depends_on: vec![],
        kind: NodeKind::MatrixGroup {
            variants: selections.iter().map(|s| s.task.nodes[0].clone()).collect(),
            fail_fast: spec.fail_fast,
            max_parallel: spec.max_parallel,
            aggregation: OutputAggregation::MatrixOrder,
        },
    };
    let inputs_digest = digest(inputs)?;
    let evaluation_digest = digest(evaluation)?;
    let expansion_digest = digest(&(&group, &selections, &inputs_digest, &evaluation_digest))?;
    let dispatches = selections
        .iter()
        .enumerate()
        .map(|(index, selection)| DerivedDispatch {
            schema_version: DISPATCH_VERSION,
            plan_digest: plan.digest.clone(),
            origin: origin.id.clone(),
            task: selection.task.id.clone(),
            index,
            inputs_digest: inputs_digest.clone(),
            evaluation_digest: evaluation_digest.clone(),
            expansion_digest: expansion_digest.clone(),
        })
        .collect();
    Ok(Derivation::Expanded(Box::new(Expansion {
        group,
        selections,
        dispatches,
        inputs: inputs.clone(),
    })))
}

/// The id of one member of the dynamic matrix of an origin. The index has no
/// `#`, so the members of two origins never share an id.
fn member_id(origin: &str, index: usize) -> String {
    format!("{origin}#{index}")
}
/// Whether a task id lies where the members of the dynamic matrix of an
/// origin are named. A plan with such a task is refused before anything runs.
pub(crate) fn names_member_of(origin: &str, id: &str) -> bool {
    id.strip_prefix(origin)
        .is_some_and(|rest| rest.starts_with('#'))
}

pub(crate) fn validate(
    plan: &FrozenPlan,
    source: &VerifiedEvaluationSource,
    facts: &PortableFacts,
    dispatch: &DerivedDispatch,
    inputs: &TaskInputs,
) -> Result<Selection> {
    let evaluation = EvaluationContext::new(plan, source, facts.clone())?;
    let origin = plan
        .task(&dispatch.origin)
        .context("unknown dispatch origin")?;
    let Derivation::Expanded(expansion) = derive(
        plan,
        &evaluation,
        origin,
        inputs,
        MAX_TASKS,
        MAX_DERIVED_BYTES,
    )?
    else {
        anyhow::bail!("dispatch origin does not expand");
    };
    let expected = expansion
        .dispatches
        .get(dispatch.index)
        .context("dispatch is not an expansion member")?;
    ensure!(expected == dispatch, "derived dispatch proof mismatch");
    Ok(expansion.selections[dispatch.index].clone())
}

#[cfg(test)]
mod survivor_tests {
    #[test]
    fn member_ids_of_distinct_origins_never_coincide() {
        // origins chosen so that one is a member id of another
        let origins = ["w::a", "w::a#0", "w::a#0#1", "w::a#", "w::a#1", "w::a1"];
        let mut seen = std::collections::BTreeMap::new();
        for origin in origins {
            for index in [0, 1, 10, 11, 100] {
                let id = super::member_id(origin, index);
                assert!(super::names_member_of(origin, &id));
                assert_eq!(seen.insert(id.clone(), (origin, index)), None, "{id}");
            }
        }
        assert_eq!(super::member_id("w::a", 12), "w::a#12");
        assert!(!super::names_member_of("w::a", "w::a"));
        assert!(!super::names_member_of("w::a", "w::ab#0"));
        assert!(!super::names_member_of("w::a", "x#w::a#0"));
        assert!(super::names_member_of("w::a", "w::a#x"));
    }
    #[test]
    fn expansion_budget_accepts_boundary_and_rejects_next_byte() {
        super::ensure_expansion_budget(4096, 4096).unwrap();
        assert!(super::ensure_expansion_budget(4097, 4096)
            .unwrap_err()
            .to_string()
            .contains("expansion evaluated byte budget exceeded"));
    }
}