fuel_dispatch/driver.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The `optimize_graph` lock-step pass driver — Phase B PR-B3 of the
3//! "plan IS the graph" rebuild
4//! ([`../../docs/session-prompts/plan-is-graph-rebuild.md`](
5//! ../../docs/session-prompts/plan-is-graph-rebuild.md) capability 5;
6//! [`../../docs/architecture/04-optimization.md`](
7//! ../../docs/architecture/04-optimization.md) §"The two-stage
8//! transformation", §"Relationship to PR 3").
9//!
10//! ## What this is
11//!
12//! `optimize_graph` was a hardcoded sequence — `execution_plan` order →
13//! [`compile_plan`](crate::plan::compile_plan) (per-node placement +
14//! cost ranking + the PR-B2 per-ending-device Pareto frontier) →
15//! `seed_placement_fork_branches` (the PR-A4 deliberate-fork
16//! pathfinder). PR-B3 restructures that sequence into a **lock-step
17//! driver** over three registered pass *kinds*, mirroring the shape of
18//! `fuel_graph::opt::RuleRegistry` (a `Vec<Box<dyn …>>` of passes +
19//! builder + a driver method that walks them) so future passes (fusion,
20//! algebraic, dtype-lowering) plug in without rewriting the loop:
21//!
22//! - **[`Pathfinder`]s** — *ADD* candidate paths / branches to the
23//! graph. The PR-A4 [`PlacementForkPathfinder`] (deliberate-fork seed,
24//! the one pathfinder that records an `Op::Branch` per genuine
25//! multi-placement fork) is the first registered pathfinder.
26//! - **Rankers** — *MEASURE* each path on the `CostVector` (PR-B1/B2
27//! `rank_by_cost`). Rankers are not a driver-visible trait in B3:
28//! ranking is applied **per kernel-bearing node inside
29//! [`crate::plan::compile_plan`]** as the per-node `AlternativeSet` is built, and
30//! the ranked result is carried into the driver via
31//! [`OptimizationContext::plan`]. The driver re-runs no ranker; the
32//! measure step is the plan it is handed. (B3 is a structural refactor
33//! — when a later PR adds a pathfinder that emits *new* candidates the
34//! plan never priced, that is the point to lift ranking into a
35//! driver-visible `Ranker` trait.)
36//! - **[`Optimizer`]s** — *MERGE / DISCARD* paths. The PR-B2
37//! per-ending-device Pareto frontier + crowding cap is applied
38//! per-node inside [`crate::plan::compile_plan`]; the registered
39//! [`FrontierConvergenceOptimizer`] is the in-graph counterpart that
40//! runs **after each pathfinder** to (a) collapse duplicate
41//! (forward-identical) arms a pathfinder may have proposed
42//! [duplicate-path convergence], and (b) assert the optimizer
43//! invariants the constitution requires — never strand the last
44//! `(device, backend)` path, never mutate a node in an active cycle /
45//! currently-executing region.
46//!
47//! ## Lock-step / prune-as-you-go (the constitution's bound)
48//!
49//! The driver runs the passes interleaved, **not** explode-then-extract:
50//! for each registered pathfinder, it ADDs its candidate paths, then
51//! immediately runs every registered optimizer to prune the region the
52//! pathfinder just touched, before moving to the next pathfinder. This
53//! is the [`PassRegistry::run_lockstep`] contract — the working set
54//! never explodes-then-extracts, so it stays bounded by construction
55//! (per [`../../docs/architecture/04-optimization.md`](
56//! ../../docs/architecture/04-optimization.md) §"Bounding the
57//! frontier": *"run the merge/discard optimizers after each pathfinder
58//! step, not once at the end"*).
59//!
60//! ## Behavior preservation (B3 is a structural refactor)
61//!
62//! The optimized result — the arm-0 winner, the retained per-device
63//! frontier (applied inside `compile_plan`, unchanged), and the emitted
64//! `Op::Branch` nodes — is **identical** to the pre-B3 hardcoded
65//! sequence on every graph. The driver is the same three operations in
66//! the same order; the only change is that they are reached through the
67//! registry rather than inlined. The load-bearing
68//! `driver_matches_legacy_sequence` test in
69//! [`crate::optimize`] proves it on a representative multi-placement
70//! graph.
71
72use std::collections::{HashMap, HashSet};
73
74use fuel_graph::{Graph, Node, NodeId, Op};
75use fuel_ir::Result;
76use fuel_ir::probe::BackendId;
77
78use crate::kernel::KernelBindingTable;
79use crate::plan::ExecutionPlan;
80
81/// Read-only context threaded to every [`Pathfinder::propose`] and
82/// [`Optimizer::prune`] call during a [`PassRegistry::run_lockstep`]
83/// drive.
84///
85/// It carries the **measure** stage's output — the ranked, per-device
86/// frontier-pruned per-node `AlternativeSet`s [`compile_plan`] produced
87/// ([`Self::plan`]) plus the dispatch [`Self::order`] — and the
88/// **incremental-reopt guard** ([`Self::cycle_guard`]): the set of nodes
89/// that lie on an active cycle or in a currently-executing region and so
90/// must never be mutated by an optimizer. Batch `optimize_graph` has no
91/// executing region, so the guard is empty there; it exists to document
92/// and enforce the incremental-reopt contract for the Phase-C runtime.
93///
94/// [`compile_plan`]: crate::plan::compile_plan
95pub struct OptimizationContext<'a> {
96 /// The dispatch order [`compile_plan`](crate::plan::compile_plan)
97 /// was driven over — data-flow topo refined by destructive-op
98 /// ordering edges.
99 pub order: &'a [NodeId],
100 /// The per-node ranked + frontier-pruned `AlternativeSet`s (the
101 /// *measure* + per-node *prune* output). Pathfinders read the
102 /// winner + runner-up placements off this; optimizers read it to
103 /// honor the never-strand-last invariant.
104 pub plan: &'a ExecutionPlan,
105 /// Nodes on an active cycle / currently-executing region — an
106 /// optimizer must not mutate any node in this set. Empty for batch
107 /// `optimize_graph`.
108 pub cycle_guard: &'a HashSet<NodeId>,
109 /// The kernel binding table `optimize_graph` was handed by its caller —
110 /// the SAME table `compile_plan` resolved placements against. Pathfinders
111 /// that need a capability-gate answer (e.g. "is a kernel bound for this
112 /// runtime-fused op on this backend?") read THIS reference rather than
113 /// re-acquiring `crate::dispatch::global_bindings()`, so a background
114 /// adopt's write can never nest against a pathfinder's read on the same
115 /// lock (Spec B Task 1 — see
116 /// `crate::runtime_fused_kernels::fused_kernel_available_in`).
117 pub bindings: &'a KernelBindingTable,
118}
119
120impl<'a> OptimizationContext<'a> {
121 /// The threaded binding table (see [`Self::bindings`]).
122 pub fn bindings(&self) -> &KernelBindingTable {
123 self.bindings
124 }
125}
126
127/// A **pathfinder** *ADDs* candidate paths / branches to the graph. The
128/// PR-A4 deliberate-fork seed ([`PlacementForkPathfinder`]) is the first
129/// registered pathfinder; later pathfinders (fusion, algebraic,
130/// dtype-lowering under tolerance, layout fixups) implement the same
131/// trait and register the same way.
132///
133/// `propose` may append nodes and record `Op::Branch` decision points
134/// (via the `fuel-graph` A1 builders). It must never *remove* a path —
135/// that is an [`Optimizer`]'s job — and it returns `Result` so a
136/// build-time failure surfaces (never panic, per the working agreement).
137pub trait Pathfinder: Send + Sync {
138 /// Stable, human-readable name. Shows up in debug traces.
139 fn name(&self) -> &'static str;
140
141 /// Add candidate paths to `graph`. `ctx` carries the ranked plan +
142 /// dispatch order the *measure* stage produced.
143 fn propose(&self, graph: &mut Graph, ctx: &OptimizationContext<'_>) -> Result<()>;
144}
145
146/// An **optimizer** *MERGEs / DISCARDs* paths. The PR-B2 per-device
147/// Pareto frontier is applied per-node inside
148/// [`compile_plan`](crate::plan::compile_plan); the registered
149/// [`FrontierConvergenceOptimizer`] is its in-graph counterpart that
150/// runs after each pathfinder to collapse duplicate (forward-identical)
151/// arms and enforce the optimizer invariants.
152///
153/// `prune` runs **after** each [`Pathfinder::propose`] (lock-step), so
154/// the working set never explodes-then-extracts. It must honor the
155/// optimizer invariants: never strand the last `(device, backend)` path,
156/// and never mutate a node in `ctx.cycle_guard`.
157pub trait Optimizer: Send + Sync {
158 /// Stable, human-readable name. Shows up in debug traces.
159 fn name(&self) -> &'static str;
160
161 /// Merge/discard candidate paths in `graph`. Runs after each
162 /// pathfinder over the region that pathfinder just touched.
163 fn prune(&self, graph: &mut Graph, ctx: &OptimizationContext<'_>) -> Result<()>;
164}
165
166/// A registry of [`Pathfinder`]s and [`Optimizer`]s, driven lock-step by
167/// [`Self::run_lockstep`]. Mirrors `fuel_graph::opt::RuleRegistry`: a
168/// `Vec<Box<dyn …>>` of passes built up with `with_*` builders and run
169/// through one driver method. Keeping the same shape means the future
170/// passes the constitution names (fusion, algebraic, dtype-lowering)
171/// register exactly as the two shipped passes do.
172#[derive(Default)]
173pub struct PassRegistry {
174 pathfinders: Vec<Box<dyn Pathfinder>>,
175 optimizers: Vec<Box<dyn Optimizer>>,
176}
177
178impl PassRegistry {
179 /// Empty registry. Use [`Self::with_pathfinder`] /
180 /// [`Self::with_optimizer`] to add passes, or [`Self::default_passes`]
181 /// for the shipped configuration.
182 pub fn new() -> Self {
183 Self {
184 pathfinders: Vec::new(),
185 optimizers: Vec::new(),
186 }
187 }
188
189 /// Append a pathfinder. Returns self for builder-style chaining.
190 pub fn with_pathfinder(mut self, p: Box<dyn Pathfinder>) -> Self {
191 self.pathfinders.push(p);
192 self
193 }
194
195 /// Append an optimizer. Returns self for builder-style chaining.
196 pub fn with_optimizer(mut self, o: Box<dyn Optimizer>) -> Self {
197 self.optimizers.push(o);
198 self
199 }
200
201 /// The shipped Phase-B configuration: the PR-A4
202 /// [`PlacementForkPathfinder`] (the one pathfinder that records an
203 /// `Op::Branch` per genuine multi-placement fork) and the
204 /// [`FrontierConvergenceOptimizer`] (duplicate-path convergence +
205 /// the per-device-frontier invariant guards). This is exactly the
206 /// pre-B3 hardcoded sequence re-expressed as registered passes.
207 pub fn default_passes() -> Self {
208 Self::new()
209 .with_pathfinder(Box::new(
210 crate::region_pathfinder::PlacementRegionPathfinder,
211 ))
212 .with_optimizer(Box::new(FrontierConvergenceOptimizer))
213 }
214
215 /// [`Self::default_passes`] **plus runtime fusion**: the
216 /// [`crate::runtime_fused_pathfinder::RuntimeFusedArmPathfinder`] runs
217 /// FIRST (before placement — placement must see the fused arms it emits;
218 /// the fork seed can't double-fork them because `ctx.plan`/`ctx.order`
219 /// predate the drive and don't contain the appended arm nodes).
220 ///
221 /// A separate constructor rather than a change to `default_passes` so the
222 /// bare registry never scans the process-global runtime-fused sidecar —
223 /// non-adopting tests stay hermetic *by construction*, not by reset
224 /// discipline (dd-shapes coordination, 2026-07-08). Transitional, like the
225 /// sidecar itself: both collapse when runtime entries fold into the one
226 /// binding registry (10-decisions-log, runtime-fused-sidecar entry).
227 pub fn default_passes_with_runtime_fusion() -> Self {
228 Self::new()
229 .with_pathfinder(Box::new(
230 crate::runtime_fused_pathfinder::RuntimeFusedArmPathfinder,
231 ))
232 .with_pathfinder(Box::new(
233 crate::region_pathfinder::PlacementRegionPathfinder,
234 ))
235 .with_optimizer(Box::new(FrontierConvergenceOptimizer))
236 }
237
238 /// Number of registered pathfinders.
239 pub fn pathfinder_count(&self) -> usize {
240 self.pathfinders.len()
241 }
242
243 /// Number of registered optimizers.
244 pub fn optimizer_count(&self) -> usize {
245 self.optimizers.len()
246 }
247
248 /// Drive the passes **lock-step / prune-as-you-go**: for each
249 /// registered pathfinder, ADD its candidate paths, then immediately
250 /// run every registered optimizer to MERGE/DISCARD over the region
251 /// that pathfinder just touched, before moving to the next
252 /// pathfinder.
253 ///
254 /// This is the constitution's bound: the merge/discard optimizers
255 /// run **after each pathfinder step, not once at the end**, so the
256 /// working set never explodes-then-extracts. Ordering is enforced by
257 /// construction — an optimizer can only ever see the paths the
258 /// pathfinders *before it in this drive* added.
259 ///
260 /// Returns `Result`; the first failing pass aborts the drive
261 /// (build-time validation, never a panic).
262 pub fn run_lockstep(&self, graph: &mut Graph, ctx: &OptimizationContext<'_>) -> Result<()> {
263 for pf in &self.pathfinders {
264 // (1) ADD.
265 pf.propose(graph, ctx)?;
266 // (2) PRUNE — every optimizer, over the region just touched.
267 // Lock-step: never deferred to a final batch pass.
268 for opt in &self.optimizers {
269 opt.prune(graph, ctx)?;
270 }
271 }
272 Ok(())
273 }
274}
275
276/// The PR-A4 deliberate-fork pathfinder, re-expressed as a registered
277/// [`Pathfinder`]. Scans the ranked plan for nodes the placement DP /
278/// ranker admitted with **≥2 distinct `(backend, device)` placements** —
279/// a genuine placement choice — and records each as ONE `Op::Branch` via
280/// the `fuel-graph` A1 builders (arm-0 = the DP winner, arm-1 = the
281/// runner-up clone, orphaned so the live data flow is untouched and the
282/// realize result is identical).
283///
284/// This is **the same logic** the pre-B3 `seed_placement_fork_branches`
285/// free function ran — moved verbatim behind the trait. The
286/// deliberate-fork gate (real ≥2-placement choice, a producer to
287/// diverge from, exactly one consumer to reconverge at) is unchanged, so
288/// the fewness gate still holds and a CPU-only build emits zero branches.
289///
290/// **No `DEFAULT_MAX_N` / fixed top-N anywhere** — the bound is the
291/// per-device frontier the plan already carries; this pass reads the
292/// winner + the first distinct-placement runner-up off that set.
293pub struct PlacementForkPathfinder;
294
295impl Pathfinder for PlacementForkPathfinder {
296 fn name(&self) -> &'static str {
297 "PlacementForkSeed"
298 }
299
300 fn propose(&self, graph: &mut Graph, ctx: &OptimizationContext<'_>) -> Result<()> {
301 // Consumer count over the realize-reachable set: a fork must
302 // have exactly one consumer (its reconverge); ≥2 is plain
303 // fan-out, not a decision point.
304 let mut consumer_count: HashMap<NodeId, usize> = HashMap::new();
305 let mut sole_consumer: HashMap<NodeId, NodeId> = HashMap::new();
306 for &id in ctx.order {
307 for &input in &graph.node(id).inputs {
308 *consumer_count.entry(input).or_insert(0) += 1;
309 sole_consumer.insert(input, id);
310 }
311 }
312
313 // Collect the fork specs first (immutable borrow of the plan),
314 // then mutate the graph — `open_branch`/`finalize_branches` need
315 // `&mut`.
316 struct ForkSpec {
317 fork: NodeId,
318 diverge: NodeId,
319 reconverge: NodeId,
320 runner_up_backend: BackendId,
321 }
322 let mut specs: Vec<ForkSpec> = Vec::new();
323
324 for &id in ctx.order {
325 let Some(set) = ctx.plan.alternatives(id) else {
326 continue;
327 };
328 // (1) A genuine ≥2-placement choice: two or more distinct
329 // (backend, device) pairs admitted by the DP/ranker.
330 let winner = match set.winner() {
331 Some(w) => (w.backend, w.device),
332 None => continue,
333 };
334 let runner_up = set
335 .alternatives()
336 .iter()
337 .map(|c| (c.backend, c.device))
338 .find(|&p| p != winner);
339 let Some((ru_backend, _ru_device)) = runner_up else {
340 continue;
341 };
342
343 // (2) A producer to serve as the shared diverge point.
344 let Some(&diverge) = graph.node(id).inputs.first() else {
345 continue;
346 };
347
348 // (3) Exactly one consumer ⇒ deliberate fork (becomes the
349 // reconverge); ≥2 ⇒ ordinary fan-out, skip.
350 if consumer_count.get(&id).copied().unwrap_or(0) != 1 {
351 continue;
352 }
353 let reconverge = sole_consumer[&id];
354
355 specs.push(ForkSpec {
356 fork: id,
357 diverge,
358 reconverge,
359 runner_up_backend: ru_backend,
360 });
361 }
362
363 for spec in specs {
364 // arm-1: a runner-up-placement clone of the fork's op reading
365 // the same inputs. Orphaned (read only by the Branch) so the
366 // live data flow is untouched and arm-0 = the original winner.
367 let (op, inputs, shape, dtype) = {
368 let n = graph.node(spec.fork);
369 (n.op.clone(), n.inputs.clone(), n.shape.clone(), n.dtype)
370 };
371 let arm1 = graph.push(Node {
372 op,
373 inputs,
374 shape,
375 dtype,
376 });
377 graph.set_target_backend(arm1, spec.runner_up_backend);
378
379 // Record the fork as a 2-arm Branch: arm-0 = the DP winner
380 // (`fork`), arm-1 = the runner-up clone. A1 validates
381 // descendant reconverge, internal disjointness, uniform
382 // dtype, and arm-0 runnability; it never panics — a rejection
383 // surfaces as a typed `Error::InvalidBranch`.
384 //
385 // A rejection is **non-fatal**: the branch is only a
386 // *recording* of an alternative placement, so a candidate
387 // fork whose surrounding graph shape happens to violate an A1
388 // invariant is simply NOT recorded — realize proceeds on the
389 // unchanged single route. The orphaned `arm1` clone left
390 // behind is unreachable from any realize root, so it never
391 // dispatches and never affects the result.
392 let mut builder = graph.open_branch(spec.diverge);
393 builder.add_arm(spec.fork); // arm-0 = winner
394 builder.add_arm(arm1); // arm-1 = runner-up
395 let _ = builder.finalize_branches(graph, spec.reconverge);
396 }
397
398 Ok(())
399 }
400}
401
402/// The PR-B2 per-device-frontier optimizer, re-expressed as a registered
403/// [`Optimizer`]. It runs **after** each pathfinder (lock-step) and is
404/// the in-graph MERGE/DISCARD counterpart of
405/// [`AlternativeSet::retain_per_device_frontier`](
406/// crate::ranker::AlternativeSet::retain_per_device_frontier), which is
407/// applied per kernel-bearing node *inside*
408/// [`compile_plan`](crate::plan::compile_plan).
409///
410/// Its two responsibilities:
411///
412/// 1. **Duplicate-path convergence (the trivial MERGE optimizer).**
413/// Detect any two arms of a just-emitted `Op::Branch` that are
414/// *forward-identical* — same op, same inputs, same target backend.
415/// Two pathfinders (or one pathfinder firing twice) could in
416/// principle propose structurally-identical routes; the constitution
417/// requires *"convergence merges only forward-identical paths"*. The
418/// PR-A4 seed proposes one runner-up per fork, distinct from arm-0 by
419/// construction (different `target_backend`), so today no duplicate
420/// arm ever arises and this detection is a no-op — it is the trivial
421/// second optimizer the spec calls for, in place (with a debug
422/// assertion that it stays a no-op) so the contract is documented and
423/// enforced before a future multi-runner-up pathfinder can leak a
424/// duplicate arm into a branch.
425///
426/// 2. **Invariant guard (the never-strand / no-active-cycle contract).**
427/// Assert that every `Op::Branch` keeps ≥1 viable `(device, backend)`
428/// route — never strand the last path (upheld by the per-node frontier
429/// inside `compile_plan`, re-asserted here over the in-graph form) —
430/// and that no branch the optimizer would touch is in `ctx.cycle_guard`
431/// (the incremental-reopt contract — batch optimize has an empty
432/// guard, but the guard documents and enforces the rule for the
433/// Phase-C runtime).
434pub struct FrontierConvergenceOptimizer;
435
436impl FrontierConvergenceOptimizer {
437 /// Forward-identical key of an arm: `(op, inputs, target_backend)`.
438 /// Two arms with equal keys are the same route and would be merged
439 /// by duplicate-path convergence.
440 fn arm_key(graph: &Graph, id: NodeId) -> (String, Vec<NodeId>, Option<BackendId>) {
441 let n = graph.node(id);
442 (
443 format!("{:?}", n.op),
444 n.inputs.clone(),
445 graph.target_backend(id),
446 )
447 }
448
449 /// Count of *distinct* (forward-identical-deduplicated) arms among
450 /// `arms`. arm-0 always counts; a later arm equal to an earlier one
451 /// does not. Equal to `arms.len()` exactly when every arm is a
452 /// distinct route.
453 fn distinct_arm_count(graph: &Graph, arms: &[NodeId]) -> usize {
454 let mut seen: Vec<(String, Vec<NodeId>, Option<BackendId>)> = Vec::new();
455 for &arm in arms {
456 let k = Self::arm_key(graph, arm);
457 if !seen.contains(&k) {
458 seen.push(k);
459 }
460 }
461 seen.len()
462 }
463}
464
465impl Optimizer for FrontierConvergenceOptimizer {
466 fn name(&self) -> &'static str {
467 "FrontierConvergence"
468 }
469
470 fn prune(&self, graph: &mut Graph, ctx: &OptimizationContext<'_>) -> Result<()> {
471 // Scan the in-graph branches. The per-device Pareto frontier
472 // proper is applied per kernel-bearing node *inside* compile_plan
473 // (PR-B2); here we run its in-graph counterpart — duplicate-path
474 // convergence + the never-strand / no-active-cycle invariant
475 // guards.
476 let n = graph.len();
477 let mut branches: Vec<(NodeId, Vec<NodeId>)> = Vec::new();
478 for i in 0..n {
479 let id = NodeId(i);
480 if matches!(graph.node(id).op, Op::Branch { .. }) {
481 branches.push((id, graph.node(id).inputs.clone()));
482 }
483 }
484
485 for (branch_id, arms) in branches {
486 // Invariant guard (incremental-reopt contract): never touch a
487 // branch whose decision point or any arm is on an active
488 // cycle / currently-executing region. Batch optimize has an
489 // empty guard, so this never trips here; it enforces the
490 // contract for the Phase-C runtime incremental re-opt.
491 if ctx.cycle_guard.contains(&branch_id)
492 || arms.iter().any(|a| ctx.cycle_guard.contains(a))
493 {
494 continue;
495 }
496
497 // (1) Duplicate-path convergence: count distinct routes.
498 let distinct = Self::distinct_arm_count(graph, &arms);
499
500 // (2) Invariant: never strand the last path — a branch always
501 // keeps ≥1 viable `(device, backend)` route.
502 debug_assert!(
503 distinct >= 1,
504 "FrontierConvergence: branch {branch_id:?} would strand to zero routes",
505 );
506
507 // The shipped PR-A4 pathfinder emits arm-1 on a distinct
508 // backend from arm-0, so every arm is a distinct route and no
509 // merge is needed. Assert that — if a future pathfinder leaks
510 // a forward-identical arm, this fires and signals that an
511 // in-place arm-rewrite (a `fuel-graph` setter) must land with
512 // it. We deliberately do NOT silently rewrite arms here in B3
513 // (it would need a new `fuel-graph` mutation API and is a
514 // behavior change for a case that cannot arise from the
515 // shipped passes) — B3 is a structural refactor only.
516 debug_assert_eq!(
517 distinct,
518 arms.len(),
519 "FrontierConvergence: branch {branch_id:?} has forward-identical arms \
520 ({} distinct of {}); a multi-route pathfinder leaked a duplicate — \
521 land an in-graph arm-merge with it",
522 distinct,
523 arms.len(),
524 );
525 }
526
527 Ok(())
528 }
529}