use crate::artifact;
use crate::expr::NeedsRef;
use crate::plan::{self, Plan};
use crate::wire::{JobSpec, MatrixValue, UnitSpec, WorkflowSpec};
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::{BTreeMap, BTreeSet, HashMap};
pub fn node_id(workflow: &str, job: &str) -> String {
format!("{workflow}::{job}")
}
fn variant_id(workflow: &str, job: &str, index: usize) -> String {
format!("{workflow}::{job}#{index}")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OutputAggregation {
MatrixOrder,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum NodeKind {
Job,
DynamicMatrix { expression: String },
MatrixVariant {
group: String,
index: usize,
values: Map<String, Value>,
label: String,
},
MatrixGroup {
variants: Vec<String>,
fail_fast: bool,
max_parallel: Option<usize>,
aggregation: OutputAggregation,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobNode {
pub id: String,
pub workflow: String,
pub job: String,
#[serde(flatten)]
pub kind: NodeKind,
pub depends_on: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct JobGraph {
pub nodes: Vec<JobNode>,
}
impl JobGraph {
pub fn node(&self, id: &str) -> Option<&JobNode> {
self.nodes.iter().find(|n| n.id == id)
}
}
pub(crate) enum MatrixPlan {
None,
Dynamic(String),
Static(Vec<Map<String, Value>>),
}
pub(crate) fn matrix_plan(job: &JobSpec) -> MatrixPlan {
let Some(m) = &job.matrix else {
return MatrixPlan::None;
};
match m {
MatrixValue::Map(_) if !m.has_expression() => match crate::matrix::expand(&m.to_json()) {
Ok(c) => MatrixPlan::Static(c),
Err(_) => MatrixPlan::Dynamic("matrix".into()),
},
MatrixValue::String(s) => MatrixPlan::Dynamic(s.clone()),
_ => MatrixPlan::Dynamic("matrix".into()),
}
}
pub fn build_graph(workflows: &[WorkflowSpec], units: &[UnitSpec]) -> Result<JobGraph> {
let mut nodes: Vec<JobNode> = Vec::new();
for wi in 0..workflows.len() {
nodes.extend(workflow_nodes(workflows, units, wi)?);
}
order(nodes)
}
pub fn unrunnable_workflows(
workflows: &[WorkflowSpec],
units: &[UnitSpec],
) -> Vec<(usize, String)> {
let mut out = Vec::new();
for (wi, w) in workflows.iter().enumerate() {
let why = w
.jobs
.iter()
.find_map(|j| {
let key = j.matrix.as_ref()?.duplicate_key()?;
Some(format!(
"the matrix of job `{}` has two keys that print as `{key}`",
j.id
))
})
.or_else(|| {
workflow_nodes(workflows, units, wi)
.and_then(order)
.err()
.map(|e| format!("{e:#}"))
});
if let Some(why) = why {
out.push((wi, why));
}
}
out
}
fn workflow_nodes(
workflows: &[WorkflowSpec],
units: &[UnitSpec],
wi: usize,
) -> Result<Vec<JobNode>> {
let w = &workflows[wi];
let mut nodes: Vec<JobNode> = Vec::new();
let planned: BTreeSet<&str> = units
.iter()
.filter(|u| u.workflow == wi)
.flat_map(|u| u.jobs.iter().map(String::as_str))
.collect();
for job in w.jobs.iter().filter(|j| planned.contains(j.id.as_str())) {
let mut deps = Vec::new();
for n in &job.needs {
if !planned.contains(n.as_str()) {
bail!(
"job `{}` of {} needs `{n}`, which is not a job of the plan",
job.id,
w.file
);
}
deps.push(node_id(&w.file, n));
}
let id = node_id(&w.file, &job.id);
let mk = |id: String, kind: NodeKind, depends_on: Vec<String>| JobNode {
id,
workflow: w.file.clone(),
job: job.id.clone(),
kind,
depends_on,
};
match matrix_plan(job) {
MatrixPlan::None => nodes.push(mk(id, NodeKind::Job, deps)),
MatrixPlan::Dynamic(expression) => {
nodes.push(mk(id, NodeKind::DynamicMatrix { expression }, deps))
}
MatrixPlan::Static(combos) => {
let mut ids = Vec::new();
for (i, c) in combos.into_iter().enumerate() {
let vid = variant_id(&w.file, &job.id, i);
ids.push(vid.clone());
let label = crate::matrix::describe(&c);
nodes.push(mk(
vid,
NodeKind::MatrixVariant {
group: id.clone(),
index: i,
values: c,
label,
},
deps.clone(),
));
}
nodes.push(mk(
id,
NodeKind::MatrixGroup {
variants: ids.clone(),
fail_fast: job.fail_fast,
max_parallel: job.max_parallel,
aggregation: OutputAggregation::MatrixOrder,
},
ids,
));
}
}
}
Ok(nodes)
}
fn order(nodes: Vec<JobNode>) -> Result<JobGraph> {
let mut done: Vec<JobNode> = Vec::with_capacity(nodes.len());
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut rest = nodes;
while !rest.is_empty() {
let at = rest
.iter()
.position(|n| n.depends_on.iter().all(|d| seen.contains(d)));
match at {
Some(i) => {
let n = rest.remove(i);
seen.insert(n.id.clone());
done.push(n);
}
None => {
let names: Vec<String> = rest
.iter()
.filter(|n| !matches!(n.kind, NodeKind::MatrixVariant { .. }))
.map(|n| n.id.clone())
.collect();
bail!(
"the jobs depend on each other in a cycle: {}",
names.join(", ")
);
}
}
}
Ok(JobGraph { nodes: done })
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "reason", rename_all = "snake_case")]
pub enum GroupedReason {
SharedOutputs { files: Vec<String> },
OrderAroundSharedOutputs,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkspacePolicy {
pub own_checkout: bool,
pub shared_by_jobs: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TaskService {
pub job: String,
pub id: String,
pub image: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RetryPolicy {
pub max_attempts: u32,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct OutputVerification {
pub job_outputs: Vec<String>,
pub artifacts: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct NeedsOutput {
pub job: String,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TaskVariant {
pub group: String,
pub index: usize,
pub values: Map<String, Value>,
pub label: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecutionTask {
pub id: String,
pub workflow: String,
pub jobs: Vec<String>,
pub nodes: Vec<String>,
pub unit: usize,
pub variant: Option<TaskVariant>,
pub dynamic_matrix: bool,
pub depends_on: Vec<String>,
pub needs_outputs: Vec<NeedsOutput>,
pub artifacts: Vec<String>,
pub workspace: WorkspacePolicy,
pub services: Vec<TaskService>,
pub exclusive: bool,
pub retry: RetryPolicy,
pub verification: OutputVerification,
pub grouped_reason: Option<GroupedReason>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NotSplit {
NoRunnerAdapter,
SharedWorkspace,
HasServices,
MatrixVariant,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShardGroup {
pub id: String,
pub workflow: String,
pub source_jobs: Vec<String>,
pub shards: Vec<String>,
pub split: bool,
pub not_split: Vec<NotSplit>,
pub aggregation: Option<OutputAggregation>,
}
fn needs_outputs_of(job: &JobSpec, wf: &WorkflowSpec) -> Vec<NeedsOutput> {
fn strings(v: &Value, bare: bool, out: &mut Vec<(String, bool)>) {
match v {
Value::String(s) => out.push((s.clone(), bare)),
Value::Array(a) => a.iter().for_each(|e| strings(e, false, out)),
Value::Object(m) => {
for (k, e) in m {
strings(e, k == "cond", out);
}
}
_ => {}
}
}
let mut texts = Vec::new();
strings(
&serde_json::to_value(job).unwrap_or_default(),
false,
&mut texts,
);
let declared = |id: &str| -> Vec<NeedsOutput> {
wf.job(id)
.map(|j| {
j.outputs
.iter()
.map(|(name, _)| NeedsOutput {
job: id.to_string(),
name: name.clone(),
})
.collect()
})
.unwrap_or_default()
};
let mut out = BTreeSet::new();
for (text, bare) in texts {
for r in crate::expr::needs_refs(&text, bare) {
match r {
NeedsRef::Output { job, name } => {
out.insert(NeedsOutput { job, name });
}
NeedsRef::JobOutputs(id) => out.extend(declared(&id)),
NeedsRef::All => job.needs.iter().for_each(|n| out.extend(declared(n))),
}
}
}
out.into_iter().collect()
}
pub(crate) fn derive_tasks(
plan: &Plan,
specs: &[WorkflowSpec],
units: &[UnitSpec],
) -> (Vec<ExecutionTask>, Vec<ShardGroup>) {
let mut tasks: Vec<ExecutionTask> = Vec::new();
for (ui, u) in units.iter().enumerate() {
let wf = &specs[u.workflow];
let w = &plan.selected[u.workflow].wf;
let pos: HashMap<&str, usize> = u
.jobs
.iter()
.enumerate()
.map(|(i, j)| (j.as_str(), i))
.collect();
let writes: Vec<BTreeSet<String>> = u
.jobs
.iter()
.map(|id| {
let j = w.jobs.iter().find(|j| &j.id == id).expect("job in plan");
plan::writes(w, j)
})
.collect();
let n = u.jobs.len();
let mut comp: Vec<usize> = (0..n).collect();
fn root(c: &[usize], mut i: usize) -> usize {
while c[i] != i {
i = c[i];
}
i
}
for a in 0..n {
for b in (a + 1)..n {
if !writes[a].is_disjoint(&writes[b]) {
let (x, y) = (root(&comp, a), root(&comp, b));
comp[x] = y;
}
}
}
let mut groups: Vec<Vec<usize>> = Vec::new();
let mut seen_root: Vec<usize> = Vec::new();
for i in 0..n {
let r = root(&comp, i);
match seen_root.iter().position(|x| *x == r) {
Some(g) => groups[g].push(i),
None => {
seen_root.push(r);
groups.push(vec![i]);
}
}
}
let mut merged = false;
let in_unit_order = |groups: &[Vec<usize>], order: &[usize]| {
order
.iter()
.flat_map(|&g| groups[g].iter().copied())
.eq(0..n)
};
let mut ordered = order_groups(wf, u, &groups, &pos).filter(|o| in_unit_order(&groups, o));
if ordered.is_none() {
groups = vec![(0..n).collect()];
merged = true;
ordered = Some(vec![0]);
}
let ordered = ordered.unwrap();
for gi in ordered {
let g = &groups[gi];
let ids: Vec<String> = g.iter().map(|&i| u.jobs[i].clone()).collect();
let specs_of: Vec<&JobSpec> = ids
.iter()
.map(|id| wf.job(id).expect("job in plan"))
.collect();
let grouped_reason = (g.len() > 1).then(|| {
if merged {
GroupedReason::OrderAroundSharedOutputs
} else {
let mut count: BTreeMap<&String, usize> = BTreeMap::new();
for &i in g {
for f in &writes[i] {
*count.entry(f).or_default() += 1;
}
}
GroupedReason::SharedOutputs {
files: count
.into_iter()
.filter(|(_, c)| *c > 1)
.map(|(f, _)| f.clone())
.collect(),
}
}
});
let base = ExecutionTask {
id: String::new(),
workflow: wf.file.clone(),
jobs: ids.clone(),
nodes: vec![],
unit: ui,
variant: None,
dynamic_matrix: false,
depends_on: vec![],
needs_outputs: vec![],
artifacts: specs_of
.iter()
.flat_map(|j| &j.steps)
.filter_map(|s| artifact::needed_download(s.uses.as_deref()?, &s.with))
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
workspace: WorkspacePolicy {
own_checkout: true,
shared_by_jobs: g.len() > 1,
},
services: specs_of
.iter()
.flat_map(|j| {
j.services.iter().map(|s| TaskService {
job: j.id.clone(),
id: s.id.clone(),
image: s.image.clone(),
})
})
.collect(),
exclusive: g.iter().any(|&i| {
let j = w.jobs.iter().find(|j| j.id == u.jobs[i]).unwrap();
plan::is_exclusive(j)
}),
retry: RetryPolicy { max_attempts: 1 },
verification: OutputVerification {
job_outputs: specs_of
.iter()
.flat_map(|j| j.outputs.iter().map(|(k, _)| format!("{}.{k}", j.id)))
.collect(),
artifacts: specs_of
.iter()
.filter(|j| j.matrix.is_none())
.flat_map(|j| &j.steps)
.filter_map(|s| {
artifact::required_upload(
s.uses.as_deref()?,
&s.with,
s.cond.as_deref().is_some_and(|c| !artifact::always_true(c))
|| s.continue_on_error,
)
})
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
},
grouped_reason,
};
let external: BTreeSet<&str> = specs_of
.iter()
.flat_map(|j| j.needs.iter().map(String::as_str))
.filter(|n| !ids.iter().any(|i| i == n))
.collect();
let needs_outputs: Vec<NeedsOutput> = specs_of
.iter()
.flat_map(|j| needs_outputs_of(j, wf))
.filter(|o| external.contains(o.job.as_str()))
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let single = (g.len() == 1).then(|| specs_of[0]);
match single.map(|j| (j, matrix_plan(j))) {
Some((j, MatrixPlan::Static(combos))) => {
for (i, c) in combos.into_iter().enumerate() {
let id = variant_id(&wf.file, &j.id, i);
tasks.push(ExecutionTask {
id: id.clone(),
nodes: vec![id],
variant: Some(TaskVariant {
group: node_id(&wf.file, &j.id),
index: i,
label: crate::matrix::describe(&c),
values: c,
}),
needs_outputs: needs_outputs.clone(),
..base.clone()
});
}
}
other => {
let dynamic = matches!(other, Some((_, MatrixPlan::Dynamic(_))));
let id = format!("{}::{}", wf.file, ids.join("+"));
tasks.push(ExecutionTask {
id,
nodes: ids.iter().map(|j| node_id(&wf.file, j)).collect(),
dynamic_matrix: dynamic,
needs_outputs,
..base
});
}
}
}
}
let mut by_job: HashMap<(String, String), Vec<String>> = HashMap::new();
for t in &tasks {
for j in &t.jobs {
by_job
.entry((t.workflow.clone(), j.clone()))
.or_default()
.push(t.id.clone());
}
}
for t in &mut tasks {
let wf = specs.iter().find(|w| w.file == t.workflow).unwrap();
let mut deps = BTreeSet::new();
for j in &t.jobs {
for n in &wf.job(j).unwrap().needs {
if t.jobs.contains(n) {
continue;
}
if let Some(ids) = by_job.get(&(t.workflow.clone(), n.clone())) {
deps.extend(ids.iter().cloned());
}
}
}
t.depends_on = deps.into_iter().collect();
}
let shard_groups = tasks
.iter()
.map(|t| {
let mut not_split = vec![NotSplit::NoRunnerAdapter];
if t.workspace.shared_by_jobs {
not_split.push(NotSplit::SharedWorkspace);
}
if !t.services.is_empty() {
not_split.push(NotSplit::HasServices);
}
if t.variant.is_some() {
not_split.push(NotSplit::MatrixVariant);
}
ShardGroup {
id: t.id.clone(),
workflow: t.workflow.clone(),
source_jobs: t.jobs.clone(),
shards: vec![t.id.clone()],
split: false,
not_split,
aggregation: None,
}
})
.collect();
(tasks, shard_groups)
}
fn order_groups(
wf: &WorkflowSpec,
u: &UnitSpec,
groups: &[Vec<usize>],
pos: &HashMap<&str, usize>,
) -> Option<Vec<usize>> {
let group_of = |job: &str| {
groups
.iter()
.position(|g| g.iter().any(|&i| u.jobs[i] == job))
};
let deps: Vec<BTreeSet<usize>> = groups
.iter()
.enumerate()
.map(|(gi, g)| {
g.iter()
.flat_map(|&i| wf.job(&u.jobs[i]).unwrap().needs.iter())
.filter(|n| pos.contains_key(n.as_str()))
.filter_map(|n| group_of(n))
.filter(|d| *d != gi)
.collect()
})
.collect();
let mut done: Vec<usize> = Vec::new();
while done.len() < groups.len() {
let next = (0..groups.len())
.filter(|g| !done.contains(g) && deps[*g].iter().all(|d| done.contains(d)))
.min_by_key(|g| groups[*g][0])?;
done.push(next);
}
Some(done)
}