edifact-mapper 0.8.0

EDIFACT to BO4E bidirectional conversion for the German energy market
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
//! Reverse-order permutation gate: BO4E carries no ordering information, so the
//! order of group repetitions that differ in their entry-segment qualifier
//! (e.g. SG2 `NAD+MS` / `NAD+MR`) must follow from the mappings and the MIG —
//! never from the order of elements in a JSON array.
//!
//! For every generated fixture `fixtures/generated/<fv>/<msg>/*.edi` the gate runs
//! the real forward pipeline (`Mapper::from_edifact`) and then, for the message
//! and each transaction, permutes every entity collection that is a JSON array:
//!
//! * top-level entity arrays (`marktteilnehmer`, `geschaeftspartner`, ...), and
//! * arrays of objects nested inside entity objects (`kontaktwege`, child
//!   entities embedded in their parent), recursively.
//!
//! Elements are grouped by their **qualifier key**: the values of the fields the
//! mapping definitions fill from the entry segment's qualifier element(s) — the
//! first coded data element of the group's entry segment in any MIG variant of
//! that group (e.g. `nad.0` → `marktrolle`, `partnerrolle`). The groups are then
//! reversed, and separately rotated by one; elements with the same qualifier key
//! keep their relative order, because the order of equal-qualifier repetitions
//! (several FTX lines, several positions) is data. An array whose elements have
//! no identifiable qualifier field, or all share one qualifier key, is left
//! unchanged.
//!
//! Each permuted JSON is rendered with `Mapper::to_edifact` (which starts from
//! BO4E alone — no `nesting_info`) and must produce exactly the EDIFACT the
//! unpermuted JSON renders to.
//!
//! Permuting cannot reveal a child collection that is paired with its parent
//! collection by array position (e.g. top-level `freitext[]` from SG15.SG25 next
//! to `status[]` from SG15): the reverse re-sorts the parents by MIG variant and
//! still hands the children out by index. So the gate also fails a fixture when
//! a top-level collection mapped from a child group of another collection's
//! group sits beside that parent collection while the parent has several
//! qualifier-distinguishable elements. Such children must be nested into their
//! parent object (`[meta] parent_field`).
//!
//! A parent group that repeats with *one* MIG variant (PRICAT SG36, MSCONS SG9,
//! REMADV SG10, …) is the same defect but invisible here twice over: the
//! generated fixtures have a single parent repetition, and repetitions of one
//! variant keep their data order, so there is nothing to permute. That class is
//! driven by `nested_child_group_pairing_test`, which builds inputs whose parent
//! repetitions carry a different number of children.
//!
//! One test per format version, e.g.
//! `cargo test -p edifact-mapper --test reverse_order_permutation_gate fv2604`.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use edifact_mapper::{DataDir, Mapper};
use mig_bo4e::definition::{FieldMapping, MappingDefinition};
use mig_bo4e::engine::{DataBundle, VariantCache};
use mig_types::schema::mig::{MigSchema, MigSegmentGroup};
use serde_json::Value;

/// Fixtures that cannot pass for a reason other than the reverse ordering by
/// MIG variant. `(format versions, "<msg dir>/<file stem>", reason)`. Keep minimal.
const KNOWN_FAILURES: &[(&[&str], &str, &str)] = &[(
    &["FV2604"],
    "mscons/13024",
    "the FV2604 data bundle has no AHB segment numbers for PID 13024, so \
         `from_edifact` fails before any reverse mapping runs (\"No MIG schema\")",
)];

fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(|p| p.parent())
        .expect("crate is two levels under the workspace root")
        .to_path_buf()
}

fn to_camel_case(s: &str) -> String {
    let mut c = s.chars();
    match c.next() {
        Some(f) => f.to_lowercase().collect::<String>() + c.as_str(),
        None => String::new(),
    }
}

/// Qualifier element of a group's entry segment: (entry tag lowercase,
/// element index, component index, data element id).
type QualifierPos = (String, usize, usize, String);

