convert-rs-core 0.2.0

Format models and deterministic conversion graph planning for convert-rs
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
//! Pure, deterministic format registration and policy-controlled route planning.
//!
//! Routes are loopless and returned in nondecreasing cost order. Equal-cost
//! ordering is deterministic for a given graph, independent of edge registration
//! order. Search uses
//! reverse shortest-path distances to avoid exploring target-unreachable paths.
//!
//! This crate only describes formats and routes. It does not inspect files,
//! execute adapters, validate codec support, or guarantee conversion fidelity.
//! Conversion classifications and costs are supplied by the graph's registrant.
//!
//! # Plan a conversion
//!
//! ```rust
//! use convert_rs_core::{Conversion, ConversionKind, Format, Graph, MediaKind, Policy};
//!
//! let mut graph = Graph::new();
//! graph.add_format(Format::new("note", "Note", MediaKind::Text)
//!     .with_extensions(&["txt"]))?;
//! graph.add_format(Format::new("speech", "Speech", MediaKind::Audio))?;
//! graph.add_conversion(Conversion::new(
//!     "note", "speech", "reader", "speak", ConversionKind::Bridge, 3,
//! ))?;
//! let routes = graph.routes(".TXT", "speech", &Policy::default())?;
//! assert_eq!(routes[0].cost, 3);
//! assert_eq!(routes[0].steps[0].operation, "speak");
//! let strict = Policy { allow_bridges: false, ..Policy::default() };
//! assert!(graph.routes("note", "speech", &strict).is_err());
//! # Ok::<(), convert_rs_core::PlanError>(())
//! ```
#![warn(missing_docs)]

use std::cmp::Reverse;
use std::collections::{BTreeMap, BinaryHeap};
use std::fmt;
use std::rc::Rc;

/// A format's media category. Categories do not restrict graph connectivity.
///
/// Its [`fmt::Display`] representation is the lowercase category name.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MediaKind {
    /// Unstructured bytes without a more specific category.
    Binary,
    /// Human-readable text.
    Text,
    /// Structured or tabular data.
    Data,
    /// Still images.
    Image,
    /// Audio streams.
    Audio,
    /// Video streams.
    Video,
    /// Documents intended for reading or printing.
    Document,
    /// Containers of files or compressed content.
    Archive,
    /// Model data, such as three-dimensional geometry.
    Model,
    /// Font files.
    Font,
}

impl fmt::Display for MediaKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Binary => "binary",
            Self::Text => "text",
            Self::Data => "data",
            Self::Image => "image",
            Self::Audio => "audio",
            Self::Video => "video",
            Self::Document => "document",
            Self::Archive => "archive",
            Self::Model => "model",
            Self::Font => "font",
        })
    }
}

/// A registered format and its lookup metadata.
///
/// A format ID describes a file representation, not an encoder configuration.
/// Registering a format does not imply that any conversion to or from it exists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Format {
    /// Stable format identifier used in plans and conversion requests.
    pub id: String,
    /// Human-readable format name.
    pub name: String,
    /// Extension aliases, normalized and deduplicated during registration.
    pub extensions: Vec<String>,
    /// Broad media category.
    pub media: MediaKind,
    /// Mark the format as decode-only for routing purposes.
    ///
    /// Unless [`Policy::allow_decode_only`] is set, search skips edges targeting
    /// this format. It may still be a source or an identity target. This flag
    /// does not itself check an adapter's encoding capabilities.
    pub decode_only: bool,
}

impl Format {
    /// Construct a format without extensions and with `decode_only` set to false.
    ///
    /// This constructor does not validate the ID; [`Graph::add_format`] does.
    pub fn new(id: &str, name: &str, media: MediaKind) -> Self {
        Self {
            id: id.to_owned(),
            name: name.to_owned(),
            extensions: Vec::new(),
            media,
            decode_only: false,
        }
    }

    /// Set extension aliases, normalizing case, whitespace, and leading dots.
    ///
    /// Replaces previous aliases, sorts and deduplicates them. Invalid aliases
    /// are rejected later by [`Graph::add_format`], not by this method.
    pub fn with_extensions(mut self, extensions: &[&str]) -> Self {
        self.extensions = extensions.iter().map(|value| extension(value)).collect();
        self.extensions.sort();
        self.extensions.dedup();
        self
    }

    /// Set the decode-only routing flag; see [`Self::decode_only`].
    #[must_use]
    pub fn decode_only(mut self) -> Self {
        self.decode_only = true;
        self
    }
}

/// An adapter-declared description of a conversion's semantics.
///
/// These labels drive policy filtering; they are not verified by the planner.
/// There is no policy switch that disables all lossy conversions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ConversionKind {
    /// Preserves the content represented by the operation, as declared by its adapter.
    Lossless,
    /// May discard quality, structure, or metadata during conversion.
    Lossy,
    /// Expresses content in a different semantic representation.
    Bridge,
    /// Interprets input bytes as another format, possibly validating them.
    Reinterpret,
    /// Packages files without converting their contents.
    Package,
    /// Extracts content from an archive or compressed stream.
    Extract,
}

