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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Running one task of a plan, given what the tasks before it produced.
//!
//! [`execute_task`] does not look at any other task and never starts a job it
//! was not asked for: the results and outputs of the jobs it `needs` come in
//! as [`TaskInputs`], and what it produced goes out as a [`TaskResult`]. The
//! caller (a local run, or a coordinator that placed the earlier tasks on other
//! hosts) decides the order and carries the inputs over.

use crate::context::ExecContext;
use crate::dag::{JobNode, NodeKind};
use crate::exec::{JobResult, Opts, Outcome, Runner, Workspace};
use crate::frozen::FrozenPlan;
use crate::setup::{PreparedReceipt, PreparedSetup, SetupRecipe, TemplateContext, TemplateKey};
use crate::shard::ShardOutcome;
use anyhow::{anyhow, bail, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, BTreeSet};

/// How a job ended, as `needs.<id>.result` sees it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum JobStatus {
    Success,
    Failure,
    Skipped,
    Cancelled,
}

impl JobStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            JobStatus::Success => "success",
            JobStatus::Failure => "failure",
            JobStatus::Skipped => "skipped",
            JobStatus::Cancelled => "cancelled",
        }
    }

    /// The status of one job (or matrix entry) from how it ended: an error
    /// counts as a failure, a job the run was cancelled under (before it
    /// started or while it ran) as cancelled.
    pub(crate) fn of(r: &JobResult) -> Self {
        if r.cancelled {
            return JobStatus::Cancelled;
        }
        match r.outcome {
            Outcome::Pass => JobStatus::Success,
            Outcome::Fail | Outcome::Error(_) => JobStatus::Failure,
            Outcome::Skip(_) => JobStatus::Skipped,
        }
    }
}

/// A finished job as the jobs that need it see it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobOutcome {
    pub job: String,
    /// The matrix entry (index in matrix order) when this is one entry of a
    /// matrix job, `None` for the job as a whole.
    pub variant: Option<usize>,
    pub status: JobStatus,
    /// `outputs:` of the job, evaluated.
    pub outputs: BTreeMap<String, String>,
    /// Why the job did not run (an `if:` that was false, `needs failed`,
    /// `fail-fast`, `cancelled`, ...).
    pub skipped: Option<String>,
    /// A job this one needs, directly or through the jobs it needs, failed
    /// (this job's own failure is `status`). This is what `failure()` of a job
    /// asks, together with the status of the jobs it needs directly; carrying it
    /// in each outcome lets a coordinator hand a task only the direct needs.
    #[serde(default)]
    pub ancestor_failed: bool,
}

impl JobOutcome {
    /// This job, or a job it needs, failed.
    pub fn failed_or_ancestor_failed(&self) -> bool {
        self.status == JobStatus::Failure || self.ancestor_failed
    }
}

/// What a task is given about the jobs it needs, by job id. Jobs of the same
/// task are not listed: they are run in order and see each other.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TaskInputs {
    /// See [`crate::wire::WIRE_SCHEMA_VERSION`].
    #[serde(default = "crate::wire::wire_version")]
    pub schema_version: u32,
    pub needs: BTreeMap<String, JobOutcome>,
    /// The run was cancelled: what `cancelled()` answers in a job, whether or
    /// not a job it needs was cancelled. A coordinator sets it for the tasks it
    /// starts after the run was cancelled; [`TaskInputs::new`] sets it from the
    /// outcomes it is given.
    #[serde(default)]
    pub run_cancelled: bool,
}

impl crate::wire::Digested for TaskInputs {
    fn schema_version(&self) -> u32 {
        self.schema_version
    }
}
impl crate::wire::Digested for TaskResult {
    fn schema_version(&self) -> u32 {
        self.schema_version
    }
}

impl Default for TaskInputs {
    fn default() -> Self {
        TaskInputs {
            schema_version: crate::wire::wire_version(),
            needs: BTreeMap::new(),
            run_cancelled: false,
        }
    }
}

impl TaskInputs {
    /// The inputs for a task that needs `needs`, from every job finished so far
    /// (the task takes the jobs it needs by id and ignores the rest).
    /// `cancel_requested`: the run was cancelled. The run also counts as
    /// cancelled when any finished job was.
    pub fn new<'a>(
        needs: impl IntoIterator<Item = &'a JobOutcome>,
        finished: impl IntoIterator<Item = &'a JobOutcome>,
        cancel_requested: bool,
    ) -> Self {
        TaskInputs {
            schema_version: crate::wire::wire_version(),
            needs: needs
                .into_iter()
                .map(|o| (o.job.clone(), o.clone()))
                .collect(),
            run_cancelled: cancel_requested
                || finished
                    .into_iter()
                    .any(|o| o.status == JobStatus::Cancelled),
        }
    }

    /// The `needs` context the expressions of a job are evaluated against.
    pub(crate) fn context(&self) -> Map<String, Value> {
        self.needs
            .iter()
            .map(|(k, o)| (k.clone(), ctx_of(o)))
            .collect()
    }
}