/// All MIG group definitions reached by following `source_group` (e.g.
/// `SG4.SG12`) through every same-ID variant at each level.
fn mig_groups_at<'a>(mig: &'a MigSchema, source_group: &str) -> Vec<&'a MigSegmentGroup> {
    let mut level: Vec<&MigSegmentGroup> = mig.segment_groups.iter().collect();
    let mut found = Vec::new();
    let parts: Vec<&str> = source_group
        .split('.')
        .map(|p| p.split(':').next().unwrap_or(p))
        .collect();
    for (i, part) in parts.iter().enumerate() {
        found = level.iter().copied().filter(|g| g.id == *part).collect();
        if i + 1 < parts.len() {
            level = found.iter().flat_map(|g| g.nested_groups.iter()).collect();
        }
    }
    found
}

/// The first coded data element of each variant's entry segment.
fn qualifier_positions(mig: &MigSchema, source_group: &str) -> Vec<QualifierPos> {
    let mut out = Vec::new();
    for g in mig_groups_at(mig, source_group) {
        let Some(entry) = g.segments.first() else {
            continue;
        };
        let tag = entry.id.to_lowercase();
        let mut coded: Vec<(usize, usize, String)> = entry
            .data_elements
            .iter()
            .filter(|d| !d.codes.is_empty())
            .map(|d| (d.position, 0, d.id.clone()))
            .collect();
        for c in &entry.composites {
            for d in &c.data_elements {
                if !d.codes.is_empty() {
                    coded.push((c.position, d.position, d.id.clone()));
                }
            }
        }
        coded.sort();
        if let Some((e, c, id)) = coded.into_iter().next() {
            let pos = (tag.clone(), e, c, id);
            if !out.contains(&pos) {
                out.push(pos);
            }
        }
    }
    out
}

/// Does a definition field path (`nad.0`, `nad.0.0`, `cci.2.0`, `nad.d3035`,
/// `rff[Z13].0.0`) address the qualifier element `pos`?
fn path_addresses(path: &str, pos: &QualifierPos) -> bool {
    let mut parts = path.split('.');
    let Some(head) = parts.next() else {
        return false;
    };
    let tag = head.split('[').next().unwrap_or(head);
    if tag != pos.0 {
        return false;
    }
    let rest: Vec<&str> = parts.collect();
    if rest.last().is_some_and(|l| {
        l.strip_prefix('d')
            .map(|id| id.split('_').next() == Some(pos.3.as_str()))
            .unwrap_or(false)
    }) {
        return true;
    }
    let nums: Option<Vec<usize>> = rest.iter().map(|p| p.parse().ok()).collect();
    match nums.as_deref() {
        Some([e]) => *e == pos.1 && pos.2 == 0,
        Some([e, c]) => *e == pos.1 && *c == pos.2,
        _ => false,
    }
}

fn target_of(mapping: &FieldMapping) -> Vec<String> {
    match mapping {
        FieldMapping::Simple(t) => vec![t.clone()],
        FieldMapping::Structured(s) => {
            let mut v = vec![s.target.clone()];
            v.extend(s.also_target.clone());
            v
        }
        FieldMapping::Nested(_) => vec![],
    }
}

/// Collection key (JSON field name) → qualifier field targets (dotted paths
/// relative to an element), derived from the mapping definitions and the MIG.
///
/// An array element is one repetition of the **shallowest** group the
/// collection's definitions map (e.g. `messlokation[]` from `SG4.SG8` with its
/// `SG4.SG8.SG10` data flattened in): only the qualifier of that group decides
/// whether two elements are distinguishable. A child group's qualifier (the
/// SG10 `CCI`) does not — SG8 repetitions with the same `SEQ` qualifier keep
/// their data order even when their SG10 children differ. When the shallowest
/// group's qualifier is not mapped to a field (defaulted or discriminated), the
/// collection is not permuted.
fn qualifier_fields(defs: &[&MappingDefinition], mig: &MigSchema) -> BTreeMap<String, Vec<String>> {
    let key_of = |def: &MappingDefinition| match &def.meta.parent_field {
        Some(pf) => pf.clone(),
        None => to_camel_case(&def.meta.entity),
    };
    let depth = |def: &MappingDefinition| def.meta.source_group.split('.').count();
    let mut min_depth: BTreeMap<String, usize> = BTreeMap::new();
    for def in defs {
        if def.meta.repeat_on_tag.is_some() || def.meta.source_group.is_empty() {
            continue;
        }
        let d = min_depth.entry(key_of(def)).or_insert(usize::MAX);
        *d = (*d).min(depth(def));
    }
    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for def in defs {
        if def.meta.repeat_on_tag.is_some() || def.meta.source_group.is_empty() {
            continue;
        }
        let key = key_of(def);
        if min_depth.get(&key) != Some(&depth(def)) {
            continue;
        }
        let positions = qualifier_positions(mig, &def.meta.source_group);
        let entry = out.entry(key).or_default();
        for (path, mapping) in &def.fields {
            if positions.iter().any(|p| path_addresses(path, p)) {
                for t in target_of(mapping) {
                    if !t.is_empty() && !entry.contains(&t) {
                        entry.push(t);
                    }
                }
            }
        }
    }
    out.retain(|_, v| !v.is_empty());
    out
}

