semi-persistent-egraph 0.3.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
Documentation
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Lexicographic min-cost transportation solver for AC/ACI matching (§3.4.4).
//!
//! Problem: rows with supplies `m_i`, columns with demands `n_j` (equal totals),
//! per-cell lexicographic cost `(size, variant_mass)` or a forbidden marker.
//! Find an integral flow meeting every margin that minimizes
//! `(Σ x_ij·s_ij, Σ x_ij·v_ij)` lexicographically, or report infeasibility.
//!
//! The lexicographic objective is scalarized: `cost = s·W + v` with
//! `W = F·v_max + 1` where `F` is the total transported multiplicity and
//! `v_max` the maximum cell variant mass. Total variant mass never exceeds
//! `F·v_max`, so a one-unit size improvement always outweighs any possible
//! variant-mass difference. All arithmetic is checked `u128`; with `u32`
//! inputs the worst-case total cost is far below `u128::MAX` for any
//! realistic multiplicity, and overflow panics with a diagnostic rather
//! than wrapping.
//!
//! Algorithm: successive shortest augmenting paths (Bellman-Ford/SPFA, which
//! tolerates the negative residual reverse edges without potentials), with
//! bottleneck augmentation so large multiplicities move in one step instead
//! of unit-at-a-time. Determinism: nodes and edges are relaxed in fixed index
//! order with strict-less updates, so equal-cost ties resolve to the first
//! (lowest-index) candidate; the returned matrix is a deterministic function
//! of the input.
//!
//! Every entry point solves in exact integer arithmetic. MCGS Q estimates
//! arrive pre-quantized through [`solve_transport_quantized`]; the successive
//! shortest-paths termination argument requires exact cost comparisons, so
//! this module accepts no float costs.

/// One cell of the transportation cost matrix.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cell {
    /// Allowed pairing with lexicographic cost (size, variant_mass).
    Cost(u32, u32),
    /// Forbidden pairing (cycle-blocked).
    Forbidden,
}

/// A transportation problem instance.
///
/// Supplies and demands are `u32`: this is the solver's own capacity limit, not
/// the e-graph's multiplicity width. Internally each cell capacity becomes an
/// `i64` and the objective a `u128`, both of which have headroom above `u32`,
/// but the flow matrix and the supply vectors do not. Callers holding
/// surface-width multiplicities must come through [`TransportProblem::narrowed`]
/// rather than casting.
#[derive(Clone, Debug)]
pub struct TransportProblem {
    pub row_supply: Vec<u32>,
    pub col_demand: Vec<u32>,
    /// `cost[i][j]` for row i, column j. Dimensions rows x cols.
    pub cost: Vec<Vec<Cell>>,
}

impl TransportProblem {
    /// Build from surface-width (`u64`) supplies and demands, or `None` if any
    /// exceeds the solver's `u32` capacity.
    ///
    /// `None` is the same signal [`solve_transport`] gives for an infeasible
    /// instance, and every caller already treats that as "this representation
    /// pair does not yield an action". An unrepresentable supply is genuinely
    /// unsolvable *by this solver*, so reporting it as infeasible loses only
    /// candidate generalizations — never soundness. Truncating instead would
    /// solve a different problem and report its cost as this one's.
    pub fn narrowed(row_supply: &[u64], col_demand: &[u64], cost: Vec<Vec<Cell>>) -> Option<Self> {
        let narrow =
            |v: &[u64]| -> Option<Vec<u32>> { v.iter().map(|&n| u32::try_from(n).ok()).collect() };
        Some(TransportProblem {
            row_supply: narrow(row_supply)?,
            col_demand: narrow(col_demand)?,
            cost,
        })
    }
}

/// An optimal solution: the matching-count matrix and its total quality.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransportSolution {
    /// `flow[i][j]` = number of copies pairing row i with column j.
    pub flow: Vec<Vec<u32>>,
    /// Total (Σ x·s, Σ x·v) as u128 to handle large multiplicities without
    /// overflow. The caller adds the +1 operator cost.
    pub total: (u128, u128),
}

struct Edge {
    to: usize,
    cap: i64,
    cost: i128,
    /// Signed net flow: augmenting the forward edge by d does
    /// `flow[e] += d; flow[e^1] -= d`, so a reverse edge with cap 0 gains
    /// residual capacity exactly equal to the cancellable forward flow.
    flow: i64,
}