pub(crate) fn ctx_of(o: &JobOutcome) -> Value {
    let outputs: Map<String, Value> = o
        .outputs
        .iter()
        .map(|(k, v)| (k.clone(), Value::String(v.clone())))
        .collect();
    json!({"result": o.status.as_str(), "outputs": outputs})
}

/// What running a task produced.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskResult {
    /// See [`crate::wire::WIRE_SCHEMA_VERSION`].
    #[serde(default = "crate::wire::wire_version")]
    pub schema_version: u32,
    pub task: String,
    /// Each job (each matrix entry) with its steps, as a run reports them.
    pub jobs: Vec<JobResult>,
    /// Each job of the task as a whole, in the order they ran. For a task that
    /// is one variant of a matrix: that variant.
    pub outcomes: Vec<JobOutcome>,
    /// Why the receipt that came with the task was not believed (another
    /// commit, another workspace, another template key); the task then did all
    /// its setup itself. `None` when there was no receipt or it was used.
    pub receipt_ignored: Option<String>,
    /// Names of the artifacts uploaded by the task's own jobs, in the area of
    /// its workflow (the `artifacts` a task's
    /// [`crate::dag::OutputVerification`] asks for are checked against this).
    pub artifacts: Vec<String>,
    /// For the task of one shard of a split job: what the shard's tests
    /// reported, read from the log of the step that ran them. `None` for any
    /// other task.
    #[serde(default)]
    pub shard: Option<ShardOutcome>,
}

/// One job, or one matrix entry of it, from its result and outputs.
pub(crate) fn outcome_of(
    job: &str,
    variant: Option<usize>,
    r: &JobResult,
    outputs: &Map<String, Value>,
) -> JobOutcome {
    JobOutcome {
        job: job.to_string(),
        variant,
        status: JobStatus::of(r),
        outputs: outputs
            .iter()
            .map(|(k, v)| (k.clone(), crate::expr::to_string(v)))
            .collect(),
        skipped: match &r.outcome {
            Outcome::Skip(why) => Some(why.clone()),
            _ => None,
        },
        ancestor_failed: false,
    }
}

/// The entries of a matrix job as the job, as `needs.<id>.result` is for a
/// matrix on GitHub: failed if any failed, otherwise cancelled if any was,
/// skipped if all were, otherwise success. Outputs are merged in matrix order
/// (by `variant`, whatever order `parts` is in), a name set by several entries
/// keeping the value of the last in matrix order.
///
/// GitHub takes, for a name set by several entries, the value of the entry that
/// finished last; that depends on timing, so a plan cannot be run twice with the
/// same outputs. The order of the matrix is the rule here instead.
pub(crate) fn combine(job: &str, mut parts: Vec<JobOutcome>) -> JobOutcome {
    parts.sort_by_key(|p| p.variant.unwrap_or(0));
    let mut outputs = BTreeMap::new();
    for p in &parts {
        for (k, v) in &p.outputs {
            outputs.insert(k.clone(), v.clone());
        }
    }
    let any = |s: JobStatus| parts.iter().any(|p| p.status == s);
    let status = if any(JobStatus::Failure) {
        JobStatus::Failure
    } else if any(JobStatus::Cancelled) {
        JobStatus::Cancelled
    } else if !parts.is_empty() && parts.iter().all(|p| p.status == JobStatus::Skipped) {
        JobStatus::Skipped
    } else {
        JobStatus::Success
    };
    let skipped = parts.iter().find_map(|p| p.skipped.clone());
    JobOutcome {
        job: job.to_string(),
        variant: None,
        status,
        outputs,
        skipped: if status == JobStatus::Success {
            None
        } else {
            skipped
        },
        ancestor_failed: parts.iter().any(|p| p.ancestor_failed),
    }
}

/// The outputs of `parts` that two of them give different values, as
/// sentences. The shards of one job run the same job: an output they disagree
/// on has no one value to publish.
pub(crate) fn conflicting_outputs(parts: &[JobOutcome]) -> Vec<String> {
    let mut first: BTreeMap<&str, &str> = BTreeMap::new();
    let mut out = BTreeSet::new();
    for (k, v) in parts.iter().flat_map(|p| &p.outputs) {
        if *first.entry(k).or_insert(v) != v {
            out.insert(k.as_str());
        }
    }
    out.into_iter()
        .map(|k| format!("the shards gave different values for the output `{k}`"))
        .collect()
}

