praxis-proxy-core 0.7.3

Configuration, error types, and server factory for Praxis
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
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024 Praxis Contributors

//! Branch chain validation: name uniqueness, chain references, and nesting depth.
//!
//! Branch chains are resolved into concrete pipelines at startup, so
//! structural problems must be caught here rather than at request time.
//! This module rejects duplicate branch names, dangling chain
//! references, and inline-nesting past the depth ceiling, and enforces
//! ceilings on branch counts and re-entrant iteration limits so that a
//! configuration cannot cause an unbounded loop when a branch rejoins at
//! or before its own filter.
//!
//! Cycles through *named* chain references are not detected here (this
//! module only follows inline chains); they are caught during pipeline
//! resolution, where the recursion trips the depth limit and the build
//! fails. The total expansion size is likewise bounded at build time by
//! the pipeline builder's per-pipeline filter-instance ceiling.

use std::collections::HashSet;

use crate::{
    config::{BranchChainConfig, ChainRef, FilterChainConfig, FilterEntry, ResultMatch},
    errors::ProxyError,
};

// -----------------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------------

/// Maximum allowed branch nesting depth (inline chains within
/// inline chains). Limits config complexity and prevents
/// combinatorial explosion during build-time resolution.
/// Each level allocates its own name index and filter vec,
/// so deep nesting multiplies startup cost.
pub const MAX_BRANCH_DEPTH: usize = 10;

/// Maximum allowed `max_iterations` value for re-entrant
/// branches. Prevents accidental infinite loops when a
/// branch rejoins at or before its own filter. Every
/// re-entrant branch must specify `max_iterations`; this
/// ceiling caps what users can configure.
pub const MAX_ITERATIONS_CEILING: u32 = 100;

/// Maximum branch chains a single filter may define.
const MAX_BRANCHES_PER_FILTER: usize = 16;

/// Maximum total branch chain count across all filter chains.
const MAX_TOTAL_BRANCHES: usize = 256;

/// Maximum length of an `on_result.result` value in bytes. Filter results are
/// capped at the same length, so a longer value could never match.
const MAX_RESULT_VALUE_LEN: usize = 256;

// -----------------------------------------------------------------------------
// Branch Chain Validation
// -----------------------------------------------------------------------------

/// Validate all branch chains across all filter chains.
pub(crate) fn validate_branch_chains(chains: &[FilterChainConfig]) -> Result<(), ProxyError> {
    let chain_names: HashSet<&str> = chains.iter().map(|chain| chain.name.as_str()).collect();
    let initial_count = chain_names.len();
    let mut all_names: HashSet<String> = chain_names.iter().map(|name| (*name).to_owned()).collect();

    for chain in chains {
        validate_filter_names_unique(&chain.filters, &chain.name)?;
        collect_branch_names(&chain.filters, &mut all_names, &chain_names, 0)?;
    }

    let branch_count = all_names.len().saturating_sub(initial_count);
    if branch_count > MAX_TOTAL_BRANCHES {
        return Err(ProxyError::Config(format!(
            "total branch count ({branch_count}) exceeds maximum ({MAX_TOTAL_BRANCHES})"
        )));
    }

    Ok(())
}