struct Network {
    edges: Vec<Edge>,
    /// adjacency: per node, indices into `edges` (each edge is paired with its
    /// reverse at index ^ 1).
    adj: Vec<Vec<usize>>,
}

impl Network {
    fn new(nodes: usize) -> Self {
        Network {
            edges: Vec::new(),
            adj: vec![Vec::new(); nodes],
        }
    }

    fn add_edge(&mut self, from: usize, to: usize, cap: u32, cost: i128) {
        let idx = self.edges.len();
        self.edges.push(Edge {
            to,
            cap: cap as i64,
            cost,
            flow: 0,
        });
        self.edges.push(Edge {
            to: from,
            cap: 0,
            cost: -cost,
            flow: 0,
        });
        self.adj[from].push(idx);
        self.adj[to].push(idx + 1);
    }

    fn residual(&self, e: usize) -> i64 {
        self.edges[e].cap - self.edges[e].flow
    }
}

/// Solve a transportation problem whose cell costs are already signed
/// integers (quantized MCGS Q values). `Some(cost)` marks an allowed cell,
/// `None` a forbidden one. Returns only the argmin flow matrix; the caller
/// re-derives its objective from the flow at whatever precision it owns.
///
/// Margins are `u32` for the same reason [`TransportProblem`]'s are: the sole
/// caller reads them back out of the AND node's stored `transport_rows` /
/// `transport_cols`, which were moved out of the very [`TransportProblem`]
/// the feasibility gate ran, so they already passed the one narrowing check.
///
/// Exact `i128` arithmetic is a termination requirement, not a precision
/// nicety: with f64 costs, two mathematically-equal path sums can differ by
/// one ulp, an augmentation along such a path leaves a residual cycle whose
/// computed cost is negative, and SPFA's strict-less relaxation then
/// decreases `dist` around that cycle forever. Integer costs make every
/// augmentation a true shortest path, so the residual graph stays free of
/// negative cycles and the successive-shortest-paths argument holds.
pub fn solve_transport_quantized(
    row_supply: &[u32],
    col_demand: &[u32],
    cost: &[Vec<Option<i128>>],
) -> Option<Vec<Vec<u32>>> {
    solve_cells(row_supply, col_demand, cost)
}

/// Solve the transportation problem. Returns `None` if infeasible (the margins
/// cannot be met using only allowed cells) and panics on arithmetic overflow
/// (unreachable for realistic u32 inputs).
pub fn solve_transport(p: &TransportProblem) -> Option<TransportSolution> {
    let rows = p.row_supply.len();
    let cols = p.col_demand.len();

    // Scalarization constants (checked). `f` uses the row total; on
    // mismatched margins the core returns None before any cost is read.
    let f: u128 = p.row_supply.iter().map(|&m| m as u128).sum();
    let v_max: u128 = p
        .cost
        .iter()
        .flatten()
        .filter_map(|c| match c {
            Cell::Cost(_, v) => Some(*v as u128),
            Cell::Forbidden => None,
        })
        .max()
        .unwrap_or(0);
    let w: u128 = f
        .checked_mul(v_max)
        .and_then(|x| x.checked_add(1))
        .expect("transport scalarization overflow (W)");

    let mut cost: Vec<Vec<Option<i128>>> = vec![vec![None; cols]; rows];
    for i in 0..rows {
        for j in 0..cols {
            if let Cell::Cost(s, v) = p.cost[i][j] {
                let scalar: u128 = (s as u128)
                    .checked_mul(w)
                    .and_then(|x| x.checked_add(v as u128))
                    .expect("transport scalarization overflow (cell)");
                cost[i][j] =
                    Some(i128::try_from(scalar).expect("transport scalar cost exceeds i128"));
            }
        }
    }

    let flow = solve_cells(&p.row_supply, &p.col_demand, &cost)?;

    // Extract the total quality from the flow.
    let mut total_s: u128 = 0;
    let mut total_v: u128 = 0;
    for i in 0..rows {
        for j in 0..cols {
            let x = flow[i][j];
            if x > 0
                && let Cell::Cost(s, v) = p.cost[i][j]
            {
                total_s += x as u128 * s as u128;
                total_v += x as u128 * v as u128;
            }
        }
    }

    Some(TransportSolution {
        flow,
        total: (total_s, total_v),
    })
}