fn get_dotted<'a>(v: &'a Value, path: &str) -> Option<&'a Value> {
    path.split('.').try_fold(v, |cur, p| cur.get(p))
}

/// Enriched code objects `{code, meaning, enum}` compare by `code`.
fn code_of(v: &Value) -> Value {
    match v.get("code") {
        Some(c) if v.get("meaning").is_some() => c.clone(),
        _ => v.clone(),
    }
}

#[derive(Clone, Copy, Debug)]
enum Perm {
    Reverse,
    Rotate,
}

/// Reorder `items` by qualifier-key group; `None` when nothing would change.
fn permute(items: &[Value], fields: &[String], perm: Perm) -> Option<Vec<Value>> {
    let keys: Vec<String> = items
        .iter()
        .map(|it| {
            fields
                .iter()
                .map(|f| get_dotted(it, f).map(code_of).unwrap_or(Value::Null))
                .map(|v| v.to_string())
                .collect::<Vec<_>>()
                .join("|")
        })
        .collect();
    // Every element must carry some qualifier value, else we cannot tell it apart.
    if keys.iter().any(|k| k.split('|').all(|p| p == "null")) {
        return None;
    }
    let mut order: Vec<&String> = Vec::new();
    for k in &keys {
        if !order.contains(&k) {
            order.push(k);
        }
    }
    if order.len() < 2 {
        return None;
    }
    match perm {
        Perm::Reverse => order.reverse(),
        Perm::Rotate => order.rotate_left(1),
    }
    let mut out = Vec::with_capacity(items.len());
    for k in order {
        for (it, key) in items.iter().zip(&keys) {
            if key == k {
                out.push(it.clone());
            }
        }
    }
    Some(out)
}

/// Permute every qualifier-distinguishable array inside `v` (an entity object
/// or collection). Returns the labels of the arrays that were changed.
/// `only`: restrict to the array with this label (for failure localization).
fn permute_value(
    v: &mut Value,
    label: &str,
    qf: &BTreeMap<String, Vec<String>>,
    perm: Perm,
    only: Option<&str>,
    changed: &mut Vec<String>,
) {
    match v {
        Value::Object(map) => {
            for (k, child) in map.iter_mut() {
                let child_label = format!("{label}.{k}");
                if let (Value::Array(items), Some(fields)) = (&*child, qf.get(k)) {
                    if only.map_or(true, |o| o == child_label) {
                        if let Some(p) = permute(items, fields, perm) {
                            *child = Value::Array(p);
                            changed.push(child_label.clone());
                        }
                    }
                }
                permute_value(child, &child_label, qf, perm, only, changed);
            }
        }
        Value::Array(items) => {
            for it in items.iter_mut() {
                permute_value(it, &format!("{label}[]"), qf, perm, only, changed);
            }
        }
        _ => {}
    }
}

/// Number of MIG variants of `parent_group` in the PID (entry segment `Number`
/// among the AHB's) that contain a PID variant of the group on the way to
/// `child_group` (e.g. `SG14.SG15` → `SG14.SG15.SG25`: SG15 variants with an SG25).
fn parent_variants_with_child(
    mig: &MigSchema,
    numbers: &[String],
    parent_group: &str,
    child_group: &str,
) -> usize {
    let in_pid = |g: &MigSegmentGroup| {
        g.segments
            .first()
            .and_then(|s| s.number.as_ref())
            .map_or(true, |n| numbers.contains(n))
    };
    let Some(next_id) = child_group
        .strip_prefix(parent_group)
        .and_then(|rest| rest.strip_prefix('.'))
        .and_then(|rest| rest.split('.').next())
    else {
        return 0;
    };
    mig_groups_at(mig, parent_group)
        .into_iter()
        .filter(|g| in_pid(g))
        .filter(|g| g.nested_groups.iter().any(|c| c.id == next_id && in_pid(c)))
        .count()
}