/// Validate branch-chain constraints for a single chain's filter entries.
///
/// This is the entry-level slice of the whole-config `validate_branch_chains`
/// pass: it enforces filter-name uniqueness, the per-filter branch cap, the
/// re-entrant [`MAX_ITERATIONS_CEILING`], the inline nesting [`MAX_BRANCH_DEPTH`],
/// the total-branch ceiling (`MAX_TOTAL_BRANCHES`), and chain-reference
/// resolution over one list of [`FilterEntry`]. It exists so outbound chains
/// bound at pipeline-build time — which never appear in `Config::filter_chains`
/// — are held to the same branch-chain limits (notably the `max_iterations`
/// ceiling that bounds re-entrant request loops) as top-level chains instead of
/// bypassing them.
///
/// `known_chains` names the top-level filter chains a [`ChainRef::Named`] branch
/// reference may resolve against; a bound chain with no reachable named chains
/// passes an empty set.
///
/// `prior_branch_count` is the number of branch definitions already counted
/// toward the total-branch ceiling elsewhere in the same build — the branches
/// present configuration-wide and in any previously bound inline outbound chains.
/// The ceiling bounds config complexity across the whole build, not each chain in
/// isolation, so this chain's own branch count is added to `prior_branch_count`
/// and the cumulative total is checked. The cumulative total is returned so a
/// caller can thread it into the next bound chain's check; seed the first call
/// with [`count_build_branches`] over the listener entries and every named chain
/// so branches already present anywhere in the configuration are counted.
///
/// # Errors
///
/// Returns [`ProxyError::Config`] if a filter or branch name duplicates, a
/// re-entrant branch exceeds `max_iterations`, inline nesting exceeds
/// [`MAX_BRANCH_DEPTH`], a chain reference is malformed or dangling, or the
/// cumulative branch total exceeds the maximum (`MAX_TOTAL_BRANCHES`).
pub fn validate_chain_entries_branch_chains(
    chain_name: &str,
    entries: &[FilterEntry],
    known_chains: &HashSet<&str>,
    prior_branch_count: usize,
) -> Result<usize, ProxyError> {
    validate_filter_names_unique(entries, chain_name)?;
    let initial_count = known_chains.len();
    let mut all_names: HashSet<String> = known_chains.iter().map(|name| (*name).to_owned()).collect();
    collect_branch_names(entries, &mut all_names, known_chains, 0)?;

    let branch_count = all_names.len().saturating_sub(initial_count);
    let total = prior_branch_count.saturating_add(branch_count);
    if total > MAX_TOTAL_BRANCHES {
        return Err(ProxyError::Config(format!(
            "total branch count ({total}) exceeds maximum ({MAX_TOTAL_BRANCHES})"
        )));
    }

    Ok(total)
}

/// Count the branch definitions across a whole pipeline build: the listener's
/// own `entries` plus every named chain in `chains`, deduplicated by name
/// exactly as the whole-config `validate_branch_chains` pass counts them.
///
/// `validate_branch_chains` enforces the total-branch ceiling only over
/// `Config::filter_chains`; outbound chains bound at pipeline-build time never
/// appear there. Seeding a build's shared branch budget with this
/// configuration-wide count — rather than the listener's entries alone — makes
/// the ceiling span the whole configuration: a named outbound chain the listener
/// never references still counts toward the budget that later-bound *inline*
/// chains accumulate on top of, so the config-wide pool and the inline pool
/// cannot each sit under the ceiling while exceeding it together. In production
/// the listener `entries` are a concatenation of chains already in `chains`, so
/// counting both merely deduplicates; a caller that passes entries not present in
/// `chains` (a direct build) still has those branches counted.
///
/// Named refs resolve to chains counted here, so they are ignored inside branch
/// chains; `known_chains` seeds the name set so a branch or inline name colliding
/// with a chain name is not double counted. This is a pure counter: unlike the
/// validating pass it emits no config-typo warnings and enforces no limits, so
/// seeding a build's budget does not re-warn about entries the whole-config pass
/// already validated.
pub fn count_build_branches(entries: &[FilterEntry], chains: &[&[FilterEntry]], known_chains: &HashSet<&str>) -> usize {
    let initial_count = known_chains.len();
    let mut all_names: HashSet<String> = known_chains.iter().map(|name| (*name).to_owned()).collect();
    count_branch_names(entries, &mut all_names);
    for &chain in chains {
        count_branch_names(chain, &mut all_names);
    }
    all_names.len().saturating_sub(initial_count)
}

/// Recursively insert branch and inline-chain names into `all_names`, ignoring
/// named references. The pure counting counterpart to [`collect_branch_names`],
/// with no validation, typo warnings, or limit checks.
fn count_branch_names(entries: &[FilterEntry], all_names: &mut HashSet<String>) {
    for entry in entries {
        let Some(branches) = &entry.branch_chains else {
            continue;
        };
        for branch in branches {
            all_names.insert(branch.name.clone());
            for chain_ref in &branch.chains {
                if let ChainRef::Inline { name, filters } = chain_ref {
                    all_names.insert(name.clone());
                    count_branch_names(filters, all_names);
                }
            }
        }
    }
}

/// Validate that filter names within a chain are unique.
fn validate_filter_names_unique(filters: &[FilterEntry], chain_name: &str) -> Result<(), ProxyError> {
    let mut seen = HashSet::new();
    for entry in filters {
        if let Some(name) = &entry.name {
            validate_filter_name_chars(name)?;
            if !seen.insert(name.as_str()) {
                return Err(ProxyError::Config(format!(
                    "duplicate filter name '{name}' in chain '{chain_name}'"
                )));
            }
        }
    }
    Ok(())
}

