vane-core 0.10.8

Core types, FlowGraph IR, and compilation pipeline for the vane proxy engine
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
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
pub mod analyze;
pub mod expand;
pub mod lower;
pub mod merge;
pub mod validate;

use std::sync::Arc;

use crate::error::{Diagnostics, Error};
use crate::ir::SymbolicFlowGraph;
use crate::metadata::{FetchMetadataProvider, MiddlewareMetadataProvider};

pub use analyze::{AnalyzedRule, AnalyzedRuleSet, InspectionLevel, Posture};
pub use expand::RawRuleSet;
pub use merge::{MergedConfig, RawRuleFile};

/// Facade for the core compile pipeline.
///
/// Runs `merge → expand → analyze → lower → validate` and returns an
/// `Arc<SymbolicFlowGraph>` ready for `vane-engine::FlowGraph::link`.
///
/// On error the message carries every diagnostic the pipeline
/// accumulated — the underlying [`compile_collecting`] runs each
/// stage's "leaf checks" with push+continue, and only the stage
/// boundary decides whether to bail. Operators running
/// `vane compile <dir>` see all problems at once instead of fixing
/// them one-at-a-time.
///
/// # Errors
/// Returns [`Error::compile`] on duplicate rule names, unknown middleware
/// or fetch names referenced by rules, bad `ListenSpec` strings, predicate
/// type mismatches, or graph-level validation failures (dangling IDs,
/// cycles, phase mismatches).
pub fn compile(
	files: Vec<RawRuleFile>,
	mw_meta: &dyn MiddlewareMetadataProvider,
	fetch_meta: &dyn FetchMetadataProvider,
) -> Result<Arc<SymbolicFlowGraph>, Error> {
	compile_collecting(files, mw_meta, fetch_meta).map_err(Error::from)
}

/// Collecting form of [`compile`]: returns the accumulated
/// [`Diagnostics`] when one or more stages report errors, instead of
/// collapsing them into a single `Error`. Used by callers (CLI,
/// management RPC dry-run) that want to surface every problem in one
/// turn.
///
/// # Errors
/// Returns [`Diagnostics`] when any stage pushes a fatal entry. The
/// accumulator's `Display` impl formats a numbered list suitable for
/// direct printing.
pub fn compile_collecting(
	files: Vec<RawRuleFile>,
	mw_meta: &dyn MiddlewareMetadataProvider,
	fetch_meta: &dyn FetchMetadataProvider,
) -> Result<Arc<SymbolicFlowGraph>, Diagnostics> {
	// merge + expand are early-bail today: each carries at most one
	// authoritative error (duplicate rule names, unknown preset,
	// etc.) so collecting buys nothing. Lift them through the
	// Diagnostics channel so the caller's match is uniform.
	let merged = merge::merge(files).map_err(Diagnostics::from)?;
	let expanded = expand::expand(merged).map_err(Diagnostics::from)?;

	// analyze collects per-rule errors and returns the partial set
	// alongside diagnostics. If anything was pushed, bail before
	// lower (every downstream stage assumes a complete rule set).
	let (analyzed, analyze_d) = analyze::analyze_collecting(expanded, mw_meta, fetch_meta);
	analyze_d.into_result(())?;

	// lower still uses ?-return internally; collect at the stage
	// boundary into the same accumulator.
	let graph = lower::lower(analyzed, mw_meta, fetch_meta).map_err(Diagnostics::from)?;

	// validate runs every IR-level check to completion, accumulates
	// all findings, and the stage boundary turns them into a single
	// Err if any.
	let validate_d = validate::validate_collecting(&graph);
	validate_d.into_result(())?;

	Ok(Arc::new(graph))
}

#[cfg(test)]
mod tests {
	use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
	use std::path::PathBuf;

	use super::*;
	use crate::fetch::{FetchKind, FetchOutputModes, FetchPhase, Terminator};
	use crate::ir::{Node, NodeId, PredicateId};
	use crate::metadata::{FetchMetadata, MiddlewareMetadata};
	use crate::middleware::MiddlewareKind;
	use crate::rule::{RawRule, TerminateSpec};

	struct Providers;

	fn validate_ok(_: &serde_json::Value) -> Result<(), Error> {
		Ok(())
	}

	impl MiddlewareMetadataProvider for Providers {
		fn get(&self, name: &str) -> Option<MiddlewareMetadata> {
			match name {
				"forward_client_ip" => Some(MiddlewareMetadata {
					kind: MiddlewareKind::L7Request,
					stateless: true,
					needs_body: false,
					validate_args: validate_ok,
				}),
				"rate_limit" => Some(MiddlewareMetadata {
					kind: MiddlewareKind::L7Request,
					stateless: false,
					needs_body: false,
					validate_args: validate_ok,
				}),
				_ => None,
			}
		}
	}

	impl FetchMetadataProvider for Providers {
		fn get(&self, kind: FetchKind) -> Option<FetchMetadata> {
			Some(FetchMetadata {
				kind,
				phase: match kind {
					FetchKind::L4Forward => FetchPhase::L4,
					_ => FetchPhase::L7,
				},
				output_modes: match kind {
					FetchKind::L4Forward => FetchOutputModes { response: false, tunnel: true },
					FetchKind::WebSocketUpgrade => FetchOutputModes { response: true, tunnel: true },
					_ => FetchOutputModes { response: true, tunnel: false },
				},
				validate_args: validate_ok,
			})
		}
	}

	fn parse_rule(j: serde_json::Value) -> RawRule {
		serde_json::from_value(j).expect("parse rule")
	}

	fn rule_file(path: &str, rules: Vec<RawRule>) -> RawRuleFile {
		let entries = rules.into_iter().map(crate::preset::RuleEntry::Raw).collect();
		RawRuleFile { path: PathBuf::from(path), order: 0, rules: entries }
	}

	fn _unused_mentions() {
		let _ = TerminateSpec { kind: FetchKind::HttpProxy, args: serde_json::Value::Null };
	}