/// A directed conversion edge supplied by an adapter.
///
/// Backend and operation IDs are opaque to the planner. They do not select
/// codecs, quality settings, or other encoder parameters in this crate.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Conversion {
    /// Source format ID, or `*` for a wildcard accepted by [`Graph::add_conversion`].
    pub from: String,
    /// Target format ID.
    pub to: String,
    /// Adapter name.
    pub backend: String,
    /// Adapter operation ID.
    pub operation: String,
    /// Semantic conversion classification.
    pub kind: ConversionKind,
    /// Positive relative route cost; lower sums are preferred, not measured runtime.
    pub cost: u32,
    /// True when executing this step spawns an out-of-process native tool.
    pub external: bool,
}

impl Conversion {
    /// Construct an edge with [`Self::external`] set to false.
    ///
    /// Values are copied without validation. [`Graph::add_conversion`] checks
    /// endpoint registration, positive cost, and nonblank backend and operation.
    pub fn new(
        from: &str,
        to: &str,
        backend: &str,
        operation: &str,
        kind: ConversionKind,
        cost: u32,
    ) -> Self {
        Self {
            from: from.to_owned(),
            to: to.to_owned(),
            backend: backend.to_owned(),
            operation: operation.to_owned(),
            kind,
            cost,
            external: false,
        }
    }

    /// Flag this edge as requiring an out-of-process native tool.
    #[must_use]
    pub fn requires_external(mut self) -> Self {
        self.external = true;
        self
    }
}

/// Gates and search budgets used by [`Graph::routes`].
///
/// Defaults allow lossless, lossy, bridge, and extraction steps. Reinterpretation,
/// packaging, external tools, external packaging, and decode-only destinations
/// are disabled. Default search budgets are 6 steps, 8 routes, and 20,000 forward
/// edge examinations. These are planning limits, not execution resource limits.
///
/// To require lossless steps, inspect each returned [`Plan`] yourself; disabling
/// bridges does not disable [`ConversionKind::Lossy`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Policy {
    /// Permit semantic bridge conversions; enabled by default.
    pub allow_bridges: bool,
    /// Permit binary reinterpretation routes; disabled by default.
    pub allow_reinterpret: bool,
    /// Permit archive packaging routes; disabled by default. Extraction is independent.
    pub allow_packaging: bool,
    /// Permit routes from native external tools. Disabled by default because
    /// out-of-process tools cannot be sandboxed by this library.
    pub allow_external: bool,
    /// Additionally permit external Reinterpret and Package steps; disabled by default.
    ///
    /// The corresponding kind gate and [`Self::allow_external`] must also be set.
    pub allow_external_packaging: bool,
    /// Permit edges targeting formats marked [`Format::decode_only`].
    ///
    /// Disabled by default. Source formats and zero-step identity routes are not
    /// restricted by this flag. Enabling it does not add encoder support.
    pub allow_decode_only: bool,
    /// Maximum conversions per route, capped at 64. Zero allows identity only.
    pub max_steps: usize,
    /// Maximum routes returned, capped at 64. Zero is invalid.
    pub max_routes: usize,
    /// Maximum candidate edges examined during forward search, capped at 100,000.
    /// Reverse shortest-path preprocessing is linearithmic in graph size and is
    /// not charged to this limit. Zero permits no forward edge examinations.
    pub max_expansions: usize,
}

impl Default for Policy {
    fn default() -> Self {
        Self {
            allow_bridges: true,
            allow_reinterpret: false,
            allow_packaging: false,
            allow_external: false,
            allow_external_packaging: false,
            allow_decode_only: false,
            max_steps: 6,
            max_routes: 8,
            max_expansions: 20_000,
        }
    }
}

impl Policy {
    /// Test only the kind gate, without inspecting external tools or formats.
    ///
    /// Lossless, lossy, and extraction steps always pass. Use [`Self::allows_edge`]
    /// to also apply the external-tool gates.
    #[must_use]
    pub fn allows(&self, kind: ConversionKind) -> bool {
        match kind {
            ConversionKind::Lossless | ConversionKind::Lossy | ConversionKind::Extract => true,
            ConversionKind::Bridge => self.allow_bridges,
            ConversionKind::Reinterpret => self.allow_reinterpret,
            ConversionKind::Package => self.allow_packaging,
        }
    }

    /// Whether the policy permits executing this exact edge, including the
    /// out-of-process tool and reinterpret/package-from-tools gates.
    ///
    /// Does not check decode-only destinations, search budgets, graph membership,
    /// or backend availability.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use convert_rs_core::{Conversion, ConversionKind, Policy};
    /// let edge = Conversion::new("txt", "zip", "archiver", "pack",
    ///     ConversionKind::Package, 1).requires_external();
    /// let mut policy = Policy {
    ///     allow_packaging: true,
    ///     allow_external: true,
    ///     ..Policy::default()
    /// };
    /// assert!(policy.allows(edge.kind));
    /// assert!(!policy.allows_edge(&edge));
    /// policy.allow_external_packaging = true;
    /// assert!(policy.allows_edge(&edge));
    /// ```
    #[must_use]
    pub fn allows_edge(&self, conversion: &Conversion) -> bool {
        if !self.allows(conversion.kind) {
            return false;
        }
        if conversion.external {
            if !self.allow_external {
                return false;
            }
            if matches!(
                conversion.kind,
                ConversionKind::Reinterpret | ConversionKind::Package
            ) && !self.allow_external_packaging
            {
                return false;
            }
        }
        true
    }
}