/// Validate that a filter name contains only valid characters.
fn validate_filter_name_chars(name: &str) -> Result<(), ProxyError> {
    if name.is_empty() {
        return Err(ProxyError::Config("filter name must not be empty".into()));
    }
    if !name
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
    {
        return Err(ProxyError::Config(format!(
            "filter name '{name}' must be ASCII alphanumeric, '_', or '-'"
        )));
    }
    Ok(())
}

/// Recursively collect and validate branch names, chain refs, and nesting depth.
fn collect_branch_names(
    filters: &[FilterEntry],
    all_names: &mut HashSet<String>,
    chain_names: &HashSet<&str>,
    depth: usize,
) -> Result<(), ProxyError> {
    // `validate_chain_ref` checks depth before recursing here,
    // so this should never fire. Keep as a safety net.
    debug_assert!(
        depth <= MAX_BRANCH_DEPTH,
        "collect_branch_names entered at depth {depth} > {MAX_BRANCH_DEPTH}"
    );

    for entry in filters {
        entry.warn_config_typos();
        let Some(branches) = &entry.branch_chains else {
            continue;
        };
        if branches.len() > MAX_BRANCHES_PER_FILTER {
            return Err(ProxyError::Config(format!(
                "filter has {} branch chains (max {MAX_BRANCHES_PER_FILTER})",
                branches.len()
            )));
        }
        for branch in branches {
            validate_branch(branch, all_names, chain_names, depth)?;
        }
    }
    Ok(())
}

/// Validate a single branch chain config.
fn validate_branch(
    branch: &BranchChainConfig,
    all_names: &mut HashSet<String>,
    chain_names: &HashSet<&str>,
    depth: usize,
) -> Result<(), ProxyError> {
    let bname = &branch.name;
    super::validate_name_chars(bname, "branch")?;
    if !all_names.insert(branch.name.clone()) {
        return Err(ProxyError::Config(format!("duplicate branch name '{bname}'")));
    }

    let rejoin = &branch.rejoin;
    if branch.rejoin.contains(':') {
        return Err(ProxyError::Config(format!(
            "branch '{bname}': cross-chain rejoin '{rejoin}' is not supported; \
             listeners flatten all referenced chains into one pipeline, \
             so use the filter's name directly (e.g. 'routing' not 'main:routing')"
        )));
    }

    if branch.chains.is_empty() {
        return Err(ProxyError::Config(format!(
            "branch '{bname}' must have at least one chain"
        )));
    }

    validate_max_iterations(branch)?;
    validate_on_result_filter_name(branch)?;
    validate_on_result_key_value(branch)?;

    for chain_ref in &branch.chains {
        validate_chain_ref(chain_ref, all_names, chain_names, depth)?;
    }

    Ok(())
}

/// Validate that `on_result.filter` is non-empty and uses valid name characters.
fn validate_on_result_filter_name(branch: &BranchChainConfig) -> Result<(), ProxyError> {
    let Some(cond) = &branch.on_result else {
        return Ok(());
    };

    let bname = &branch.name;
    let filter = &cond.filter;
    if cond.filter.is_empty() {
        return Err(ProxyError::Config(format!(
            "branch '{bname}': on_result.filter must not be empty"
        )));
    }
    if !cond
        .filter
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
    {
        return Err(ProxyError::Config(format!(
            "branch '{bname}': on_result.filter '{filter}' must be ASCII alphanumeric, '_', or '-'"
        )));
    }
    Ok(())
}

/// Validate `on_result.key` and every `on_result.result` value are non-empty
/// and contain only safe characters.
fn validate_on_result_key_value(branch: &BranchChainConfig) -> Result<(), ProxyError> {
    let Some(cond) = &branch.on_result else {
        return Ok(());
    };
    let bname = &branch.name;
    if cond.key.is_empty() {
        return Err(ProxyError::Config(format!(
            "branch '{bname}': on_result.key must not be empty"
        )));
    }
    validate_on_result_field(&cond.key, "key", bname)?;

    let (field, values) = match &cond.value {
        ResultMatch::Exact(value) => ("result", std::slice::from_ref(value)),
        ResultMatch::AnyOf { any_of } => ("result.any_of", any_of.as_slice()),
        ResultMatch::Contains { contains } => ("result.contains", std::slice::from_ref(contains)),
        ResultMatch::Not { not } => ("result.not", std::slice::from_ref(not)),
    };
    if values.is_empty() {
        return Err(ProxyError::Config(format!(
            "branch '{bname}': on_result.{field} must list at least one value"
        )));
    }
    values
        .iter()
        .try_for_each(|value| validate_on_result_value(value, field, bname))
}

