gras 2.0.1

A Genetic Programming framework for Neural Architecture Search in Rust
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
//! Markdown rendering for topologies — includes nodes table, edge list,
//! ASCII wiring diagram, and Mermaid flowchart.

use super::ascii::{AsciiNode, edge_list, render_wire_diagram};
use super::mermaid::{split_policy_name, topology_mermaid};
use crate::graph::network::Network;
use crate::graph::node::NodeKind;
use crate::graph::topology::{FeatureSplitPolicy, Topology};

/// Markdown for a [`Topology`]: header, nodes table, edge list, wiring diagram
/// and Mermaid. Stamp-free by design — scores live in the CSV, not here.
pub fn topology_markdown(graph: &Topology, net: Option<&Network>) -> String {
    let mut out = String::new();

    // Header
    out.push_str(&format!("# Topology #{}\n\n", graph.id));

    // Summary
    let hidden_range: Vec<usize> = graph.nodes.iter().filter_map(|n| n.hidden_dim).collect();
    let hidden_info = if hidden_range.is_empty() {
        "hidden 8".to_string()
    } else {
        let min = *hidden_range.iter().min().unwrap();
        let max = *hidden_range.iter().max().unwrap();
        if min == max {
            format!("hidden {min}")
        } else {
            format!("hidden {min}–{max}")
        }
    };
    out.push_str(&format!(
        "**{} nodes** · **{} wires** · input {} → {} → output {}\n\n",
        graph.nodes.len(),
        graph.connections.len(),
        graph
            .options
            .input_dim
            .map(|x| x.to_string())
            .unwrap_or_else(|| "?".into()),
        hidden_info,
        graph
            .options
            .output_dim
            .map(|x| x.to_string())
            .unwrap_or_else(|| "?".into()),
    ));

    // ── The two blueprint knobs that never appear in a box ── A reader diffing two `champion-*-*-*.md`
    // files needs the split and the seed: the split decides WHICH features each branch can see,
    let mut knobs: Vec<String> = Vec::new();
    match graph.input_feature_masks() {
        Some(masks) => knobs.push(format!(
            "feature split `{}` over {} Input port(s)",
            split_policy_name(graph.options.feature_split),
            masks.len()
        )),
        None => knobs.push("no feature split — every Input port sees every feature".to_string()),
    }
    // ALWAYS printed, even at 0.00: a gene that vanishes at its own default cannot be diffed
    // between two files, and dropout is a real gene on every net (an elite at 0.00 and one at 0.25
    knobs.push(format!("dropout {:.2}", graph.options.dropout_prob));
    // Seed PLUS the bounds it was drawn from: a seed alone reproduces a blueprint
    // ranges that constrained the draw travel with it, and this file is meant to outlive the run
    let o = &graph.options;
    out.push_str(&format!(
        "Blueprint: {} · topology seed {} · sampled {}–{} nodes · {}–{} in · {}–{} out\n\n",
        knobs.join(" · "),
        o.topology_seed,
        o.min_hidden_num_nodes,
        o.max_hidden_num_nodes,
        o.min_hidden_inputs_per_node,
        o.max_hidden_inputs_per_node,
        o.min_hidden_outputs_per_node,
        o.max_hidden_outputs_per_node
    ));

    // ── Nodes table (merged topology + network layer info) ──
    out.push_str("## Nodes\n\n");
    if let Some(net) = net {
        // Full table: ID, Kind, In, Out, Linear, Activation, Combine, Std, Sources
        out.push_str("| ID | Kind | In | Out | Linear | Activation | Combine | Std | Sources |\n");
        out.push_str("|----|------|----|-----|--------|------------|---------|-----|---------|\n");
        let node_sources = super::graph_utils::build_node_sources(
            &net.connections,
            &net.nodes.iter().map(|n| n.num_inputs).collect::<Vec<_>>(),
        );
        for (i, node) in graph.nodes.iter().enumerate() {
            let kind = match node.kind {
                NodeKind::Input => "Input",
                NodeKind::Hidden => "Hidden",
                NodeKind::Output => "Output",
            };
            // Activation column: node-level, plus `[a|b|…]` when ports
            // diverge — mirrors the mermaid per-port sig.
            let act = match &node.port_activations {
                Some(ports) if ports.iter().any(|a| *a != node.activation) => {
                    let list: Vec<String> = ports.iter().map(|a| format!("{a}")).collect();
                    format!("{} [{}]", node.activation, list.join("|"))
                }
                _ => format!("{}", node.activation),
            };
            let combine = node
                .combine_op
                .map_or(crate::utils::cfy::NO_VALUE.into(), |op| format!("{op}"));
            let std = node
                .standardize
                .map_or(crate::utils::cfy::NO_VALUE.into(), |s| format!("{s}"));
            let (in_dim, out_dim) = graph.node_dims().get(i).copied().unwrap_or((0, 0));
            let marker = if i == net.output_node { " " } else { "" };
            let sources: Vec<String> = node_sources[i]
                .iter()
                .flatten()
                .map(|p| format!("n{}_o{}", p.node, p.index))
                .collect();
            let src_str = if sources.is_empty() {
                "*".into()
            } else {
                sources.join(", ")
            };
            let in_wires = graph
                .connections
                .iter()
                .filter(|c| c.to.node == node.id)
                .count();
            let out_wires = graph
                .connections
                .iter()
                .filter(|c| c.from.node == node.id)
                .count();
            out.push_str(&format!(
                "| {id} {kind}{marker} | {kind} | {ni} | {no} | {in_dim} → {out_dim} | {act} | {combine} | {std} | {src_str} |\n",
                id = i,
                ni = ports_cell(node.num_inputs, in_wires),
                no = ports_cell(node.num_outputs, out_wires),
            ));
        }
    } else {
        // Topology-only table: no linear dims or sources
        out.push_str("| ID | Kind | In | Out | Activation | Combine | Std | Dims |\n");
        out.push_str("|----|------|----|-----|------------|---------|-----|------|\n");
        for (node_id, node) in graph.nodes.iter().enumerate() {
            let kind = match node.kind {
                NodeKind::Input => "Input",
                NodeKind::Hidden => "Hidden",
                NodeKind::Output => "Output",
            };
            let act = node.activation;
            let combine = node
                .combine_op
                .map_or(crate::utils::cfy::NO_VALUE.into(), |op| format!("{op}"));
            let std = node
                .standardize
                .map_or(crate::utils::cfy::NO_VALUE.into(), |s| format!("{s}"));
            let (in_dim, out_dim) = graph.node_dims().get(node_id).copied().unwrap_or((0, 0));
            let in_wires = graph
                .connections
                .iter()
                .filter(|c| c.to.node == node.id)
                .count();
            let out_wires = graph
                .connections
                .iter()
                .filter(|c| c.from.node == node.id)
                .count();
            out.push_str(&format!(
                "| {id} | {kind} | {ni} | {no} | {act} | {combine} | {std} | {in_dim}→{out_dim} |\n",
                id = node.id,
                ni = ports_cell(node.num_inputs, in_wires),
                no = ports_cell(node.num_outputs, out_wires),
            ));
        }
    }
    out.push('\n');

    // ── Feature split — the Input node's per-port genome ── The rows are genome (`M:<width>`
    // the diversity tokens) but a table cannot show them: they live per PORT, not per node.
    if let Some(masks) = graph.input_feature_masks() {
        let input_dim = graph.options.input_dim.unwrap_or(1).max(1);
        let seen = (0..input_dim)
            .filter(|f| masks.iter().any(|m| m.get(*f).copied().unwrap_or(0) != 0))
            .count();
        let total: usize = masks
            .iter()
            .map(|m| m.iter().filter(|b| **b != 0).count())
            .sum();
        let mean = total as f32 / masks.len().max(1) as f32;
        // The accounting is the check a reader can do at a glance: `exclusive` is a partition,
        // the rows must add up to exactly one full vector (100%).
        let pct = 100.0 * total as f32 / input_dim as f32;
        // A partition is a PER-FEATURE claim, so the total cannot prove it: rows `[1,1,0] [0,1,0]` add up to one full vector yet own feature 1 twice and feature 2 never.
        let owned_by: Vec<usize> = (0..input_dim)
            .map(|f| {
                masks
                    .iter()
                    .filter(|m| m.get(f).copied().unwrap_or(0) != 0)
                    .count()
            })
            .collect();
        let shared: Vec<usize> = (0..input_dim).filter(|f| owned_by[*f] > 1).collect();
        let unowned: Vec<usize> = (0..input_dim).filter(|f| owned_by[*f] == 0).collect();
        // Capped so a 784-wide vector cannot turn one sentence into a wall of indices.
        let name_features = |feats: &[usize]| -> String {
            const CAP: usize = 8;
            let mut shown: Vec<String> = feats.iter().take(CAP).map(|f| format!("`{f}`")).collect();
            if feats.len() > CAP {
                shown.push(format!("… +{}", feats.len() - CAP));
            }
            shown.join(", ")
        };
        // The accounting means something DIFFERENT per policy, so the sentence says what this net's
        // own label makes of it: 100% is a partition, >100% is sharing, <100% is dropped features —
        let accounting = match graph.options.feature_split {
            Some(FeatureSplitPolicy::Exclusive) => {
                if shared.is_empty() && unowned.is_empty() {
                    "`exclusive` is a partition, so this must account for exactly **100%** — it does: every feature is owned by exactly one port.".to_string()
                } else {
                    let shared_note = if shared.is_empty() {
                        String::new()
                    } else {
                        format!(" (first {})", name_features(&shared))
                    };
                    let unowned_note = if unowned.is_empty() {
                        String::new()
                    } else {
                        format!(" (first {})", name_features(&unowned))
                    };
                    format!(
                        "`exclusive` is a partition, so this must account for exactly **100%** — it does not: {} feature(s) are shared by two or more ports{} and {} feature(s) reach no port{}. A shared feature and an unowned one can cancel out in the total, so a 100% sum cannot prove a partition on its own.",
                        shared.len(),
                        shared_note,
                        unowned.len(),
                        unowned_note
                    )
                }
            }
            Some(FeatureSplitPolicy::Random) => format!(
                "`random` flips one coin per (port, feature), so **above 100% is normal** (ports share features) and features can be missed entirely — {seen} of {input_dim} are seen by some port here."
            ),
            // The label names PROVENANCE, and the sentence has to say so: a run whose pool is `exclusive` produces these children too, and calling one `exclusive` would claim a…
            Some(FeatureSplitPolicy::Inherited) => "`inherited` rows are a per-port **crossover blend** of two parents' masks, so this net does NOT carry the policy the run configured — a run drawing only `exclusive` still produces children like this. A blend of two partitions is not itself a partition (a feature can reach two ports, which is why the total may pass 100%), and which policy the blend came from is not recoverable, so claiming one would be a lie: the label states provenance, not a draw rule."
                .to_string(),
            None => "No policy recorded, so read the rows themselves.".to_string(),
        };
        out.push_str("## Feature split\n\n");
        out.push_str(&format!(
            "`{}` over **{}** Input port(s): **{seen} of {input_dim}** features reach at least one port, **{total} keeps = {pct:.0}%** of the vector, mean **{mean:.1}** per port. {accounting} Rows are genome — a port keeps a feature where its row reads `1` and hides it where it reads `0`, and the rows cross over with the ports that carry them. The `features` column is that row written out: a bit string while the vector is at most {MASK_BIT_MAX_DIM} wide (bit `f` is feature `f`), and the kept INDICES above it — capped at {MASK_INDEX_CAP} with `… +n` on a wide net, where `keeps` is still the exact count.\n\n",
            split_policy_name(graph.options.feature_split),
            masks.len()
        ));
        out.push_str("| port | keeps | share | features |\n|---:|---:|---:|---|\n");
        for (port, mask) in masks.iter().enumerate() {
            let keeps = mask.iter().filter(|b| **b != 0).count();
            let note = if keeps == 0 { " (bias only)" } else { "" };
            out.push_str(&format!(
                "| {port} | {keeps}{note} | {:.1}% | {} |\n",
                100.0 * keeps as f32 / input_dim as f32,
                kept_features(mask, input_dim)
            ));
        }
        out.push('\n');
    } else {
        // The other half of the consistency rule: a net WITHOUT the gene says so where a net WITH it lists its rows.
        let input_dim = graph.options.input_dim.unwrap_or(1).max(1);
        let ports = graph
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Input)
            .map(|n| n.num_outputs.max(1))
            .unwrap_or(1);
        out.push_str("## Feature split\n\n");
        out.push_str(&format!(
            "`{}` over **{ports}** Input port(s) — no mask rows are recorded, so every port projects the FULL **{input_dim}**-feature vector and this net carries no split genome (`keeps` = {input_dim} on every port, 100% each). That is the ABSENCE of the gene, not a partition of it: an `exclusive` or `random` split writes one row per port, and those rows cross over with the ports that carry them.\n\n",
            split_policy_name(graph.options.feature_split)
        ));
    }

    // ── Edge list with distance markers ──
    out.push_str("## Edges\n\n");
    out.push_str("```text\n");
    out.push_str(&edge_list(graph));
    out.push_str("```\n\n");

    // ── Wiring diagram (with out dims) ──
    out.push_str("## Wiring diagram\n\n");
    out.push_str("```text\n");
    let node_dims = graph.node_dims();
    let nodes: Vec<AsciiNode> = graph
        .nodes
        .iter()
        .enumerate()
        .map(|(i, n)| {
            let in_wires = graph
                .connections
                .iter()
                .filter(|c| c.to.node == n.id)
                .count();
            let out_wires = graph
                .connections
                .iter()
                .filter(|c| c.from.node == n.id)
                .count();
            AsciiNode {
                id: n.id,
                kind: n.kind,
                num_inputs: n.num_inputs,
                num_outputs: n.num_outputs,
                out_dim: node_dims.get(i).map(|&(_, out)| out),
                in_wires,
                out_wires,
            }
        })
        .collect();
    out.push_str(&render_wire_diagram(&nodes, &graph.connections));
    out.push_str("```\n");
    out.push_str("\n> **Legend**:\n");
    out.push_str("> - I=input  H=hidden  O=output\n");
    out.push_str("> - `2w→2i/1o→5w` = wires→input ports / output ports→wires. An input port carries exactly ONE wire (fan-in is extra ports), so `w == i`; only the Input node fans out, which is why its labels can repeat (`o1 o1`). Every marker maps to exactly one wire\n");
    out.push_str("> - ->dim = output dimension\n");
    out.push_str("> - ▶ connected output  ◀ connected input  * orphaned port\n");

    // Mermaid flowchart
    out.push_str("\n## Graph\n\n");
    out.push_str(&topology_mermaid(graph));

    // ── Legend — one entry per visual channel, so a reader never has to guess
    // which structural fact a border, wire or label encodes. ──
    out.push_str("\n## How to read this\n\n");
    out.push_str("| Visual | Meaning |\n");
    out.push_str("|---|---|");
    out.push_str("\n| **Box border thickness (Graph)** | node width (`hidden_dim`, scaled min→max within this net). |");
    out.push_str("\n| **Wire thickness (Graph)** | hop distance — thick = long-range skip, thin = neighbor. |");
    out.push_str("\n| **Box height (Wiring diagram)** | the node's port count (`max(i, o)`, scaled min→max within this net) — a tall box is a wide fan-in/fan-out node. Wire thickness is a Graph-only channel by design; in the text diagram, hop distance is the `N hops <<<<` marker in the edge list. |");
    out.push_str("\n| **Box label (Graph)** | `H<id> <combine>·<std> <dim>` — the node's internal processing. Activation is NOT here: it lives on each outgoing arrow. |");
    out.push_str("\n| **Arrow label (Graph)** | the wire's own activation — per-port, so one node can emit `mish` to one neighbor and `tanh` to another. Equal labels from the same node = same signal; duplicates are impossible (dedup collapses them). |");
    out.push_str("\n| **Dashed stub `selu (input)` / `mish (orphan)`** | orphaned port — an input nothing feeds / an output nothing reads (mermaid's counterpart of the ASCII `*`). |");
    out.push_str("\n| **`in <n>` / `out <n>`** | dataset shape (fixed by the problem). |");
    out.push_str("\n| **Input box → second line** | the feature split when the net has one: `split <policy> · <ports>p · <seen>/<n> seen`. Present for ANY policy that carries rows (`exclusive`, `random`, `inherited`); absent for `none`, where every port already carries the full mixed vector — that is the common case, and why the box is usually one line. Per-port rows are in *Feature split* above. |");
    out.push_str("\n| **`na` in `Combine` / `Std`** | no per-node override, so the forward pass uses `Add` / no standardisation. `na` is not a missing gene: it is the gene spelled as its default (the diversity metric folds `None` and `Identity` into one token for the same reason). |");
    out.push_str("\n| **Nodes table → `Sources`** | which output port feeds each input port (`n1_o2` = output 2 of node 1), one entry per port in port order — the `k`-th entry feeds `i<k>`; `*` = an unwired port (never left behind by `finalize`). |");
    out.push_str("\n| **Nodes table → `In` / `Out` with `(Nw)`** | PORT counts; a parenthesised wire count appears only where the two differ (`Out 2 (3w)` = 2 ports, 3 wires). Only the Input node fans out, so only it can differ — the wiring diagram draws one slot per WIRE, which is why its `Out` slots can outnumber its ports. |");
    out.push_str("\n| **Nodes table → `In` / `Out`** | PORT counts. Only the Input node can fan out, so only its cell can read `2 (3w)` — two ports carrying three wires, the same numbers the wiring diagram labels `2o→3w` and the edge list shows as a repeated port (`n0_o0` twice). A hidden/output row reads plain numbers because an input port carries exactly one wire. |");
    out.push_str("\n| **Nodes table → `Combine` / `Std`** | how multiple inputs are merged / whether they're normalized first. |");
    out.push_str("\n| **Edge list & wiring diagram** | one line per wire, exact ports (`n0_o1 → n2_i0`); `<<<<` = long jump; `▶ ◀ *` = wired out / wired in / orphaned. |");
    out.push('\n');

    out
}