/// The job that a matrix is, from the outcomes of its variants, which may
/// arrive in any order. Every variant of the node must be there exactly once.
pub fn aggregate_matrix(group: &JobNode, variants: &[JobOutcome]) -> Result<JobOutcome> {
    let NodeKind::MatrixGroup { variants: ids, .. } = &group.kind else {
        bail!("{} is not a matrix", group.id);
    };
    let mut seen = vec![false; ids.len()];
    for v in variants {
        let i = v
            .variant
            .filter(|i| *i < ids.len())
            .ok_or_else(|| anyhow!("an outcome of {} names no variant of it", group.id))?;
        if std::mem::replace(&mut seen[i], true) {
            bail!("variant {i} of {} is there twice", group.id);
        }
    }
    if let Some(i) = seen.iter().position(|s| !s) {
        bail!("variant {i} of {} has no outcome", group.id);
    }
    Ok(combine(&group.job, variants.to_vec()))
}

/// Do `recipe`, the setup of a task, in `ws` and return what was prepared.
/// `key` is the template key the result is for. Steps that were run are in
/// `steps` as a run reports them; the receipt names only those that passed (or
/// that an equal install in the same workspace had already done).
pub fn execute_setup(
    ctx: &ExecContext,
    fp: &FrozenPlan,
    recipe: &SetupRecipe,
    key: &TemplateKey,
    ws: &Workspace,
    opts: Opts,
) -> Result<PreparedSetup> {
    fp.require_git_source()?;
    crate::wire::check_version("setup recipe", recipe.schema_version)?;
    let runner = Runner::new(ctx, fp, ws, opts)?;
    runner.prepare_tools()?;
    let r = runner.run_recipe(recipe, key.digest())?;
    ctx.cancel.remove_containers(ctx);
    Ok(r)
}

/// Run task `task_id` of `fp` in `ws`, with `inputs` as the results of the jobs
/// it needs, and return what it produced. Jobs it does not hold are not
/// started, and `-j`/units are not looked at again.
///
/// The workspace is a checkout of the planned commit. `prepared` says which
/// install steps of the task were done in it already (see [`execute_setup`]);
/// those are skipped and every other one is run by the task. The receipt is
/// believed only when it was made on this commit, in this very workspace
/// (its id is in the workspace) and under the template key the task's recipe
/// has with the given [`TemplateContext`]; otherwise it is ignored, the task
/// does all its setup itself, and `receipt_ignored` of the result says why.
/// With `None` the task prepares everything itself. The workspace is left for the caller to
/// remove.
/// Cleanup is attempted for acknowledged resources. Failures and ambiguous
/// creation remain tracked in the attempt context and emit separate warnings;
/// a returned task result is not a physical-stop capability.
///
/// Conditions (`needs.*.result`, `success()`, `failure()`, `always()`,
/// `cancelled()`) and `needs.<id>.outputs.*` are evaluated against `inputs`.
/// A job whose condition is false is not run and the result says why.
pub fn execute_task(
    ctx: &ExecContext,
    fp: &FrozenPlan,
    task_id: &str,
    inputs: &TaskInputs,
    prepared: Option<(&PreparedReceipt, &TemplateContext)>,
    ws: &Workspace,
    opts: Opts,
) -> Result<TaskResult> {
    fp.require_git_source()?;
    let runner = Runner::new(ctx, fp, ws, opts)?;
    execute_with_runner(ctx, fp, task_id, inputs, prepared, ws, runner)
}

/// Execute one source-verified ordinary Git dynamic member.
///
/// The host must authenticate `dispatch`, `inputs` and `facts` against its
/// committed claim. Scheduling facts are reread from the exact frozen Git
/// commit in `ws.repo_root`, and the complete dispatch is recomputed before
/// constructing a runner or starting work. The workspace has the same
/// caller-owned checkout/prepared-state contract as [`execute_task`].
///
/// `ctx` MUST belong exclusively to this attempt: like [`execute_task`], this
/// entry cleans the context's containers and releases workspace ports. It is
/// not a persistent shared-unit runner or a concurrent shared-context API.
#[allow(clippy::too_many_arguments)]
pub fn execute_git_dispatch(
    ctx: &ExecContext,
    fp: &FrozenPlan,
    dispatch: &crate::driver::DerivedDispatch,
    inputs: &TaskInputs,
    facts: &crate::driver::PortableFacts,
    prepared: Option<(&PreparedReceipt, &TemplateContext)>,
    ws: &Workspace,
    opts: Opts,
) -> Result<TaskResult> {
    let selection = verify_git_dispatch(ctx, fp, &ws.repo_root, dispatch, inputs, facts)?;
    let task = selection.task.clone();
    let runner = Runner::new(ctx, fp, ws, opts)?.select_derived(selection, facts.clone());
    execute_resolved_with_runner(ctx, &task, inputs, prepared, ws, runner)
}