/// Validate one `on_result.result` value: non-empty, short enough that a
/// filter result could ever equal it, and made of safe characters.
fn validate_on_result_value(value: &str, field: &str, branch_name: &str) -> Result<(), ProxyError> {
    if value.is_empty() {
        return Err(ProxyError::Config(format!(
            "branch '{branch_name}': on_result.{field} must not be empty"
        )));
    }
    if value.len() > MAX_RESULT_VALUE_LEN {
        return Err(ProxyError::Config(format!(
            "branch '{branch_name}': on_result.{field} must be at most {MAX_RESULT_VALUE_LEN} bytes"
        )));
    }
    validate_on_result_field(value, field, branch_name)
}

/// Validate a single `on_result` field uses safe characters.
fn validate_on_result_field(val: &str, field: &str, branch_name: &str) -> Result<(), ProxyError> {
    if !val
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
    {
        return Err(ProxyError::Config(format!(
            "branch '{branch_name}': on_result.{field} '{val}' must be ASCII alphanumeric, '_', or '-'"
        )));
    }
    Ok(())
}

/// Validate `max_iterations` constraints.
fn validate_max_iterations(branch: &BranchChainConfig) -> Result<(), ProxyError> {
    let bname = &branch.name;
    if let Some(max) = branch.max_iterations
        && !(1..=MAX_ITERATIONS_CEILING).contains(&max)
    {
        return Err(ProxyError::Config(format!(
            "branch '{bname}': max_iterations must be 1-{MAX_ITERATIONS_CEILING}, got {max}"
        )));
    }
    Ok(())
}

/// Validate a single chain reference.
fn validate_chain_ref(
    chain_ref: &ChainRef,
    all_names: &mut HashSet<String>,
    chain_names: &HashSet<&str>,
    depth: usize,
) -> Result<(), ProxyError> {
    match chain_ref {
        ChainRef::Named(name) => {
            if !chain_names.contains(name.as_str()) {
                return Err(ProxyError::Config(format!("branch references unknown chain '{name}'")));
            }
        },
        ChainRef::Inline { name, filters } => {
            super::validate_name_chars(name, "inline chain")?;
            if depth.saturating_add(1) > MAX_BRANCH_DEPTH {
                return Err(ProxyError::Config(format!(
                    "branch nesting depth exceeds maximum ({MAX_BRANCH_DEPTH})"
                )));
            }
            if filters.len() > super::filter_chain::MAX_FILTERS_PER_CHAIN {
                return Err(ProxyError::Config(format!(
                    "inline chain '{name}' has too many filters ({}, max {})",
                    filters.len(),
                    super::filter_chain::MAX_FILTERS_PER_CHAIN
                )));
            }
            if !all_names.insert(name.clone()) {
                return Err(ProxyError::Config(format!("duplicate inline chain name '{name}'")));
            }
            collect_branch_names(filters, all_names, chain_names, depth.saturating_add(1))?;
        },
    }
    Ok(())
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::needless_raw_strings,
    clippy::needless_raw_string_hashes,
    clippy::too_many_lines,
    clippy::items_after_statements,
    clippy::panic,
    reason = "tests use unwrap/expect/indexing/raw strings/panic for brevity"
)]
mod tests {
    use std::fmt::Write as _;

    use crate::config::Config;