/// Successive shortest augmenting paths over integer cell costs: the shared
/// core of [`solve_transport`] and [`solve_transport_quantized`]. Returns the
/// min-cost flow matrix meeting every margin, or `None` if the margins cannot
/// be met using only allowed cells. Panics on distance overflow (checked
/// `i128` adds).
fn solve_cells(
    row_supply: &[u32],
    col_demand: &[u32],
    cost: &[Vec<Option<i128>>],
) -> Option<Vec<Vec<u32>>> {
    let rows = row_supply.len();
    let cols = col_demand.len();
    if rows == 0 || cols == 0 {
        return None;
    }
    let total_supply: u64 = row_supply.iter().map(|&m| m as u64).sum();
    let total_demand: u64 = col_demand.iter().map(|&n| n as u64).sum();
    if total_supply != total_demand {
        return None;
    }
    if total_supply == 0 {
        return Some(vec![vec![0; cols]; rows]);
    }

    // Nodes: source=0, rows 1..=rows, cols rows+1..=rows+cols, sink=rows+cols+1.
    let source = 0usize;
    let sink = rows + cols + 1;
    let mut net = Network::new(rows + cols + 2);

    for (i, &m) in row_supply.iter().enumerate() {
        net.add_edge(source, 1 + i, m, 0);
    }
    for (j, &n) in col_demand.iter().enumerate() {
        net.add_edge(1 + rows + j, sink, n, 0);
    }
    // Remember the edge index of each (i,j) cell for flow extraction.
    let mut cell_edge: Vec<Vec<Option<usize>>> = vec![vec![None; cols]; rows];
    for i in 0..rows {
        for j in 0..cols {
            if let Some(c) = cost[i][j] {
                let cap = row_supply[i].min(col_demand[j]);
                if cap > 0 {
                    cell_edge[i][j] = Some(net.edges.len());
                    net.add_edge(1 + i, 1 + rows + j, cap, c);
                }
            }
        }
    }

    // Successive shortest augmenting paths with SPFA and bottleneck augmentation.
    let n_nodes = rows + cols + 2;
    // Debug-build relaxation budget: without negative residual cycles, SPFA's
    // successful relaxations per solve stay within the Bellman-Ford count
    // (n_nodes passes over every edge). A breach means the exact-arithmetic
    // invariant broke and the loop would otherwise spin; fail loudly instead.
    let relaxation_budget = (n_nodes as u64).saturating_mul(net.edges.len() as u64);
    let mut pushed_total: u64 = 0;
    loop {
        // SPFA from source: dist, parent edge.
        let mut dist: Vec<Option<i128>> = vec![None; n_nodes];
        let mut parent_edge: Vec<Option<usize>> = vec![None; n_nodes];
        let mut in_queue = vec![false; n_nodes];
        let mut queue = std::collections::VecDeque::new();
        dist[source] = Some(0);
        queue.push_back(source);
        in_queue[source] = true;

        let mut relaxations: u64 = 0;
        while let Some(u) = queue.pop_front() {
            in_queue[u] = false;
            let du = dist[u].unwrap();
            for &e in &net.adj[u] {
                if net.residual(e) == 0 {
                    continue;
                }
                let v = net.edges[e].to;
                let nd = du
                    .checked_add(net.edges[e].cost)
                    .expect("transport distance overflow");
                // Strict-less relaxation: deterministic first-found ties.
                if dist[v].is_none() || nd < dist[v].unwrap() {
                    relaxations += 1;
                    debug_assert!(
                        relaxations <= relaxation_budget,
                        "SPFA relaxations exceeded the Bellman-Ford bound: \
                         negative residual cycle (broken cost invariant)"
                    );
                    dist[v] = Some(nd);
                    parent_edge[v] = Some(e);
                    if !in_queue[v] {
                        queue.push_back(v);
                        in_queue[v] = true;
                    }
                }
            }
        }

        if dist[sink].is_none() {
            break; // no augmenting path
        }

        // Bottleneck along the path.
        let mut bottleneck = i64::MAX;
        let mut node = sink;
        while node != source {
            let e = parent_edge[node].unwrap();
            bottleneck = bottleneck.min(net.residual(e));
            // The edge e enters `node`; its reverse (e^1) points back.
            node = net.edges[e ^ 1].to;
        }
        debug_assert!(bottleneck > 0);

        // Apply: standard signed-flow update. Pushing d along e cancels d units
        // of any flow on the reverse edge (flow[e^1] -= d), which is what makes
        // residual(e^1) = cap - flow correct for both directions.
        let mut node = sink;
        while node != source {
            let e = parent_edge[node].unwrap();
            net.edges[e].flow += bottleneck;
            net.edges[e ^ 1].flow -= bottleneck;
            node = net.edges[e ^ 1].to;
        }
        pushed_total += bottleneck as u64;
        if pushed_total == total_supply {
            break;
        }
    }

    if pushed_total != total_supply {
        return None; // infeasible: margins cannot be met with allowed cells
    }

    // Extract the flow matrix.
    let mut flow = vec![vec![0u32; cols]; rows];
    for i in 0..rows {
        for j in 0..cols {
            if let Some(e) = cell_edge[i][j] {
                let x = net.edges[e].flow;
                debug_assert!(x >= 0, "forward cell edge cannot end with negative flow");
                if x > 0 {
                    flow[i][j] = u32::try_from(x).expect("cell flow exceeds u32");
                }
            }
        }
    }
    Some(flow)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Exhaustive reference: enumerate every feasible integer matrix, return
    /// the lexicographic minimum total quality (or None if infeasible).
    fn exhaustive_min(p: &TransportProblem) -> Option<(u128, u128)> {
        let rows = p.row_supply.len();
        let cols = p.col_demand.len();
        let mut best: Option<(u128, u128)> = None;
        let mut matrix = vec![vec![0u32; cols]; rows];
        let mut col_residual = p.col_demand.clone();

        fn rec(
            p: &TransportProblem,
            matrix: &mut Vec<Vec<u32>>,
            col_residual: &mut Vec<u32>,
            row: usize,
            best: &mut Option<(u128, u128)>,
        ) {
            let rows = p.row_supply.len();
            let cols = p.col_demand.len();
            if row == rows {
                if col_residual.iter().any(|&c| c != 0) {
                    return;
                }
                let mut s: u128 = 0;
                let mut v: u128 = 0;
                for i in 0..rows {
                    for j in 0..cols {
                        let x = matrix[i][j];
                        if x > 0 {
                            match p.cost[i][j] {
                                Cell::Cost(cs, cv) => {
                                    s += x as u128 * cs as u128;
                                    v += x as u128 * cv as u128;
                                }
                                Cell::Forbidden => return, // invalid matrix
                            }
                        }
                    }
                }
                let q = (s, v);
                if best.is_none() || q < best.unwrap() {
                    *best = Some(q);
                }
                return;
            }
            // Distribute row `row` across columns.
            fn dist(
                p: &TransportProblem,
                matrix: &mut Vec<Vec<u32>>,
                col_residual: &mut Vec<u32>,
                row: usize,
                col: usize,
                remaining: u32,
                best: &mut Option<(u128, u128)>,
            ) {
                let cols = p.col_demand.len();
                if col == cols {
                    if remaining == 0 {
                        rec(p, matrix, col_residual, row + 1, best);
                    }
                    return;
                }
                let max = remaining.min(col_residual[col]);
                for x in 0..=max {
                    if x > 0 && matches!(p.cost[row][col], Cell::Forbidden) {
                        break;
                    }
                    matrix[row][col] = x;
                    col_residual[col] -= x;
                    dist(p, matrix, col_residual, row, col + 1, remaining - x, best);
                    col_residual[col] += x;
                    matrix[row][col] = 0;
                }
            }
            dist(p, matrix, col_residual, row, 0, p.row_supply[row], best);
        }

        rec(p, &mut matrix, &mut col_residual, 0, &mut best);
        best
    }

    fn check_margins(p: &TransportProblem, sol: &TransportSolution) {
        for (i, &m) in p.row_supply.iter().enumerate() {
            let row_sum: u32 = sol.flow[i].iter().sum();
            assert_eq!(row_sum, m, "row {i} margin violated");
        }
        for (j, &n) in p.col_demand.iter().enumerate() {
            let col_sum: u32 = sol.flow.iter().map(|r| r[j]).sum();
            assert_eq!(col_sum, n, "col {j} margin violated");
        }
        for (i, row) in sol.flow.iter().enumerate() {
            for (j, &x) in row.iter().enumerate() {
                if x > 0 {
                    assert!(
                        matches!(p.cost[i][j], Cell::Cost(_, _)),
                        "flow on forbidden cell ({i},{j})"
                    );
                }
            }
        }
    }

    #[test]
    fn trivial_1x1() {
        let p = TransportProblem {
            row_supply: vec![3],
            col_demand: vec![3],
            cost: vec![vec![Cell::Cost(2, 1)]],
        };
        let sol = solve_transport(&p).unwrap();
        assert_eq!(sol.flow, vec![vec![3]]);
        assert_eq!(sol.total, (6, 3));
    }

    #[test]
    fn intersection_counterexample_costs() {
        // The [2,1] x [2,1] instance with the cross vertex optimal:
        // costs: (0,0)=3 self-pair X-X; (0,1)=4 X-Z; (1,0)=4 Y-X; (1,1)=6 Y-Z.
        // Diagonal matrix [[2,0],[0,1]] costs 2*3 + 6 = 12? No: X appears twice
        // in acop{X,X,Y}? Use the actual margins from the counterexample:
        // left {X^2, Y}, right {X^2, Z}... simplified to [2,1] margins:
        let p = TransportProblem {
            row_supply: vec![2, 1],
            col_demand: vec![2, 1],
            cost: vec![
                vec![Cell::Cost(3, 0), Cell::Cost(4, 2)],
                vec![Cell::Cost(4, 2), Cell::Cost(6, 6)],
            ],
        };
        let sol = solve_transport(&p).unwrap();
        check_margins(&p, &sol);
        // Diagonal: 2*3 + 1*6 = 12. Cross: 1*3 + 1*4 + 1*4 = 11.
        assert_eq!(sol.total.0, 11, "the cross matching must win");
        assert_eq!(sol.flow, vec![vec![1, 1], vec![1, 0]]);
    }

    #[test]
    fn forbidden_cell_forces_detour() {
        let p = TransportProblem {
            row_supply: vec![1, 1],
            col_demand: vec![1, 1],
            cost: vec![
                vec![Cell::Cost(1, 0), Cell::Cost(10, 0)],
                vec![Cell::Forbidden, Cell::Cost(1, 0)],
            ],
        };
        // Row 1 can only go to col 1, so row 0 must take col 0: total 2.
        let sol = solve_transport(&p).unwrap();
        check_margins(&p, &sol);
        assert_eq!(sol.total, (2, 0));
    }

    #[test]
    fn infeasible_when_column_unreachable() {
        let p = TransportProblem {
            row_supply: vec![1, 1],
            col_demand: vec![1, 1],
            cost: vec![
                vec![Cell::Cost(1, 0), Cell::Forbidden],
                vec![Cell::Cost(1, 0), Cell::Forbidden],
            ],
        };
        assert!(solve_transport(&p).is_none());
    }

    #[test]
    fn hall_style_infeasibility() {
        // Every row and column has an edge, but capacity constraints fail:
        // rows 0,1 (supply 2 each) can only reach col 0 (demand 1).
        let p = TransportProblem {
            row_supply: vec![2, 2],
            col_demand: vec![1, 3],
            cost: vec![
                vec![Cell::Cost(1, 0), Cell::Forbidden],
                vec![Cell::Cost(1, 0), Cell::Cost(1, 0)],
            ],
        };
        // Row 0 needs 2 units into col 0 (demand 1): infeasible.
        assert!(solve_transport(&p).is_none());
    }

    #[test]
    fn lexicographic_vmass_tiebreak() {
        // Two flows with equal size totals; vmass must decide.
        let p = TransportProblem {
            row_supply: vec![1, 1],
            col_demand: vec![1, 1],
            cost: vec![
                // diagonal: sizes 5+5=10, vmass 3+3=6
                // crossed:  sizes 5+5=10, vmass 1+1=2
                vec![Cell::Cost(5, 3), Cell::Cost(5, 1)],
                vec![Cell::Cost(5, 1), Cell::Cost(5, 3)],
            ],
        };
        let sol = solve_transport(&p).unwrap();
        check_margins(&p, &sol);
        assert_eq!(sol.total, (10, 2), "vmass must break the size tie");
    }

    #[test]
    fn zero_cost_cells() {
        let p = TransportProblem {
            row_supply: vec![2],
            col_demand: vec![1, 1],
            cost: vec![vec![Cell::Cost(0, 0), Cell::Cost(0, 0)]],
        };
        let sol = solve_transport(&p).unwrap();
        check_margins(&p, &sol);
        assert_eq!(sol.total, (0, 0));
    }

    #[test]
    fn large_multiplicities_bottleneck() {
        // Bottleneck augmentation must handle this without 2M iterations.
        let m = 1_000_000u32;
        let p = TransportProblem {
            row_supply: vec![m, m],
            col_demand: vec![m, m],
            cost: vec![
                vec![Cell::Cost(1, 0), Cell::Cost(2, 0)],
                vec![Cell::Cost(2, 0), Cell::Cost(1, 0)],
            ],
        };
        let sol = solve_transport(&p).unwrap();
        check_margins(&p, &sol);
        assert_eq!(sol.total.0, 2 * m as u128);
    }

    #[test]
    fn u32_max_multiplicities_no_overflow() {
        let m = u32::MAX;
        let p = TransportProblem {
            row_supply: vec![m, m],
            col_demand: vec![m, m],
            cost: vec![
                vec![Cell::Cost(m, m), Cell::Forbidden],
                vec![Cell::Forbidden, Cell::Cost(m, m)],
            ],
        };
        let sol = solve_transport(&p).unwrap();
        check_margins(&p, &sol);
        let expected = 2u128 * m as u128 * m as u128;
        assert_eq!(sol.total, (expected, expected));
    }

    #[test]
    fn differential_random_small() {
        // Deterministic pseudo-random exploration of small instances.
        let mut seed: u64 = 0x9E3779B97F4A7C15;
        let mut next = move || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed
        };
        for _case in 0..200 {
            let rows = 1 + (next() % 3) as usize;
            let cols = 1 + (next() % 3) as usize;
            // Random margins with equal totals: generate row supplies, then
            // distribute the same total across columns.
            let row_supply: Vec<u32> = (0..rows).map(|_| 1 + (next() % 3) as u32).collect();
            let total: u32 = row_supply.iter().sum();
            let mut col_demand = vec![0u32; cols];
            let mut rem = total;
            for j in 0..cols - 1 {
                let d = next() as u32 % (rem + 1);
                col_demand[j] = d;
                rem -= d;
            }
            col_demand[cols - 1] = rem;

            let cost: Vec<Vec<Cell>> = (0..rows)
                .map(|_| {
                    (0..cols)
                        .map(|_| {
                            if next() % 5 == 0 {
                                Cell::Forbidden
                            } else {
                                Cell::Cost((next() % 10) as u32, (next() % 10) as u32)
                            }
                        })
                        .collect()
                })
                .collect();

            let p = TransportProblem {
                row_supply,
                col_demand,
                cost,
            };
            let flow = solve_transport(&p);
            let reference = exhaustive_min(&p);
            match (flow, reference) {
                (Some(sol), Some(expected)) => {
                    check_margins(&p, &sol);
                    assert_eq!(
                        sol.total, expected,
                        "flow quality diverged from exhaustive minimum on {p:?}"
                    );
                }
                (None, None) => {}
                (flow, reference) => {
                    panic!("feasibility disagreement on {p:?}: flow={flow:?} ref={reference:?}");
                }
            }
        }
    }

    #[test]
    fn determinism() {
        let p = TransportProblem {
            row_supply: vec![2, 2],
            col_demand: vec![2, 2],
            cost: vec![
                vec![Cell::Cost(1, 1), Cell::Cost(1, 1)],
                vec![Cell::Cost(1, 1), Cell::Cost(1, 1)],
            ],
        };
        let a = solve_transport(&p).unwrap();
        let b = solve_transport(&p).unwrap();
        assert_eq!(a.flow, b.flow, "equal-cost ties must resolve identically");
    }
}