/// Top-level collections of `scope` paired with a parent collection by array
/// position: `child` is mapped (without `parent_field`) from a group below the
/// group of `parent`, several PID variants of the parent group can hold that
/// child group, and `parent` is an array whose elements differ in their
/// qualifier. The transaction group itself (`tx_group`) is no parent: each
/// transaction is its own JSON object.
fn positional_pairings(
    defs: &[&MappingDefinition],
    scope: &Value,
    qf: &BTreeMap<String, Vec<String>>,
    tx_group: Option<&str>,
    mig: &MigSchema,
    numbers: &[String],
) -> Vec<String> {
    let Some(obj) = scope.as_object() else {
        return Vec::new();
    };
    let mut groups: BTreeMap<String, BTreeSet<&str>> = BTreeMap::new();
    for def in defs {
        if def.meta.parent_field.is_some() || def.meta.source_group.is_empty() {
            continue;
        }
        groups
            .entry(to_camel_case(&def.meta.entity))
            .or_default()
            .insert(def.meta.source_group.as_str());
    }
    let mut out = Vec::new();
    for (parent, parent_groups) in &groups {
        let Some(Value::Array(items)) = obj.get(parent) else {
            continue;
        };
        let distinguishable = qf
            .get(parent)
            .is_some_and(|fields| permute(items, fields, Perm::Reverse).is_some());
        if !distinguishable {
            continue;
        }
        for (child, child_groups) in &groups {
            let present = obj
                .get(child)
                .is_some_and(|v| v.as_array().map_or(v.is_object(), |a| !a.is_empty()));
            if child == parent || !present || !child_groups.is_disjoint(parent_groups) {
                continue;
            }
            let below = child_groups.iter().any(|c| {
                parent_groups.iter().any(|p| {
                    Some(*p) != tx_group && parent_variants_with_child(mig, numbers, p, c) >= 2
                })
            });
            if below {
                out.push(format!("`{child}` paired with `{parent}[]` by position"));
            }
        }
    }
    out
}

enum Outcome {
    Pass { permuted: usize },
    Skip(String),
    Fail(String),
}

fn first_diff(a: &str, b: &str) -> String {
    let sa: Vec<&str> = a.split('\'').collect();
    let sb: Vec<&str> = b.split('\'').collect();
    sa.iter()
        .zip(&sb)
        .find(|(x, y)| x != y)
        .map(|(x, y)| format!("{x}' vs {y}'"))
        .unwrap_or_else(|| format!("{} vs {} segments", sa.len(), sb.len()))
}