    #[test]
    fn reject_branch_name_with_special_chars() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: "bad.branch"
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("alphanumeric"),
            "branch name with dots should be rejected: {err}"
        );
    }

    #[test]
    fn reject_inline_chain_name_with_special_chars() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: branch
            chains:
              - name: "bad.inline"
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("alphanumeric"),
            "inline chain name with dots should be rejected: {err}"
        );
    }

    #[test]
    fn reject_empty_branch_and_inline_chain_names() {
        for (branch, inline, expected) in [
            ("\"\"", "inline", "branch name must not be empty"),
            ("branch", "\"\"", "inline chain name must not be empty"),
        ] {
            let yaml = format!(
                r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: {branch}
            chains:
              - name: {inline}
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#
            );
            let err = Config::from_yaml(&yaml).unwrap_err();
            assert!(err.to_string().contains(expected), "expected '{expected}': {err}");
        }
    }

    #[test]
    fn reject_empty_on_result_key() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: branch
            on_result:
              filter: cache
              key: ""
              result: hit
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("on_result.key must not be empty"),
            "empty on_result key should be rejected: {err}"
        );
    }

    #[test]
    fn reject_empty_on_result_value() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: branch
            on_result:
              filter: cache
              result: ""
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("on_result.result must not be empty"),
            "empty on_result value should be rejected: {err}"
        );
    }

    #[test]
    fn reject_on_result_key_with_special_chars() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: branch
            on_result:
              filter: cache
              key: "bad.key"
              result: hit
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("on_result.key"),
            "on_result key with dots should be rejected: {err}"
        );
    }

    #[test]
    fn valid_branch_config() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: utility
    filters:
      - filter: headers
  - name: main
    filters:
      - filter: headers
        name: pre_route
        branch_chains:
          - name: my_branch
            chains:
              - utility
      - filter: static_response
        status: 200
"#;
        let config = Config::from_yaml(yaml).unwrap();
        assert_eq!(config.filter_chains.len(), 2, "should have 2 chains");
    }

    #[test]
    fn reject_duplicate_branch_name() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: dup
            chains:
              - name: inline1
                filters:
                  - filter: headers
          - name: dup
            chains:
              - name: inline2
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("duplicate branch name"),
            "should reject duplicate branch name: {err}"
        );
    }

    #[test]
    fn reject_duplicate_filter_name_in_chain() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        name: same
      - filter: cors
        name: same
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("duplicate filter name"),
            "should reject duplicate filter name: {err}"
        );
    }

    #[test]
    fn reject_unknown_chain_ref() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: my_branch
            chains:
              - nonexistent_chain
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("unknown chain"),
            "should reject unknown chain ref: {err}"
        );
    }

    #[test]
    fn reject_empty_branch_chains() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: empty_branch
            chains: []
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("at least one chain"),
            "should reject empty branch chains: {err}"
        );
    }

    #[test]
    fn reject_max_iterations_zero() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: retry
            max_iterations: 0
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("max_iterations must be 1-100"),
            "should reject max_iterations=0: {err}"
        );
    }

    #[test]
    fn reject_max_iterations_too_high() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: retry
            max_iterations: 101
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("max_iterations must be 1-100"),
            "should reject max_iterations=101: {err}"
        );
    }

    #[test]
    fn accept_max_iterations_valid_range() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: retry
            max_iterations: 3
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        Config::from_yaml(yaml).unwrap();
    }

    #[test]
    fn reject_invalid_filter_name_chars() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        name: "bad.name"
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("alphanumeric"),
            "should reject filter name with dots: {err}"
        );
    }

    #[test]
    fn accept_valid_filter_names() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        name: pre-route_1
      - filter: static_response
        status: 200
"#;
        Config::from_yaml(yaml).unwrap();
    }

    #[test]
    fn reject_duplicate_inline_chain_name() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: branch_a
            chains:
              - name: inline
                filters:
                  - filter: headers
          - name: branch_b
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("duplicate inline chain name"),
            "should reject duplicate inline chain name: {err}"
        );
    }

    #[test]
    fn reject_nesting_depth_exceeded() {
        fn nested_yaml(depth: usize) -> String {
            let mut yaml = String::from(
                r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
"#,
            );

            fn write_level(yaml: &mut String, depth: usize, current: usize, indent: usize) {
                let pad = " ".repeat(indent);
                let filter_name = format!("branch_{current}");
                let chain_name = format!("inline_{current}");
                writeln!(yaml, "{pad}- filter: headers").unwrap();
                if current < depth {
                    writeln!(yaml, "{pad}  branch_chains:").unwrap();
                    writeln!(yaml, "{pad}    - name: {filter_name}").unwrap();
                    writeln!(yaml, "{pad}      chains:").unwrap();
                    writeln!(yaml, "{pad}        - name: {chain_name}").unwrap();
                    writeln!(yaml, "{pad}          filters:").unwrap();
                    write_level(yaml, depth, current + 1, indent + 12);
                }
            }

            write_level(&mut yaml, depth, 0, 6);

            yaml.push_str(
                r#"      - filter: static_response
        status: 200
"#,
            );
            yaml
        }

        let yaml = nested_yaml(11);
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("nesting depth"),
            "should reject excessive nesting depth: {err}"
        );
    }

    #[test]
    fn accept_nesting_within_limit() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: level_0
            chains:
              - name: inline_0
                filters:
                  - filter: headers
                    branch_chains:
                      - name: level_1
                        chains:
                          - name: inline_1
                            filters:
                              - filter: headers
      - filter: static_response
        status: 200