/// An ordered sequence of conversion steps and its declared total cost.
///
/// [`Graph::routes`] produces connected, loopless plans. Public fields also allow
/// callers to construct plans directly; this type does not validate them.
/// An empty plan represents an identity operation, not a format validation pass.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Plan {
    /// Steps in execution order.
    ///
    /// Plans returned by [`Graph::routes`] replace wildcard inputs with the
    /// source format at that step. Manually constructed plans must do the same.
    pub steps: Vec<Conversion>,
    /// Sum of edge costs in [`Self::steps`] for planner-generated plans.
    ///
    /// The type does not recalculate this field after manual changes.
    pub cost: u64,
}

/// Errors returned while validating or searching the conversion graph.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum PlanError {
    /// Invalid format metadata, edge metadata, or policy, with an explanation.
    #[error("invalid graph or policy: {0}")]
    Invalid(
        /// Human-readable validation failure.
        String,
    ),
    /// An endpoint or lookup value does not resolve to a registered format.
    #[error("unknown format: {0}")]
    UnknownFormat(
        /// Unresolved ID or lookup value.
        String,
    ),
    /// No route satisfies the policy and step budget.
    #[error("no route from {from} to {to}")]
    NoRoute {
        /// Resolved source format ID.
        from: String,
        /// Resolved target format ID.
        to: String,
    },
    /// The forward edge budget was exhausted before any route was found.
    #[error("route search limit reached before finding a route")]
    SearchLimit,
}

/// An in-memory registry of formats and directed conversion edges.
///
/// Registration validates metadata, not adapter availability or file contents.
/// Search is read-only; no adapter or external process is executed.
#[derive(Clone, Debug, Default)]
pub struct Graph {
    formats: BTreeMap<String, Format>,
    conversions: BTreeMap<String, Vec<Conversion>>,
}

impl Graph {
    /// Create an empty format graph.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a lowercase ASCII ID of 1..=64 bytes using letters, digits,
    /// `-`, `_`, `.`, or `+`. Extensions follow the same rules after normalization.
    /// Duplicate IDs merge sorted, unique extensions and keep the lexicographically
    /// smallest name. Conflicting media categories are rejected without changes.
    /// The first registration's `decode_only` flag is retained for duplicate IDs.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError::Invalid`] for invalid IDs or aliases, or a conflicting
    /// media category. The graph is unchanged on error.
    pub fn add_format(&mut self, mut format: Format) -> Result<(), PlanError> {
        if !valid_id(&format.id) {
            return Err(PlanError::Invalid(format!(
                "invalid format ID: {:?}",
                format.id
            )));
        }
        for value in &mut format.extensions {
            *value = extension(value);
            if !valid_id(value) {
                return Err(PlanError::Invalid(format!(
                    "invalid extension for {}: {value:?}",
                    format.id
                )));
            }
        }
        format.extensions.sort();
        format.extensions.dedup();
        if let Some(existing) = self.formats.get_mut(&format.id) {
            if existing.media != format.media {
                return Err(PlanError::Invalid(format!(
                    "conflicting media categories for {}",
                    format.id
                )));
            }
            if format.name < existing.name {
                existing.name = format.name;
            }
            existing.extensions.extend(format.extensions);
            existing.extensions.sort();
            existing.extensions.dedup();
        } else {
            self.formats.insert(format.id.clone(), format);
        }
        Ok(())
    }

    /// Register an edge between existing IDs. `*` is allowed only as the input
    /// of a Reinterpret or Package edge and matches every registered format.
    /// Identical edges are idempotent; distinct parallel edges are retained.
    ///
    /// Endpoint IDs are exact and case-sensitive, not extension aliases. This
    /// method does not verify that the named backend implements the operation.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError::Invalid`] for zero cost, blank backend or operation,
    /// or an unsupported wildcard kind. Returns [`PlanError::UnknownFormat`]
    /// for unregistered endpoints. The graph is unchanged on error.
    pub fn add_conversion(&mut self, conversion: Conversion) -> Result<(), PlanError> {
        if conversion.cost == 0 {
            return Err(PlanError::Invalid(
                "conversion cost must be positive".into(),
            ));
        }
        if conversion.backend.trim().is_empty() || conversion.operation.trim().is_empty() {
            return Err(PlanError::Invalid(
                "conversion backend and operation must be nonempty".into(),
            ));
        }
        if conversion.from == "*" {
            if !matches!(
                conversion.kind,
                ConversionKind::Reinterpret | ConversionKind::Package
            ) {
                return Err(PlanError::Invalid(
                    "wildcard input requires Reinterpret or Package".into(),
                ));
            }
        } else if !self.formats.contains_key(&conversion.from) {
            return Err(PlanError::UnknownFormat(conversion.from));
        }
        if !self.formats.contains_key(&conversion.to) {
            return Err(PlanError::UnknownFormat(conversion.to));
        }
        let edges = self.conversions.entry(conversion.from.clone()).or_default();
        if let Err(index) = edges.binary_search(&conversion) {
            edges.insert(index, conversion);
        }
        Ok(())
    }

    /// Iterate in ascending format ID order.
    pub fn formats(&self) -> impl Iterator<Item = &Format> {
        self.formats.values()
    }

    /// Look up an exact, case-sensitive registered ID.
    pub fn format(&self, id: &str) -> Option<&Format> {
        self.formats.get(id)
    }

