1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The `optimize_graph` lock-step pass driver — Phase B PR-B3 of the
//! "plan IS the graph" rebuild
//! ([`../../docs/session-prompts/plan-is-graph-rebuild.md`](
//! ../../docs/session-prompts/plan-is-graph-rebuild.md) capability 5;
//! [`../../docs/architecture/04-optimization.md`](
//! ../../docs/architecture/04-optimization.md) §"The two-stage
//! transformation", §"Relationship to PR 3").
//!
//! ## What this is
//!
//! `optimize_graph` was a hardcoded sequence — `execution_plan` order →
//! [`compile_plan`](crate::plan::compile_plan) (per-node placement +
//! cost ranking + the PR-B2 per-ending-device Pareto frontier) →
//! `seed_placement_fork_branches` (the PR-A4 deliberate-fork
//! pathfinder). PR-B3 restructures that sequence into a **lock-step
//! driver** over three registered pass *kinds*, mirroring the shape of
//! `fuel_graph::opt::RuleRegistry` (a `Vec<Box<dyn …>>` of passes +
//! builder + a driver method that walks them) so future passes (fusion,
//! algebraic, dtype-lowering) plug in without rewriting the loop:
//!
//! - **[`Pathfinder`]s** — *ADD* candidate paths / branches to the
//! graph. The PR-A4 [`PlacementForkPathfinder`] (deliberate-fork seed,
//! the one pathfinder that records an `Op::Branch` per genuine
//! multi-placement fork) is the first registered pathfinder.
//! - **Rankers** — *MEASURE* each path on the `CostVector` (PR-B1/B2
//! `rank_by_cost`). Rankers are not a driver-visible trait in B3:
//! ranking is applied **per kernel-bearing node inside
//! [`crate::plan::compile_plan`]** as the per-node `AlternativeSet` is built, and
//! the ranked result is carried into the driver via
//! [`OptimizationContext::plan`]. The driver re-runs no ranker; the
//! measure step is the plan it is handed. (B3 is a structural refactor
//! — when a later PR adds a pathfinder that emits *new* candidates the
//! plan never priced, that is the point to lift ranking into a
//! driver-visible `Ranker` trait.)
//! - **[`Optimizer`]s** — *MERGE / DISCARD* paths. The PR-B2
//! per-ending-device Pareto frontier + crowding cap is applied
//! per-node inside [`crate::plan::compile_plan`]; the registered
//! [`FrontierConvergenceOptimizer`] is the in-graph counterpart that
//! runs **after each pathfinder** to (a) collapse duplicate
//! (forward-identical) arms a pathfinder may have proposed
//! [duplicate-path convergence], and (b) assert the optimizer
//! invariants the constitution requires — never strand the last
//! `(device, backend)` path, never mutate a node in an active cycle /
//! currently-executing region.
//!
//! ## Lock-step / prune-as-you-go (the constitution's bound)
//!
//! The driver runs the passes interleaved, **not** explode-then-extract:
//! for each registered pathfinder, it ADDs its candidate paths, then
//! immediately runs every registered optimizer to prune the region the
//! pathfinder just touched, before moving to the next pathfinder. This
//! is the [`PassRegistry::run_lockstep`] contract — the working set
//! never explodes-then-extracts, so it stays bounded by construction
//! (per [`../../docs/architecture/04-optimization.md`](
//! ../../docs/architecture/04-optimization.md) §"Bounding the
//! frontier": *"run the merge/discard optimizers after each pathfinder
//! step, not once at the end"*).
//!
//! ## Behavior preservation (B3 is a structural refactor)
//!
//! The optimized result — the arm-0 winner, the retained per-device
//! frontier (applied inside `compile_plan`, unchanged), and the emitted
//! `Op::Branch` nodes — is **identical** to the pre-B3 hardcoded
//! sequence on every graph. The driver is the same three operations in
//! the same order; the only change is that they are reached through the
//! registry rather than inlined. The load-bearing
//! `driver_matches_legacy_sequence` test in
//! [`crate::optimize`] proves it on a representative multi-placement
//! graph.
use ;
use ;
use Result;
use BackendId;
use crateKernelBindingTable;
use crateExecutionPlan;
/// Read-only context threaded to every [`Pathfinder::propose`] and
/// [`Optimizer::prune`] call during a [`PassRegistry::run_lockstep`]
/// drive.
///
/// It carries the **measure** stage's output — the ranked, per-device
/// frontier-pruned per-node `AlternativeSet`s [`compile_plan`] produced
/// ([`Self::plan`]) plus the dispatch [`Self::order`] — and the
/// **incremental-reopt guard** ([`Self::cycle_guard`]): the set of nodes
/// that lie on an active cycle or in a currently-executing region and so
/// must never be mutated by an optimizer. Batch `optimize_graph` has no
/// executing region, so the guard is empty there; it exists to document
/// and enforce the incremental-reopt contract for the Phase-C runtime.
///
/// [`compile_plan`]: crate::plan::compile_plan
/// A **pathfinder** *ADDs* candidate paths / branches to the graph. The
/// PR-A4 deliberate-fork seed ([`PlacementForkPathfinder`]) is the first
/// registered pathfinder; later pathfinders (fusion, algebraic,
/// dtype-lowering under tolerance, layout fixups) implement the same
/// trait and register the same way.
///
/// `propose` may append nodes and record `Op::Branch` decision points
/// (via the `fuel-graph` A1 builders). It must never *remove* a path —
/// that is an [`Optimizer`]'s job — and it returns `Result` so a
/// build-time failure surfaces (never panic, per the working agreement).
/// An **optimizer** *MERGEs / DISCARDs* paths. The PR-B2 per-device
/// Pareto frontier is applied per-node inside
/// [`compile_plan`](crate::plan::compile_plan); the registered
/// [`FrontierConvergenceOptimizer`] is its in-graph counterpart that
/// runs after each pathfinder to collapse duplicate (forward-identical)
/// arms and enforce the optimizer invariants.
///
/// `prune` runs **after** each [`Pathfinder::propose`] (lock-step), so
/// the working set never explodes-then-extracts. It must honor the
/// optimizer invariants: never strand the last `(device, backend)` path,
/// and never mutate a node in `ctx.cycle_guard`.
/// A registry of [`Pathfinder`]s and [`Optimizer`]s, driven lock-step by
/// [`Self::run_lockstep`]. Mirrors `fuel_graph::opt::RuleRegistry`: a
/// `Vec<Box<dyn …>>` of passes built up with `with_*` builders and run
/// through one driver method. Keeping the same shape means the future
/// passes the constitution names (fusion, algebraic, dtype-lowering)
/// register exactly as the two shipped passes do.
/// The PR-A4 deliberate-fork pathfinder, re-expressed as a registered
/// [`Pathfinder`]. Scans the ranked plan for nodes the placement DP /
/// ranker admitted with **≥2 distinct `(backend, device)` placements** —
/// a genuine placement choice — and records each as ONE `Op::Branch` via
/// the `fuel-graph` A1 builders (arm-0 = the DP winner, arm-1 = the
/// runner-up clone, orphaned so the live data flow is untouched and the
/// realize result is identical).
///
/// This is **the same logic** the pre-B3 `seed_placement_fork_branches`
/// free function ran — moved verbatim behind the trait. The
/// deliberate-fork gate (real ≥2-placement choice, a producer to
/// diverge from, exactly one consumer to reconverge at) is unchanged, so
/// the fewness gate still holds and a CPU-only build emits zero branches.
///
/// **No `DEFAULT_MAX_N` / fixed top-N anywhere** — the bound is the
/// per-device frontier the plan already carries; this pass reads the
/// winner + the first distinct-placement runner-up off that set.
;
/// The PR-B2 per-device-frontier optimizer, re-expressed as a registered
/// [`Optimizer`]. It runs **after** each pathfinder (lock-step) and is
/// the in-graph MERGE/DISCARD counterpart of
/// [`AlternativeSet::retain_per_device_frontier`](
/// crate::ranker::AlternativeSet::retain_per_device_frontier), which is
/// applied per kernel-bearing node *inside*
/// [`compile_plan`](crate::plan::compile_plan).
///
/// Its two responsibilities:
///
/// 1. **Duplicate-path convergence (the trivial MERGE optimizer).**
/// Detect any two arms of a just-emitted `Op::Branch` that are
/// *forward-identical* — same op, same inputs, same target backend.
/// Two pathfinders (or one pathfinder firing twice) could in
/// principle propose structurally-identical routes; the constitution
/// requires *"convergence merges only forward-identical paths"*. The
/// PR-A4 seed proposes one runner-up per fork, distinct from arm-0 by
/// construction (different `target_backend`), so today no duplicate
/// arm ever arises and this detection is a no-op — it is the trivial
/// second optimizer the spec calls for, in place (with a debug
/// assertion that it stays a no-op) so the contract is documented and
/// enforced before a future multi-runner-up pathfinder can leak a
/// duplicate arm into a branch.
///
/// 2. **Invariant guard (the never-strand / no-active-cycle contract).**
/// Assert that every `Op::Branch` keeps ≥1 viable `(device, backend)`
/// route — never strand the last path (upheld by the per-node frontier
/// inside `compile_plan`, re-asserted here over the in-graph form) —
/// and that no branch the optimizer would touch is in `ctx.cycle_guard`
/// (the incremental-reopt contract — batch optimize has an empty
/// guard, but the guard documents and enforces the rule for the
/// Phase-C runtime).
;