"#;
        Config::from_yaml(yaml).unwrap();
    }

    #[test]
    fn reject_cross_chain_rejoin() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: cross
            rejoin: "other:routing"
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("cross-chain rejoin"),
            "should reject cross-chain rejoin syntax: {err}"
        );
    }

    #[test]
    fn reject_empty_filter_name() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        name: ""
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("must not be empty"),
            "should reject empty filter name: {err}"
        );
    }

    #[test]
    fn accept_max_iterations_at_boundaries() {
        let yaml_1 = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: retry
            max_iterations: 1
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        Config::from_yaml(yaml_1).unwrap();

        let yaml_100 = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: retry
            max_iterations: 100
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        Config::from_yaml(yaml_100).unwrap();
    }

    #[test]
    fn reject_empty_on_result_filter() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: bad_branch
            on_result:
              filter: ""
              result: hit
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("on_result.filter must not be empty"),
            "should reject empty on_result.filter: {err}"
        );
    }

    #[test]
    fn reject_on_result_filter_invalid_chars() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: bad_branch
            on_result:
              filter: "my.filter"
              result: hit
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("alphanumeric"),
            "should reject on_result.filter with invalid chars: {err}"
        );
    }

    #[test]
    fn accept_nesting_at_exact_max_depth() {
        fn nested_yaml(depth: usize) -> String {
            let mut yaml = String::from(
                r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
"#,
            );

            fn write_level(yaml: &mut String, depth: usize, current: usize, indent: usize) {
                let pad = " ".repeat(indent);
                let filter_name = format!("branch_{current}");
                let chain_name = format!("inline_{current}");
                writeln!(yaml, "{pad}- filter: headers").unwrap();
                if current < depth {
                    writeln!(yaml, "{pad}  branch_chains:").unwrap();
                    writeln!(yaml, "{pad}    - name: {filter_name}").unwrap();
                    writeln!(yaml, "{pad}      chains:").unwrap();
                    writeln!(yaml, "{pad}        - name: {chain_name}").unwrap();
                    writeln!(yaml, "{pad}          filters:").unwrap();
                    write_level(yaml, depth, current + 1, indent + 12);
                }
            }

            write_level(&mut yaml, depth, 0, 6);

            yaml.push_str(
                r#"      - filter: static_response
        status: 200
"#,
            );
            yaml
        }

        let yaml = nested_yaml(super::super::branch_chain::MAX_BRANCH_DEPTH);
        Config::from_yaml(&yaml).expect("nesting at exactly MAX_BRANCH_DEPTH should pass");
    }

    #[test]
    fn reject_too_many_branches_per_filter() {
        let mut branches = String::new();
        for i in 0..17 {
            write!(
                branches,
                "          - name: branch_{i}\n            chains:\n              \
                 - name: inline_{i}\n                filters:\n                  \
                 - filter: headers\n"
            )
            .unwrap();
        }
        let yaml = format!(
            r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
{branches}      - filter: static_response
        status: 200
"#
        );
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("branch chains"),
            "should reject >16 branches per filter: {err}"
        );
    }

    #[test]
    fn accept_max_branches_per_filter() {
        let mut branches = String::new();
        for i in 0..16 {
            write!(
                branches,
                "          - name: branch_{i}\n            chains:\n              \
                 - name: inline_{i}\n                filters:\n                  \
                 - filter: headers\n"
            )
            .unwrap();
        }
        let yaml = format!(
            r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
{branches}      - filter: static_response
        status: 200
"#
        );
        Config::from_yaml(&yaml).expect("exactly 16 branches per filter should pass");
    }

    #[test]
    fn reject_inline_chain_too_many_filters() {
        let mut filters = String::new();
        for _ in 0..101 {
            filters.push_str("                  - filter: headers\n");
        }
        let yaml = format!(
            r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: big_branch
            chains:
              - name: big_inline
                filters:
{filters}      - filter: static_response
        status: 200
"#
        );
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("too many filters"),
            "inline chain with >100 filters should be rejected: {err}"
        );
    }

    #[test]
    fn accept_valid_on_result_filter() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: good_branch
            on_result:
              filter: cache-check_1
              result: hit
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#;
        Config::from_yaml(yaml).unwrap();
    }

    // -------------------------------------------------------------------------
    // Entry-level validation (validate_chain_entries_branch_chains)
    //
    // The whole-config pass (validate_branch_chains) is reached through
    // Config::from_yaml above. Outbound chains bound at pipeline-build time never
    // appear in Config::filter_chains, so they are held to the same branch limits
    // through validate_chain_entries_branch_chains instead. These exercise that
    // function directly.
    // -------------------------------------------------------------------------

    #[test]
    fn chain_entries_reject_total_branch_count_over_ceiling() {
        use std::collections::HashSet;

        use crate::config::FilterEntry;

        let mut yaml = String::new();
        let mut n = 0;
        for _ in 0..17 {
            yaml.push_str("- filter: headers\n  branch_chains:\n");
            for _ in 0..16 {
                writeln!(yaml, "    - name: br_{n}\n      chains: [utility]").unwrap();
                n += 1;
            }
        }
        let entries: Vec<FilterEntry> = serde_yaml::from_str(&yaml).unwrap();
        let known: HashSet<&str> = HashSet::from(["utility"]);

        let err = super::validate_chain_entries_branch_chains("outbound", &entries, &known, 0).unwrap_err();
        assert!(
            err.to_string().contains("total branch count")
                && err.to_string().contains(&super::MAX_TOTAL_BRANCHES.to_string()),
            "an outbound chain whose branch total exceeds the ceiling must be rejected: {err}"
        );
    }

    #[test]
    fn chain_entries_reject_branches_over_per_filter_cap() {
        use std::collections::HashSet;

        use crate::config::FilterEntry;

        let mut yaml = String::from("- filter: headers\n  branch_chains:\n");
        for n in 0..17 {
            writeln!(yaml, "    - name: br_{n}\n      chains: [utility]").unwrap();
        }
        let entries: Vec<FilterEntry> = serde_yaml::from_str(&yaml).unwrap();
        let known: HashSet<&str> = HashSet::from(["utility"]);

        let err = super::validate_chain_entries_branch_chains("outbound", &entries, &known, 0).unwrap_err();
        assert!(
            err.to_string().contains("branch chains") && err.to_string().contains("16"),
            "a filter exceeding the per-filter branch cap must be rejected: {err}"
        );
    }

    #[test]
    fn chain_entries_reject_invalid_on_result_condition() {
        use std::collections::HashSet;

        use crate::config::FilterEntry;

        let entries: Vec<FilterEntry> = serde_yaml::from_str(
            "
- filter: headers
  branch_chains:
    - name: br
      on_result:
        filter: \"\"
        result: hit
      chains: [utility]
",
        )
        .unwrap();
        let known: HashSet<&str> = HashSet::from(["utility"]);

        let err = super::validate_chain_entries_branch_chains("outbound", &entries, &known, 0).unwrap_err();
        assert!(
            err.to_string().contains("on_result.filter must not be empty"),
            "a branch with an empty on_result filter must be rejected: {err}"
        );
    }

    #[test]
    fn count_build_branches_counts_entries_and_named_chains_ignoring_named_refs() {
        use std::collections::HashSet;

        use crate::config::FilterEntry;

        let entries: Vec<FilterEntry> = serde_yaml::from_str(
            "
- filter: headers
  branch_chains:
    - name: br_named
      chains: [utility]
    - name: br_inline
      chains:
        - name: sub
          filters:
            - filter: headers
",
        )
        .unwrap();
        let utility: Vec<FilterEntry> = serde_yaml::from_str(
            "
- filter: headers
  branch_chains:
    - name: u_br
      chains: [utility]
",
        )
        .unwrap();
        let chains: [&[FilterEntry]; 1] = [utility.as_slice()];
        let known: HashSet<&str> = HashSet::from(["utility"]);

        assert_eq!(
            super::count_build_branches(&entries, &chains, &known),
            4,
            "config-wide counting must count entries and named chains, but not named refs"
        );
    }

    #[test]
    fn chain_entries_branch_count_accumulates_prior_and_returns_total() {
        use std::collections::HashSet;

        use crate::config::FilterEntry;

        let mut yaml = String::from("- filter: headers\n  branch_chains:\n");
        for n in 0..10 {
            writeln!(yaml, "    - name: br_{n}\n      chains: [utility]").unwrap();
        }
        let entries: Vec<FilterEntry> = serde_yaml::from_str(&yaml).unwrap();
        let known: HashSet<&str> = HashSet::from(["utility"]);

        let total = super::validate_chain_entries_branch_chains("outbound", &entries, &known, 0).unwrap();
        assert_eq!(total, 10, "the cumulative total must include this chain's 10 branches");

        let err =
            super::validate_chain_entries_branch_chains("outbound", &entries, &known, super::MAX_TOTAL_BRANCHES - 5)
                .unwrap_err();
        assert!(
            err.to_string().contains("total branch count")
                && err.to_string().contains(&(super::MAX_TOTAL_BRANCHES + 5).to_string()),
            "prior branch count must accumulate into the cumulative total: {err}"
        );
    }

    #[test]
    fn result_operators_load_through_config() {
        for result in [
            "result: 0",
            "result: true",
            "result: {contains: unsafe}",
            "result: {not: safe}",
            "result: {any_of: [2, 4, 6]}",
        ] {
            let config = Config::from_yaml(&on_result_config(result))
                .unwrap_or_else(|err| panic!("{result} should load through the full config: {err}"));
            assert_eq!(config.filter_chains.len(), 1, "{result}: the chain should be kept");
        }
    }

    #[test]
    fn reject_empty_result_operands() {
        let cases = [
            (
                "result: {any_of: []}",
                "on_result.result.any_of must list at least one value",
            ),
            (
                "result: {any_of: [ok, \"\"]}",
                "on_result.result.any_of must not be empty",
            ),
            (
                "result: {contains: \"\"}",
                "on_result.result.contains must not be empty",
            ),
            ("result: {not: \"\"}", "on_result.result.not must not be empty"),
        ];
        for (result, expected) in cases {
            let err = Config::from_yaml(&on_result_config(result)).unwrap_err();
            assert!(
                err.to_string().contains(expected),
                "{result} should be rejected with '{expected}': {err}"
            );
        }
    }

    #[test]
    fn reject_result_operand_with_special_chars() {
        let cases = [
            (
                "result: {any_of: [ok, \"bad.value\"]}",
                "on_result.result.any_of 'bad.value'",
            ),
            ("result: {contains: \"un safe\"}", "on_result.result.contains 'un safe'"),
            ("result: {not: \"safe!\"}", "on_result.result.not 'safe!'"),
        ];
        for (result, expected) in cases {
            let err = Config::from_yaml(&on_result_config(result)).unwrap_err();
            assert!(
                err.to_string().contains(expected),
                "{result} should be rejected with '{expected}': {err}"
            );
        }
    }

    #[test]
    fn reject_result_value_longer_than_a_filter_result() {
        let at_limit = "a".repeat(super::MAX_RESULT_VALUE_LEN);
        let over_limit = "a".repeat(super::MAX_RESULT_VALUE_LEN + 1);

        Config::from_yaml(&on_result_config(&format!("result: {{contains: {at_limit}}}")))
            .unwrap_or_else(|err| panic!("a value at the limit should load: {err}"));
        let exact = Config::from_yaml(&on_result_config(&format!("result: {over_limit}"))).unwrap_err();
        let any_of =
            Config::from_yaml(&on_result_config(&format!("result: {{any_of: [ok, {over_limit}]}}"))).unwrap_err();

        assert!(
            exact.to_string().contains("on_result.result must be at most 256 bytes"),
            "an exact value over the limit should be rejected: {exact}"
        );
        assert!(
            any_of
                .to_string()
                .contains("on_result.result.any_of must be at most 256 bytes"),
            "an any_of entry over the limit should be rejected: {any_of}"
        );
    }

    // -------------------------------------------------------------------------
    // Test Utilities
    // -------------------------------------------------------------------------

    /// A config with one branch whose `on_result` uses the given `result:` line.
    fn on_result_config(result: &str) -> String {
        format!(
            r#"
listeners:
  - name: web
    address: "0.0.0.0:8080"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: headers
        branch_chains:
          - name: branch
            on_result:
              filter: headers
              key: verdict
              {result}
            chains:
              - name: inline
                filters:
                  - filter: headers
      - filter: static_response
        status: 200
"#
        )
    }
}