Skip to main content

flm_core/core/plan/
selection.rs

1//! The two choices made while a plan is built: provider selection, which chooses
2//! the stage that provides each needed capability, and lowering rule selection,
3//! which chooses the lowering rule for each element on each backend.
4//!
5//! Both choices are made before anything runs, from what the registry holds and
6//! what the plan request says; see [`crate::core::plan`] for the whole process.
7//! The public results are [`SelectedRules`], the rules chosen for one backend,
8//! and [`Excluded`], a stage that provider selection ruled out. Every choice is
9//! made in name order, so the outcome and every message are the same regardless
10//! of the order in which the features registered.
11//!
12//! # Lowering rule selection
13//!
14//! Lowering rule selection chooses one rule per element and backend in a fixed
15//! order: the rule the request prefers by name, else the backend's native
16//! emission, else a rule marked default on that backend, else a rule marked
17//! default everywhere, else the sole candidate. A lowering rule is a named
18//! registry entity written for one element, which stages (builds into the lowered
19//! tree) the element's presentation for one backend
20//! ([`LoweringRule`](crate::core::lowering::LoweringRule)); its
21//! [`DefaultMark`] says when it is the rule to choose.
22//!
23//! The candidates on a backend are the registered rules for the element, except
24//! two kinds, which are never candidates, not even as the only rule for their
25//! element and not even when the request prefers them by name:
26//!
27//! - a rule that is set aside (excluded from rule selection; see
28//!   [`PeerName`](crate::core::registry::PeerName)): a peer declaration the rule
29//!   depends on (a backend it is marked as the default on, an element it produces
30//!   or a table it reads other than as an optional read, which the rule's feature
31//!   expects another feature to declare) resolved to nothing
32//!   ([`RuleEntry::set_aside`](crate::core::registry::RuleEntry::set_aside));
33//! - a rule marked as the default on other backends only
34//!   ([`DefaultMark::OnBackends`] without this backend). This mark says where the
35//!   rule belongs, not only where it ranks first, because such a rule builds
36//!   elements that only the backend it was written for writes natively. A rule marked
37//!   [`DefaultMark::Never`] remains a candidate on every backend: that mark
38//!   restricts the rule's rank, not where it may be used.
39//!
40//! Among the candidates, the rule is, in this order:
41//!
42//! 1. the first candidate the request prefers by name for this backend, even when
43//!    the backend would otherwise write the element natively;
44//! 2. otherwise no rule at all, when the backend writes the element natively;
45//! 3. otherwise the rule marked as the default on this backend
46//!    ([`DefaultMark::OnBackends`]);
47//! 4. otherwise the rule marked as the default everywhere
48//!    ([`DefaultMark::Everywhere`]);
49//! 5. otherwise the only candidate, when there is exactly one.
50//!
51//! When several candidates remain and none of these decides (for example two
52//! rules marked as the default on this backend), the plan build fails with
53//! [`PlanError::RuleContest`]. An element with no candidate gets no rule; the
54//! plan's completeness check then requires that the backend writes the element
55//! natively or that the plan request accepts it as unrenderable
56//! ([`PlanError::Incomplete`] otherwise). An element whose only rule is marked
57//! for one backend therefore makes the plan fail on every other backend that
58//! takes part in the plan and does not write the element natively, unless the
59//! plan request accepts the element as unrenderable there.
60//!
61//! A preferred rule that cannot be used, because it is set aside or because it
62//! is not a candidate on the backend, becomes a [`PlanWarning`], which the
63//! runner reports as a Warning diagnostic at the start of the run.
64//!
65//! # Provider selection
66//!
67//! Several stages may provide one capability, and the plan schedules exactly one
68//! of them. Provider selection chooses one stage for each capability the plan
69//! needs: the forced choices are made first and followed to a fixed point, then
70//! one tie is broken by the request's preferences or a default refinement, and
71//! the forced choices are followed again, until nothing is left to decide. In
72//! detail:
73//!
74//! 1. The needed capabilities start as the demanded ones. A **candidate** of a
75//!    capability is a stage that provides it, directly or by providing a
76//!    capability that refines it ([refinement](crate::guide::pipeline#refinement)),
77//!    and that has not been ruled out.
78//! 2. The forced choices are followed to a fixed point. A needed capability with
79//!    exactly one candidate schedules that stage. The stage's required
80//!    capabilities become needed too, and **every other stage that provides any of
81//!    the same capabilities is ruled out**. A stage is therefore indivisible:
82//!    scheduling it commits the plan to everything it provides, so no second
83//!    stage may provide any part of that.
84//! 3. A needed capability whose candidates have all been ruled out makes the
85//!    plan build fail with [`PlanError::Unsatisfiable`], which lists each provider
86//!    and the stage that ruled it out. A capability of an external table that
87//!    no registered stage provides is the exception: no stage writes such a
88//!    table, and the caller installs its value when the run is constructed
89//!    ([`Externals`](crate::core::run::Externals)).
90//! 4. When no choice is forced, the remaining ties are decided one at a time. The
91//!    first stage in the request's preferences that is a candidate of a contested
92//!    capability is scheduled. A preferred stage that is already ruled out is
93//!    skipped and reported as [`PlanWarning::IgnoredPreference`]. Without such a
94//!    preference, the first contested capability in name order is decided by its
95//!    default refinement (the capability that refines it and is marked as the one
96//!    a demand for it selects), following the chain of defaults down while the
97//!    default itself has several candidates. A tie that neither decides makes the plan build fail
98//!    with [`PlanError::Contested`], which lists the candidates. After each
99//!    choice, selection resumes at item 2.
100//!
101//! A preferred stage that was ruled out is reported as
102//! [`PlanWarning::IgnoredPreference`] even when no tie ever involved it.
103
104use std::collections::{BTreeMap, BTreeSet};
105
106use crate::core::lowering::DefaultMark;
107use crate::model::names::{CapName, ElementName, FeatureName, RuleName, StageName, WorkflowName};
108use crate::core::plan::build::{PlanError, PlanWarning};
109use crate::core::registry::frozen::{BackendEntry, CapId, FlmRegistry, RuleIdx, StageIdx};
110use crate::core::data::table::TableId;
111
112/// The lowering rules one backend uses in one plan, one rule per element.
113///
114/// Lowering rule selection chooses one rule per element and backend in a fixed
115/// order: the rule the request prefers by name, else the backend's native
116/// emission, else a rule marked default on that backend, else a rule marked
117/// default everywhere, else the sole candidate. The [module documentation](self)
118/// describes which rules are candidates and when the choice fails.
119///
120/// A backend's lowering stage reads this value to work out what it needs, and the
121/// lowering driver reads it at every node to find the rule to call. Read it from
122/// [`Plan::selection`](crate::core::plan::Plan::selection) or, while the plan is
123/// being built, from
124/// [`PlanCx::lowering_selection`](crate::core::plan::PlanCx::lowering_selection).
125///
126/// The rule indices ([`RuleIdx`]) are numbers of the registry the plan was built
127/// against, and mean nothing with any other registry.
128#[derive(Debug, Clone, Default, PartialEq, Eq)]
129pub struct SelectedRules {
130    /// The rule chosen for each element. An element the backend writes natively
131    /// has no entry, unless the request preferred a rule for it.
132    pub by_element: BTreeMap<ElementName, RuleIdx>,
133    /// The elements the backend writes natively for which the request preferred
134    /// a rule, which is used instead of the native emission.
135    pub overridden_native: BTreeSet<ElementName>,
136}
137
138impl SelectedRules {
139    /// The rule chosen for `element`, or `None` when no rule was chosen for it on
140    /// this backend.
141    pub fn rule_for(&self, element: &str) -> Option<RuleIdx> {
142        self.by_element.get(element).copied()
143    }
144
145    /// Every chosen rule, in element-name order.
146    pub fn rules(&self) -> impl Iterator<Item = RuleIdx> + '_ {
147        self.by_element.values().copied()
148    }
149}
150
151/// Chooses one rule per element for `backend`, under the rule preferences
152/// `prefer` (most preferred first), as the module documentation describes.
153///
154/// Returns the choice and its warnings: one [`PlanWarning`] per preference that
155/// cannot be honored (a preferred rule that is set aside, and a preferred rule
156/// that is not a candidate on this backend), then the unchecked outputs of the
157/// chosen rules ([`unchecked_outputs`]). `workflow` is the workflow the plan
158/// request was made from, which the error and the warnings carry.
159///
160/// # Errors
161///
162/// Returns [`PlanError::RuleContest`] when several rules could lower an element
163/// and nothing chooses between them.
164pub(crate) fn select_rules(
165    registry: &FlmRegistry,
166    backend: &BackendEntry,
167    prefer: &[RuleName],
168    workflow: &Option<WorkflowName>,
169) -> Result<(SelectedRules, Vec<PlanWarning>), PlanError> {
170    let mut selected = SelectedRules::default();
171    let mut warnings = unhonored_rule_preferences(registry, backend, prefer, workflow);
172    let mut elements: BTreeSet<ElementName> =
173        registry.rules().iter().map(|entry| entry.rule.element.clone()).collect();
174    elements.extend(backend.native.iter().cloned());
175    for element in elements {
176        let candidates: Vec<RuleIdx> = registry
177            .rules_for(&element)
178            .iter()
179            .copied()
180            .filter(|idx| !registry.rule(*idx).is_set_aside())
181            .filter(|idx| registry.rule(*idx).rule.default.takes_part_on(&backend.name))
182            .collect();
183        let preferred = prefer.iter().find_map(|name| {
184            candidates.iter().copied().find(|idx| &registry.rule(*idx).rule.name == name)
185        });
186        if let Some(rule) = preferred {
187            if backend.native.contains(&element) {
188                selected.overridden_native.insert(element.clone());
189            }
190            selected.by_element.insert(element, rule);
191            continue;
192        }
193        if backend.native.contains(&element) {
194            continue;
195        }
196        let specific: Vec<RuleIdx> = candidates
197            .iter()
198            .copied()
199            .filter(|idx| registry.rule(*idx).rule.default.is_specific_to(&backend.name))
200            .collect();
201        let general: Vec<RuleIdx> = candidates
202            .iter()
203            .copied()
204            .filter(|idx| matches!(registry.rule(*idx).rule.default, DefaultMark::Everywhere))
205            .collect();
206        let chosen = match (specific.as_slice(), general.as_slice(), candidates.as_slice()) {
207            ([rule], _, _) | ([], [rule], _) | ([], [], [rule]) => *rule,
208            ([], [], []) => continue,
209            _ => {
210                let mut names: Vec<RuleName> =
211                    candidates.iter().map(|idx| registry.rule(*idx).rule.name.clone()).collect();
212                names.sort();
213                return Err(PlanError::RuleContest {
214                    backend: backend.name.clone(),
215                    element,
216                    candidates: names,
217                    workflow: workflow.clone(),
218                });
219            }
220        };
221        selected.by_element.insert(element, chosen);
222    }
223    warnings.extend(unchecked_outputs(registry, backend, &selected, workflow));
224    Ok((selected, warnings))
225}
226
227/// One [`PlanWarning::UncheckedOutput`] per feature whose chosen rules on this
228/// backend declare it in
229/// [`LoweringDecl::unchecked_output`](crate::core::lowering::LoweringDecl::unchecked_output),
230/// in feature name order.
231///
232/// The rules of one feature on one backend describe the same output, so the
233/// warning takes what is written and what reads it from the first declaring
234/// rule in rule-name order.
235fn unchecked_outputs(
236    registry: &FlmRegistry,
237    backend: &BackendEntry,
238    selected: &SelectedRules,
239    workflow: &Option<WorkflowName>,
240) -> Vec<PlanWarning> {
241    let mut rules: Vec<RuleIdx> = selected.rules().collect();
242    rules.sort_by(|a, b| registry.rule(*a).rule.name.cmp(&registry.rule(*b).rule.name));
243    rules.dedup();
244    let mut by_feature: BTreeMap<FeatureName, PlanWarning> = BTreeMap::new();
245    for idx in rules {
246        let entry = registry.rule(idx);
247        let Some(declared) =
248            entry.rule.decl.unchecked_output.iter().find(|decl| decl.backend == backend.name)
249        else {
250            continue;
251        };
252        by_feature.entry(entry.owner.clone()).or_insert_with(|| PlanWarning::UncheckedOutput {
253            backend: backend.name.clone(),
254            feature: entry.owner.clone(),
255            written: declared.written.clone(),
256            reader: declared.reader.clone(),
257            workflow: workflow.clone(),
258        });
259    }
260    by_feature.into_values().collect()
261}
262
263/// One [`PlanWarning`] per preference in `prefer` that this backend cannot
264/// honor, in the order the preferences are written.
265///
266/// A preference is honored whenever the rule it refers to is a candidate for its
267/// element on this backend, because the rule selection order consults the
268/// preferences first. The two ways it cannot be honored are the two warnings:
269/// the rule is set aside, or it is marked for other backends and so is not a
270/// candidate here. A preference passed over because an earlier preference chose
271/// a rule for the same element counts as honored and gives no warning, because
272/// the caller ranked the two itself.
273///
274/// A name that no rule of this registry carries is not one of these cases: the
275/// plan refuses such a request before choosing anything
276/// ([`PlanError::UnknownRule`]). The last match arm below, which would report
277/// it, only makes the function return a result for every input instead of
278/// panicking.
279fn unhonored_rule_preferences(
280    registry: &FlmRegistry,
281    backend: &BackendEntry,
282    prefer: &[RuleName],
283    workflow: &Option<WorkflowName>,
284) -> Vec<PlanWarning> {
285    let mut warnings: Vec<PlanWarning> = Vec::new();
286    for name in prefer {
287        let entry = registry.rule_idx(name).map(|idx| registry.rule(idx));
288        match entry {
289            Some(entry) if entry.is_set_aside() => {
290                warnings.push(PlanWarning::PreferredRuleSetAside {
291                    backend: backend.name.clone(),
292                    rule: name.clone(),
293                    unresolved: entry.set_aside.clone(),
294                    workflow: workflow.clone(),
295                });
296            }
297            Some(entry) if entry.rule.default.takes_part_on(&backend.name) => {}
298            _ => warnings.push(PlanWarning::PreferredRuleNotCandidate {
299                backend: backend.name.clone(),
300                rule: name.clone(),
301                workflow: workflow.clone(),
302            }),
303        }
304    }
305    warnings
306}
307
308/// A record of a stage that provider selection ruled out, with the scheduled stage
309/// that ruled it out and a capability both provide.
310///
311/// Scheduling a stage rules out every other stage that provides any of the same
312/// capabilities (see the [module documentation](self)). Each record lets a
313/// message say which stage was ruled out, by which stage and over which
314/// capability. [`Plan::excluded`](crate::core::plan::Plan::excluded) lists every
315/// record of a plan, and [`PlanError::Unsatisfiable`] lists the ones that left a
316/// needed capability without a provider.
317///
318/// It is written to data with `Serialize`; see [serialized
319/// forms](crate::core::registry#serialized-forms).
320#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
321#[derive(serde::Serialize, schemars::JsonSchema)]
322pub struct Excluded {
323    /// The stage that was ruled out.
324    pub stage: StageName,
325    /// The stage that was scheduled, which ruled it out.
326    pub excluded_by: StageName,
327    /// A capability both stages provide; the first in name order when there are
328    /// several, so that the record does not depend on the order in which the
329    /// features registered.
330    pub over: CapName,
331}
332
333/// The outcome of provider selection.
334#[derive(Debug, Default)]
335pub(crate) struct Selection {
336    /// The stages that will run.
337    pub scheduled: BTreeSet<StageIdx>,
338    /// The scheduled stages in the order they were chosen, kept so that a
339    /// reader can follow how the choice went.
340    pub commit_order: Vec<StageIdx>,
341    /// The stages that were ruled out, and why.
342    pub excluded: BTreeMap<StageIdx, Excluded>,
343    /// Every capability needed once provider selection has finished.
344    pub needed: BTreeSet<CapId>,
345    /// The external tables that must be installed when the run is constructed.
346    pub externals: BTreeSet<TableId>,
347    /// The stage preferences that could not be honored.
348    pub warnings: Vec<PlanWarning>,
349}
350
351/// The state of one run of provider selection.
352struct Solver<'a> {
353    registry: &'a FlmRegistry,
354    /// Every stage by name, which is the order every scan iterates in.
355    by_name: BTreeMap<StageName, StageIdx>,
356    requires_of: &'a dyn Fn(StageIdx) -> &'a BTreeSet<CapId>,
357    prefer: &'a [StageIdx],
358    needed: BTreeMap<CapName, CapId>,
359    committed: BTreeSet<StageIdx>,
360    commit_order: Vec<StageIdx>,
361    excluded: BTreeMap<StageIdx, Excluded>,
362    externals: BTreeSet<TableId>,
363    warnings: Vec<PlanWarning>,
364    warned: BTreeSet<StageIdx>,
365    /// The workflow the plan request was made from, which the errors and
366    /// warnings name.
367    workflow: &'a Option<WorkflowName>,
368}
369
370impl<'a> Solver<'a> {
371    fn provides(&self, stage: StageIdx) -> &'a BTreeSet<CapId> {
372        &self.registry.stage(stage).provides
373    }
374
375    fn name(&self, stage: StageIdx) -> StageName {
376        self.registry.stage(stage).name.clone()
377    }
378
379    /// The stages still eligible as providers of `cap`, in name order.
380    fn candidates(&self, cap: CapId) -> Vec<StageIdx> {
381        self.by_name
382            .values()
383            .copied()
384            .filter(|stage| !self.excluded.contains_key(stage))
385            .filter(|stage| self.provides(*stage).contains(&cap))
386            .collect()
387    }
388
389    /// Every stage providing `cap`, ruled out or not, in name order.
390    fn providers(&self, cap: CapId) -> Vec<StageIdx> {
391        self.by_name
392            .values()
393            .copied()
394            .filter(|stage| self.provides(*stage).contains(&cap))
395            .collect()
396    }
397
398    fn need(&mut self, cap: CapId) {
399        self.needed.insert(self.registry.capability(cap).name.clone(), cap);
400    }
401
402    fn commit(&mut self, stage: StageIdx) {
403        self.committed.insert(stage);
404        self.commit_order.push(stage);
405        for cap in (self.requires_of)(stage).iter().copied().collect::<Vec<_>>() {
406            self.need(cap);
407        }
408        let closure = self.provides(stage);
409        let others: Vec<StageIdx> = self.by_name.values().copied().collect();
410        for other in others {
411            if other == stage
412                || self.committed.contains(&other)
413                || self.excluded.contains_key(&other)
414            {
415                continue;
416            }
417            let shared = closure.intersection(self.provides(other));
418            // The name-least shared capability, so that the recorded reason does
419            // not depend on registration order.
420            let over = shared.map(|cap| &self.registry.capability(*cap).name).min().cloned();
421            if let Some(over) = over {
422                self.excluded.insert(
423                    other,
424                    Excluded { stage: self.name(other), excluded_by: self.name(stage), over },
425                );
426            }
427        }
428    }
429
430    /// Items 2 and 3 of provider selection as the [module documentation](self)
431    /// describes it: follows the forced choices until none is left.
432    fn propagate(&mut self) -> Result<(), PlanError> {
433        loop {
434            let mut progressed = false;
435            let needed: Vec<CapId> = self.needed.values().copied().collect();
436            for cap in needed {
437                let candidates = self.candidates(cap);
438                if candidates.is_empty() {
439                    let entry = self.registry.capability(cap);
440                    if entry.external && self.providers(cap).is_empty() {
441                        if let Some(table) = entry.table {
442                            self.externals.insert(table);
443                        }
444                        continue;
445                    }
446                    let blocked: Vec<Excluded> = self
447                        .providers(cap)
448                        .into_iter()
449                        .filter_map(|stage| self.excluded.get(&stage).cloned())
450                        .collect();
451                    return Err(PlanError::Unsatisfiable {
452                        capability: entry.name.clone(),
453                        unprovided: if blocked.is_empty() { entry.unprovided.clone() } else { None },
454                        blocked,
455                        workflow: self.workflow.clone(),
456                    });
457                }
458                if candidates.len() == 1 && !self.committed.contains(&candidates[0]) {
459                    self.commit(candidates[0]);
460                    progressed = true;
461                    break; // `needed` may have grown: restart the sweep
462                }
463            }
464            if !progressed {
465                return Ok(());
466            }
467        }
468    }
469
470    /// The needed capabilities that still have several candidates and none of
471    /// them scheduled, in name order.
472    fn contested(&self) -> Vec<CapId> {
473        self.needed
474            .values()
475            .copied()
476            .filter(|cap| {
477                let candidates = self.candidates(*cap);
478                candidates.len() > 1
479                    && !candidates.iter().any(|stage| self.committed.contains(stage))
480            })
481            .collect()
482    }
483
484    /// Item 4 of provider selection, first half: the first preferred stage that
485    /// is a candidate of one of the `contested` capabilities. Records a warning
486    /// for each preferred stage already ruled out.
487    fn preferred(&mut self, contested: &[CapId]) -> Option<StageIdx> {
488        for stage in self.prefer.iter().copied() {
489            if self.committed.contains(&stage) {
490                continue;
491            }
492            if let Some(excluded) = self.excluded.get(&stage) {
493                if self.warned.insert(stage) {
494                    self.warnings.push(PlanWarning::IgnoredPreference {
495                        stage: excluded.stage.clone(),
496                        excluded_by: excluded.excluded_by.clone(),
497                        over: excluded.over.clone(),
498                        workflow: self.workflow.clone(),
499                    });
500                }
501                continue;
502            }
503            if contested.iter().any(|cap| self.candidates(*cap).contains(&stage)) {
504                return Some(stage);
505            }
506        }
507        None
508    }
509
510    /// Item 4 of provider selection, second half: decides one contested
511    /// capability by its default refinement, following the chain of defaults down
512    /// until exactly one candidate is left.
513    fn by_default(&self, cap: CapId) -> Option<StageIdx> {
514        let mut current = self.registry.default_refinement(cap)?;
515        loop {
516            let candidates = self.candidates(current);
517            match candidates.as_slice() {
518                [stage] => return Some(*stage),
519                [] => return None,
520                _ => current = self.registry.default_refinement(current)?,
521            }
522        }
523    }
524
525    fn solve(mut self) -> Result<Selection, PlanError> {
526        loop {
527            self.propagate()?;
528            let contested = self.contested();
529            if contested.is_empty() {
530                break;
531            }
532            if let Some(stage) = self.preferred(&contested) {
533                self.commit(stage);
534                continue;
535            }
536            let cap = contested[0];
537            match self.by_default(cap) {
538                Some(stage) => self.commit(stage),
539                None => {
540                    let candidates =
541                        self.candidates(cap).into_iter().map(|stage| self.name(stage)).collect();
542                    return Err(PlanError::Contested {
543                        capability: self.registry.capability(cap).name.clone(),
544                        candidates,
545                        workflow: self.workflow.clone(),
546                    });
547                }
548            }
549        }
550        // A preference naming a stage the deduction ruled out is reported even
551        // when no contest ever looked at that preference: the caller asked for
552        // something that did not happen, and the reason is the same either way.
553        for stage in self.prefer.iter().copied() {
554            if let Some(excluded) = self.excluded.get(&stage) {
555                if self.warned.insert(stage) {
556                    self.warnings.push(PlanWarning::IgnoredPreference {
557                        stage: excluded.stage.clone(),
558                        excluded_by: excluded.excluded_by.clone(),
559                        over: excluded.over.clone(),
560                        workflow: self.workflow.clone(),
561                    });
562                }
563            }
564        }
565        Ok(Selection {
566            scheduled: self.committed,
567            commit_order: self.commit_order,
568            excluded: self.excluded,
569            needed: self.needed.values().copied().collect(),
570            externals: self.externals,
571            warnings: self.warnings,
572        })
573    }
574}
575
576/// Chooses one provider per needed capability, starting from `demands`, by the
577/// provider selection described in the module documentation.
578///
579/// `prefer` is the request's stage preferences, most preferred first.
580/// `requires_of` returns what one stage requires, already resolved against the
581/// registry. `workflow` is the workflow the plan request was made from, which
582/// the errors and the warnings name.
583///
584/// # Errors
585///
586/// Returns [`PlanError::Unsatisfiable`] when a needed capability has no
587/// candidate left, and [`PlanError::Contested`] when several candidates remain
588/// and neither a preference nor a marked default chooses between them.
589pub(crate) fn select_providers<'a>(
590    registry: &'a FlmRegistry,
591    demands: impl IntoIterator<Item = CapId>,
592    prefer: &'a [StageIdx],
593    requires_of: &'a dyn Fn(StageIdx) -> &'a BTreeSet<CapId>,
594    workflow: &'a Option<WorkflowName>,
595) -> Result<Selection, PlanError> {
596    let by_name: BTreeMap<StageName, StageIdx> =
597        registry.stages().iter().map(|entry| (entry.name.clone(), entry.idx)).collect();
598    let mut solver = Solver {
599        registry,
600        by_name,
601        requires_of,
602        prefer,
603        needed: BTreeMap::new(),
604        committed: BTreeSet::new(),
605        commit_order: Vec::new(),
606        excluded: BTreeMap::new(),
607        externals: BTreeSet::new(),
608        warnings: Vec::new(),
609        warned: BTreeSet::new(),
610        workflow,
611    };
612    for cap in demands {
613        solver.need(cap);
614    }
615    solver.solve()
616}