Skip to main content

flm_core/core/plan/
build.rs

1//! The [`Plan`] and how it is built and checked.
2//!
3//! A plan is the list of stages that satisfies a plan request, in dependency order
4//! and grouped in batches; it is a pure value of the registry and the request, with
5//! nothing of any document in it. [`Plan::build`] builds the plan of a
6//! [`PlanRequest`]; [`Plan::for_workflow`] first turns a registered workflow into a
7//! plan request ([`workflow_request`]) and then builds it. Every reason a plan
8//! cannot be built is a [`PlanError`] that identifies the stages, capabilities,
9//! elements or names involved; a preference the plan cannot honor, or output of a
10//! selected lowering rule that nothing checks, is a [`PlanWarning`] kept in the
11//! plan. See [`crate::core::plan`] for the whole
12//! process.
13//!
14//! # What a plan holds
15//!
16//! - Its **order**: the scheduled stages that run after the rewrite stages, sorted
17//!   so that every stage follows the stages it depends on, with registration
18//!   order breaking ties. Two registries built from the same features,
19//!   registered in the same order, therefore give the same order.
20//! - Its **batches**: consecutive groups of stages in that order, none of which
21//!   depends on another stage of the same group. The batches are computed here,
22//!   once. Whether the runner runs a batch's stages one after another or at the
23//!   same time (the `parallel` cargo feature), it runs exactly these batches, so
24//!   both produce identical results.
25//! - Its **rewrites**: the rewrite stages that will run, in the total order the
26//!   plan fixes for them. A rewrite stage runs before the document's trees are
27//!   frozen and turns one tree into another
28//!   ([`RewriteStage`](crate::core::stage::RewriteStage)); every rewrite stage
29//!   runs before every other stage.
30//! - A [`StagePlan`] for every registered stage: the stage's manifest (its
31//!   declaration together with what it needs for this plan) and its reads and
32//!   writes resolved against the registry. The runner and every check read these
33//!   records instead of asking the stage again, so a stage cannot state one thing
34//!   while the plan is built and another while it runs.
35//! - The record of the choices: the lowering rules chosen per backend, the
36//!   backends that take part, the stages that were ruled out, the external tables
37//!   the run needs (tables no stage writes, whose values the caller installs;
38//!   [`Externals`](crate::core::run::Externals)), and the warnings.
39//!
40//! # The steps of building a plan
41//!
42//! 1. **The plan request is checked.** Every demanded capability, preferred
43//!    stage, backend, preferred rule, accepted unrenderable element and render
44//!    option value must be something the registry declares. Each failure
45//!    identifies what was written and, except for an unknown element, lists what
46//!    is registered.
47//! 2. **A lowering rule is chosen per element, for every registered backend**
48//!    ([`SelectedRules`]). Which backends take part is not known yet, because it
49//!    follows from which stages are scheduled. When the rules of a backend cannot
50//!    be chosen, the failure is kept and returned only if that backend takes part.
51//! 3. **Every registered stage is asked what it needs**, and the needs are
52//!    resolved against the registry into [`StagePlan`] records.
53//! 4. **One stage is chosen to provide each needed capability**, by the provider
54//!    selection of [`crate::core::plan::selection`].
55//! 5. **The stages are ordered, and the plan is checked**, as described below.
56//!
57//! # What a plan refuses
58//!
59//! Besides names the registry does not declare, a plan refuses:
60//!
61//! - a stage that needs a capability, table or option type no feature declares,
62//!   or reads a table under the wrong value type;
63//! - a stage that reads an option type whose value is fixed when the registry is
64//!   built;
65//! - a rewrite stage that declares that it reads a table, or that requires the
66//!   capability of a table that a stage running after the rewrite stages writes:
67//!   every rewrite stage runs before any table is computed;
68//! - a stage that requires a collection, which can only be demanded;
69//! - a stage that requires a capability that scheduling the stage itself would
70//!   rule out ([`PlanError::SelfExclusion`]);
71//! - a needed capability with no provider left, or with several and nothing to
72//!   choose between them;
73//! - several lowering rules able to lower one element on one backend, with
74//!   nothing to choose between them;
75//! - a cycle among the scheduled stages;
76//! - two scheduled stages that write one table;
77//! - two rewrite stages with nothing that orders them relative to each other;
78//! - a stage without effects outside the store (the run's collection of
79//!   computed tables, [`Computed`](crate::core::data::store::Computed)) that
80//!   depends on a stage with such effects;
81//! - a cycle among the elements that the chosen lowering rules produce;
82//! - a backend that cannot render every element a document may contain.
83//!
84//! Each case is a variant of [`PlanError`], which documents it.
85//!
86//! # Two placement rules
87//!
88//! **Stages with effects outside the store run last.** A stage's effect
89//! ([`Effect`]) is `Compute` (it writes data and diagnostics), `Check` (it writes
90//! diagnostics only) or `Io` (it has effects outside the store, such as writing
91//! the output a caller asked for). The scheduled stages are ordered as two
92//! blocks: first every [`Effect::Compute`] and [`Effect::Check`] stage, then
93//! every [`Effect::Io`] stage, each block in its own dependency order. A
94//! dependency in the other direction, from a `Compute` or `Check` stage on an
95//! `Io` stage, is refused ([`PlanError::IoProductReadByPure`]). No batch mixes
96//! the two blocks, so a run that stops before its first `Io` stage because of
97//! errors stops at a batch boundary ([`Plan::first_io_batch`]).
98//!
99//! **Ordering edges between a rewrite stage and a later stage are ignored.** An
100//! ordering edge places one stage before or after another without making either
101//! one run ([`OrderingDef`]). Every rewrite stage runs before every other stage,
102//! so such an edge cannot change any placement. The same holds for a rewrite
103//! stage's requirement on a capability without a table that a later stage
104//! provides. A rewrite stage that requires the capability of a table computed by
105//! a later stage is a different case, and is refused
106//! ([`PlanError::RewriteNeedsComputed`]).
107
108use std::collections::{BTreeMap, BTreeSet};
109use std::fmt;
110use std::ops::Range;
111use std::sync::Arc;
112
113use crate::model::names::{
114    BackendName, CapName, ElementName, FeatureName, Name, OutputName, RuleName, StageName,
115    WorkflowName,
116};
117use crate::model::options::{BindSite, OptionError, OptionRef};
118use crate::core::plan::cx::PlanCx;
119use crate::core::plan::request::{Overrides, PlanKey, PlanRequest};
120use crate::core::plan::selection::{self, Excluded, SelectedRules};
121use crate::core::registry::{StageKind, WorkflowDef};
122use crate::model::digest::Fnv1a64;
123use crate::core::registry::entities::{OrderingDef, PeerName};
124use crate::core::registry::frozen::{CapId, FlmRegistry, StageIdx};
125use crate::core::registry::order::sort_by_priority;
126use crate::core::stage::{Effect, Manifest, Needs, Scope};
127use crate::core::data::store::{ReadEntry, ReadSet, WriteEntry, WriteSet};
128use crate::core::data::table::{TableId, TableRef};
129
130/// The reason a plan could not be built, returned by [`Plan::build`],
131/// [`Plan::for_workflow`] and [`workflow_request`].
132///
133/// Every variant holds the names of the stages, capabilities, elements or other
134/// entities involved. A variant about a name that is not declared also holds the
135/// list of the declared names of that kind, except `UnknownElement`, so that its
136/// message can list the alternatives. The `Display` text is a message for a person; match on the
137/// variant to act on the error. The [module documentation](self) gives the order
138/// in which the checks run.
139///
140/// Every variant that [`Plan::build`] returns also holds the workflow the plan
141/// request was made from ([`PlanRequest::workflow`]), and its message names
142/// that workflow: as the subject of the sentence where the request asks for
143/// something ("the plan request for workflow `html` demands …"; "the plan
144/// request demands …" for a request built by hand), and as an opening "for
145/// workflow `html`, " where the sentence is about a stage, a backend or the
146/// plan. The request of a workflow also holds the caller's overrides, so the
147/// subject is the request made for the workflow, not the workflow itself.
148/// `RenderOption` carries the name inside its [`OptionError`].
149/// `UnknownWorkflow` and `UnknownOutput` hold the name of the workflow they
150/// are about.
151#[derive(Debug, Clone)]
152pub enum PlanError {
153    /// A demanded name is neither a declared capability nor a declared
154    /// collection.
155    UnknownDemand {
156        /// The demanded name.
157        name: CapName,
158        /// Every declared capability and collection, in name order.
159        roster: Vec<Name>,
160        /// The workflow the plan request was made from, or `None` for a request
161        /// built by hand ([`PlanRequest::workflow`]).
162        workflow: Option<WorkflowName>,
163    },
164    /// A preferred stage is not registered.
165    UnknownPreference {
166        /// The preferred stage name.
167        stage: StageName,
168        /// Every registered stage, in name order.
169        roster: Vec<Name>,
170        /// The workflow the plan request was made from, or `None` for a request
171        /// built by hand ([`PlanRequest::workflow`]).
172        workflow: Option<WorkflowName>,
173    },
174    /// The plan request refers to a backend that is not registered, in its
175    /// lowering selections or in its accepted unrenderable elements.
176    UnknownBackend {
177        /// The backend name written in the plan request.
178        backend: BackendName,
179        /// Every registered backend, in name order.
180        roster: Vec<Name>,
181        /// The workflow the plan request was made from, or `None` for a request
182        /// built by hand ([`PlanRequest::workflow`]).
183        workflow: Option<WorkflowName>,
184    },
185    /// A preferred lowering rule is not registered.
186    UnknownRule {
187        /// The backend the preference was written for.
188        backend: BackendName,
189        /// The preferred rule name.
190        rule: RuleName,
191        /// Every registered rule, in name order.
192        roster: Vec<Name>,
193        /// The workflow the plan request was made from, or `None` for a request
194        /// built by hand ([`PlanRequest::workflow`]).
195        workflow: Option<WorkflowName>,
196    },
197    /// An element the plan request accepts as unrenderable is not registered.
198    UnknownElement {
199        /// The backend on which the element is accepted as unrenderable.
200        backend: BackendName,
201        /// The element name written in the plan request.
202        element: ElementName,
203        /// The workflow the plan request was made from, or `None` for a request
204        /// built by hand ([`PlanRequest::workflow`]).
205        workflow: Option<WorkflowName>,
206    },
207    /// The plan request sets an option value that the render request may not
208    /// set: the option type is not declared, or its binding does not admit the
209    /// render request ([`Bind`](crate::model::options::Bind)). The option error
210    /// holds the workflow the request was made from, if any.
211    RenderOption(OptionError),
212    /// A stage needs a capability, a table or an option type that no feature
213    /// declares.
214    NeedsUndeclared {
215        /// The stage.
216        stage: StageName,
217        /// The kind of the undeclared thing: `capability`, `table` or
218        /// `option type`.
219        kind: &'static str,
220        /// The undeclared name the stage needs.
221        name: Name,
222        /// Every declared name of that kind, in name order.
223        roster: Vec<Name>,
224        /// The workflow the plan request was made from, or `None` for a request
225        /// built by hand ([`PlanRequest::workflow`]).
226        workflow: Option<WorkflowName>,
227    },
228    /// A stage reads a table as a different value type than the one the table is
229    /// declared to hold.
230    NeedsTableType {
231        /// The stage.
232        stage: StageName,
233        /// The table.
234        table: CapName,
235        /// The value type the table is declared to hold.
236        declared: &'static str,
237        /// The value type the stage's read expects.
238        referenced: &'static str,
239        /// The workflow the plan request was made from, or `None` for a request
240        /// built by hand ([`PlanRequest::workflow`]).
241        workflow: Option<WorkflowName>,
242    },
243    /// A stage declares a read of an option type whose value is fixed when the
244    /// registry is built ([`Bind::Registry`](crate::model::options::Bind::Registry)).
245    /// No stage may read such an option type: the feature that owns it holds the
246    /// value in its configuration, and a read could only return the type's
247    /// default.
248    RegistryBoundRead {
249        /// The option error, an [`OptionError::RegistryBoundRead`].
250        error: OptionError,
251        /// The workflow the plan request was made from, or `None` for a request
252        /// built by hand ([`PlanRequest::workflow`]).
253        workflow: Option<WorkflowName>,
254    },
255    /// A rewrite stage declares that it reads a table. A rewrite stage may not
256    /// read tables: it runs before any table is computed.
257    RewriteReads {
258        /// The rewrite stage.
259        stage: StageName,
260        /// The table it declared it reads.
261        table: CapName,
262        /// The workflow the plan request was made from, or `None` for a request
263        /// built by hand ([`PlanRequest::workflow`]).
264        workflow: Option<WorkflowName>,
265    },
266    /// A rewrite stage requires the capability of a table that a scheduled stage
267    /// other than a rewrite stage provides. Such a stage runs after every rewrite
268    /// stage, so the rewrite stage would wait for data computed after it.
269    RewriteNeedsComputed {
270        /// The rewrite stage.
271        stage: StageName,
272        /// The capability it requires.
273        capability: CapName,
274        /// The scheduled stage that provides that capability.
275        provider: StageName,
276        /// The workflow the plan request was made from, or `None` for a request
277        /// built by hand ([`PlanRequest::workflow`]).
278        workflow: Option<WorkflowName>,
279    },
280    /// A stage requires a collection. A collection is a name for a set of
281    /// capabilities ([`CollectionDef`](crate::core::registry::CollectionDef)); a
282    /// plan request may demand one, but a stage may not require one.
283    CollectionRequired {
284        /// The stage.
285        stage: StageName,
286        /// The collection it requires.
287        collection: CapName,
288        /// The workflow the plan request was made from, or `None` for a request
289        /// built by hand ([`PlanRequest::workflow`]).
290        workflow: Option<WorkflowName>,
291    },
292    /// A stage requires a capability that scheduling the stage itself would
293    /// rule out.
294    ///
295    /// Scheduling a stage rules out every other stage that provides any of the
296    /// same capabilities, including the capabilities that what it provides
297    /// refines ([refinement](crate::guide::pipeline#refinement)). Suppose a stage
298    /// requires a capability that is related by refinement to one it provides:
299    /// one refines the other, or both refine a common capability. Every provider
300    /// of the required capability then provides that common capability too, so
301    /// scheduling the stage would rule out every provider of what it requires.
302    /// The check runs over every registered stage, scheduled or not. Requiring
303    /// exactly a capability the stage itself declares as provided is allowed:
304    /// the stage satisfies that requirement itself.
305    SelfExclusion {
306        /// The stage.
307        stage: StageName,
308        /// The capability it requires.
309        requires: CapName,
310        /// The capability it provides that is related by refinement to the
311        /// required one.
312        provides: CapName,
313        /// The workflow the plan request was made from, or `None` for a request
314        /// built by hand ([`PlanRequest::workflow`]).
315        workflow: Option<WorkflowName>,
316    },
317    /// A needed capability has no provider left: no registered stage provides
318    /// it, or provider selection ruled out every stage that provides it.
319    Unsatisfiable {
320        /// The capability.
321        capability: CapName,
322        /// Each stage that provides the capability, with the scheduled stage that
323        /// ruled it out; empty when no registered stage provides the capability.
324        blocked: Vec<Excluded>,
325        /// When no registered stage provides the capability, the text its
326        /// declaration gives for that case
327        /// ([`CapabilityDef::unprovided`](crate::core::registry::CapabilityDef::unprovided)),
328        /// which the message gives in place of the generic one; `None` otherwise.
329        unprovided: Option<String>,
330        /// The workflow the plan request was made from, or `None` for a request
331        /// built by hand ([`PlanRequest::workflow`]).
332        workflow: Option<WorkflowName>,
333    },
334    /// A needed capability has several possible providers, and neither a
335    /// preferred stage nor a default refinement chooses one of them. A default
336    /// refinement is the refinement that a demand for its parent capability
337    /// selects when nothing else decides
338    /// ([refinement](crate::guide::pipeline#refinement)).
339    Contested {
340        /// The capability.
341        capability: CapName,
342        /// The stages that could provide it, in name order.
343        candidates: Vec<StageName>,
344        /// The workflow the plan request was made from, or `None` for a request
345        /// built by hand ([`PlanRequest::workflow`]).
346        workflow: Option<WorkflowName>,
347    },
348    /// Several lowering rules could lower one element on one backend, and
349    /// neither a preference nor a default mark
350    /// ([`DefaultMark`](crate::core::lowering::DefaultMark)) chooses one of them.
351    RuleContest {
352        /// The backend.
353        backend: BackendName,
354        /// The element.
355        element: ElementName,
356        /// The rules that could lower it, in name order.
357        candidates: Vec<RuleName>,
358        /// The workflow the plan request was made from, or `None` for a request
359        /// built by hand ([`PlanRequest::workflow`]).
360        workflow: Option<WorkflowName>,
361    },
362    /// The scheduled stages depend on one another in a cycle.
363    Cycle {
364        /// The cycle, in dependency order, starting at the stage whose name comes
365        /// first and ending with that stage again.
366        stages: Vec<StageName>,
367        /// The workflow the plan request was made from, or `None` for a request
368        /// built by hand ([`PlanRequest::workflow`]).
369        workflow: Option<WorkflowName>,
370    },
371    /// Two scheduled stages write one table. At most one scheduled stage may
372    /// write a table.
373    TwoWriters {
374        /// The table.
375        table: CapName,
376        /// The two stages, in registration order.
377        stages: Vec<StageName>,
378        /// The workflow the plan request was made from, or `None` for a request
379        /// built by hand ([`PlanRequest::workflow`]).
380        workflow: Option<WorkflowName>,
381    },
382    /// Two scheduled rewrite stages have no order relative to each other.
383    ///
384    /// Each rewrite stage works on the trees the previous one produced, so the
385    /// rewrite stages of a plan need one total order. An ordering declaration
386    /// ([`OrderingDef`]) between two of them supplies it.
387    RewriteTie {
388        /// Every scheduled rewrite stage, in dependency order, with registration
389        /// order breaking ties.
390        active: Vec<StageName>,
391        /// One of the two unordered rewrites.
392        first: StageName,
393        /// The other one.
394        second: StageName,
395        /// Ordering declarations that would order the two; registering either one
396        /// is enough.
397        resolving: Vec<OrderingDef>,
398        /// The workflow the plan request was made from, or `None` for a request
399        /// built by hand ([`PlanRequest::workflow`]).
400        workflow: Option<WorkflowName>,
401    },
402    /// A stage whose effect is `Compute` or `Check` depends on a stage whose
403    /// effect is [`Effect::Io`] (a stage that acts outside the run's computed
404    /// data, for example by writing files).
405    ///
406    /// Every `Io` stage runs after every other stage, so only another `Io` stage
407    /// may depend on one.
408    IoProductReadByPure {
409        /// The `Compute` or `Check` stage.
410        reader: StageName,
411        /// The `Io` stage it depends on.
412        io_stage: StageName,
413        /// The workflow the plan request was made from, or `None` for a request
414        /// built by hand ([`PlanRequest::workflow`]).
415        workflow: Option<WorkflowName>,
416    },
417    /// The elements that the chosen lowering rules produce lead back to an
418    /// element already on the path, so lowering would never finish.
419    ///
420    /// Each lowering rule declares the elements it produces; lowering an element
421    /// with its rule gives nodes of those elements, which are lowered in turn.
422    ProducesCycle {
423        /// The backend.
424        backend: BackendName,
425        /// The elements of the cycle, starting at the one whose name comes first;
426        /// the rule of the last one produces the first.
427        cycle: Vec<ElementName>,
428        /// The workflow the plan request was made from, or `None` for a request
429        /// built by hand ([`PlanRequest::workflow`]).
430        workflow: Option<WorkflowName>,
431    },
432    /// A backend that takes part in the plan cannot render every element a
433    /// document may contain.
434    ///
435    /// An element passes when the backend writes it natively (and the request
436    /// does not prefer a lowering rule for it instead), or when the lowering rule
437    /// chosen for it produces only elements that pass. Every element a document
438    /// may contain must pass, except the elements the plan request accepts as
439    /// unrenderable on that backend. An accepted element still does not pass
440    /// when another element's rule produces it.
441    Incomplete {
442        /// The backend.
443        backend: BackendName,
444        /// The elements that do not pass.
445        missing: Vec<ElementName>,
446        /// The workflow the plan request was made from, or `None` for a request
447        /// built by hand ([`PlanRequest::workflow`]).
448        workflow: Option<WorkflowName>,
449    },
450    /// The requested workflow is not registered.
451    UnknownWorkflow {
452        /// The requested workflow name.
453        workflow: WorkflowName,
454        /// Every registered workflow, in name order.
455        roster: Vec<Name>,
456    },
457    /// A workflow lists an output that is not registered.
458    UnknownOutput {
459        /// The workflow listing it.
460        workflow: WorkflowName,
461        /// The output it lists.
462        output: OutputName,
463        /// Every registered output, in name order.
464        roster: Vec<Name>,
465    },
466}
467
468fn join<'a>(names: impl IntoIterator<Item = &'a Name>) -> String {
469    names.into_iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
470}
471
472/// The subject of a sentence about what a plan request asks for: "the plan
473/// request for workflow `w`" when the request was made from the workflow `w`
474/// ([`PlanRequest::workflow`]), and "the plan request" for a request built by
475/// hand. The request of a workflow merges the workflow's fields with the
476/// caller's overrides, so what it asks for may come from either. The messages of [`PlanError`] and of the preference variants of [`PlanWarning`], and those of the
477/// run's diagnostics built from those warnings, take their subject from here.
478pub(crate) fn request_subject(workflow: Option<&str>) -> String {
479    match workflow {
480        Some(workflow) => format!("the plan request for workflow `{workflow}`"),
481        None => "the plan request".to_string(),
482    }
483}
484
485/// The opening of a message whose subject is not the plan request itself (a
486/// stage, a backend, the plan): "for workflow `w`, " when the request was made
487/// from the workflow `w`, and nothing for a request built by hand.
488fn workflow_opening(workflow: Option<&str>) -> String {
489    match workflow {
490        Some(workflow) => format!("for workflow `{workflow}`, "),
491        None => String::new(),
492    }
493}
494
495fn name_of(workflow: &Option<WorkflowName>) -> Option<&str> {
496    workflow.as_ref().map(|workflow| workflow.as_str())
497}
498
499impl fmt::Display for PlanError {
500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501        let subject = |workflow: &Option<WorkflowName>| request_subject(name_of(workflow));
502        let opening = |workflow: &Option<WorkflowName>| workflow_opening(name_of(workflow));
503        match self {
504            PlanError::UnknownDemand { name, roster, workflow } => write!(
505                f,
506                "{} demands `{name}`, but no feature declares a capability or a collection of \
507                 that name; declared capabilities and collections: [{}]",
508                subject(workflow),
509                join(roster)
510            ),
511            PlanError::UnknownPreference { stage, roster, workflow } => {
512                write!(
513                    f,
514                    "{} prefers the stage `{stage}`, but no stage of that name is registered; \
515                     registered stages: [{}]",
516                    subject(workflow),
517                    join(roster)
518                )
519            }
520            PlanError::UnknownBackend { backend, roster, workflow } => {
521                write!(f, "{} refers to the backend `{backend}`, but no backend of that name is \
522                           registered; registered backends: [{}]", subject(workflow), join(roster))
523            }
524            PlanError::UnknownRule { backend, rule, roster, workflow } => write!(
525                f,
526                "{} prefers the lowering rule `{rule}` on backend `{backend}`, but no lowering \
527                 rule of that name is registered; registered lowering rules: [{}]",
528                subject(workflow),
529                join(roster)
530            ),
531            PlanError::UnknownElement { backend, element, workflow } => {
532                write!(
533                    f,
534                    "{} accepts the element `{element}` as unrenderable on backend `{backend}`, \
535                     but no element of that name is registered",
536                    subject(workflow)
537                )
538            }
539            PlanError::RenderOption(error) => fmt::Display::fmt(error, f),
540            PlanError::RegistryBoundRead { error, workflow } => {
541                write!(f, "{}{error}", opening(workflow))
542            }
543            PlanError::NeedsUndeclared { stage, kind, name, roster, workflow } => write!(
544                f,
545                "{}stage `{stage}` needs the {kind} `{name}`, but no feature declares this \
546                 {kind}; declared {kind} names: [{}]",
547                opening(workflow),
548                join(roster)
549            ),
550            PlanError::NeedsTableType { stage, table, declared, referenced, workflow } => write!(
551                f,
552                "{}stage `{stage}` reads the table `{table}` as `{referenced}`, but the table \
553                 is declared to hold `{declared}`",
554                opening(workflow)
555            ),
556            PlanError::RewriteReads { stage, table, workflow } => {
557                write!(
558                    f,
559                    "{}rewrite stage `{stage}` declares a read of the table `{table}`, but a \
560                     rewrite stage must not read tables: it runs before any table is computed",
561                    opening(workflow)
562                )
563            }
564            PlanError::RewriteNeedsComputed { stage, capability, provider, workflow } => write!(
565                f,
566                "{}rewrite stage `{stage}` requires `{capability}`, the capability of a table \
567                 that stage `{provider}` computes, but a rewrite stage runs before every other \
568                 stage and must not require a table another stage computes",
569                opening(workflow)
570            ),
571            PlanError::CollectionRequired { stage, collection, workflow } => {
572                write!(
573                    f,
574                    "{}stage `{stage}` requires the collection `{collection}`, but a collection \
575                     can only be demanded in a plan request, not required by a stage",
576                    opening(workflow)
577                )
578            }
579            PlanError::SelfExclusion { stage, requires, provides, workflow } => write!(
580                f,
581                "{}stage `{stage}` requires `{requires}` and provides `{provides}`, but one of \
582                 `{requires}` and `{provides}` refines the other or both refine a common \
583                 capability, so scheduling the stage would rule out every provider of \
584                 `{requires}`",
585                opening(workflow)
586            ),
587            PlanError::Unsatisfiable { capability, blocked, unprovided, workflow } => {
588                if let (true, Some(text)) = (blocked.is_empty(), unprovided) {
589                    write!(f, "{}{text}", opening(workflow))
590                } else if blocked.is_empty() {
591                    write!(
592                        f,
593                        "{}the plan needs the capability `{capability}`, but no registered stage \
594                         provides it",
595                        opening(workflow)
596                    )
597                } else {
598                    let detail: Vec<String> = blocked
599                        .iter()
600                        .map(|b| {
601                            format!(
602                                "stage `{}` was ruled out by the scheduled stage `{}`, which \
603                                 also provides `{}`",
604                                b.stage, b.excluded_by, b.over
605                            )
606                        })
607                        .collect();
608                    write!(f, "{}the plan needs the capability `{capability}`, but every stage \
609                               that provides it was ruled out, because only one scheduled stage \
610                               may provide each capability: {}", opening(workflow),
611                               detail.join("; "))
612                }
613            }
614            PlanError::Contested { capability, candidates, workflow } => write!(
615                f,
616                "{}the plan needs the capability `{capability}`, which several stages provide \
617                 ([{}]), and neither a preference of the plan request nor a capability marked \
618                 as the default among those that refine `{capability}` chooses one of these \
619                 stages; prefer one of them in the plan request",
620                opening(workflow),
621                candidates.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", ")
622            ),
623            PlanError::RuleContest { backend, element, candidates, workflow } => write!(
624                f,
625                "{}several lowering rules can lower `{element}` on backend `{backend}` ([{}]), \
626                 and none of them is preferred or marked as the default",
627                opening(workflow),
628                candidates.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", ")
629            ),
630            PlanError::Cycle { stages, workflow } => write!(
631                f,
632                "{}the scheduled stages depend on one another in a cycle: {}",
633                opening(workflow),
634                stages.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(" -> ")
635            ),
636            PlanError::TwoWriters { table, stages, workflow } => write!(
637                f,
638                "{}only one scheduled stage may write the table `{table}`, but two do: {}",
639                opening(workflow),
640                stages.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", ")
641            ),
642            PlanError::RewriteTie { active, first, second, resolving, workflow } => write!(
643                f,
644                "{}the scheduled rewrite stages [{}] include `{first}` and `{second}`, which \
645                 must run in a defined order, but nothing orders them; an ordering declaration \
646                 such as {} would order them",
647                opening(workflow),
648                active.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", "),
649                resolving
650                    .iter()
651                    .map(|edge| format!(
652                        "`{}` after `{}`",
653                        edge.stage,
654                        join(edge.after.iter().map(|c| c.name()))
655                    ))
656                    .collect::<Vec<_>>()
657                    .join(" or ")
658            ),
659            PlanError::IoProductReadByPure { reader, io_stage, workflow } => write!(
660                f,
661                "{}stage `{reader}` depends on stage `{io_stage}`, whose effect is `Io` (it acts \
662                 outside the run's computed data, for example by writing output), but only \
663                 another stage with effect `Io` may depend on it",
664                opening(workflow)
665            ),
666            PlanError::ProducesCycle { backend, cycle, workflow } => write!(
667                f,
668                "{}on backend `{backend}`, the selected lowering rules produce one another's \
669                 elements in a cycle, so lowering would never finish: {}",
670                opening(workflow),
671                cycle.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(" -> ")
672            ),
673            PlanError::Incomplete { backend, missing, workflow } => write!(
674                f,
675                "backend `{backend}` cannot render the elements [{}]: it does not write them \
676                 natively, the selected lowering rules do not lower them to elements it writes \
677                 natively, and {} does not accept them as unrenderable",
678                missing.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", "),
679                subject(workflow)
680            ),
681            PlanError::UnknownWorkflow { workflow, roster } => {
682                write!(f, "the workflow `{workflow}` is requested, but no workflow of that name \
683                           is registered; registered workflows: [{}]", join(roster))
684            }
685            PlanError::UnknownOutput { workflow, output, roster } => write!(
686                f,
687                "workflow `{workflow}` lists the output `{output}`, but no output of that name \
688                 is registered; registered outputs: [{}]",
689                join(roster)
690            ),
691        }
692    }
693}
694
695impl std::error::Error for PlanError {}
696
697/// A warning the plan keeps about what it was built from: a preference of the
698/// plan request that the plan could not honor, or output of a selected lowering
699/// rule that nothing checks.
700///
701/// A plan request may prefer something the registry cannot give: a lowering rule
702/// that is set aside (excluded from rule selection; see [`PeerName`]), a lowering
703/// rule that belongs to
704/// other backends, or a stage that provider selection had to rule out. The plan
705/// is still built, without that preference, and the plan keeps one warning per
706/// such preference, because the caller asked for something it did not get.
707/// The plan also keeps one [`UncheckedOutput`](PlanWarning::UncheckedOutput)
708/// per backend that takes part and feature whose selected rules declare that
709/// backend in
710/// [`LoweringDecl::unchecked_output`](crate::core::lowering::LoweringDecl::unchecked_output).
711///
712/// Read the warnings from [`Plan::warnings`]. The runner reports each one as a
713/// diagnostic of Warning severity at the start of every run of the plan
714/// ([`Run`](crate::core::run::Run)). The `Display` text describes the warning
715/// for a person; the runner's diagnostic carries its own message. Each variant
716/// holds the workflow the plan request was made from ([`PlanRequest::workflow`]).
717/// The messages of the three preference variants name it in the subject of the
718/// sentence ("the plan request for workflow `html` prefers …"; "the plan
719/// request prefers …" for a request built by hand).
720///
721/// It is written to data with `Serialize`; see [serialized
722/// forms](crate::core::registry#serialized-forms).
723#[derive(Debug, Clone, PartialEq, Eq)]
724#[derive(serde::Serialize, schemars::JsonSchema)]
725#[serde(tag = "kind", rename_all = "kebab-case")]
726pub enum PlanWarning {
727    /// A preferred lowering rule is set aside: a peer declaration the rule
728    /// depends on (a backend it is marked as the default on, an element it
729    /// produces or a table it reads other than as an optional read, which its
730    /// feature expects another feature to declare; see [`PeerName`]) resolves to nothing in this registry, so no
731    /// plan can choose the rule.
732    PreferredRuleSetAside {
733        /// The backend the preference was stated for.
734        backend: BackendName,
735        /// The rule the request preferred.
736        rule: RuleName,
737        /// The peer declarations the rule depends on that did not resolve, in
738        /// the order of the rule's dependencies: the backends it is marked as the
739        /// default on, then the elements it produces, then the tables it reads.
740        unresolved: Vec<PeerName>,
741        /// The workflow the plan request was made from, or `None` for a request
742        /// built by hand ([`PlanRequest::workflow`]).
743        workflow: Option<WorkflowName>,
744    },
745    /// A preferred lowering rule is not a candidate on the backend the preference
746    /// was stated for: the rule is marked as the default on other backends only
747    /// ([`DefaultMark::OnBackends`](crate::core::lowering::DefaultMark::OnBackends)),
748    /// and that mark also restricts the rule to those backends.
749    PreferredRuleNotCandidate {
750        /// The backend the preference was stated for.
751        backend: BackendName,
752        /// The rule the request preferred.
753        rule: RuleName,
754        /// The workflow the plan request was made from, or `None` for a request
755        /// built by hand ([`PlanRequest::workflow`]).
756        workflow: Option<WorkflowName>,
757    },
758    /// A preferred stage could not be scheduled, because provider selection had
759    /// ruled it out when it scheduled another stage that provides a capability
760    /// in common.
761    IgnoredPreference {
762        /// The stage the request preferred.
763        stage: StageName,
764        /// The stage that was scheduled instead, which ruled it out.
765        excluded_by: StageName,
766        /// A capability both of them provide.
767        over: CapName,
768        /// The workflow the plan request was made from, or `None` for a request
769        /// built by hand ([`PlanRequest::workflow`]).
770        workflow: Option<WorkflowName>,
771    },
772    /// Lowering rules of one feature, selected on a backend that takes part,
773    /// write output there that nothing checks before the program reading it
774    /// does
775    /// ([`LoweringDecl::unchecked_output`](crate::core::lowering::LoweringDecl::unchecked_output)).
776    ///
777    /// The plan keeps one such warning per backend and feature, however many of
778    /// the feature's selected rules declare the backend; `written` and `reader`
779    /// come from the first of them in rule-name order.
780    UncheckedOutput {
781        /// The backend whose output holds what the rules write.
782        backend: BackendName,
783        /// The feature that registered the rules.
784        feature: FeatureName,
785        /// What the rules write, as the rule declares it.
786        written: String,
787        /// What reads the output, as the rule declares it.
788        reader: String,
789        /// The workflow the plan request was made from, or `None` for a request
790        /// built by hand ([`PlanRequest::workflow`]).
791        workflow: Option<WorkflowName>,
792    },
793}
794
795/// The message of an unchecked output: the `Display` text of
796/// [`PlanWarning::UncheckedOutput`] and the message of the run's diagnostic
797/// built from it.
798pub(crate) fn unchecked_output_message(
799    feature: &str,
800    backend: &str,
801    written: &str,
802    reader: &str,
803) -> String {
804    format!(
805        "Unchecked output for {reader}: feature ‘{feature}’ writes {written} as is \
806         (backend ‘{backend}’)"
807    )
808}
809
810impl fmt::Display for PlanWarning {
811    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812        match self {
813            PlanWarning::PreferredRuleSetAside { backend, rule, unresolved, workflow } => write!(
814                f,
815                "{} prefers the lowering rule `{rule}` on backend `{backend}`, but that rule \
816                 cannot be used: it depends on {}, which no registered feature declares",
817                request_subject(name_of(workflow)),
818                unresolved.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ")
819            ),
820            PlanWarning::PreferredRuleNotCandidate { backend, rule, workflow } => write!(
821                f,
822                "{} prefers the lowering rule `{rule}` on backend `{backend}`, but that rule is \
823                 marked as the default on other backends only, which restricts it to those \
824                 backends",
825                request_subject(name_of(workflow))
826            ),
827            PlanWarning::IgnoredPreference { stage, excluded_by, over, workflow } => write!(
828                f,
829                "{} prefers the stage `{stage}`, but that stage cannot be scheduled: the \
830                 scheduled stage `{excluded_by}` also provides `{over}`, and only one scheduled \
831                 stage may provide each capability",
832                request_subject(name_of(workflow))
833            ),
834            PlanWarning::UncheckedOutput { backend, feature, written, reader, workflow: _ } => {
835                f.write_str(&unchecked_output_message(
836                    feature.as_str(),
837                    backend.as_str(),
838                    written,
839                    reader,
840                ))
841            }
842        }
843    }
844}
845
846/// The record a plan keeps about one registered stage: the stage's manifest,
847/// and its reads, writes and requirements resolved against the registry.
848///
849/// A stage manifest ([`Manifest`]) is the stage's declaration, fixed when it was
850/// registered, together with the needs it stated for this plan
851/// ([`Needs`]). The plan keeps one record for every registered stage, whether or
852/// not the stage will run; [`Plan::manifest`] returns one and
853/// [`Plan::manifests`] all of them. The runner reads these records instead of
854/// asking the stage again.
855///
856/// It is written to data with `Serialize`; see [serialized
857/// forms](crate::core::registry#serialized-forms).
858#[derive(Debug, Clone)]
859#[derive(serde::Serialize, schemars::JsonSchema)]
860pub struct StagePlan {
861    /// The stage's number in the registry.
862    pub idx: StageIdx,
863    /// The stage's declaration, together with the needs it stated for this
864    /// plan.
865    #[serde(serialize_with = "serialize_manifest")]
866    pub manifest: Arc<Manifest>,
867    /// The tables the stage reads, optional reads included, each with the name
868    /// of the scheduled stage that writes it, when there is one.
869    pub reads: ReadSet,
870    /// The tables the stage writes, resolved.
871    pub writes: WriteSet,
872    /// The option types the stage declared that it reads.
873    pub options: Vec<OptionRef>,
874    /// Every capability the stage requires, including the capabilities of the
875    /// tables it reads (not those of its optional reads).
876    pub requires: BTreeSet<CapId>,
877    /// Capabilities whose providers this stage runs after, when those providers
878    /// are scheduled. These order the stage without causing anything to be
879    /// scheduled.
880    pub after: BTreeSet<CapId>,
881    /// Capabilities whose providers this stage runs before, when those providers
882    /// are scheduled. These order the stage without causing anything to be
883    /// scheduled.
884    pub before: BTreeSet<CapId>,
885}
886
887/// Writes the manifest a stage plan shares, for [`StagePlan`]'s serialized
888/// form.
889fn serialize_manifest<S: serde::Serializer>(manifest: &Arc<Manifest>, serializer: S) -> Result<S::Ok, S::Error> {
890    serde::Serialize::serialize(&**manifest, serializer)
891}
892
893/// A plan: the list of stages that satisfies a plan request, in dependency order
894/// and grouped in batches.
895///
896/// A plan is a pure value of the registry and the request, with nothing of any
897/// document in it; one plan therefore serves every document rendered the same
898/// way. Build one with [`Plan::for_workflow`] from the name of a registered
899/// workflow, or with [`Plan::build`] from a [`PlanRequest`]; then run it over a
900/// document with [`Run::new`](crate::core::run::Run::new), which takes it in an
901/// `Arc`. The [module documentation](self) describes what a plan holds and how
902/// it is checked.
903///
904/// Besides the order of the stages, a plan exposes the record of how it was
905/// built: [`Plan::warnings`] for the preferences it could not honor and the
906/// output nothing checks,
907/// [`Plan::excluded`] and [`Plan::commit_order`] for the provider choices,
908/// [`Plan::selections`] for the lowering rules, and [`Plan::render`] for all of
909/// it as stable text.
910///
911/// # Examples
912///
913/// ```
914/// use flm_core::core::plan::{Overrides, Plan};
915/// use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
916/// use flm_core::stdlib::{self, StdlibConfig};
917///
918/// let mut builder = RegistryBuilder::new();
919/// builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
920/// builder.use_package(flm_core::math_passthrough::package());
921/// let registry = builder.build(&RegistryInputs::new())?;
922///
923/// let plan = Plan::for_workflow(&registry, "text", &Overrides::none())?;
924///
925/// // The rewrite stages run first, then the other stages, in order.
926/// assert!(!plan.rewrite_names().is_empty());
927/// assert!(plan.active_backends().iter().any(|name| name.as_str() == "text"));
928/// # Ok::<(), Box<dyn std::error::Error>>(())
929/// ```
930pub struct Plan {
931    registry: Arc<FlmRegistry>,
932    request: PlanRequest,
933    demands: BTreeSet<CapName>,
934    manifests: BTreeMap<StageIdx, StagePlan>,
935    rewrites: Vec<StageIdx>,
936    order: Vec<StageIdx>,
937    batches: Vec<Range<usize>>,
938    first_io_batch: Option<usize>,
939    selections: BTreeMap<BackendName, SelectedRules>,
940    active_backends: BTreeSet<BackendName>,
941    needed: BTreeSet<CapId>,
942    externals: BTreeSet<TableId>,
943    key: PlanKey,
944    warnings: Vec<PlanWarning>,
945    excluded: Vec<Excluded>,
946    commit_order: Vec<StageIdx>,
947    preds: BTreeMap<StageIdx, BTreeSet<StageIdx>>,
948}
949
950impl Plan {
951    /// Builds the plan that satisfies `request` against `registry`.
952    ///
953    /// The [module documentation](self) describes the steps and every check.
954    /// The plan keeps the registry (an `Arc` clone) and a copy of `request`.
955    ///
956    /// # Errors
957    ///
958    /// Returns a [`PlanError`] for a name in `request` that the registry does
959    /// not declare, a contradiction between what the stages declare, a choice
960    /// that cannot be made, or a backend taking part in the plan that cannot
961    /// render every element a document may contain. The variant holds the
962    /// names of the entities involved.
963    ///
964    /// # Panics
965    ///
966    /// Building a plan asks every registered stage what it needs
967    /// ([`Stage::needs`](crate::core::stage::Stage::needs) or
968    /// [`RewriteStage::needs`](crate::core::stage::RewriteStage::needs)); a
969    /// panic in that method propagates out of this call.
970    pub fn build(registry: &Arc<FlmRegistry>, request: &PlanRequest) -> Result<Plan, PlanError> {
971        let registry = Arc::clone(registry);
972        let reg: &FlmRegistry = &registry;
973
974        // --- the request is checked -----------------------------------------------------------
975        let mut demands: BTreeSet<CapName> = BTreeSet::new();
976        for demand in &request.demands {
977            if reg.cap_id(demand).is_some() {
978                demands.insert(demand.clone());
979            } else if let Some(collection) = reg.collection(demand) {
980                for member in &collection.members {
981                    demands.insert(reg.capability(*member).name.clone());
982                }
983            } else {
984                let mut roster: Vec<Name> =
985                    reg.capabilities().iter().map(|c| c.name.name().clone()).collect();
986                roster.extend(reg.collections().map(|c| c.name.name().clone()));
987                roster.sort();
988                return Err(PlanError::UnknownDemand {
989                    name: demand.clone(),
990                    roster,
991                    workflow: request.workflow.clone(),
992                });
993            }
994        }
995        let stage_roster = || -> Vec<Name> {
996            let mut names: Vec<Name> = reg.stages().iter().map(|s| s.name.name().clone()).collect();
997            names.sort();
998            names
999        };
1000        let backend_roster =
1001            || -> Vec<Name> { reg.backends().map(|b| b.name.name().clone()).collect() };
1002        let mut prefer: Vec<StageIdx> = Vec::new();
1003        for stage in &request.prefer {
1004            match reg.stage_idx(stage) {
1005                Some(idx) => prefer.push(idx),
1006                None => {
1007                    return Err(PlanError::UnknownPreference {
1008                        stage: stage.clone(),
1009                        roster: stage_roster(),
1010                        workflow: request.workflow.clone(),
1011                    });
1012                }
1013            }
1014        }
1015        for (backend, selection) in &request.lowering {
1016            if reg.backend(backend).is_none() {
1017                return Err(PlanError::UnknownBackend {
1018                    backend: backend.clone(),
1019                    roster: backend_roster(),
1020                    workflow: request.workflow.clone(),
1021                });
1022            }
1023            for rule in &selection.prefer {
1024                if reg.rule_idx(rule).is_none() {
1025                    let mut roster: Vec<Name> =
1026                        reg.rules().iter().map(|r| r.rule.name.name().clone()).collect();
1027                    roster.sort();
1028                    return Err(PlanError::UnknownRule {
1029                        backend: backend.clone(),
1030                        rule: rule.clone(),
1031                        roster,
1032                        workflow: request.workflow.clone(),
1033                    });
1034                }
1035            }
1036        }
1037        for (backend, holes) in &request.unsupported {
1038            if reg.backend(backend).is_none() {
1039                return Err(PlanError::UnknownBackend {
1040                    backend: backend.clone(),
1041                    roster: backend_roster(),
1042                    workflow: request.workflow.clone(),
1043                });
1044            }
1045            for element in holes {
1046                if reg.elements_named(element).is_empty() {
1047                    return Err(PlanError::UnknownElement {
1048                        backend: backend.clone(),
1049                        element: element.clone(),
1050                        workflow: request.workflow.clone(),
1051                    });
1052                }
1053            }
1054        }
1055        let option_roster: Vec<_> = reg.options().keys().cloned().collect();
1056        if let Some(error) = crate::model::options::validate_values(
1057            &request.render_options,
1058            BindSite::Render,
1059            |key| reg.option_decl(key),
1060            &option_roster,
1061            request.workflow.as_ref(),
1062        )
1063        .into_iter()
1064        .next()
1065        {
1066            return Err(PlanError::RenderOption(error));
1067        }
1068
1069        // --- a lowering rule is chosen per element, for every backend ---------------------------
1070        let mut selections: BTreeMap<BackendName, SelectedRules> = BTreeMap::new();
1071        let mut selection_errors: BTreeMap<BackendName, PlanError> = BTreeMap::new();
1072        // Per backend, its selection warnings: the preferences it cannot honor and
1073        // the unchecked outputs of its chosen rules. Only the
1074        // backends that take part are reported on, for the same reason that a
1075        // failure to choose their rules matters only for those.
1076        let mut selection_warnings: BTreeMap<BackendName, Vec<PlanWarning>> = BTreeMap::new();
1077        for backend in reg.backends() {
1078            let prefer =
1079                request.lowering.get(&backend.name).map(|s| s.prefer.as_slice()).unwrap_or(&[]);
1080            match selection::select_rules(reg, backend, prefer, &request.workflow) {
1081                Ok((selected, warnings)) => {
1082                    selections.insert(backend.name.clone(), selected);
1083                    selection_warnings.insert(backend.name.clone(), warnings);
1084                }
1085                Err(error) => {
1086                    selection_errors.insert(backend.name.clone(), error);
1087                }
1088            }
1089        }
1090
1091        // --- every stage is asked what it needs -------------------------------------------------
1092        let cx = PlanCx::new(reg, request, &demands, &selections);
1093        let mut manifests: BTreeMap<StageIdx, StagePlan> = BTreeMap::new();
1094        for entry in reg.stages() {
1095            let needs = match &entry.kind {
1096                StageKind::Pipeline(stage) => stage.needs(&cx),
1097                StageKind::Rewrite(stage) => stage.needs(&cx),
1098            };
1099            let plan = resolve_needs(reg, entry.idx, &entry.decl, needs, &request.workflow)?;
1100            manifests.insert(entry.idx, plan);
1101        }
1102
1103        // A stage may not require what its own scheduling would rule out. The
1104        // check runs over every registered stage and does not depend on the
1105        // demands, but it lives here rather than in the registry build because
1106        // what a stage requires is only known once it has been asked, which is
1107        // a per-plan question. A requirement that is exactly one of the stage's
1108        // own direct provides is allowed; any other requirement whose
1109        // refinement closure meets the closure of a direct provide would rule
1110        // out every provider of that requirement, the stage's own commitment
1111        // included. Requiring the parent of a capability the stage provides
1112        // falls under that too. A stage is selected as a whole, and committing
1113        // it excludes every other stage that shares a capability with it, so
1114        // such a requirement constrains nothing and is almost always a
1115        // modeling mistake, which the check turns into a message. The reported
1116        // pair is the name-least one, so the message does not depend on
1117        // registration order.
1118        for entry in reg.stages() {
1119            let plan = &manifests[&entry.idx];
1120            let direct: Vec<CapId> = entry
1121                .decl
1122                .provides
1123                .iter()
1124                .filter_map(|c| reg.cap_id(c))
1125                .chain(entry.writes.iter().map(|t| reg.table(*t).cap))
1126                .collect();
1127            let mut offending: Option<(CapName, CapName)> = None;
1128            for req in &plan.requires {
1129                if direct.contains(req) {
1130                    continue;
1131                }
1132                let req_closure: BTreeSet<CapId> =
1133                    reg.capability(*req).ancestors().iter().copied().collect();
1134                for prov in &direct {
1135                    let shares_an_ancestor =
1136                        reg.capability(*prov).ancestors().iter().any(|a| req_closure.contains(a));
1137                    if !shares_an_ancestor {
1138                        continue;
1139                    }
1140                    let pair =
1141                        (reg.capability(*req).name.clone(), reg.capability(*prov).name.clone());
1142                    if offending.as_ref().is_none_or(|least| pair < *least) {
1143                        offending = Some(pair);
1144                    }
1145                }
1146            }
1147            if let Some((requires, provides)) = offending {
1148                return Err(PlanError::SelfExclusion {
1149                    stage: entry.name.clone(),
1150                    requires,
1151                    provides,
1152                    workflow: request.workflow.clone(),
1153                });
1154            }
1155        }
1156
1157        // --- a provider is chosen for each needed capability ------------------------------------
1158        let demand_ids: Vec<CapId> = demands.iter().filter_map(|name| reg.cap_id(name)).collect();
1159        let requires_of = |idx: StageIdx| -> &BTreeSet<CapId> { &manifests[&idx].requires };
1160        let selected = selection::select_providers(reg, demand_ids, &prefer, &requires_of, &request.workflow)?;
1161
1162        // A backend takes part exactly when its lowering stage is scheduled, so
1163        // a failure to choose its rules matters only now.
1164        let mut active_backends: BTreeSet<BackendName> = BTreeSet::new();
1165        for backend in reg.backends() {
1166            if selected.scheduled.contains(&backend.lowering) {
1167                if let Some(error) = selection_errors.remove(&backend.name) {
1168                    return Err(error);
1169                }
1170                active_backends.insert(backend.name.clone());
1171            }
1172        }
1173
1174        // --- the stages are ordered and the plan is checked -------------------------------------
1175        // Who writes each table and who provides each capability, among the
1176        // stages that will run.
1177        let mut writers: BTreeMap<TableId, Vec<StageIdx>> = BTreeMap::new();
1178        let mut providers: BTreeMap<CapId, Vec<StageIdx>> = BTreeMap::new();
1179        for idx in &selected.scheduled {
1180            let entry = reg.stage(*idx);
1181            for table in &entry.writes {
1182                writers.entry(*table).or_default().push(*idx);
1183            }
1184            for cap in &entry.provides {
1185                providers.entry(*cap).or_default().push(*idx);
1186            }
1187        }
1188        for (table, stages) in &writers {
1189            if stages.len() > 1 {
1190                return Err(PlanError::TwoWriters {
1191                    table: reg.table(*table).def.name.clone(),
1192                    stages: stages.iter().map(|idx| reg.stage(*idx).name.clone()).collect(),
1193                    workflow: request.workflow.clone(),
1194                });
1195            }
1196        }
1197        for plan in manifests.values_mut() {
1198            let names: Vec<CapName> = plan.reads.names();
1199            for name in names {
1200                let entry = plan.reads.get(&name).cloned();
1201                if let Some(mut entry) = entry {
1202                    entry.producer = writers
1203                        .get(&entry.id)
1204                        .and_then(|w| w.first())
1205                        .map(|idx| reg.stage(*idx).name.clone());
1206                    plan.reads.insert(name, entry);
1207                }
1208            }
1209        }
1210
1211        // The dependency edges: an edge from b to a means a runs after b.
1212        let mut preds: BTreeMap<StageIdx, BTreeSet<StageIdx>> =
1213            selected.scheduled.iter().map(|idx| (*idx, BTreeSet::new())).collect();
1214        let mut add_edge = |from: StageIdx, to: StageIdx| {
1215            if from == to {
1216                return;
1217            }
1218            if let Some(set) = preds.get_mut(&to) {
1219                set.insert(from);
1220            }
1221        };
1222        let providers_of = |cap: CapId| -> Vec<StageIdx> {
1223            // Every scheduled stage that provides `cap`, whether directly or
1224            // by providing something that refines it.
1225            selected
1226                .scheduled
1227                .iter()
1228                .copied()
1229                .filter(|idx| reg.stage(*idx).provides.contains(&cap))
1230                .collect()
1231        };
1232        for idx in &selected.scheduled {
1233            let plan = &manifests[idx];
1234            for cap in &plan.requires {
1235                for provider in providers_of(*cap) {
1236                    add_edge(provider, *idx);
1237                }
1238            }
1239            // Reads declared as optional are in `plan.reads` as well, so a
1240            // scheduled writer of one orders its reader even though the read
1241            // caused nothing to be scheduled.
1242            for table in plan.reads.iter().map(|(_, e)| e.id) {
1243                if let Some(writer) = writers.get(&table).and_then(|w| w.first()) {
1244                    add_edge(*writer, *idx);
1245                }
1246            }
1247            for cap in &plan.after {
1248                for provider in providers_of(*cap) {
1249                    add_edge(provider, *idx);
1250                }
1251            }
1252            for cap in &plan.before {
1253                for provider in providers_of(*cap) {
1254                    add_edge(*idx, provider);
1255                }
1256            }
1257        }
1258        for ordering in reg.orderings() {
1259            let Some(idx) = reg.stage_idx(&ordering.stage) else { continue };
1260            if !selected.scheduled.contains(&idx) {
1261                continue;
1262            }
1263            for cap in ordering.after.iter().filter_map(|c| reg.cap_id(c)) {
1264                for provider in providers_of(cap) {
1265                    add_edge(provider, idx);
1266                }
1267            }
1268            for cap in ordering.before.iter().filter_map(|c| reg.cap_id(c)) {
1269                for provider in providers_of(cap) {
1270                    add_edge(idx, provider);
1271                }
1272            }
1273        }
1274
1275        // The rewrites: refuse a need for computed data, drop the edges that
1276        // cross between rewrites and pipeline stages, and fix one total order.
1277        let is_rewrite = |idx: StageIdx| reg.stage(idx).is_rewrite();
1278        let rewrites_scheduled: Vec<StageIdx> =
1279            selected.scheduled.iter().copied().filter(|idx| is_rewrite(*idx)).collect();
1280        for idx in &rewrites_scheduled {
1281            for cap in &manifests[idx].requires {
1282                if reg.capability(*cap).table.is_some() {
1283                    if let Some(provider) = providers_of(*cap).into_iter().find(|p| !is_rewrite(*p))
1284                    {
1285                        return Err(PlanError::RewriteNeedsComputed {
1286                            stage: reg.stage(*idx).name.clone(),
1287                            capability: reg.capability(*cap).name.clone(),
1288                            provider: reg.stage(provider).name.clone(),
1289                            workflow: request.workflow.clone(),
1290                        });
1291                    }
1292                }
1293            }
1294        }
1295        for (idx, set) in preds.iter_mut() {
1296            let rewrite = is_rewrite(*idx);
1297            set.retain(|pred| is_rewrite(*pred) == rewrite);
1298        }
1299        let rewrite_preds: BTreeMap<StageIdx, BTreeSet<StageIdx>> =
1300            rewrites_scheduled.iter().map(|idx| (*idx, preds[idx].clone())).collect();
1301        let rewrites = topo_order(reg, &rewrites_scheduled, &rewrite_preds, &request.workflow)?;
1302        {
1303            // Every pair of rewrites must be ordered relative to each other,
1304            // directly or through others: they feed each other's output.
1305            let reach = |from: StageIdx, to: StageIdx| -> bool {
1306                let mut stack = vec![to];
1307                let mut seen = BTreeSet::new();
1308                while let Some(node) = stack.pop() {
1309                    if node == from {
1310                        return true;
1311                    }
1312                    if seen.insert(node) {
1313                        stack.extend(rewrite_preds[&node].iter().copied());
1314                    }
1315                }
1316                false
1317            };
1318            for (i, a) in rewrites.iter().enumerate() {
1319                for b in &rewrites[i + 1..] {
1320                    if !reach(*a, *b) && !reach(*b, *a) {
1321                        let first = reg.stage(*a);
1322                        let second = reg.stage(*b);
1323                        let cap_of = |idx: StageIdx| {
1324                            reg.stage(idx).rewrite.as_ref().map(|r| r.publishes.clone())
1325                        };
1326                        let mut resolving = Vec::new();
1327                        if let Some(cap) = cap_of(*a) {
1328                            resolving.push(OrderingDef::new(second.name.clone()).after(cap));
1329                        }
1330                        if let Some(cap) = cap_of(*b) {
1331                            resolving.push(OrderingDef::new(first.name.clone()).after(cap));
1332                        }
1333                        return Err(PlanError::RewriteTie {
1334                            active: rewrites
1335                                .iter()
1336                                .map(|idx| reg.stage(*idx).name.clone())
1337                                .collect(),
1338                            first: first.name.clone(),
1339                            second: second.name.clone(),
1340                            resolving,
1341                            workflow: request.workflow.clone(),
1342                        });
1343                    }
1344                }
1345            }
1346        }
1347
1348        // The pipeline stages: dependency order, with the stages that have
1349        // effects outside the store placed after every stage that has none.
1350        let pipeline: Vec<StageIdx> =
1351            selected.scheduled.iter().copied().filter(|idx| !is_rewrite(*idx)).collect();
1352        let pipeline_preds: BTreeMap<StageIdx, BTreeSet<StageIdx>> =
1353            pipeline.iter().map(|idx| (*idx, preds[idx].clone())).collect();
1354        let topo = topo_order(reg, &pipeline, &pipeline_preds, &request.workflow)?;
1355        let is_io = |idx: StageIdx| reg.stage(idx).decl.effect == Effect::Io;
1356        for idx in &topo {
1357            if !is_io(*idx) {
1358                if let Some(io) = pipeline_preds[idx].iter().copied().find(|p| is_io(*p)) {
1359                    return Err(PlanError::IoProductReadByPure {
1360                        reader: reg.stage(*idx).name.clone(),
1361                        io_stage: reg.stage(io).name.clone(),
1362                        workflow: request.workflow.clone(),
1363                    });
1364                }
1365            }
1366        }
1367        let mut order: Vec<StageIdx> = topo.iter().copied().filter(|idx| !is_io(*idx)).collect();
1368        let pure_len = order.len();
1369        order.extend(topo.iter().copied().filter(|idx| is_io(*idx)));
1370        let batches = batch(&order, &pipeline_preds, pure_len);
1371        let first_io_batch = if pure_len < order.len() {
1372            batches.iter().position(|range| range.start == pure_len)
1373        } else {
1374            None
1375        };
1376
1377        // Every backend that takes part must be able to render every element.
1378        for backend in &active_backends {
1379            let entry = reg.backend(backend).expect("an active backend is registered");
1380            let selected_rules = &selections[backend];
1381            let holes: BTreeSet<ElementName> =
1382                request.unsupported.get(backend).into_iter().flatten().cloned().collect();
1383            check_completeness(reg, entry, selected_rules, &holes, &request.workflow)?;
1384        }
1385
1386        let mut warnings: Vec<PlanWarning> = Vec::new();
1387        for backend in &active_backends {
1388            warnings.extend(selection_warnings.remove(backend).into_iter().flatten());
1389        }
1390        warnings.extend(selected.warnings);
1391
1392        let key = plan_key(reg, request, &demands);
1393        // Name order, so the plan's shape does not depend on the order features
1394        // registered in.
1395        let mut excluded: Vec<Excluded> = selected.excluded.into_values().collect();
1396        excluded.sort();
1397        Ok(Plan {
1398            registry: Arc::clone(&registry),
1399            request: request.clone(),
1400            demands,
1401            manifests,
1402            rewrites,
1403            order,
1404            batches,
1405            first_io_batch,
1406            selections,
1407            active_backends,
1408            needed: selected.needed,
1409            externals: selected.externals,
1410            key,
1411            warnings,
1412            excluded,
1413            commit_order: selected.commit_order,
1414            preds,
1415        })
1416    }
1417
1418    /// Builds the plan of the registered workflow `name`, with `overrides`
1419    /// applied.
1420    ///
1421    /// This is the usual way to get a plan. A workflow ([`WorkflowDef`]) is a
1422    /// named set of demands together with the choices that go with them, held
1423    /// in the registry as a complete plan request, and a caller changes only
1424    /// what it needs to through [`Overrides`]. This
1425    /// method turns the workflow into a [`PlanRequest`] with
1426    /// [`workflow_request`], which documents exactly how, and builds that
1427    /// request with [`Plan::build`].
1428    ///
1429    /// # Errors
1430    ///
1431    /// Returns [`PlanError::UnknownWorkflow`] when no workflow named `name` is
1432    /// registered, [`PlanError::UnknownOutput`] when the workflow lists an
1433    /// output that is not registered, and any error [`Plan::build`] returns.
1434    ///
1435    /// # Panics
1436    ///
1437    /// As [`Plan::build`]: a panic in a registered stage's
1438    /// [`Stage::needs`](crate::core::stage::Stage::needs) or
1439    /// [`RewriteStage::needs`](crate::core::stage::RewriteStage::needs)
1440    /// propagates out of this call.
1441    pub fn for_workflow(
1442        registry: &Arc<FlmRegistry>,
1443        name: &str,
1444        overrides: &Overrides,
1445    ) -> Result<Plan, PlanError> {
1446        let request = workflow_request(registry, name, overrides)?;
1447        Plan::build(registry, &request)
1448    }
1449
1450    /// The registry the plan was built against. Every stage, capability, table
1451    /// and rule number the plan holds is a number of this registry.
1452    pub fn registry(&self) -> &Arc<FlmRegistry> {
1453        &self.registry
1454    }
1455
1456    /// The plan request the plan was built from; for a plan built with
1457    /// [`Plan::for_workflow`], the request the workflow was turned into, with the
1458    /// overrides applied.
1459    pub fn request(&self) -> &PlanRequest {
1460        &self.request
1461    }
1462
1463    /// Every demanded capability, with collections replaced by their members, in
1464    /// name order.
1465    pub fn demands(&self) -> &BTreeSet<CapName> {
1466        &self.demands
1467    }
1468
1469    /// The number that identifies the plan by everything it was built from: see
1470    /// [`PlanKey`].
1471    pub fn key(&self) -> PlanKey {
1472        self.key
1473    }
1474
1475    /// The record the plan keeps about the stage `idx`, or `None` when `idx` is
1476    /// not a stage number of this plan's registry.
1477    ///
1478    /// Every registered stage has a record, whether or not it will run;
1479    /// [`Plan::is_scheduled`] says whether it will.
1480    pub fn manifest(&self, idx: StageIdx) -> Option<&StagePlan> {
1481        self.manifests.get(&idx)
1482    }
1483
1484    /// The records the plan keeps about every registered stage, in registration
1485    /// order.
1486    pub fn manifests(&self) -> &BTreeMap<StageIdx, StagePlan> {
1487        &self.manifests
1488    }
1489
1490    /// The rewrite stages that will run, in the order they run.
1491    pub fn rewrites(&self) -> &[StageIdx] {
1492        &self.rewrites
1493    }
1494
1495    /// The names of the rewrite stages that will run, in the order they run.
1496    pub fn rewrite_names(&self) -> Vec<StageName> {
1497        self.rewrites.iter().map(|idx| self.registry.stage(*idx).name.clone()).collect()
1498    }
1499
1500    /// The stages that will run after the rewrite stages, in the order they run.
1501    pub fn order(&self) -> &[StageIdx] {
1502        &self.order
1503    }
1504
1505    /// The names of the stages that will run after the rewrite stages, in the
1506    /// order they run.
1507    pub fn stage_names(&self) -> Vec<StageName> {
1508        self.order.iter().map(|idx| self.registry.stage(*idx).name.clone()).collect()
1509    }
1510
1511    /// Whether the stage `idx` will run, as a rewrite stage or as a later stage.
1512    pub fn is_scheduled(&self, idx: StageIdx) -> bool {
1513        self.rewrites.contains(&idx) || self.order.contains(&idx)
1514    }
1515
1516    /// The names of every stage that will run, rewrite stages included, in name
1517    /// order.
1518    pub fn scheduled_names(&self) -> Vec<StageName> {
1519        let mut names: Vec<StageName> = self.rewrite_names();
1520        names.extend(self.stage_names());
1521        names.sort();
1522        names
1523    }
1524
1525    /// The batches the runner executes, as ranges of positions in
1526    /// [`Plan::order`].
1527    ///
1528    /// No stage of a batch depends on another stage of the same batch, so the
1529    /// stages of a batch may run at the same time. See the [module
1530    /// documentation](self).
1531    pub fn batches(&self) -> &[Range<usize>] {
1532        &self.batches
1533    }
1534
1535    /// The batches, each as the names of its stages in order.
1536    pub fn batch_names(&self) -> Vec<Vec<StageName>> {
1537        self.batches
1538            .iter()
1539            .map(|range| {
1540                self.order[range.clone()]
1541                    .iter()
1542                    .map(|idx| self.registry.stage(*idx).name.clone())
1543                    .collect()
1544            })
1545            .collect()
1546    }
1547
1548    /// The index of the first batch that holds a stage with effect
1549    /// [`Effect::Io`] (a stage that acts outside the run's computed data, for
1550    /// example by writing the output), or `None` when the plan schedules no such
1551    /// stage.
1552    ///
1553    /// A run that has recorded an error diagnostic stops before this batch,
1554    /// unless the caller sets
1555    /// [`RunOptions::continue_with_errors`](crate::core::run::RunOptions::continue_with_errors).
1556    pub fn first_io_batch(&self) -> Option<usize> {
1557        self.first_io_batch
1558    }
1559
1560    /// The lowering rules chosen for every registered backend whose rules could
1561    /// be chosen, whether or not that backend takes part in this plan.
1562    pub fn selections(&self) -> &BTreeMap<BackendName, SelectedRules> {
1563        &self.selections
1564    }
1565
1566    /// The lowering rules chosen for `backend`, or `None` when `backend` is not
1567    /// registered or its rules could not be chosen (which makes the plan build
1568    /// fail only when that backend takes part).
1569    pub fn selection(&self, backend: &str) -> Option<&SelectedRules> {
1570        self.selections.get(backend)
1571    }
1572
1573    /// The backends that take part in this plan, in name order: those whose
1574    /// lowering stage is scheduled.
1575    pub fn active_backends(&self) -> &BTreeSet<BackendName> {
1576        &self.active_backends
1577    }
1578
1579    /// The names of every capability the plan needs, in name order: the demanded
1580    /// capabilities, together with every capability the scheduled stages
1581    /// require.
1582    pub fn needed_names(&self) -> Vec<CapName> {
1583        let mut names: Vec<CapName> =
1584            self.needed.iter().map(|id| self.registry.capability(*id).name.clone()).collect();
1585        names.sort();
1586        names
1587    }
1588
1589    /// The external tables of this plan. An external table is a table that no
1590    /// stage of the run writes: the caller installs its value when the run is
1591    /// constructed ([`Externals`](crate::core::run::Externals)).
1592    pub fn externals(&self) -> &BTreeSet<TableId> {
1593        &self.externals
1594    }
1595
1596    /// The names of the external tables of this plan, in the registry's table
1597    /// order.
1598    pub fn external_names(&self) -> Vec<CapName> {
1599        self.externals.iter().map(|id| self.registry.table(*id).def.name.clone()).collect()
1600    }
1601
1602    /// The warnings of this plan ([`PlanWarning`]): first, for each backend that
1603    /// takes part, in backend name order, its lowering rule preferences that
1604    /// could not be honored, then its unchecked outputs in feature name order;
1605    /// then the stage preferences that could not be honored.
1606    pub fn warnings(&self) -> &[PlanWarning] {
1607        &self.warnings
1608    }
1609
1610    /// The stages that provider selection ruled out ([`Excluded`]), sorted by
1611    /// the name of the stage ruled out, then by the name of the stage that ruled
1612    /// it out.
1613    pub fn excluded(&self) -> &[Excluded] {
1614        &self.excluded
1615    }
1616
1617    /// The names of the scheduled stages in the order in which provider
1618    /// selection chose them, which is not the order in which they run. It shows
1619    /// how the plan was built.
1620    pub fn commit_order(&self) -> Vec<StageName> {
1621        self.commit_order.iter().map(|idx| self.registry.stage(*idx).name.clone()).collect()
1622    }
1623
1624    /// The scheduled stages that the stage `idx` depends on directly, or `None`
1625    /// when `idx` is not scheduled.
1626    ///
1627    /// The dependencies come from the stage's requirements, its reads, its
1628    /// ordering edges and the registry's ordering declarations. A rewrite stage's
1629    /// dependencies are rewrite stages only, and a later stage's dependencies are
1630    /// later stages only.
1631    pub fn predecessors(&self, idx: StageIdx) -> Option<&BTreeSet<StageIdx>> {
1632        self.preds.get(&idx)
1633    }
1634
1635    /// The stages that run once per tree and that the stage `idx` depends on,
1636    /// directly or through other stages, in the order they run; `idx` itself is
1637    /// not among them, and neither is any stage with effect [`Effect::Io`].
1638    ///
1639    /// [Value catch-up](crate::guide::concepts_overview#value-catch-up) runs
1640    /// these stages over a synthesized value, so that the stage that renders the
1641    /// value finds the same kinds of computed data it would find for a tree of
1642    /// the document. A synthesized value is a small tree that a stage builds while
1643    /// a run is under way, held outside the document's trees
1644    /// ([synthesized values](crate::guide::concepts_overview#synthesized-values)).
1645    pub fn per_tree_closure(&self, idx: StageIdx) -> Vec<StageIdx> {
1646        let mut seen: BTreeSet<StageIdx> = BTreeSet::new();
1647        let mut stack = vec![idx];
1648        while let Some(node) = stack.pop() {
1649            if let Some(preds) = self.preds.get(&node) {
1650                for pred in preds {
1651                    if seen.insert(*pred) {
1652                        stack.push(*pred);
1653                    }
1654                }
1655            }
1656        }
1657        self.order
1658            .iter()
1659            .copied()
1660            .filter(|stage| seen.contains(stage))
1661            .filter(|stage| {
1662                let decl = &self.registry.stage(*stage).decl;
1663                decl.scope == Scope::PerTree && decl.effect != Effect::Io
1664            })
1665            .collect()
1666    }
1667
1668    /// The plan as five lines of text: its rewrite stages, its order, the order
1669    /// in which provider selection chose the stages, the stages that were ruled
1670    /// out, and the external tables.
1671    ///
1672    /// The format is fixed and lists stage, capability and table names only, so a report
1673    /// can print it and a test can compare the text of two plans, for example to
1674    /// check that a plan does not depend on the order in which the features
1675    /// registered.
1676    pub fn render(&self) -> String {
1677        let mut out = String::new();
1678        out.push_str(&format!(
1679            "rewrites: [{}]\n",
1680            join(self.rewrite_names().iter().map(|n| n.name()))
1681        ));
1682        out.push_str(&format!("order: [{}]\n", join(self.stage_names().iter().map(|n| n.name()))));
1683        out.push_str(&format!(
1684            "committed: [{}]\n",
1685            join(self.commit_order().iter().map(|n| n.name()))
1686        ));
1687        let excluded: Vec<String> = self
1688            .excluded
1689            .iter()
1690            .map(|e| format!("{} by {} over {}", e.stage, e.excluded_by, e.over))
1691            .collect();
1692        out.push_str(&format!("excluded: [{}]\n", excluded.join("; ")));
1693        out.push_str(&format!(
1694            "externals: [{}]",
1695            join(self.external_names().iter().map(|n| n.name()))
1696        ));
1697        out
1698    }
1699}
1700
1701impl fmt::Debug for Plan {
1702    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1703        f.debug_struct("Plan")
1704            .field("rewrites", &self.rewrite_names())
1705            .field("order", &self.stage_names())
1706            .field("batches", &self.batch_names())
1707            .field("active_backends", &self.active_backends)
1708            .field("key", &self.key)
1709            .finish()
1710    }
1711}
1712
1713/// Resolves one stage's declaration and needs against the registry into the
1714/// record the plan keeps for it.
1715///
1716/// Every name is looked up here. This function therefore refuses an undeclared
1717/// capability, table or option type, a table read as the wrong value type, a
1718/// rewrite stage declaring a read, a stage requiring a collection, and a stage
1719/// reading an option type whose value is fixed when the registry is built.
1720fn resolve_needs(
1721    reg: &FlmRegistry,
1722    idx: StageIdx,
1723    decl: &crate::core::stage::StageDecl,
1724    needs: Needs,
1725    workflow: &Option<WorkflowName>,
1726) -> Result<StagePlan, PlanError> {
1727    let entry = reg.stage(idx);
1728    let stage = entry.name.clone();
1729    let cap_roster = || -> Vec<Name> {
1730        let mut names: Vec<Name> =
1731            reg.capabilities().iter().map(|c| c.name.name().clone()).collect();
1732        names.sort();
1733        names
1734    };
1735    let table_roster = || -> Vec<Name> {
1736        let mut names: Vec<Name> = reg.tables().iter().map(|t| t.def.name.name().clone()).collect();
1737        names.sort();
1738        names
1739    };
1740    let resolve_cap = |name: &CapName, kind: &str| -> Result<CapId, PlanError> {
1741        if let Some(id) = reg.cap_id(name) {
1742            return Ok(id);
1743        }
1744        if reg.collection(name).is_some() && kind == "requires" {
1745            return Err(PlanError::CollectionRequired {
1746                stage: stage.clone(),
1747                collection: name.clone(),
1748                workflow: workflow.clone(),
1749            });
1750        }
1751        Err(PlanError::NeedsUndeclared {
1752            stage: stage.clone(),
1753            kind: "capability",
1754            name: name.name().clone(),
1755            roster: cap_roster(),
1756            workflow: workflow.clone(),
1757        })
1758    };
1759    let resolve_table = |table: &TableRef| -> Result<TableId, PlanError> {
1760        let Some(entry) = reg.table_named(&table.name) else {
1761            return Err(PlanError::NeedsUndeclared {
1762                stage: stage.clone(),
1763                kind: "table",
1764                name: table.name.name().clone(),
1765                roster: table_roster(),
1766                workflow: workflow.clone(),
1767            });
1768        };
1769        if entry.def.ty.type_id() != table.type_id {
1770            return Err(PlanError::NeedsTableType {
1771                stage: stage.clone(),
1772                table: table.name.clone(),
1773                declared: entry.def.ty.short_name(),
1774                referenced: table.short_type_name(),
1775                workflow: workflow.clone(),
1776            });
1777        }
1778        Ok(entry.id)
1779    };
1780
1781    let mut requires: BTreeSet<CapId> = BTreeSet::new();
1782    for cap in &needs.requires {
1783        requires.insert(resolve_cap(cap, "requires")?);
1784    }
1785    let mut reads = ReadSet::new();
1786    for table in &needs.reads {
1787        if entry.is_rewrite() {
1788            return Err(PlanError::RewriteReads {
1789                stage: stage.clone(),
1790                table: table.name.clone(),
1791                workflow: workflow.clone(),
1792            });
1793        }
1794        let id = resolve_table(table)?;
1795        requires.insert(reg.table(id).cap);
1796        reads.insert(
1797            table.name.clone(),
1798            ReadEntry { id, ty: reg.table(id).def.ty, optional: false, producer: None },
1799        );
1800    }
1801    for table in &needs.reads_opt {
1802        if entry.is_rewrite() {
1803            return Err(PlanError::RewriteReads {
1804                stage: stage.clone(),
1805                table: table.name.clone(),
1806                workflow: workflow.clone(),
1807            });
1808        }
1809        let id = resolve_table(table)?;
1810        reads.insert(
1811            table.name.clone(),
1812            ReadEntry { id, ty: reg.table(id).def.ty, optional: true, producer: None },
1813        );
1814    }
1815    let mut writes = WriteSet::new();
1816    for table in &decl.writes {
1817        let id = resolve_table(table)?;
1818        writes.insert(table.name.clone(), WriteEntry { id, ty: reg.table(id).def.ty });
1819    }
1820    for option in &needs.options {
1821        match reg.option_decl(option.key()) {
1822            None => {
1823                let mut roster: Vec<Name> =
1824                    reg.options().keys().map(|k| Name::from(k.short_name())).collect();
1825                roster.sort();
1826                return Err(PlanError::NeedsUndeclared {
1827                    stage: stage.clone(),
1828                    kind: "option type",
1829                    name: Name::from(option.key().short_name()),
1830                    roster,
1831                    workflow: workflow.clone(),
1832                });
1833            }
1834            Some(decl) if decl.bind == crate::model::options::Bind::Registry => {
1835                return Err(PlanError::RegistryBoundRead {
1836                    error: OptionError::RegistryBoundRead {
1837                        stage: stage.clone(),
1838                        option: option.key().short_name().to_string(),
1839                        owner: decl.owner.clone(),
1840                    },
1841                    workflow: workflow.clone(),
1842                });
1843            }
1844            Some(_) => {}
1845        }
1846    }
1847    let mut after: BTreeSet<CapId> = BTreeSet::new();
1848    for cap in &needs.after {
1849        after.insert(resolve_cap(cap, "after")?);
1850    }
1851    let mut before: BTreeSet<CapId> = BTreeSet::new();
1852    for cap in &needs.before {
1853        before.insert(resolve_cap(cap, "before")?);
1854    }
1855    let options = needs.options.clone();
1856    Ok(StagePlan {
1857        idx,
1858        manifest: Arc::new(Manifest { decl: decl.clone(), needs }),
1859        reads,
1860        writes,
1861        options,
1862        requires,
1863        after,
1864        before,
1865    })
1866}
1867
1868/// Sorts `stages` so that every stage follows the stages it depends on,
1869/// breaking ties by registration order so that the result depends on nothing
1870/// else. The registry build sorts features with the same function
1871/// ([`crate::core::registry::order`]).
1872///
1873/// `preds` gives, for each stage, the stages it depends on. Returns
1874/// [`PlanError::Cycle`] when the dependencies form a cycle, listing the cycle
1875/// from the stage whose name comes first and repeating that stage at the end.
1876fn topo_order(
1877    reg: &FlmRegistry,
1878    stages: &[StageIdx],
1879    preds: &BTreeMap<StageIdx, BTreeSet<StageIdx>>,
1880    workflow: &Option<WorkflowName>,
1881) -> Result<Vec<StageIdx>, PlanError> {
1882    let cycle = match sort_by_priority(stages, preds) {
1883        Ok(order) => return Ok(order),
1884        Err(cycle) => cycle,
1885    };
1886    let names: Vec<StageName> = cycle.iter().map(|idx| reg.stage(*idx).name.clone()).collect();
1887    let least =
1888        names.iter().enumerate().min_by(|(_, a), (_, b)| a.cmp(b)).map(|(i, _)| i).unwrap_or(0);
1889    let mut rotated = names;
1890    rotated.rotate_left(least);
1891    let first = rotated[0].clone();
1892    rotated.push(first);
1893    Err(PlanError::Cycle { stages: rotated, workflow: workflow.clone() })
1894}
1895
1896/// Cuts an ordered list of stages into batches: a stage joins the current batch
1897/// when it depends on no stage already in it, and starts a new batch otherwise.
1898///
1899/// A batch always ends at `pure_len`, the position where the stages with
1900/// effect [`Effect::Io`] begin, so that no batch holds both kinds and a run
1901/// that stops before the first `Io` stage stops at a batch boundary.
1902fn batch(
1903    order: &[StageIdx],
1904    preds: &BTreeMap<StageIdx, BTreeSet<StageIdx>>,
1905    pure_len: usize,
1906) -> Vec<Range<usize>> {
1907    let mut batches: Vec<Range<usize>> = Vec::new();
1908    let mut start = 0usize;
1909    for (pos, stage) in order.iter().copied().enumerate() {
1910        let independent = order[start..pos].iter().all(|other| !preds[&stage].contains(other));
1911        if pos > start && (!independent || pos == pure_len) {
1912            batches.push(start..pos);
1913            start = pos;
1914        }
1915    }
1916    if start < order.len() {
1917        batches.push(start..order.len());
1918    }
1919    batches
1920}
1921
1922/// Checks that `backend` can render every element a document may contain.
1923///
1924/// The elements checked are those a document may contain
1925/// ([`FlmRegistry::occurrable_elements`]). An element passes if the backend
1926/// writes it natively and no preferred rule replaces that, or if the rule
1927/// chosen for it produces only elements that pass in turn. Every element must
1928/// pass except the elements of `holes`, the elements the plan request accepts as
1929/// unrenderable on this backend; an element of `holes` that a rule produces
1930/// still does not pass.
1931///
1932/// Returns [`PlanError::Incomplete`] listing the elements that do not pass,
1933/// and [`PlanError::ProducesCycle`] when following what the rules produce leads
1934/// back to an element already on the path.
1935fn check_completeness(
1936    reg: &FlmRegistry,
1937    backend: &crate::core::registry::frozen::BackendEntry,
1938    selected: &SelectedRules,
1939    holes: &BTreeSet<ElementName>,
1940    workflow: &Option<WorkflowName>,
1941) -> Result<(), PlanError> {
1942    #[derive(Clone, Copy, PartialEq, Eq)]
1943    enum State {
1944        Visiting,
1945        Reachable,
1946        Unreachable,
1947    }
1948    let mut states: BTreeMap<ElementName, State> = BTreeMap::new();
1949    fn reach(
1950        reg: &FlmRegistry,
1951        backend: &crate::core::registry::frozen::BackendEntry,
1952        selected: &SelectedRules,
1953        element: &ElementName,
1954        states: &mut BTreeMap<ElementName, State>,
1955        path: &mut Vec<ElementName>,
1956    ) -> Result<bool, Vec<ElementName>> {
1957        if let Some(state) = states.get(element) {
1958            return match state {
1959                State::Reachable => Ok(true),
1960                State::Unreachable => Ok(false),
1961                State::Visiting => {
1962                    let start = path.iter().position(|e| e == element).unwrap_or(0);
1963                    Err(path[start..].to_vec())
1964                }
1965            };
1966        }
1967        if backend.native.contains(element) && !selected.overridden_native.contains(element) {
1968            states.insert(element.clone(), State::Reachable);
1969            return Ok(true);
1970        }
1971        let Some(rule) = selected.rule_for(element) else {
1972            states.insert(element.clone(), State::Unreachable);
1973            return Ok(false);
1974        };
1975        states.insert(element.clone(), State::Visiting);
1976        path.push(element.clone());
1977        let mut all = true;
1978        for produced in &reg.rule(rule).rule.decl.produces {
1979            if !reach(reg, backend, selected, produced, states, path)? {
1980                all = false;
1981            }
1982        }
1983        path.pop();
1984        states.insert(element.clone(), if all { State::Reachable } else { State::Unreachable });
1985        Ok(all)
1986    }
1987    let mut missing: Vec<ElementName> = Vec::new();
1988    for element in reg.occurrable_elements() {
1989        if holes.contains(element) {
1990            continue;
1991        }
1992        let mut path = Vec::new();
1993        match reach(reg, backend, selected, element, &mut states, &mut path) {
1994            Ok(true) => {}
1995            Ok(false) => missing.push(element.clone()),
1996            Err(cycle) => {
1997                let least = cycle
1998                    .iter()
1999                    .enumerate()
2000                    .min_by(|(_, a), (_, b)| a.cmp(b))
2001                    .map(|(i, _)| i)
2002                    .unwrap_or(0);
2003                let mut rotated = cycle;
2004                rotated.rotate_left(least);
2005                return Err(PlanError::ProducesCycle {
2006                    backend: backend.name.clone(),
2007                    cycle: rotated,
2008                    workflow: workflow.clone(),
2009                });
2010            }
2011        }
2012    }
2013    if missing.is_empty() {
2014        Ok(())
2015    } else {
2016        Err(PlanError::Incomplete { backend: backend.name.clone(), missing, workflow: workflow.clone() })
2017    }
2018}
2019
2020/// Computes the plan's key: a digest over the registry's own digest together
2021/// with exactly what plan building consults (see [`PlanKey`]).
2022fn plan_key(reg: &FlmRegistry, request: &PlanRequest, demands: &BTreeSet<CapName>) -> PlanKey {
2023    let mut hasher = Fnv1a64::new();
2024    hasher.write_u64(reg.digest());
2025    for demand in demands {
2026        hasher.write_str(demand.as_str());
2027    }
2028    hasher.write_str("|prefer");
2029    for stage in &request.prefer {
2030        hasher.write_str(stage.as_str());
2031    }
2032    hasher.write_str("|lowering");
2033    for (backend, selection) in &request.lowering {
2034        hasher.write_str(backend.as_str());
2035        for rule in &selection.prefer {
2036            hasher.write_str(rule.as_str());
2037        }
2038    }
2039    hasher.write_str("|unsupported");
2040    for (backend, holes) in &request.unsupported {
2041        hasher.write_str(backend.as_str());
2042        for element in holes {
2043            hasher.write_str(element.as_str());
2044        }
2045    }
2046    hasher.write_str("|options");
2047    hasher.write_u64(request.render_options.digest());
2048    PlanKey(hasher.value())
2049}
2050
2051/// Turns the registered workflow `name` into a plan request, with `overrides`
2052/// applied, without building the plan.
2053///
2054/// A workflow ([`WorkflowDef`]) is a named set of demands together with the
2055/// choices that go with them, held in the registry as a complete plan request.
2056/// [`Plan::for_workflow`] calls this function and builds the result;
2057/// call it directly to inspect or adjust the request before building it with
2058/// [`Plan::build`].
2059///
2060/// A workflow may extend another. The request is then built from the fields
2061/// combined along the chain of workflows it extends
2062/// ([`FlmRegistry::combined_workflow`]): each field a workflow declares replaces
2063/// the one it inherits. The request's demands are, in this order, the
2064/// capability of each output the workflow lists
2065/// ([`OutputDef`](crate::core::registry::OutputDef)), the workflow's own
2066/// demands, and the demands of `overrides`. [`Overrides`] documents how each of
2067/// its other fields combines with the workflow's. The request's
2068/// [`workflow`](PlanRequest#structfield.workflow) is `name`, so that the errors
2069/// and warnings of the plan name the workflow, including for what `overrides`
2070/// adds.
2071///
2072/// # Errors
2073///
2074/// Returns [`PlanError::UnknownWorkflow`] when no workflow named `name` is
2075/// registered, and [`PlanError::UnknownOutput`] when the workflow lists an
2076/// output that is not registered. The other names of the request are checked
2077/// only when the plan is built.
2078pub fn workflow_request(
2079    registry: &Arc<FlmRegistry>,
2080    name: &str,
2081    overrides: &Overrides,
2082) -> Result<PlanRequest, PlanError> {
2083    let reg: &FlmRegistry = registry;
2084    let workflow_roster =
2085        || -> Vec<Name> { reg.workflows().map(|w| w.def.name.name().clone()).collect() };
2086    let Some(combined) = reg.combined_workflow(name) else {
2087        return Err(PlanError::UnknownWorkflow {
2088            workflow: WorkflowName::from(name),
2089            roster: workflow_roster(),
2090        });
2091    };
2092    let WorkflowDef { outputs, demands, prefer, lowering, unsupported, render_options, .. } = combined;
2093    let output_roster =
2094        || -> Vec<Name> { reg.outputs().map(|o| o.def.name.name().clone()).collect() };
2095    let mut request = PlanRequest::new();
2096    request.workflow = Some(WorkflowName::from(name));
2097    for output in &outputs {
2098        let Some(output_entry) = reg.output(output) else {
2099            return Err(PlanError::UnknownOutput {
2100                workflow: WorkflowName::from(name),
2101                output: output.clone(),
2102                roster: output_roster(),
2103            });
2104        };
2105        request.demands.push(output_entry.def.capability.clone());
2106    }
2107    request.demands.extend(demands);
2108    request.demands.extend(overrides.demands.iter().cloned());
2109    request.prefer.extend(overrides.prefer.iter().cloned());
2110    request.prefer.extend(prefer);
2111    request.lowering = lowering;
2112    for (backend, selection) in &overrides.lowering {
2113        request.lowering.insert(backend.clone(), selection.clone());
2114    }
2115    request.unsupported = unsupported;
2116    for (backend, holes) in &overrides.unsupported {
2117        request.unsupported.entry(backend.clone()).or_default().extend(holes.iter().cloned());
2118    }
2119    // Render-time values: the workflow's, with the host's replacing them one
2120    // option type at a time.
2121    let mut merged = render_options;
2122    merged.merge_from(&overrides.render_options);
2123    request.render_options = merged;
2124    Ok(request)
2125}