    /// Resolve a trimmed, case-insensitive ID or extension, optionally dot-prefixed.
    /// IDs take precedence over aliases; ambiguous extensions select the smallest
    /// format ID. This does not interpret paths or MIME types.
    pub fn resolve(&self, value: &str) -> Option<&Format> {
        let normalized = value.trim().to_ascii_lowercase();
        if let Some(format) = self.formats.get(&normalized) {
            return Some(format);
        }
        let alias = normalized.trim_start_matches('.');
        self.formats.get(alias).or_else(|| {
            self.formats
                .values()
                .find(|format| format.extensions.iter().any(|value| value == alias))
        })
    }

    /// Enumerate cheapest loopless routes using policy-filtered A* search.
    /// Inputs are resolved as IDs or extension aliases. Equal formats yield one
    /// empty, zero-cost plan. Policy limits above their hard caps are clamped.
    ///
    /// Each path retains its own visited formats, so parallel edges and alternative
    /// prefixes remain eligible. At most `max_expansions` candidate edges are examined,
    /// with shared prefixes rather than copied plans. Equal estimated costs favor
    /// higher spent cost, then deterministic insertion order (specific edges before
    /// wildcard edges, each ordered by the fields of Conversion).
    ///
    /// Reaching the expansion limit returns routes already found, even if fewer
    /// than requested. If none have been found, it returns SearchLimit. Exhausting
    /// the search without a route returns NoRoute, including the step-limit case.
    /// Identity routes do not apply edge or decode-only gates. A successful plan
    /// is a metadata route, not proof that execution will succeed.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError::UnknownFormat`] for an unresolved endpoint,
    /// [`PlanError::Invalid`] for zero `max_routes`, [`PlanError::NoRoute`] when
    /// no permitted route exists within the step budget, or
    /// [`PlanError::SearchLimit`] when the edge budget is exhausted before a route
    /// is found. Partial results carry no separate truncation indicator.
    pub fn routes(&self, from: &str, to: &str, policy: &Policy) -> Result<Vec<Plan>, PlanError> {
        let from = self
            .resolve(from)
            .ok_or_else(|| PlanError::UnknownFormat(from.to_owned()))?;
        let to = self
            .resolve(to)
            .ok_or_else(|| PlanError::UnknownFormat(to.to_owned()))?;
        if policy.max_routes == 0 {
            return Err(PlanError::Invalid("max_routes must be positive".into()));
        }
        if from.id == to.id {
            return Ok(vec![Plan {
                steps: Vec::new(),
                cost: 0,
            }]);
        }
        let no_route = || PlanError::NoRoute {
            from: from.id.clone(),
            to: to.id.clone(),
        };
        let max_steps = policy.max_steps.min(64);
        let max_routes = policy.max_routes.min(64);
        let max_expansions = policy.max_expansions.min(100_000);
        if max_steps == 0 {
            return Err(no_route());
        }
        let distances = self.distances_to(&to.id, policy);
        let Some(&estimate) = distances.get(from.id.as_str()) else {
            return Err(no_route());
        };
        let mut frontier = BTreeMap::new();
        frontier.insert(
            (estimate, Reverse(0_u64), 0_usize),
            Rc::new(SearchPath {
                format: &from.id,
                edge: None,
                previous: None,
                cost: 0,
                depth: 0,
            }),
        );
        let mut plans = Vec::new();
        let mut expansions = 0;
        while let Some((_, path)) = frontier.pop_first() {
            if path.format == to.id {
                let plan = path.plan();
                // A wildcard and a specific edge can materialize the same plan.
                if !plans.contains(&plan) {
                    plans.push(plan);
                }
                if plans.len() == max_routes {
                    return Ok(plans);
                }
                continue;
            }
            if path.depth == max_steps {
                continue;
            }
            let edges = self
                .conversions
                .get(path.format)
                .into_iter()
                .flatten()
                .chain(self.conversions.get("*").into_iter().flatten());
            for edge in edges {
                if expansions == max_expansions {
                    return if plans.is_empty() {
                        Err(PlanError::SearchLimit)
                    } else {
                        Ok(plans)
                    };
                }
                expansions += 1;
                if !policy.allows_edge(edge) || path.contains(&edge.to) {
                    continue;
                }
                if self
                    .formats
                    .get(&edge.to)
                    .is_some_and(|format| format.decode_only)
                    && !policy.allow_decode_only
                {
                    continue;
                }
                let Some(&remaining) = distances.get(edge.to.as_str()) else {
                    continue;
                };
                let cost = path.cost + u64::from(edge.cost);
                frontier.insert(
                    (cost.saturating_add(remaining), Reverse(cost), expansions),
                    Rc::new(SearchPath {
                        format: &edge.to,
                        edge: Some(edge),
                        previous: Some(Rc::clone(&path)),
                        cost,
                        depth: path.depth + 1,
                    }),
                );
            }
        }
        if plans.is_empty() {
            Err(no_route())
        } else {
            Ok(plans)
        }
    }