#[allow(clippy::too_many_arguments)]
fn check_fixture(
    mapper: &Mapper,
    vc: &VariantCache,
    fv: &str,
    variant: &str,
    pid: &str,
    edifact: &str,
) -> Outcome {
    let ic = match mapper.from_edifact::<Value, Value>(edifact, fv, variant, pid) {
        Ok(ic) => ic,
        Err(e) => return Outcome::Fail(format!("forward error: {e}")),
    };
    let Some(mig) = vc.mig_schema.as_ref() else {
        return Outcome::Skip("no MIG".into());
    };
    let msg_defs: Vec<&MappingDefinition> = vc.message_defs.iter().collect();
    let tx_defs: Vec<&MappingDefinition> = vc
        .transaction_defs
        .get(&format!("pid_{pid}"))
        .map(|d| d.iter().collect())
        .unwrap_or_default();
    let qf_msg = qualifier_fields(&msg_defs, mig);
    let qf_tx = qualifier_fields(&tx_defs, mig);

    let n = &ic.nachrichten[0];
    let msg = n.stammdaten.clone();
    let txs = n.transaktionen.clone();

    let tx_group = vc.tx_group(pid).filter(|g| !g.is_empty());
    let numbers = vc
        .pid_segment_numbers
        .get(&format!("pid_{pid}"))
        .cloned()
        .unwrap_or_default();
    let mut pairings = positional_pairings(&msg_defs, &msg, &qf_msg, None, mig, &numbers);
    for tx in &txs {
        for p in positional_pairings(&tx_defs, tx, &qf_tx, tx_group, mig, &numbers) {
            if !pairings.contains(&p) {
                pairings.push(p);
            }
        }
    }
    if !pairings.is_empty() {
        return Outcome::Fail(format!("positional pairing: {}", pairings.join("; ")));
    }
    let render = |m: &Value, t: &[Value]| mapper.to_edifact(m, t, fv, variant, pid);
    let original = match render(&msg, &txs) {
        Ok(s) => s,
        Err(e) => return Outcome::Skip(format!("unpermuted JSON does not render: {e}")),
    };

    let apply = |perm: Perm, only: Option<&str>| {
        let mut changed = Vec::new();
        let mut m = msg.clone();
        permute_value(&mut m, "message", &qf_msg, perm, only, &mut changed);
        let mut t = txs.clone();
        for (i, tx) in t.iter_mut().enumerate() {
            permute_value(tx, &format!("tx[{i}]"), &qf_tx, perm, only, &mut changed);
        }
        (m, t, changed)
    };

    let mut permuted = 0;
    for perm in [Perm::Reverse, Perm::Rotate] {
        let (m, t, changed) = apply(perm, None);
        if changed.is_empty() {
            continue;
        }
        permuted += 1;
        let result = render(&m, &t);
        // Debug aid: `PERMUTATION_GATE_DUMP=<dir>` writes JSON and both renders.
        if let Some(dir) = std::env::var_os("PERMUTATION_GATE_DUMP") {
            let path = PathBuf::from(dir).join(format!("{fv}_{variant}_{pid}_{perm:?}.json"));
            let json = serde_json::json!({
                "original": { "message": msg, "transaktionen": txs, "edifact": original },
                "permuted": { "message": m, "transaktionen": t,
                              "edifact": result.as_ref().map_err(|e| e.to_string()) },
            });
            std::fs::write(path, serde_json::to_string_pretty(&json).unwrap()).unwrap();
        }
        if result.as_deref().ok() == Some(original.as_str()) {
            continue;
        }
        // Localize: which arrays change the output on their own?
        let mut culprits = Vec::new();
        for label in &changed {
            let (m1, t1, _) = apply(perm, Some(label));
            match render(&m1, &t1) {
                Ok(s) if s == original => {}
                Ok(s) => culprits.push(format!("{label} ({})", first_diff(&original, &s))),
                Err(e) => culprits.push(format!("{label} (render error: {e})")),
            }
        }
        if culprits.is_empty() {
            culprits.push(match result {
                Ok(s) => format!("combined only: {}", first_diff(&original, &s)),
                Err(e) => format!("combined only: render error {e}"),
            });
        }
        return Outcome::Fail(format!("{perm:?}: {}", culprits.join("; ")));
    }
    Outcome::Pass { permuted }
}

/// Find the variant and PID of a fixture: the file stem is the PID for all but
/// message-only types, whose PID comes from `detect_pid` or the variant's
/// single PID.
fn resolve(
    mapper: &Mapper,
    bundle: &DataBundle,
    msg: &str,
    stem: &str,
    edifact: &str,
) -> Option<(String, String)> {
    let detected = mapper.detect_pid(edifact).ok();
    let mut variants: Vec<&String> = bundle.variants.keys().collect();
    variants.sort();
    for variant in variants {
        let lower = variant.to_lowercase();
        if lower != msg && !lower.starts_with(&format!("{msg}_")) {
            continue;
        }
        let vc = bundle.variant(variant).unwrap();
        let mut candidates = vec![stem.to_string()];
        candidates.extend(detected.clone());
        if vc.tx_groups.len() == 1 {
            let only = vc.tx_groups.keys().next().unwrap();
            candidates.push(only.trim_start_matches("pid_").to_string());
        }
        // Variants whose AHB has a PID-less workflow (APERAK) register it as "".
        candidates.push(String::new());
        for pid in candidates {
            if vc.tx_group(&pid).is_some() {
                return Some((variant.to_string(), pid));
            }
        }
    }
    None
}