	#[test]
	fn reverse_proxy_end_to_end_compiles_with_dual_stack_entries() {
		let r = parse_rule(serde_json::json!({
			"name": "proxy",
			"listen": [":443"],
			"middleware_chain": [{ "use": "forward_client_ip" }, { "use": "rate_limit", "args": { "rate": 100 } }],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}));
		let graph =
			compile(vec![rule_file("30-proxy.json", vec![r])], &Providers, &Providers).expect("compile");
		assert!(!graph.nodes.is_empty());
		// Dual-stack `:443` expands to both v4 and v6 SocketAddrs sharing one entry NodeId.
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 443);
		let v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 443);
		let e_v4 = graph.entries.get(&v4).expect("v4 entry present");
		let e_v6 = graph.entries.get(&v6).expect("v6 entry present");
		assert_eq!(e_v4, e_v6);
		// The terminator set contains WriteHttpResponse (both the rule terminator
		// and the synthesised default-miss write it).
		assert!(
			graph.terminators.iter().any(|t| matches!(t, Terminator::WriteHttpResponse)),
			"expected WriteHttpResponse terminator",
		);
	}

	#[test]
	fn predicate_hash_cons_shares_id_across_rules() {
		// Two rules on different listeners both match `tls.sni == "api"`.
		// Spec spec/flow-model.md § _Hash-consing_: predicates always dedup.
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":8443"],
			"match": { "tls.sni": { "equals": "api" } },
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":9443"],
			"match": { "tls.sni": { "equals": "api" } },
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers).expect("compile");
		assert_eq!(graph.predicates.len(), 1, "identical predicates must hash-cons to one slot");
	}

	#[test]
	fn stateless_middleware_hash_cons_across_rules() {
		// Two rules sharing an identical `forward_client_ip` (stateless, no args)
		// must share one MiddlewareId.
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":7001"],
			"middleware_chain": [{ "use": "forward_client_ip" }],
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":7002"],
			"middleware_chain": [{ "use": "forward_client_ip" }],
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers).expect("compile");
		let shared = graph
			.middlewares
			.iter()
			.filter(|m| m.name.as_ref() == "forward_client_ip" && m.stateless)
			.count();
		assert_eq!(shared, 1, "stateless middleware dedups across rules");
	}

	#[test]
	fn stateful_middleware_per_site_not_shared() {
		// Two rules both use `rate_limit` (stateful). Each call site must get
		// its own MiddlewareId per `spec/flow-model.md` § _Hash-consing_ — sharing buckets
		// would silently halve the effective rate.
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":7003"],
			"middleware_chain": [{ "use": "rate_limit", "args": { "rate": 100 } }],
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":7004"],
			"middleware_chain": [{ "use": "rate_limit", "args": { "rate": 100 } }],
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers).expect("compile");
		let rate_limit_count =
			graph.middlewares.iter().filter(|m| m.name.as_ref() == "rate_limit").count();
		assert_eq!(rate_limit_count, 2, "stateful middleware must not share ids across call sites");
	}

	#[test]
	fn terminator_variant_derives_from_fetch_kind() {
		// HttpProxy / HttpSynthesize → WriteHttpResponse; L4Forward → ByteTunnel.
		let http = parse_rule(serde_json::json!({
			"name": "http",
			"listen": [":8080"],
			"terminate": { "type": "http_proxy" },
		}));
		let tcp = parse_rule(serde_json::json!({
			"name": "tcp",
			"listen": [":2222"],
			"terminate": { "type": "tcp_forward", "upstream": "10.0.0.5:22" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![http, tcp])], &Providers, &Providers).expect("compile");
		let terms: std::collections::HashSet<_> = graph.terminators.iter().copied().collect();
		assert!(terms.contains(&Terminator::WriteHttpResponse));
		assert!(terms.contains(&Terminator::ByteTunnel));
	}

	#[test]
	fn l7_rule_inserts_upgrade_node() {
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":443"],
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let upgrades = graph.nodes.iter().filter(|n| matches!(n, Node::Upgrade { .. })).count();
		assert!(upgrades >= 1, "L7 listener must have at least one Upgrade node");
	}

	#[test]
	fn l4_only_rule_has_no_upgrade() {
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":2222"],
			"terminate": { "type": "tcp_forward", "upstream": "10.0.0.5:22" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let upgrades = graph.nodes.iter().filter(|n| matches!(n, Node::Upgrade { .. })).count();
		assert_eq!(upgrades, 0);
	}

	#[test]
	fn duplicate_rule_names_fail_at_merge_stage() {
		let a = parse_rule(serde_json::json!({
			"name": "same",
			"listen": [":1000"],
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "same",
			"listen": [":1001"],
			"terminate": { "type": "http_proxy" },
		}));
		let err = compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers)
			.expect_err("duplicate must fail");
		assert!(err.to_string().contains("duplicate"));
	}

	#[test]
	fn wildcard_port_listen_spec_is_rejected() {
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":0"],
			"terminate": { "type": "http_proxy" },
		}));
		let err = compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers)
			.expect_err("wildcard port must fail");
		assert!(err.to_string().contains("wildcard port"));
	}

	#[test]
	fn validate_runs_and_catches_basic_graph_integrity() {
		// End-to-end: `compile` runs `validate` inside. A clean reverse_proxy
		// graph must pass — this is an end-to-end sanity check that validate
		// is wired into the pipeline and doesn't falsely reject good graphs.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":443"],
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		// Running validate again on the returned graph must still succeed.
		validate::validate(&graph).expect("re-validate");
	}

	#[test]
	#[allow(
		clippy::cognitive_complexity,
		reason = "exhaustive Node-variant round-trip assertion: complexity grows with the number of variants, not with logic. Splitting to a per-variant helper just renames the variant-tag dispatch"
	)]
	fn symbolic_flow_graph_round_trip_preserves_structure_and_revalidates() {
		// Dry-run JSON contract (spec/flow-model.md § _The compiled form_): a compiled
		// SymbolicFlowGraph serializes to JSON and the result deserializes
		// back to an equivalent graph that re-`validate()`s green. Slab
		// contents and `entries` map key set must survive the round-trip.
		use crate::ir::SymbolicFlowGraph;
		let r = parse_rule(serde_json::json!({
			"name": "proxy",
			"listen": [":443"],
			"middleware_chain": [{ "use": "forward_client_ip" }, { "use": "rate_limit", "args": { "rate": 100 } }],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");

		let encoded = serde_json::to_string(&*graph).expect("serialize graph");
		let decoded: SymbolicFlowGraph = serde_json::from_str(&encoded).expect("deserialize graph");

		// Re-validate the decoded graph: the contract is that dry-run JSON
		// is a ground-truth snapshot that the engine could rehydrate.
		validate::validate(&decoded).expect("decoded graph revalidates");

		// Slab lengths survive.
		assert_eq!(decoded.nodes.len(), graph.nodes.len(), "nodes slab length");
		assert_eq!(decoded.predicates.len(), graph.predicates.len(), "predicates slab length");
		assert_eq!(decoded.middlewares.len(), graph.middlewares.len(), "middlewares slab length");
		assert_eq!(decoded.fetches.len(), graph.fetches.len(), "fetches slab length");
		assert_eq!(decoded.terminators.len(), graph.terminators.len(), "terminators slab length");

		// `entries` key set (SocketAddr → NodeId) survives.
		let orig_keys: std::collections::BTreeSet<_> = graph.entries.keys().copied().collect();
		let dec_keys: std::collections::BTreeSet<_> = decoded.entries.keys().copied().collect();
		assert_eq!(orig_keys, dec_keys, "entries key set must round-trip");

		// PredicateInst / SymbolicMiddlewareRef / Terminator implement
		// PartialEq; compare their slabs directly.
		assert_eq!(decoded.predicates, graph.predicates, "predicates slab content");
		assert_eq!(decoded.middlewares, graph.middlewares, "middlewares slab content");
		assert_eq!(decoded.terminators, graph.terminators, "terminators slab content");

		// `Node` does not implement PartialEq (by design — the enum holds
		// id newtypes and Option<NodeId>s only). Compare node-by-node via
		// variant destructuring to pin that the control-flow structure
		// survived the round-trip.
		for (i, (a, b)) in graph.nodes.iter().zip(decoded.nodes.iter()).enumerate() {
			match (a, b) {
				(
					Node::Check {
						predicate: pa,
						on_match: ma,
						on_miss: sa,
						collect_body_before: ca,
						body_limit: la,
					},
					Node::Check {
						predicate: pb,
						on_match: mb,
						on_miss: sb,
						collect_body_before: cb,
						body_limit: lb,
					},
				) => {
					assert_eq!(pa, pb, "node[{i}] Check predicate");
					assert_eq!(ma, mb, "node[{i}] Check on_match");
					assert_eq!(sa, sb, "node[{i}] Check on_miss");
					assert_eq!(ca, cb, "node[{i}] Check collect_body_before");
					assert_eq!(la, lb, "node[{i}] Check body_limit");
				}
				(
					Node::Middleware {
						id: ia,
						next: na,
						on_error: ea,
						collect_body_before: ca,
						body_limit: la,
					},
					Node::Middleware {
						id: ib,
						next: nb,
						on_error: eb,
						collect_body_before: cb,
						body_limit: lb,
					},
				) => {
					assert_eq!(ia, ib, "node[{i}] Middleware id");
					assert_eq!(na, nb, "node[{i}] Middleware next");
					assert_eq!(ea, eb, "node[{i}] Middleware on_error");
					assert_eq!(ca, cb, "node[{i}] Middleware collect_body_before");
					assert_eq!(la, lb, "node[{i}] Middleware body_limit");
				}
				(
					Node::Fetch {
						id: ia,
						next_response: ra,
						next_tunnel: ta,
						collect_body_before: ca,
						body_limit: la,
					},
					Node::Fetch {
						id: ib,
						next_response: rb,
						next_tunnel: tb,
						collect_body_before: cb,
						body_limit: lb,
					},
				) => {
					assert_eq!(ia, ib, "node[{i}] Fetch id");
					assert_eq!(ra, rb, "node[{i}] Fetch next_response");
					assert_eq!(ta, tb, "node[{i}] Fetch next_tunnel");
					assert_eq!(ca, cb, "node[{i}] Fetch collect_body_before");
					assert_eq!(la, lb, "node[{i}] Fetch body_limit");
				}
				(Node::Upgrade { next: a }, Node::Upgrade { next: b }) => {
					assert_eq!(a, b, "node[{i}] Upgrade next");
				}
				(Node::Terminate(a), Node::Terminate(b)) => {
					assert_eq!(a, b, "node[{i}] Terminate");
				}
				(a, b) => panic!("node[{i}] variant changed across round-trip: {a:?} -> {b:?}"),
			}
		}
	}

	// AnyOf / Not lowering tests
	fn check_rule(name: &str, port: u16, match_predicate: &serde_json::Value) -> RawRule {
		parse_rule(serde_json::json!({
			"name": name,
			"listen": [format!(":{port}")],
			"match": match_predicate,
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}))
	}

	fn find_entry_check(graph: &SymbolicFlowGraph, port: u16) -> NodeId {
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port);
		let entry = *graph.entries.get(&v4).expect("entry present");
		// Per spec/flow-model.md § _The compiled form_, every L7
		// listener carries one shared Upgrade above the rule chains. Tests
		// that probe Check structure below the Upgrade skip past it here.
		match &graph[entry] {
			Node::Upgrade { next } => *next,
			_ => entry,
		}
	}

	fn unwrap_check(node: &Node) -> (PredicateId, NodeId, NodeId) {
		match node {
			Node::Check { predicate, on_match, on_miss, .. } => (*predicate, *on_match, *on_miss),
			other => panic!("expected Check, got {other:?}"),
		}
	}

	#[test]
	fn any_of_two_checks_chains_via_on_miss_sharing_on_match() {
		let r = check_rule(
			"r",
			7100,
			&serde_json::json!({
				"any_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "tls.sni": { "equals": "b" } },
				],
			}),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");

		let entry = find_entry_check(&graph, 7100);
		let (_, match_a, miss_a) = unwrap_check(&graph[entry]);
		let (_, match_b, _miss_b) = unwrap_check(&graph[miss_a]);
		assert_eq!(match_a, match_b, "both any_of branches share on_match");
		let check_count = graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count();
		assert_eq!(check_count, 2);
		assert_eq!(graph.predicates.len(), 2, "tls.sni=\"a\" and tls.sni=\"b\" are distinct");
	}

	#[test]
	fn any_of_three_checks_chains_right_to_left() {
		let r = check_rule(
			"r",
			7101,
			&serde_json::json!({
				"any_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "tls.sni": { "equals": "b" } },
					{ "tls.sni": { "equals": "c" } },
				],
			}),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");

		let c0 = find_entry_check(&graph, 7101);
		let (_, m0, miss0) = unwrap_check(&graph[c0]);
		let (_, m1, miss1) = unwrap_check(&graph[miss0]);
		let (_, m2, _miss2) = unwrap_check(&graph[miss1]);
		assert_eq!(m0, m1);
		assert_eq!(m1, m2, "all three any_of branches share on_match");
		assert_eq!(graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count(), 3);
	}

	#[test]
	fn not_wrapping_a_check_swaps_on_match_and_on_miss() {
		let r =
			check_rule("r", 7102, &serde_json::json!({ "not": { "tls.sni": { "equals": "internal" } } }));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");

		// Not adds no node — exactly one Check.
		let check_count = graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count();
		assert_eq!(check_count, 1);
		let entry = find_entry_check(&graph, 7102);
		let (_, on_match, on_miss) = unwrap_check(&graph[entry]);
		// Per the equivalence `not P match=>X miss=>Y` ≡ lower(P, match=>Y, miss=>X),
		// the emitted Check has swapped edges: its on_match is the outer on_miss
		// (the default-miss fallback) and its on_miss is the rule body entry.
		// Assert they're distinct — before-task-2 code had them both pointing
		// at the body entry.
		assert_ne!(on_match, on_miss);
		// Walking `on_miss` should land at something reachable; walking
		// `on_match` should land at a node that cannot reach the rule's Fetch.
		// Minimal structural check: the two targets differ.
	}

	#[test]
	fn not_wrapping_any_of_swaps_edges_and_produces_two_checks() {
		let r = check_rule(
			"r",
			7103,
			&serde_json::json!({
				"not": {
					"any_of": [
						{ "tls.sni": { "equals": "a" } },
						{ "tls.sni": { "equals": "b" } },
					],
				},
			}),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");

		assert_eq!(graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count(), 2);
		let c0 = find_entry_check(&graph, 7103);
		let (_, m0, miss0) = unwrap_check(&graph[c0]);
		let (_, m1, _miss1) = unwrap_check(&graph[miss0]);
		// `not (any_of [A, B])` = lower(any_of, match=>Y, miss=>X) =
		//   Check(A) match=>Y miss=>Check(B) match=>Y miss=>X.
		// Both Checks share on_match (== outer on_miss, i.e. the default-miss).
		assert_eq!(m0, m1);
	}

	#[test]
	fn any_of_nested_inside_any_of_produces_three_checks_with_shared_on_match() {
		let r = check_rule(
			"r",
			7104,
			&serde_json::json!({
				"any_of": [
					{ "tls.sni": { "equals": "a" } },
					{
						"any_of": [
							{ "tls.sni": { "equals": "b" } },
							{ "tls.sni": { "equals": "c" } },
						],
					},
				],
			}),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");

		let c0 = find_entry_check(&graph, 7104);
		let (_, m0, miss0) = unwrap_check(&graph[c0]);
		let (_, m1, miss1) = unwrap_check(&graph[miss0]);
		let (_, m2, _miss2) = unwrap_check(&graph[miss1]);
		assert_eq!(m0, m1);
		assert_eq!(m1, m2);
		assert_eq!(graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count(), 3);
	}

	#[test]
	fn empty_any_of_short_circuits_to_on_miss() {
		let r = check_rule("r", 7105, &serde_json::json!({ "any_of": [] }));
		// Empty any_of ≡ never matches. The rule's chain entry equals the
		// on_miss target (default-miss); no Check node is emitted for the
		// empty any_of itself.
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let check_count = graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count();
		assert_eq!(check_count, 0, "empty any_of must not emit a Check node");
	}

	#[test]
	fn any_of_hash_cons_shares_predicate_slot_across_rules() {
		// Two rules on different listeners both use the same `tls.sni ==
		// "shared"` predicate inside any_of. Per spec/flow-model.md § _Hash-consing_,
		// predicates dedup transparently regardless of the combinator tree
		// they're nested inside.
		let a = check_rule(
			"a",
			7106,
			&serde_json::json!({ "any_of": [{ "tls.sni": { "equals": "shared" } }] }),
		);
		let b = check_rule(
			"b",
			7107,
			&serde_json::json!({ "any_of": [{ "tls.sni": { "equals": "shared" } }] }),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers).expect("compile");
		assert_eq!(graph.predicates.len(), 1);
	}

	#[test]
	fn l4_predicate_on_l7_rule_sits_post_upgrade() {
		// Every L7 listener carries one shared Upgrade above the rule
		// chains, so L4-level Check leaves on L7 rules sit AFTER the
		// Upgrade. `PredicateView::L7Req` carries `conn`, so reads of
		// `tls.sni` / `remote.ip` remain functionally correct.
		let r = check_rule("r", 7300, &serde_json::json!({ "tls.sni": { "equals": "a" } }));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		// Listener entry is the shared Upgrade.
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7300);
		let listener_entry = *graph.entries.get(&v4).expect("entry present");
		assert!(matches!(&graph[listener_entry], Node::Upgrade { .. }));
		// One step below the Upgrade is the Check.
		let check_below = find_entry_check(&graph, 7300);
		assert!(matches!(&graph[check_below], Node::Check { .. }));
	}

	#[test]
	fn l7_predicate_on_l7_rule_sits_after_upgrade() {
		// Upgrade is listener-level rather than per-rule; L7-level Checks
		// still descend from it.
		let r = check_rule(
			"r",
			7301,
			&serde_json::json!({ "http.header.host": { "equals": "api.example.com" } }),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7301);
		let listener_entry = *graph.entries.get(&v4).expect("entry present");
		assert!(
			matches!(&graph[listener_entry], Node::Upgrade { .. }),
			"L7 listener entry is the shared Upgrade",
		);
		let Node::Upgrade { next } = &graph[listener_entry] else {
			panic!("expected Upgrade");
		};
		assert!(matches!(&graph[*next], Node::Check { .. }));
	}

	#[test]
	fn pure_l4_rule_with_predicate_synthesises_close_miss() {
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7302"],
			"match": { "remote.ip": { "cidr": "10.0.0.0/8" } },
			"terminate": { "type": "tcp_forward", "upstream": "10.0.0.5:22" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let entry = find_entry_check(&graph, 7302);
		assert!(matches!(&graph[entry], Node::Check { .. }));
		let upgrades = graph.nodes.iter().filter(|n| matches!(n, Node::Upgrade { .. })).count();
		assert_eq!(upgrades, 0, "L4 posture never Upgrades");
		assert!(
			graph.terminators.iter().any(|t| matches!(t, Terminator::Close)),
			"default-miss must synthesise a Close terminator",
		);
	}

	#[test]
	fn l7_rule_with_predicate_uses_close_not_500_for_default_miss() {
		// Pre-task-4 the L7 default-miss was a synthesised 500. Task 4 unified
		// both postures on `Terminator::Close`, so no HttpSynthesize fetch
		// should appear in the graph for a rule whose terminator is http_proxy.
		let r = check_rule("r", 7400, &serde_json::json!({ "tls.sni": { "equals": "api" } }));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		assert!(
			graph.terminators.iter().any(|t| matches!(t, Terminator::Close)),
			"default-miss must be Close",
		);
		let synth_fetches =
			graph.fetches.iter().filter(|f| f.kind == FetchKind::HttpSynthesize).count();
		assert_eq!(synth_fetches, 0, "no 500 synth for unmatched L7 traffic — just Close");
	}

	#[test]
	fn catch_all_rule_set_omits_close_fallback() {
		// A predicate-less rule is always matched; the default-miss is dead
		// code and must not appear in the graph.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7401"],
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let close_count = graph.terminators.iter().filter(|t| matches!(t, Terminator::Close)).count();
		assert_eq!(close_count, 0, "no predicate means no miss path means no Close");
	}

	#[test]
	fn close_terminator_serde_round_trip() {
		// Pin the wire form of the new variant for dry-run JSON.
		let t = Terminator::Close;
		let encoded = serde_json::to_string(&t).expect("serialize");
		let decoded: Terminator = serde_json::from_str(&encoded).expect("deserialize");
		assert_eq!(decoded, t);
	}

	#[test]
	fn l7_rule_without_predicate_has_upgrade_as_entry() {
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7303"],
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7303);
		let listener_entry = *graph.entries.get(&v4).expect("entry present");
		assert!(matches!(&graph[listener_entry], Node::Upgrade { .. }));
	}

	#[test]
	fn cross_level_any_of_is_rejected() {
		let r = check_rule(
			"r",
			7304,
			&serde_json::json!({
				"any_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "http.method": { "equals": "GET" } },
				],
			}),
		);
		let err = compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers)
			.expect_err("cross-level any_of must fail");
		assert!(err.to_string().contains("cross-level"), "error message names the constraint: {err}");
	}

	#[test]
	fn cross_level_not_is_rejected() {
		let r = check_rule(
			"r",
			7305,
			&serde_json::json!({
				"not": {
					"any_of": [
						{ "tls.sni": { "equals": "a" } },
						{ "http.method": { "equals": "GET" } },
					],
				},
			}),
		);
		let err = compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers)
			.expect_err("cross-level not(any_of) must fail");
		assert!(err.to_string().contains("cross-level"));
	}

	#[test]
	fn same_level_any_of_compiles_at_one_side_of_upgrade() {
		// Two L4Peek checks: Upgrade sits BELOW both Checks.
		let r = check_rule(
			"r",
			7306,
			&serde_json::json!({
				"any_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "tls.sni": { "equals": "b" } },
				],
			}),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let entry = find_entry_check(&graph, 7306);
		// Entry is a Check; walking any_of's shared on_match must reach an Upgrade.
		assert!(matches!(&graph[entry], Node::Check { .. }));
	}

	#[test]
	fn validate_stays_green_for_all_combinator_shapes() {
		let shapes = [
			serde_json::json!({ "tls.sni": { "equals": "x" } }),
			serde_json::json!({
				"any_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "tls.sni": { "equals": "b" } },
				],
			}),
			serde_json::json!({ "not": { "tls.sni": { "equals": "y" } } }),
			serde_json::json!({
				"not": {
					"any_of": [
						{ "tls.sni": { "equals": "a" } },
						{ "tls.sni": { "equals": "b" } },
					],
				},
			}),
			serde_json::json!({
				"all_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "tls.sni": { "equals": "b" } },
				],
			}),
			serde_json::json!({
				"not": {
					"all_of": [
						{ "tls.sni": { "equals": "a" } },
						{ "tls.sni": { "equals": "b" } },
					],
				},
			}),
		];
		for (i, m) in shapes.iter().enumerate() {
			let port = 7200 + u16::try_from(i).expect("fits u16");
			let r = check_rule(&format!("r{i}"), port, m);
			let graph =
				compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
			validate::validate(&graph).expect("validate");
		}
	}

	#[test]
	fn all_of_two_checks_chains_left_match_to_right_entry() {
		// all_of [A, B] match=>X miss=>Y  ≡
		//   Check(A) match=>Check(B) match=>X miss=>Y, miss=>Y
		// Both Checks share on_miss; the first Check's on_match points at
		// the second Check's entry, not at X directly.
		let r = check_rule(
			"r",
			7500,
			&serde_json::json!({
				"all_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "tls.sni": { "equals": "b" } },
				],
			}),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let entry = find_entry_check(&graph, 7500);
		let (_, match_a, miss_a) = unwrap_check(&graph[entry]);
		let (_, _match_b, miss_b) = unwrap_check(&graph[match_a]);
		assert_eq!(miss_a, miss_b, "both all_of branches share on_miss");
		assert_eq!(graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count(), 2);
	}

	#[test]
	fn all_of_empty_array_short_circuits_to_on_match() {
		// `all_of: []` is vacuously true → no Check emitted, the rule's
		// chain entry equals on_match (the rule body).
		let r = check_rule("r", 7501, &serde_json::json!({ "all_of": [] }));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let check_count = graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count();
		assert_eq!(check_count, 0, "empty all_of must not emit a Check node");
	}

	#[test]
	fn all_of_cross_level_combinator_is_rejected() {
		// Same uniform-level rule as any_of: AllOf can't mix L4 and L7 leaves.
		let r = check_rule(
			"r",
			7502,
			&serde_json::json!({
				"all_of": [
					{ "tls.sni": { "equals": "a" } },
					{ "http.method": { "equals": "GET" } },
				],
			}),
		);
		let err = compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers)
			.expect_err("cross-level all_of must fail");
		let msg = err.to_string();
		assert!(msg.contains("cross-level"), "error names the constraint: {msg}");
		assert!(msg.contains("all_of"), "error mentions all_of: {msg}");
	}

	#[test]
	fn all_of_nested_inside_any_of_works() {
		let r = check_rule(
			"r",
			7503,
			&serde_json::json!({
				"any_of": [
					{ "all_of": [
						{ "http.header.upgrade": { "equals": "websocket" } },
						{ "http.uri.path": { "prefix": "/ws" } },
					]},
					{ "all_of": [
						{ "http.header.upgrade": { "equals": "websocket" } },
						{ "http.uri.path": { "prefix": "/api/stream" } },
					]},
				],
			}),
		);
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		assert_eq!(graph.nodes.iter().filter(|n| matches!(n, Node::Check { .. })).count(), 4);
	}

	#[test]
	fn l7_listener_emits_single_upgrade_at_top_for_two_rules() {
		// spec/flow-model.md § _The compiled form_: two L7 rules on
		// the same listener share one Upgrade — the entire graph must
		// contain exactly one Upgrade node, not two.
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":7600"],
			"match": { "http.header.host": { "equals": "a.example.com" } },
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":7600"],
			"match": { "http.header.host": { "equals": "b.example.com" } },
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers).expect("compile");
		let upgrades = graph.nodes.iter().filter(|n| matches!(n, Node::Upgrade { .. })).count();
		assert_eq!(upgrades, 1, "exactly one Upgrade per L7 listener regardless of rule count");
	}

	#[test]
	fn l4_listener_has_no_upgrade() {
		// L4 posture stays as-is — no Upgrade emitted.
		let r = parse_rule(serde_json::json!({
			"name": "fwd",
			"listen": [":7601"],
			"terminate": { "type": "tcp_forward", "upstream": "10.0.0.5:22" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let upgrades = graph.nodes.iter().filter(|n| matches!(n, Node::Upgrade { .. })).count();
		assert_eq!(upgrades, 0);
	}

	#[test]
	fn websocket_upgrade_emits_two_distinct_terminators() {
		// `WebSocketUpgrade` is dual-output — the response branch lands at
		// `WriteHttpResponse` (rejection); the tunnel branch lands at
		// `ByteTunnel` (101 Switching handoff).
		let r = parse_rule(serde_json::json!({
			"name": "ws",
			"listen": [":7602"],
			"match": { "http.header.upgrade": { "equals": "websocket" } },
			"terminate": { "type": "websocket", "upstream": "127.0.0.1:8080" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let terms: std::collections::HashSet<_> = graph.terminators.iter().copied().collect();
		assert!(terms.contains(&Terminator::WriteHttpResponse), "response branch terminator");
		assert!(terms.contains(&Terminator::ByteTunnel), "tunnel branch terminator");
	}

	// Short(Response) synth target
	#[test]
	fn lower_l7_listener_synthesizes_short_circuit_response_target() {
		// Every L7 listener gets a synth `Terminate(WriteHttpResponse)` that
		// `meta.short_circuit_response_entry` maps the listener entry to.
		// Without this synth, an L7 request middleware returning
		// `Decision::Short(ShortCircuit::Response(_))` has nowhere to land.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7700"],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		// L7 listener → exactly one synth target per *unique* entry NodeId.
		// Dual-stack `:N` shorthand maps both v4 and v6 SocketAddrs to the
		// same listener NodeId, so the synth map keys by NodeId and is
		// smaller than `entries.len()` for the dual-stack case.
		let unique_entries: std::collections::HashSet<_> = graph.entries.values().copied().collect();
		assert_eq!(graph.meta.short_circuit_response_entry.len(), unique_entries.len());
		// Every value points at a `Terminate(WriteHttpResponse)`.
		for synth in graph.meta.short_circuit_response_entry.values() {
			let Node::Terminate(tid) = &graph[*synth] else {
				panic!("synth node is not a Terminate: {:?}", &graph[*synth]);
			};
			assert_eq!(graph.terminators[tid.get() as usize], Terminator::WriteHttpResponse);
		}
	}

	#[test]
	fn lower_l4_listener_has_no_short_circuit_response_target() {
		// Pure L4 (port_forward) listeners never go through Upgrade — no
		// L7Request middleware can run, so no synth target is needed.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7701"],
			"terminate": { "type": "tcp_forward", "upstream": "10.0.0.5:22" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		assert!(graph.meta.short_circuit_response_entry.is_empty());
	}

	#[test]
	fn lower_derives_raw_when_only_l4_forward_terminator() {
		// `port_forward`-shaped rule: single `tcp_forward` upstream on a
		// listener with no L7 path. Per `spec/crates/core.md` § _Listener kind
		// derivation_, every reachable terminator is L4 → `Raw`.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7800"],
			"terminate": { "type": "tcp_forward", "upstream": "10.0.0.5:22" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7800);
		assert_eq!(graph.meta.listener_kinds.get(&v4), Some(&crate::ir::ListenerKind::Raw));
	}

	#[test]
	fn lower_derives_http_when_only_l7_terminators() {
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7801"],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7801);
		assert_eq!(graph.meta.listener_kinds.get(&v4), Some(&crate::ir::ListenerKind::Http));
	}

	#[test]
	fn lower_derives_http_for_udp_prefix_listener() {
		// `spec/crates/core.md` § _Listener kind derivation_ is graph-shape-only —
		// transport doesn't enter the rule. The `udp:` prefix flows
		// through `parse_listen` to `listener_transports`, while the
		// L7 terminator independently picks `Http`. The combination is
		// what the engine needs to spawn the per-listener H3 stack.
		let r = parse_rule(serde_json::json!({
			"name": "h3",
			"listen": ["udp:7802"],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7802);
		assert_eq!(
			graph.meta.listener_kinds.get(&v4),
			Some(&crate::ir::ListenerKind::Http),
			"udp listener with http_proxy terminator must derive ListenerKind::Http",
		);
		assert_eq!(
			graph.meta.listener_transports.get(&v4),
			Some(&crate::conn_context::Transport::Udp),
			"udp: prefix must populate listener_transports as Udp",
		);
	}

	#[test]
	fn lower_derives_auto_when_l4_and_l7_share_listener() {
		// `analyze` currently rejects a single rule set with mixed L4 + L7
		// postures on the same listener (the protocol-detect frontend
		// that legitimises that combination is a separate feature). We
		// exercise the kind-derivation rule directly by hand-building a
		// graph whose entry can reach both an `L4Forward` fetch and an
		// `HttpProxy` fetch — the union of the two paths is what the
		// spec says yields `Auto`.
		use crate::compile::lower::test_only::derive_listener_kind_for_test;
		use crate::fetch::{FetchKind, SymbolicFetchRef};
		use crate::ir::{FetchId, ListenerKind, Node, NodeId, TerminatorId};

		let nodes = vec![
			Node::Check {
				predicate: PredicateId::new(0),
				on_match: NodeId::new(1),
				on_miss: NodeId::new(2),
				collect_body_before: None,
				body_limit: 0,
			},
			Node::Fetch {
				id: FetchId::new(0),
				next_response: None,
				next_tunnel: Some(NodeId::new(3)),
				collect_body_before: None,
				body_limit: 0,
			},
			Node::Fetch {
				id: FetchId::new(1),
				next_response: Some(NodeId::new(3)),
				next_tunnel: None,
				collect_body_before: None,
				body_limit: 0,
			},
			Node::Terminate(TerminatorId::new(0)),
		];
		let fetches = vec![
			SymbolicFetchRef {
				kind: FetchKind::L4Forward,
				args: serde_json::Value::Null,
				retry_buffer_required: false,
				allow_zero_rtt: None,
			},
			SymbolicFetchRef {
				kind: FetchKind::HttpProxy,
				args: serde_json::Value::Null,
				retry_buffer_required: false,
				allow_zero_rtt: None,
			},
		];
		assert_eq!(derive_listener_kind_for_test(&nodes, &fetches, NodeId::new(0)), ListenerKind::Auto);
	}

	#[test]
	fn listener_kinds_round_trip_through_dry_run_json() {
		let l4 = parse_rule(serde_json::json!({
			"name": "tcp",
			"listen": [":7803"],
			"terminate": { "type": "tcp_forward", "upstream": "10.0.0.5:22" },
		}));
		let l7 = parse_rule(serde_json::json!({
			"name": "http",
			"listen": [":7804"],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![l4, l7])], &Providers, &Providers).expect("compile");
		let encoded = serde_json::to_string(&*graph).expect("serialize graph");
		let decoded: crate::ir::SymbolicFlowGraph =
			serde_json::from_str(&encoded).expect("deserialize graph");
		let v4_raw = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7803);
		let v4_http = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7804);
		assert_eq!(decoded.meta.listener_kinds.get(&v4_raw), Some(&crate::ir::ListenerKind::Raw));
		assert_eq!(decoded.meta.listener_kinds.get(&v4_http), Some(&crate::ir::ListenerKind::Http));
	}

	#[test]
	fn lower_force_buffering_triggers_collect_body_before_request() {
		// `retry: { max_attempts: 3, buffering: "force" }` flags the
		// fetch node itself with `collect_body_before:
		// Some(BodySide::Request)` so the executor buffers the body
		// before the fetch runs. See `spec/crates/engine.md`
		// § _Retry_.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7900"],
			"terminate": {
				"type": "http_proxy",
				"upstream": "127.0.0.1:8080",
				"retry": { "max_attempts": 3, "buffering": "force" },
			},
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let fetch_with_collect = graph.nodes.iter().find_map(|n| match n {
			crate::ir::Node::Fetch {
				collect_body_before: Some(crate::ir::BodySide::Request), ..
			} => Some(()),
			_ => None,
		});
		assert!(
			fetch_with_collect.is_some(),
			"force buffering must flag fetch with collect_body_before"
		);
	}

	#[test]
	fn lower_opportunistic_buffering_does_not_trigger_collect() {
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7901"],
			"terminate": {
				"type": "http_proxy",
				"upstream": "127.0.0.1:8080",
				"retry": { "max_attempts": 3, "buffering": "opportunistic" },
			},
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let any_fetch_collects = graph.nodes.iter().any(|n| {
			matches!(
				n,
				crate::ir::Node::Fetch { collect_body_before: Some(crate::ir::BodySide::Request), .. },
			)
		});
		assert!(
			!any_fetch_collects,
			"opportunistic buffering must NOT flag fetch with collect_body_before",
		);
	}

	#[test]
	fn lower_max_attempts_one_with_force_does_not_trigger_collect() {
		// `force` only means anything together with `max_attempts > 1`.
		// Pinning `max_attempts: 1` keeps retry off and the buffering
		// trigger inactive even when the JSON spells `force`.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7902"],
			"terminate": {
				"type": "http_proxy",
				"upstream": "127.0.0.1:8080",
				"retry": { "max_attempts": 1, "buffering": "force" },
			},
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let any_fetch_collects = graph.nodes.iter().any(|n| {
			matches!(
				n,
				crate::ir::Node::Fetch { collect_body_before: Some(crate::ir::BodySide::Request), .. },
			)
		});
		assert!(!any_fetch_collects, "max_attempts=1 disables the force-buffering trigger");
	}

	#[test]
	fn lower_two_l7_listeners_have_independent_synth_entries() {
		// Two L7 listeners on distinct ports each get their own synth
		// target keyed by their listener entry. (Whether the synth nodes
		// collapse via terminator-id hash-cons is an internal detail; the
		// public contract is one map entry per listener entry.)
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":7702"],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8080" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":7703"],
			"terminate": { "type": "http_proxy", "upstream": "127.0.0.1:8081" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers).expect("compile");
		// One synth entry per listener entry — the dual-stack `:7702`
		// expands to v4+v6 sharing one entry NodeId, so map size matches
		// the number of *unique* entry NodeIds in the graph.
		let unique_entries: std::collections::HashSet<_> = graph.entries.values().copied().collect();
		assert_eq!(graph.meta.short_circuit_response_entry.len(), unique_entries.len());
		assert!(
			graph.meta.short_circuit_response_entry.len() >= 2,
			"two listeners → at least two synth entries"
		);
	}

	#[test]
	fn http_body_check_node_sets_collect_body_before_request() {
		// A rule whose predicate reads http.body must produce a Check node
		// with collect_body_before = Some(BodySide::Request). The executor
		// uses this flag to materialise the request body before running the
		// predicate test — without it, as_static() would panic.
		//
		// "aGVsbG8=" is standard base64 for the ASCII bytes "hello".
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7910"],
			"match": { "http.body": { "contains": "aGVsbG8=" } },
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let has_collecting_check = graph.nodes.iter().any(|n| {
			matches!(
				n,
				crate::ir::Node::Check { collect_body_before: Some(crate::ir::BodySide::Request), .. }
			)
		});
		assert!(has_collecting_check, "http.body Check must carry collect_body_before = Some(Request)");
	}

	#[test]
	fn rule_without_http_body_predicate_has_no_request_collect_on_check() {
		// A rule whose predicate does not read http.body must not trigger
		// request-side buffering. The Check node produced for an
		// http.method predicate must have collect_body_before = None so the
		// pay-as-you-go invariant holds.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7911"],
			"match": { "http.method": { "equals": "GET" } },
			"terminate": { "type": "http_proxy" },
		}));
		let graph =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect("compile");
		let any_check_collects = graph.nodes.iter().any(|n| {
			matches!(
				n,
				crate::ir::Node::Check { collect_body_before: Some(crate::ir::BodySide::Request), .. }
			)
		});
		assert!(
			!any_check_collects,
			"non-body predicate must not set collect_body_before on any Check node"
		);
	}

	#[test]
	fn compile_collecting_surfaces_every_analyze_failure_in_one_pass() {
		// Two rules each reference an unknown middleware — the legacy
		// `compile()` short-circuits on the first; the collecting form
		// must accumulate both.
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":9201"],
			"middleware_chain": [{ "use": "does_not_exist_a" }],
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":9202"],
			"middleware_chain": [{ "use": "does_not_exist_b" }],
			"terminate": { "type": "http_proxy" },
		}));
		let d =
			super::compile_collecting(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers)
				.expect_err("must accumulate errors");
		assert_eq!(d.len(), 2, "expected one error per bad rule, got {d}");
		let s = d.to_string();
		assert!(s.contains("does_not_exist_a"), "{s}");
		assert!(s.contains("does_not_exist_b"), "{s}");
	}

	#[test]
	fn compile_facade_collapses_diagnostics_into_single_error_message() {
		// The back-compat `compile()` API must keep emitting one
		// Error whose message names every accumulated failure, so
		// existing callers (daemon RPC, etc.) still surface every
		// problem in one turn.
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":9301"],
			"middleware_chain": [{ "use": "does_not_exist_x" }],
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":9302"],
			"middleware_chain": [{ "use": "does_not_exist_y" }],
			"terminate": { "type": "http_proxy" },
		}));
		let err = super::compile(vec![rule_file("a.json", vec![a, b])], &Providers, &Providers)
			.expect_err("must error");
		let msg = err.to_string();
		assert!(msg.contains("does_not_exist_x"), "{msg}");
		assert!(msg.contains("does_not_exist_y"), "{msg}");
		assert!(msg.contains("2 compile errors"), "{msg}");
	}

	#[test]
	fn version_hash_changes_with_match_predicate() {
		let with_match = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":9001"],
			"match": { "tls.sni": { "equals": "a.example.com" } },
			"terminate": { "type": "http_proxy" },
		}));
		let without_match = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":9001"],
			"terminate": { "type": "http_proxy" },
		}));
		let g1 = compile(vec![rule_file("a.json", vec![with_match])], &Providers, &Providers)
			.expect("compile with match");
		let g2 = compile(vec![rule_file("a.json", vec![without_match])], &Providers, &Providers)
			.expect("compile without match");
		assert_ne!(
			g1.meta.version_hash, g2.meta.version_hash,
			"version_hash must distinguish rules whose match predicate differs",
		);
	}

	#[test]
	fn version_hash_changes_with_middleware_chain() {
		let with_mw = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":9002"],
			"middleware_chain": [{ "use": "forward_client_ip" }],
			"terminate": { "type": "http_proxy" },
		}));
		let without_mw = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":9002"],
			"terminate": { "type": "http_proxy" },
		}));
		let g1 = compile(vec![rule_file("a.json", vec![with_mw])], &Providers, &Providers)
			.expect("compile with chain");
		let g2 = compile(vec![rule_file("a.json", vec![without_mw])], &Providers, &Providers)
			.expect("compile without chain");
		assert_ne!(
			g1.meta.version_hash, g2.meta.version_hash,
			"version_hash must distinguish rules whose middleware_chain differs",
		);
	}

	#[test]
	fn version_hash_stable_under_rule_input_order_and_source_path() {
		// Two equivalent configs differing only in rule input order and
		// the file path they come from must produce the same hash —
		// `hash_rules` sorts by rule name and strips source metadata.
		let a = parse_rule(serde_json::json!({
			"name": "a",
			"listen": [":9101"],
			"terminate": { "type": "http_proxy" },
		}));
		let b = parse_rule(serde_json::json!({
			"name": "b",
			"listen": [":9102"],
			"terminate": { "type": "http_proxy" },
		}));
		let g1 =
			compile(vec![rule_file("first.json", vec![a.clone(), b.clone()])], &Providers, &Providers)
				.expect("compile first order");
		let g2 = compile(vec![rule_file("second.json", vec![b, a])], &Providers, &Providers)
			.expect("compile reversed order");
		assert_eq!(
			g1.meta.version_hash, g2.meta.version_hash,
			"version_hash must be stable across rule order and file path",
		);
	}

	#[test]
	fn malformed_base64_in_http_body_predicate_fails_compile() {
		// The base64 literal in a Bytes-typed field predicate is decoded at
		// lower time, not at predicate-test time. A syntactically invalid
		// base64 string must produce a compile-time error so the rule never
		// reaches the runtime graph. "not-valid-base64!!!" contains '!'
		// which is not in the standard base64 alphabet.
		let r = parse_rule(serde_json::json!({
			"name": "r",
			"listen": [":7912"],
			"match": { "http.body": { "contains": "not-valid-base64!!!" } },
			"terminate": { "type": "http_proxy" },
		}));
		let err =
			compile(vec![rule_file("a.json", vec![r])], &Providers, &Providers).expect_err("must fail");
		let msg = err.to_string();
		assert!(
			msg.contains("base64") || msg.contains("base 64"),
			"error must mention base64 decoding failure, got: {msg}"
		);
	}
}