    fn distances_to<'a>(&'a self, target: &'a str, policy: &Policy) -> BTreeMap<&'a str, u64> {
        let mut reverse: BTreeMap<&str, Vec<(&str, u64)>> = BTreeMap::new();
        for edge in self.conversions.values().flatten() {
            if policy.allows_edge(edge) {
                reverse
                    .entry(&edge.to)
                    .or_default()
                    .push((&edge.from, u64::from(edge.cost)));
            }
        }
        let mut distances = BTreeMap::from([(target, 0_u64)]);
        let mut queue = BinaryHeap::from([Reverse((0_u64, target))]);
        while let Some(Reverse((cost, current))) = queue.pop() {
            if distances.get(current) != Some(&cost) {
                continue;
            }
            let mut relax = |source, weight| {
                let next = cost.saturating_add(weight);
                if distances.get(source).is_none_or(|&known| next < known) {
                    distances.insert(source, next);
                    queue.push(Reverse((next, source)));
                }
            };
            if current == "*" {
                // One virtual wildcard vertex avoids materializing V * W edges.
                for source in self.formats.keys() {
                    relax(source.as_str(), 0);
                }
            } else if let Some(edges) = reverse.get(current) {
                for &(source, weight) in edges {
                    relax(source, weight);
                }
            }
        }
        distances
    }
}

fn valid_id(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 64
        && value.bytes().all(|byte| {
            byte.is_ascii_lowercase()
                || byte.is_ascii_digit()
                || matches!(byte, b'-' | b'_' | b'.' | b'+')
        })
}

fn extension(value: &str) -> String {
    value.trim().trim_start_matches('.').to_ascii_lowercase()
}

// References borrow the immutable graph; Rc shares prefixes only within a query.
struct SearchPath<'a> {
    format: &'a str,
    edge: Option<&'a Conversion>,
    previous: Option<Rc<Self>>,
    cost: u64,
    depth: usize,
}