fn run_gate(fv: &str) {
    let root = repo_root();
    let dist = root.join("dist");
    let bundle_path = dist.join(format!("edifact-data-{fv}.bin"));
    let fixtures = root.join("fixtures/generated").join(fv.to_lowercase());
    if !bundle_path.exists() || !fixtures.is_dir() {
        eprintln!("skipping {fv}: bundle or fixtures missing");
        return;
    }
    let mapper = Mapper::from_data_dir(DataDir::path(&dist).eager(&[fv])).expect("load bundle");
    let bundle = DataBundle::load(&bundle_path).expect("load bundle");

    let mut report: BTreeMap<String, BTreeMap<&str, usize>> = BTreeMap::new();
    let mut failures: Vec<(String, String)> = Vec::new();
    let mut skips: Vec<(String, String)> = Vec::new();

    let mut files: Vec<PathBuf> = walk(&fixtures);
    files.sort();
    for file in files {
        let msg = file
            .parent()
            .and_then(|p| p.file_name())
            .unwrap()
            .to_string_lossy()
            .to_string();
        let stem = file.file_stem().unwrap().to_string_lossy().to_string();
        let key = format!("{msg}/{stem}");
        let edifact = std::fs::read_to_string(&file).unwrap();
        let entry = report.entry(msg.clone()).or_default();
        let Some((variant, pid)) = resolve(&mapper, &bundle, &msg, &stem, &edifact) else {
            // Stray fixtures without a PID of their bundle (e.g. `##alt##.edi`).
            *entry.entry("skip").or_default() += 1;
            skips.push((key, "cannot resolve variant/PID".into()));
            continue;
        };
        let vc = bundle.variant(&variant).unwrap();
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            check_fixture(&mapper, vc, fv, &variant, &pid, &edifact)
        }))
        .unwrap_or_else(|p| {
            let detail = p
                .downcast_ref::<String>()
                .cloned()
                .or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string()))
                .unwrap_or_default();
            Outcome::Fail(format!("panic: {detail}"))
        });
        match outcome {
            Outcome::Pass { permuted: 0 } => *entry.entry("pass-unpermuted").or_default() += 1,
            Outcome::Pass { .. } => *entry.entry("pass").or_default() += 1,
            Outcome::Skip(why) => {
                *entry.entry("skip").or_default() += 1;
                skips.push((key, why));
            }
            Outcome::Fail(why) => {
                *entry.entry("FAIL").or_default() += 1;
                failures.push((key, why));
            }
        }
    }

    eprintln!("\n=== reverse-order permutation gate {fv} ===");
    for (msg, counts) in &report {
        let line: Vec<String> = counts.iter().map(|(k, c)| format!("{k}={c}")).collect();
        eprintln!("{msg:>8}: {}", line.join(" "));
    }
    for (key, why) in &skips {
        eprintln!("[skip] {key}: {why}");
    }
    let known: BTreeSet<&str> = KNOWN_FAILURES
        .iter()
        .filter(|(fvs, _, _)| fvs.contains(&fv))
        .map(|(_, k, _)| *k)
        .collect();
    for (key, why) in &failures {
        let marker = if known.contains(key.as_str()) {
            "known"
        } else {
            "FAIL"
        };
        let short: String = why.chars().take(700).collect();
        eprintln!("[{marker}] {key}: {short}");
    }
    let unexpected = failures
        .iter()
        .filter(|(k, _)| !known.contains(k.as_str()))
        .count();
    let stale: Vec<&&str> = known
        .iter()
        .filter(|k| !failures.iter().any(|(key, _)| key == **k))
        .collect();
    assert!(
        unexpected == 0 && stale.is_empty(),
        "{fv}: {unexpected} fixture(s) render differently when entity arrays are permuted; \
         stale KNOWN_FAILURES entries: {stale:?}"
    );
}

fn walk(dir: &PathBuf) -> Vec<PathBuf> {
    let mut out = Vec::new();
    for e in std::fs::read_dir(dir).unwrap().flatten() {
        let p = e.path();
        if p.is_dir() {
            out.extend(walk(&p));
        } else if p.extension().is_some_and(|x| x == "edi") {
            out.push(p);
        }
    }
    out
}

#[test]
fn permutation_gate_fv2504() {
    run_gate("FV2504");
}

#[test]
fn permutation_gate_fv2510() {
    run_gate("FV2510");
}

#[test]
fn permutation_gate_fv2604() {
    run_gate("FV2604");
}

#[test]
fn permutation_gate_fv2610() {
    run_gate("FV2610");
}