/// A node's `In` / `Out` cell: the PORT count, annotated with the wire count only when the node carries MORE wires than ports.
fn ports_cell(ports: usize, wires: usize) -> String {
    if wires > ports {
        format!("{ports} ({wires}w)")
    } else {
        ports.to_string()
    }
}

/// Above this `input_dim`, a mask row is printed as kept INDICES instead of a bit
/// string: 32 bits is still one glance, 784
const MASK_BIT_MAX_DIM: usize = 32;

/// How many indices the index form may list before it says `… +n`.
const MASK_INDEX_CAP: usize = 32;

/// One mask row, spelled so the reader can check WHICH features a port keeps, not just how many:
/// bit string while the vector is short (`1010`), else the kept indices (`0,2,… +41`).
fn kept_features(mask: &[u8], input_dim: usize) -> String {
    if input_dim <= MASK_BIT_MAX_DIM {
        return (0..input_dim)
            .map(|f| {
                if mask.get(f).copied().unwrap_or(0) != 0 {
                    '1'
                } else {
                    '0'
                }
            })
            .collect();
    }
    let kept: Vec<usize> = (0..input_dim)
        .filter(|f| mask.get(*f).copied().unwrap_or(0) != 0)
        .collect();
    if kept.is_empty() {
        return crate::utils::cfy::NO_VALUE.to_string();
    }
    let shown: Vec<String> = kept
        .iter()
        .take(MASK_INDEX_CAP)
        .map(|i| i.to_string())
        .collect();
    if kept.len() > MASK_INDEX_CAP {
        format!("{} … +{}", shown.join(","), kept.len() - MASK_INDEX_CAP)
    } else {
        shown.join(",")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::node::Node;
    use crate::graph::topology::{Connection, Port, TopologyOptions};

    /// The topology graph curves its wires like the lineage graph does.
    #[test]
    fn the_topology_mermaid_curves_its_wires_like_the_lineage_graph() {
        let m = super::topology_mermaid(&sample());
        // FRONT MATTER, not an `%%{init}%%` directive: directives are deprecated since 10.5 and are ignored at the default `securityLevel: "strict"`, so a pinned renderer written…
        assert!(m.starts_with("```mermaid\n---\nconfig:\n"), "{m}");
        // …and the LAYOUT is named, not inherited: Mermaid 12 defaults to ELK, whose wires are
        // right-angle segments, and `curve` can only round their corners.
        assert!(
            m.contains("\n  layout: dagre\n"),
            "the layout is pinned: {m}"
        );
        assert!(m.contains("\n    curve: basis\n"), "{m}");
        // The block has to close BEFORE the diagram keyword, or `---` is parsed as diagram text.
        let config = m.find("  layout: dagre").expect("config present");
        let diagram = m.find("flowchart LR").expect("diagram keyword present");
        assert!(
            config < diagram,
            "front matter must precede the diagram: {m}"
        );
        assert!(m.contains("---\nflowchart LR\n"), "{m}");
        assert!(
            !m.contains("%%{init"),
            "directives are deprecated, and ignored at strict: {m}"
        );
        assert!(!m.contains("graph LR"), "the legacy keyword is gone: {m}");
    }

    fn sample() -> Topology {
        let mut g = Topology::new(
            7,
            Some(TopologyOptions {
                input_dim: Some(3),
                output_dim: Some(1),
                ..Default::default()
            }),
        );
        g.create_random_hidden_nodes(3);
        g.finalize();
        g
    }

    /// The consistency rule: a net WITHOUT the gene names it in the same section a net WITH it lists rows, instead of the section vanishing and leaving "no split"…
    #[test]
    fn a_net_with_no_feature_split_still_gets_the_section() {
        let md = topology_markdown(&sample(), None);
        assert!(
            md.contains("## Feature split"),
            "the heading is unconditional: {md}"
        );
        assert!(
            md.contains("no mask rows are recorded"),
            "and it says why there are no rows: {md}"
        );
        assert!(
            !md.contains("| port | keeps"),
            "the rows table stays exclusive to nets that carry rows"
        );
    }

    /// The allele the counts used to hide: a split row now names WHICH features it keeps,
    /// the difference `[1,0,1,0]` makes against `[0,1,0,0]` — both are "keeps 2 of 4"-ish rows
    #[test]
    fn a_split_row_names_its_features_instead_of_only_counting_them() {
        use crate::graph::node::Node;
        use crate::graph::topology::{Connection, Port};
        let mut g = Topology::new(
            9,
            Some(TopologyOptions {
                input_dim: Some(4),
                output_dim: Some(1),
                dropout_prob: 0.0,
                ..Default::default()
            }),
        );
        g.nodes.push(Node::new_input(0, 2));
        g.nodes.push(Node::new_hidden(1, 2, 1));
        g.nodes.push(Node::new_output(2, 1, 1));
        for (from, to) in [(0, 0), (1, 1)] {
            g.connections.push(Connection {
                from: Port {
                    node: 0,
                    index: from,
                },
                to: Port { node: 1, index: to },
            });
        }
        g.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        g.finalize();
        // Masks are genome but `finalize` drops them (a rebuild may renumber ports),
        // the fixture installs them exactly where the engine does: after the build.
        g.nodes[0].feature_masks = Some(vec![vec![1, 0, 1, 0], vec![0, 1, 0, 0]]);
        g.options.feature_split = Some(FeatureSplitPolicy::Exclusive);

        let md = topology_markdown(&g, None);
        assert!(md.contains("| port | keeps | share | features |"), "{md}");
        assert!(
            md.contains("| 0 | 2 | 50.0% | 1010 |"),
            "port 0 keeps features 0 and 2:\n{md}"
        );
        assert!(
            md.contains("| 1 | 1 | 25.0% | 0100 |"),
            "port 1 keeps feature 1, which the count alone could not say:\n{md}"
        );
        // The blueprint line is complete: dropout stated even at 0, and the seed travels
        // with the bounds it was drawn from, so the draw is reproducible from the file.
        assert!(md.contains("dropout 0.00"), "{md}");
        assert!(
            md.contains("sampled 2–15 nodes · 2–15 in · 2–15 out"),
            "the topology seed needs its bounds beside it:\n{md}"
        );
    }

    /// A 100% total is NOT proof of a partition: rows `[1,1,0]` and `[0,1,0]` add up to a full 3-wide vector while owning feature 1 twice and feature 2 never.
    #[test]
    fn a_hundred_percent_total_does_not_make_an_exclusive_split_a_partition() {
        use crate::graph::node::Node;
        use crate::graph::topology::{Connection, Port};
        let mut g = Topology::new(
            11,
            Some(TopologyOptions {
                input_dim: Some(3),
                output_dim: Some(1),
                dropout_prob: 0.0,
                ..Default::default()
            }),
        );
        g.nodes.push(Node::new_input(0, 2));
        g.nodes.push(Node::new_hidden(1, 2, 1));
        g.nodes.push(Node::new_output(2, 1, 1));
        for (from, to) in [(0, 0), (1, 1)] {
            g.connections.push(Connection {
                from: Port {
                    node: 0,
                    index: from,
                },
                to: Port { node: 1, index: to },
            });
        }
        g.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        g.finalize();
        g.nodes[0].feature_masks = Some(vec![vec![1, 1, 0], vec![0, 1, 0]]);
        g.options.feature_split = Some(FeatureSplitPolicy::Exclusive);

        let md = topology_markdown(&g, None);
        assert!(
            md.contains("3 keeps = 100%"),
            "the fixture is the trap: the totals DO read 100%:\n{md}"
        );
        assert!(
            !md.contains("it does: every feature is owned by exactly one port"),
            "a 100% total must not be reported as a partition:\n{md}"
        );
        assert!(
            md.contains("1 feature(s) are shared by two or more ports (first `1`)"),
            "the shared feature is named:\n{md}"
        );
        assert!(
            md.contains("1 feature(s) reach no port (first `2`)"),
            "and so is the one left unowned:\n{md}"
        );
    }

    /// A BLENDED child names itself `inherited`, not `crossover`: crossover is the MECHANISM, and the run's `feature_split` pool never contains it…
    #[test]
    fn a_blended_split_is_labelled_inherited_not_crossover() {
        let mut g = Topology::new(
            0,
            Some(TopologyOptions {
                input_dim: Some(3),
                output_dim: Some(1),
                ..Default::default()
            }),
        );
        g.nodes.push(Node::new_input(0, 2));
        g.nodes.push(Node::new_hidden(1, 2, 1));
        g.nodes.push(Node::new_output(2, 1, 1));
        for (from, to) in [(0, 0), (1, 1)] {
            g.connections.push(Connection {
                from: Port {
                    node: 0,
                    index: from,
                },
                to: Port { node: 1, index: to },
            });
        }
        g.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        g.finalize();
        // Two rows that share feature 1 and leave feature 2 unowned: exactly what a per-port
        // blend of two partitions looks like, and why its total can pass 100%.
        g.nodes[0].feature_masks = Some(vec![vec![1, 1, 0], vec![0, 1, 0]]);
        g.options.feature_split = Some(FeatureSplitPolicy::Inherited);
        let md = topology_markdown(&g, None);
        assert!(md.contains("`inherited` over"), "{md}");
        assert!(
            !md.contains("`crossover` over"),
            "`crossover` is the mechanism, never the label:\n{md}"
        );
        assert!(
            md.contains("crossover blend"),
            "the mechanism is still named so the reader knows what produced the rows:\n{md}"
        );
    }

    /// Wide vectors switch to indices, and a mask past the cap says how many it trimmed
    /// rather than silently truncating into a lie about the row.
    #[test]
    fn kept_features_caps_a_wide_row() {
        assert_eq!(kept_features(&[1, 0, 1, 0], 4), "1010");
        assert_eq!(kept_features(&[0, 0, 0, 0], 4), "0000");
        assert_eq!(kept_features(&[0u8; 40], 40), crate::utils::cfy::NO_VALUE);
        let every: Vec<u8> = vec![1; 40];
        let spelled = kept_features(&every, 40);
        assert!(spelled.starts_with("0,1,2,"), "{spelled}");
        assert!(spelled.ends_with("… +8"), "32 shown, 8 trimmed: {spelled}");
    }

    #[test]
    fn markdown_legend_describes_one_wire_per_port() {
        // The old caveat ("a port with several wires is drawn once per wire") described
        // the wiring model that no longer exists; the legend must say what replaced
        let md = topology_markdown(&sample(), None);
        assert!(
            md.contains("An input port carries exactly ONE wire"),
            "legend must state the one-wire rule:\n{md}"
        );
        assert!(
            !md.contains("a port with several wires is drawn once per wire"),
            "stale wire-per-port caveat still in the legend:\n{md}"
        );
    }

    /// The Input node is the ONE fan-out, so its `Out` cell must carry both numbers: the port count the topology declares and the wire count the diagram draws.
    #[test]
    fn a_fanning_input_names_its_wire_count_beside_its_ports() {
        use crate::graph::node::Node;
        use crate::graph::topology::{Connection, Port};
        let mut g = Topology::new(
            11,
            Some(TopologyOptions {
                input_dim: Some(4),
                output_dim: Some(2),
                ..Default::default()
            }),
        );
        g.nodes.push(Node::new_input(0, 2));
        g.nodes.push(Node::new_hidden(1, 2, 2));
        g.nodes.push(Node::new_output(2, 1, 1));
        // Two ports, three wires: port 0 feeds both the hidden and the output node.
        for (from, to_node, to_index) in [(0usize, 1usize, 0usize), (0, 2, 0), (1, 1, 1)] {
            g.connections.push(Connection {
                from: Port {
                    node: 0,
                    index: from,
                },
                to: Port {
                    node: to_node,
                    index: to_index,
                },
            });
        }

        let md = topology_markdown(&g, None);
        assert!(
            md.contains("| 0 | Input | 0 | 2 (3w) |"),
            "the fan-out is named where the numbers differ:\n{md}"
        );
        assert!(
            md.contains("PORT counts"),
            "the legend must explain what the cells are:\n{md}"
        );
        assert!(
            !md.contains("(1w)") && !md.contains("(0w)"),
            "no annotation where wires do not exceed ports:\n{md}"
        );
    }
}