impl SearchPath<'_> {
    fn contains(&self, format: &str) -> bool {
        let mut current = Some(self);
        while let Some(path) = current {
            if path.format == format {
                return true;
            }
            current = path.previous.as_deref();
        }
        false
    }

    fn plan(&self) -> Plan {
        let mut steps = Vec::with_capacity(self.depth);
        let mut current = self;
        while let (Some(edge), Some(previous)) = (current.edge, current.previous.as_deref()) {
            let mut step = edge.clone();
            step.from = previous.format.to_owned();
            steps.push(step);
            current = previous;
        }
        steps.reverse();
        Plan {
            steps,
            cost: self.cost,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;

    fn graph(ids: &[&str]) -> Graph {
        let mut graph = Graph::new();
        for id in ids {
            graph
                .add_format(Format::new(id, id, MediaKind::Data))
                .unwrap();
        }
        graph
    }

    fn edge(from: &str, to: &str, backend: &str, cost: u32) -> Conversion {
        Conversion::new(from, to, backend, "convert", ConversionKind::Lossless, cost)
    }

    #[test]
    fn registration_validates_ids_and_normalizes_extensions() {
        let mut graph = Graph::new();
        for id in ["", "UPPER", "*", "a/b", "a b", "a\0b", "a:b"] {
            assert!(matches!(
                graph.add_format(Format::new(id, "name", MediaKind::Binary)),
                Err(PlanError::Invalid(_))
            ));
        }
        assert!(
            graph
                .add_format(Format::new(&"a".repeat(65), "name", MediaKind::Binary))
                .is_err()
        );
        graph
            .add_format(Format::new(&"a".repeat(64), "name", MediaKind::Binary))
            .unwrap();
        graph
            .add_format(
                Format::new("a-z_0.9+", "name", MediaKind::Binary)
                    .with_extensions(&[" .ABC ", "abc", "tar.gz"]),
            )
            .unwrap();
        assert_eq!(
            graph.format("a-z_0.9+").unwrap().extensions,
            ["abc", "tar.gz"]
        );
        for alias in ["", ".", "a/b", "*"] {
            assert!(
                graph
                    .add_format(
                        Format::new("bad", "bad", MediaKind::Data).with_extensions(&[alias])
                    )
                    .is_err()
            );
        }
        assert!(graph.format("bad").is_none());
    }

    #[test]
    fn duplicate_formats_merge_independently_of_registration_order() {
        let first = Format::new("jpeg", "JPEG", MediaKind::Image).with_extensions(&["jpeg", "jpg"]);
        let second = Format::new("jpeg", "Joint photographic", MediaKind::Image)
            .with_extensions(&["JPG", "jpe"]);
        let mut forward = Graph::new();
        let mut backward = Graph::new();
        for format in [first.clone(), second.clone()] {
            forward.add_format(format).unwrap();
        }
        for format in [second, first] {
            backward.add_format(format).unwrap();
        }
        assert_eq!(forward.formats, backward.formats);
        let before = forward.formats.clone();
        assert!(
            forward
                .add_format(Format::new("jpeg", "wrong", MediaKind::Audio))
                .is_err()
        );
        assert_eq!(forward.formats, before);
        assert_eq!(
            forward.format("jpeg").unwrap().extensions,
            ["jpe", "jpeg", "jpg"]
        );
    }

    #[test]
    fn resolving_prefers_ids_then_sorted_extension_aliases() {
        let mut graph = graph(&["z", "a", "jpg", ".special"]);
        graph
            .add_format(Format::new("z", "z", MediaKind::Data).with_extensions(&["jpg", "shared"]))
            .unwrap();
        graph
            .add_format(
                Format::new("a", "a", MediaKind::Data).with_extensions(&["shared", "tar.gz"]),
            )
            .unwrap();
        assert_eq!(graph.resolve(" .JPG ").unwrap().id, "jpg");
        assert_eq!(graph.resolve("SHARED").unwrap().id, "a");
        assert_eq!(graph.resolve(".tar.GZ").unwrap().id, "a");
        assert_eq!(graph.resolve(".SPECIAL").unwrap().id, ".special");
        assert!(graph.format("JPG").is_none());
        assert!(graph.resolve("image/jpeg").is_none());
        assert!(graph.resolve("file.tar.gz").is_none());
        assert!(graph.resolve("").is_none());
        assert_eq!(
            graph
                .formats()
                .map(|format| format.id.as_str())
                .collect::<Vec<_>>(),
            [".special", "a", "jpg", "z"]
        );
    }

    #[test]
    fn conversions_require_valid_endpoints_metadata_and_cost() {
        let mut graph = graph(&["a", "b"]);
        for conversion in [
            edge("a", "b", "backend", 0),
            edge("a", "b", "  ", 1),
            Conversion::new("a", "b", "backend", "\n", ConversionKind::Lossless, 1),
            edge("*", "b", "backend", 1),
        ] {
            assert!(matches!(
                graph.add_conversion(conversion),
                Err(PlanError::Invalid(_))
            ));
        }
        for conversion in [
            edge("missing", "b", "backend", 1),
            edge("a", "*", "backend", 1),
        ] {
            assert!(matches!(
                graph.add_conversion(conversion),
                Err(PlanError::UnknownFormat(_))
            ));
        }
        let conversion = edge("a", "b", "backend", 1);
        graph.add_conversion(conversion.clone()).unwrap();
        graph.add_conversion(conversion).unwrap();
        assert_eq!(graph.routes("a", "b", &Policy::default()).unwrap().len(), 1);
    }

    #[test]
    fn defaults_allow_lossless_lossy_bridge_and_extract_only() {
        let policy = Policy::default();
        assert_eq!(
            (policy.max_steps, policy.max_routes, policy.max_expansions),
            (6, 8, 20_000)
        );
        let mut graph = graph(&["a", "b"]);
        for kind in [
            ConversionKind::Lossless,
            ConversionKind::Lossy,
            ConversionKind::Bridge,
            ConversionKind::Reinterpret,
            ConversionKind::Package,
            ConversionKind::Extract,
        ] {
            graph
                .add_conversion(Conversion::new("a", "b", "backend", "convert", kind, 1))
                .unwrap();
        }
        let kinds = |policy: &Policy| {
            graph
                .routes("a", "b", policy)
                .unwrap()
                .iter()
                .map(|plan| plan.steps[0].kind)
                .collect::<BTreeSet<_>>()
        };
        assert_eq!(
            kinds(&policy),
            BTreeSet::from([
                ConversionKind::Lossless,
                ConversionKind::Lossy,
                ConversionKind::Bridge,
                ConversionKind::Extract,
            ])
        );
        let restricted = Policy {
            allow_bridges: false,
            ..policy.clone()
        };
        assert_eq!(kinds(&restricted).len(), 3);
        let enabled = Policy {
            allow_reinterpret: true,
            allow_packaging: true,
            ..policy
        };
        assert_eq!(kinds(&enabled).len(), 6);
    }

    #[test]
    fn weighted_routes_keep_parallel_edges_and_alternative_prefixes() {
        let mut graph = graph(&["s", "a", "b", "t"]);
        for conversion in [
            edge("s", "t", "direct", 20),
            edge("s", "a", "first", 1),
            edge("s", "a", "second", 2),
            edge("s", "b", "third", 2),
            edge("b", "a", "merge", 2),
            edge("a", "t", "finish", 1),
            edge("a", "s", "cycle", 1),
            edge("a", "a", "self", 1),
        ] {
            graph.add_conversion(conversion).unwrap();
        }
        let plans = graph.routes("s", "t", &Policy::default()).unwrap();
        assert_eq!(
            plans.iter().map(|plan| plan.cost).collect::<Vec<_>>(),
            [2, 3, 5, 20]
        );
        assert_eq!(plans[0].steps[0].backend, "first");
        assert_eq!(plans[1].steps[0].backend, "second");
        for plan in plans {
            let mut seen = BTreeSet::from(["s"]);
            for step in &plan.steps {
                assert!(seen.insert(&step.to));
            }
        }
        assert!(matches!(
            graph.routes("t", "s", &Policy::default()),
            Err(PlanError::NoRoute { .. })
        ));
    }

    #[test]
    fn wildcard_edges_are_opt_in_and_materialize_actual_inputs() {
        let mut graph = graph(&["source", "binary", "target", "zip"]);
        graph
            .add_conversion(Conversion::new(
                "*",
                "binary",
                "bytes",
                "read",
                ConversionKind::Reinterpret,
                1,
            ))
            .unwrap();
        graph
            .add_conversion(Conversion::new(
                "*",
                "zip",
                "zip",
                "pack",
                ConversionKind::Package,
                2,
            ))
            .unwrap();
        graph
            .add_conversion(edge("binary", "target", "decode", 3))
            .unwrap();
        assert!(matches!(
            graph.routes("source", "target", &Policy::default()),
            Err(PlanError::NoRoute { .. })
        ));
        assert!(matches!(
            graph.routes("source", "zip", &Policy::default()),
            Err(PlanError::NoRoute { .. })
        ));
        let policy = Policy {
            allow_reinterpret: true,
            ..Policy::default()
        };
        let plans = graph.routes("source", "target", &policy).unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].cost, 4);
        assert_eq!(plans[0].steps[0].from, "source");
        assert_eq!(plans[0].steps[1].from, "binary");
        let policy = Policy {
            allow_packaging: true,
            ..Policy::default()
        };
        let plans = graph.routes("source", "zip", &policy).unwrap();
        assert_eq!(plans[0].steps[0].from, "source");
        assert_eq!(plans[0].cost, 2);
    }

    #[test]
    fn wildcard_specific_duplicates_do_not_repeat_plans() {
        let mut graph = graph(&["a", "b"]);
        for from in ["a", "*"] {
            graph
                .add_conversion(Conversion::new(
                    from,
                    "b",
                    "bytes",
                    "read",
                    ConversionKind::Reinterpret,
                    1,
                ))
                .unwrap();
        }
        let policy = Policy {
            allow_reinterpret: true,
            ..Policy::default()
        };
        assert_eq!(graph.routes("a", "b", &policy).unwrap().len(), 1);
    }

    #[test]
    fn identity_unknown_and_cross_media_routes() {
        let mut graph = Graph::new();
        graph
            .add_format(Format::new("text", "Text", MediaKind::Text).with_extensions(&["txt"]))
            .unwrap();
        graph
            .add_format(Format::new("speech", "Speech", MediaKind::Audio))
            .unwrap();
        graph
            .add_conversion(Conversion::new(
                "text",
                "speech",
                "tts",
                "speak",
                ConversionKind::Bridge,
                1,
            ))
            .unwrap();
        assert_eq!(
            graph.routes(".TXT", "speech", &Policy::default()).unwrap()[0].cost,
            1
        );
        let policy = Policy {
            max_steps: 0,
            max_expansions: 0,
            ..Policy::default()
        };
        assert_eq!(
            graph.routes("text", "TXT", &policy).unwrap(),
            [Plan {
                steps: vec![],
                cost: 0
            }]
        );
        assert!(matches!(
            graph.routes("text", "speech", &policy),
            Err(PlanError::NoRoute { .. })
        ));
        assert_eq!(
            graph.routes("unknown", "unknown", &policy),
            Err(PlanError::UnknownFormat("unknown".into()))
        );
        assert_eq!(
            graph.routes("text", "unknown", &policy),
            Err(PlanError::UnknownFormat("unknown".into()))
        );
    }

    #[test]
    fn step_limit_and_large_costs_are_respected() {
        let mut graph = graph(&["a", "b", "c"]);
        graph
            .add_conversion(edge("a", "b", "backend", u32::MAX))
            .unwrap();
        graph
            .add_conversion(edge("b", "c", "backend", u32::MAX))
            .unwrap();
        let policy = Policy {
            max_steps: 1,
            ..Policy::default()
        };
        assert!(matches!(
            graph.routes("a", "c", &policy),
            Err(PlanError::NoRoute { .. })
        ));
        assert_eq!(
            graph.routes("a", "c", &Policy::default()).unwrap()[0].cost,
            2 * u64::from(u32::MAX)
        );
    }

    #[test]
    fn expansion_bound_distinguishes_failure_from_partial_results() {
        let mut graph = graph(&["s", "a", "t"]);
        graph.add_conversion(edge("s", "a", "indirect", 5)).unwrap();
        graph.add_conversion(edge("s", "t", "direct", 1)).unwrap();
        graph.add_conversion(edge("a", "t", "finish", 5)).unwrap();
        let policy = Policy {
            max_expansions: 0,
            ..Policy::default()
        };
        assert_eq!(graph.routes("s", "t", &policy), Err(PlanError::SearchLimit));
        let policy = Policy {
            max_expansions: 2,
            ..policy
        };
        let plans = graph.routes("s", "t", &policy).unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].cost, 1);
        let policy = Policy {
            max_routes: 0,
            ..policy
        };
        assert!(matches!(
            graph.routes("s", "t", &policy),
            Err(PlanError::Invalid(_))
        ));
    }

    #[test]
    fn target_heuristic_avoids_combinatorial_dead_ends() {
        let mut graph = graph(&["s", "t"]);
        for index in 0..10 {
            graph
                .add_format(Format::new(
                    &format!("dead{index}"),
                    "Dead",
                    MediaKind::Data,
                ))
                .unwrap();
        }
        for from in 0..10 {
            graph
                .add_conversion(edge("s", &format!("dead{from}"), "dead", 1))
                .unwrap();
            for to in 0..10 {
                graph
                    .add_conversion(edge(
                        &format!("dead{from}"),
                        &format!("dead{to}"),
                        "dead",
                        1,
                    ))
                    .unwrap();
            }
        }
        graph.add_conversion(edge("s", "t", "direct", 100)).unwrap();
        let policy = Policy {
            max_expansions: 11,
            ..Policy::default()
        };
        let plans = graph.routes("s", "t", &policy).unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].cost, 100);
    }

    #[test]
    fn ties_stop_at_requested_routes_without_expanding_all_prefixes() {
        let mut graph = graph(&["s", "a", "t"]);
        graph.add_conversion(edge("s", "a", "indirect", 1)).unwrap();
        graph.add_conversion(edge("s", "t", "direct", 2)).unwrap();
        graph.add_conversion(edge("a", "t", "finish", 1)).unwrap();
        let policy = Policy {
            max_routes: 1,
            max_expansions: 2,
            ..Policy::default()
        };
        let plans = graph.routes("s", "t", &policy).unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].steps.len(), 1);
    }

    #[test]
    fn registration_order_does_not_change_route_order() {
        let mut forward = graph(&["s", "a", "b", "t"]);
        let mut backward = graph(&["t", "b", "a", "s"]);
        let edges = [
            edge("s", "a", "z", 1),
            edge("s", "a", "a", 1),
            edge("s", "b", "b", 1),
            edge("a", "t", "end", 1),
            edge("b", "t", "end", 1),
            edge("s", "t", "direct", 2),
            edge("a", "b", "cycle", 1),
            edge("b", "a", "cycle", 1),
            Conversion::new("*", "t", "zip", "pack", ConversionKind::Package, 2),
        ];
        for edge in &edges {
            forward.add_conversion(edge.clone()).unwrap();
        }
        for edge in edges.iter().rev() {
            backward.add_conversion(edge.clone()).unwrap();
        }
        let policy = Policy {
            allow_packaging: true,
            max_routes: 64,
            ..Policy::default()
        };
        assert_eq!(
            forward.routes("s", "t", &policy),
            backward.routes("s", "t", &policy)
        );
    }

    #[test]
    fn route_and_step_limits_have_hard_caps() {
        let mut graph = graph(&["s", "t"]);
        for index in 0..70 {
            graph
                .add_conversion(edge("s", "t", &format!("backend{index:02}"), 1))
                .unwrap();
        }
        let policy = Policy {
            max_routes: usize::MAX,
            max_steps: usize::MAX,
            max_expansions: usize::MAX,
            ..Policy::default()
        };
        assert_eq!(graph.routes("s", "t", &policy).unwrap().len(), 64);
        for index in 0..66 {
            graph
                .add_format(Format::new(&format!("f{index}"), "Format", MediaKind::Data))
                .unwrap();
            if index > 0 {
                graph
                    .add_conversion(edge(
                        &format!("f{}", index - 1),
                        &format!("f{index}"),
                        "chain",
                        1,
                    ))
                    .unwrap();
            }
        }
        assert_eq!(
            graph.routes("f0", "f64", &policy).unwrap()[0].steps.len(),
            64
        );
        assert!(matches!(
            graph.routes("f0", "f65", &policy),
            Err(PlanError::NoRoute { .. })
        ));
    }

    #[test]
    fn astar_matches_exhaustive_loopless_enumeration() {
        fn enumerate(
            graph: &Graph,
            current: &str,
            visited: &mut Vec<String>,
            steps: &mut Vec<Conversion>,
            plans: &mut Vec<Plan>,
            policy: &Policy,
        ) {
            if current == "t" {
                plans.push(Plan {
                    steps: steps.clone(),
                    cost: steps.iter().map(|step| u64::from(step.cost)).sum(),
                });
                return;
            }
            if steps.len() == policy.max_steps {
                return;
            }
            for edge in graph
                .conversions
                .get(current)
                .into_iter()
                .flatten()
                .chain(graph.conversions.get("*").into_iter().flatten())
            {
                if policy.allows_edge(edge) && !visited.contains(&edge.to) {
                    visited.push(edge.to.clone());
                    let mut step = edge.clone();
                    step.from = current.to_owned();
                    steps.push(step);
                    enumerate(graph, &edge.to, visited, steps, plans, policy);
                    steps.pop();
                    visited.pop();
                }
            }
        }
        let ids = ["s", "a", "b", "c", "t"];
        for seed in 0..24 {
            let policy = Policy {
                allow_packaging: seed % 2 == 0,
                max_steps: seed % 5 + 1,
                max_routes: 64,
                ..Policy::default()
            };
            let mut graph = graph(&ids);
            for (i, from) in ids.iter().enumerate() {
                for (j, to) in ids.iter().enumerate() {
                    let value = seed * 31 + i * 17 + j * 7;
                    if value % 4 != 0 {
                        graph
                            .add_conversion(edge(from, to, "backend", (value % 11 + 1) as u32))
                            .unwrap();
                    }
                }
            }
            for target in ["a", "t"] {
                graph
                    .add_conversion(Conversion::new(
                        "*",
                        target,
                        "wildcard",
                        "pack",
                        ConversionKind::Package,
                        (seed % 3 + 1) as u32,
                    ))
                    .unwrap();
            }
            let mut expected = vec![];
            enumerate(
                &graph,
                "s",
                &mut vec!["s".into()],
                &mut vec![],
                &mut expected,
                &policy,
            );
            if expected.is_empty() {
                assert!(matches!(
                    graph.routes("s", "t", &policy),
                    Err(PlanError::NoRoute { .. })
                ));
                continue;
            }
            let mut actual = graph.routes("s", "t", &policy).unwrap();
            assert!(actual.windows(2).all(|pair| pair[0].cost <= pair[1].cost));
            expected.sort_by(|a, b| (a.cost, &a.steps).cmp(&(b.cost, &b.steps)));
            actual.sort_by(|a, b| (a.cost, &a.steps).cmp(&(b.cost, &b.steps)));
            assert_eq!(actual, expected, "seed {seed}");
        }
    }
}