/// The provenance/rederivation boundary is separate from runner construction
/// and cleanup so a future persistent unit host can reuse the same proof.
/// Captured and Git execution both use dispatch::validate, not separate
/// expansion or equality rules. Selection has no public unchecked constructor.
pub(crate) fn verify_git_dispatch(
    ctx: &ExecContext,
    fp: &FrozenPlan,
    repository: &std::path::Path,
    dispatch: &crate::driver::DerivedDispatch,
    inputs: &TaskInputs,
    facts: &crate::driver::PortableFacts,
) -> Result<crate::driver::dispatch::Selection> {
    let source = crate::source_execute::git_evaluation_source(ctx, repository, fp)?;
    crate::driver::dispatch::validate(fp, &source, facts, dispatch, inputs)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn execute_with_runner(
    ctx: &ExecContext,
    fp: &FrozenPlan,
    task_id: &str,
    inputs: &TaskInputs,
    prepared: Option<(&PreparedReceipt, &TemplateContext)>,
    ws: &Workspace,
    runner: Runner<'_>,
) -> Result<TaskResult> {
    let task = fp
        .task(task_id)
        .ok_or_else(|| anyhow!("the plan has no task `{task_id}`"))?;
    execute_resolved_with_runner(ctx, task, inputs, prepared, ws, runner)
}

/// Only frozen lookup or a source-validated derived proof may reach this helper.
#[allow(clippy::too_many_arguments)]
pub(crate) fn execute_resolved_with_runner(
    ctx: &ExecContext,
    task: &crate::dag::ExecutionTask,
    inputs: &TaskInputs,
    prepared: Option<(&PreparedReceipt, &TemplateContext)>,
    ws: &Workspace,
    runner: Runner<'_>,
) -> Result<TaskResult> {
    execute_resolved_outcome(ctx, task, inputs, prepared, ws, runner).legacy_result()
}

/// Fresh attempt cleanup policy. Persistent unit hosts must keep their own
/// context lifetime and call the execution-only boundary instead.
#[allow(clippy::too_many_arguments)]
pub(crate) fn execute_resolved_outcome(
    ctx: &ExecContext,
    task: &crate::dag::ExecutionTask,
    inputs: &TaskInputs,
    prepared: Option<(&PreparedReceipt, &TemplateContext)>,
    ws: &Workspace,
    runner: Runner<'_>,
) -> crate::execution_outcome::AttemptExecutionOutcome {
    let validation = (|| {
        crate::wire::check_version("task inputs", inputs.schema_version)?;
        if let Some((receipt, _)) = prepared {
            crate::wire::check_version("receipt", receipt.schema_version)?;
        }
        Ok(())
    })();
    if let Err(error) = validation {
        return crate::execution_outcome::AttemptExecutionOutcome {
            execution: Err(error),
            final_error: None,
            cleanup: crate::execution_outcome::CleanupOutcome {
                diagnostics: vec![],
                pending: ctx.cancel.pending_ownership(),
            },
        };
    }
    if let Some(refused) = runner.refused_task(task) {
        return crate::execution_outcome::AttemptExecutionOutcome {
            execution: Ok(refused),
            final_error: None,
            cleanup: crate::execution_outcome::CleanupOutcome {
                diagnostics: vec![],
                pending: ctx.cancel.pending_ownership(),
            },
        };
    }
    let keep = runner.opts.keep;
    let execution = execute_resolved_body(task, inputs, prepared, ws, &runner);
    let mut cleanup = ctx.cancel.cleanup_owned(ctx);
    let final_error = if !keep {
        runner.release_ports_checked(&ws.root).err()
    } else {
        None
    };
    cleanup.pending = ctx.cancel.pending_ownership();
    crate::execution_outcome::AttemptExecutionOutcome {
        execution,
        cleanup,
        final_error,
    }
}

/// Execution only: no context-wide container/port release. The enclosing host
/// still owns resource cleanup; returning is not a physical-stop assertion.
fn execute_resolved_body(
    task: &crate::dag::ExecutionTask,
    inputs: &TaskInputs,
    prepared: Option<(&PreparedReceipt, &TemplateContext)>,
    ws: &Workspace,
    runner: &Runner<'_>,
) -> Result<TaskResult> {
    runner.prepare_tools()?;
    let lock = if runner.task_locked(task) {
        runner.lock().ok()
    } else {
        None
    };
    let result = runner.run_task(
        &ws.root,
        task,
        inputs,
        prepared,
        true,
        lock.is_some(),
        false,
    );
    drop(lock);
    result
}

#[cfg(test)]
mod git_dispatch_tests;