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
use std::collections::HashMap;
use std::net::SocketAddr;
use std::ops::Index;
use std::path::PathBuf;
use std::time::SystemTime;

use crate::conn_context::Transport;
use crate::fetch::{SymbolicFetchRef, Terminator};
use crate::middleware::SymbolicMiddlewareRef;
use crate::predicate::PredicateInst;

macro_rules! id_newtype {
	($name:ident) => {
		#[derive(
			Copy, Clone, Eq, PartialEq, Hash, Debug, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
		)]
		pub struct $name(u32);

		impl $name {
			// `new` is the internal construction loophole; IDs in
			// production are produced by the compile/link pass and
			// flow through the IR. Narrowing to `pub(crate)` keeps
			// downstream crates from fabricating IDs that point at
			// non-existent nodes. Tests that need to mint IDs from
			// raw integers use [`Self::for_testing`] instead.
			#[must_use]
			pub(crate) const fn new(raw: u32) -> Self {
				Self(raw)
			}

			/// Construct an ID from a raw integer for use in tests.
			///
			/// Only available when the `test-support` feature is
			/// enabled, or within `vane-core`'s own test builds. The
			/// resulting ID is **not** validated against any
			/// `SymbolicFlowGraph` — callers are responsible for
			/// keeping their fixture IDs internally consistent.
			#[cfg(any(test, feature = "test-support"))]
			#[must_use]
			pub const fn for_testing(raw: u32) -> Self {
				Self(raw)
			}

			#[must_use]
			pub const fn get(self) -> u32 {
				self.0
			}
		}
	};
}

id_newtype!(NodeId);
id_newtype!(PredicateId);
id_newtype!(MiddlewareId);
id_newtype!(FetchId);
id_newtype!(TerminatorId);

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, serde::Serialize, serde::Deserialize)]
pub enum BodySide {
	Request,
	Response,
}

/// Per-listener dispatch posture. **Derived by the lower pass from
/// the listener's entry subgraph — not user-configured.** See
/// `spec/crates/core.md` § _Listener kind derivation_ for the
/// derivation rule and `spec/crates/engine.md` § _Dispatch table_ for the runtime
/// behavior the listener picks based on this value.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, serde::Serialize, serde::Deserialize)]
pub enum ListenerKind {
	/// Every reachable terminator is L4 (e.g. `L4Forward`). The
	/// listener never runs a TLS handshake or hyper driver — bytes
	/// flow through the L4 subgraph as-is. SNI passthrough lives here.
	Raw,
	/// Every L4→L7 path crosses an `Upgrade` node and the only
	/// reachable terminators are L7. Cleartext H1/H2 on the wire is
	/// rejected; that mixed-posture role belongs to `Auto`.
	Http,
	/// Both L4 and L7 terminators are reachable from the same entry.
	/// The listener peeks the connection prefix and dispatches per
	/// `(detected, listener_tls)` per the dispatch decision table.
	Auto,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum Node {
	Check {
		predicate: PredicateId,
		on_match: NodeId,
		on_miss: NodeId,
		collect_body_before: Option<BodySide>,
		#[serde(default)]
		body_limit: usize,
	},
	Middleware {
		id: MiddlewareId,
		next: NodeId,
		on_error: Option<NodeId>,
		collect_body_before: Option<BodySide>,
		#[serde(default)]
		body_limit: usize,
	},
	Fetch {
		id: FetchId,
		next_response: Option<NodeId>,
		next_tunnel: Option<NodeId>,
		collect_body_before: Option<BodySide>,
		#[serde(default)]
		body_limit: usize,
	},
	Upgrade {
		next: NodeId,
	},
	Terminate(TerminatorId),
}

impl Node {
	#[must_use]
	pub const fn collect_body_before(&self) -> Option<BodySide> {
		match self {
			Self::Check { collect_body_before, .. }
			| Self::Middleware { collect_body_before, .. }
			| Self::Fetch { collect_body_before, .. } => *collect_body_before,
			Self::Upgrade { .. } | Self::Terminate(_) => None,
		}
	}

	#[must_use]
	pub const fn body_limit(&self) -> usize {
		match self {
			Self::Check { body_limit, .. }
			| Self::Middleware { body_limit, .. }
			| Self::Fetch { body_limit, .. } => *body_limit,
			_ => 0,
		}
	}
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct FlowGraphMeta {
	pub version_hash: [u8; 32],
	pub compiled_at: SystemTime,
	pub source_files: Vec<PathBuf>,
	// `feature_set` is a compile-time slice the daemon fills in at link, not
	// a user-authored value; dry-run JSON omits it and deserialization
	// restores the empty slice. Engine's link step installs the real value.
	#[serde(skip, default = "empty_feature_set")]
	pub feature_set: &'static [&'static str],

	/// Map of L7-listener entry `NodeId` → synthesised
	/// `Terminate(WriteHttpResponse)` `NodeId`. The executor jumps here
	/// when an L7 request middleware returns
	/// `Decision::Short(ShortCircuit::Response(_))`: it sets the response
	/// slot and walks to the synth target so the response runs through
	/// the standard `WriteHttpResponse` write path. Empty for L4-only
	/// graphs and for any L7 entry whose listener is not bound to a
	/// post-`Upgrade` chain (which the lower pass guarantees never
	/// happens for legal L7 listeners). See spec/flow-model.md
	/// § _The compiled form_.
	///
	/// `#[serde(default)]` keeps older dry-run JSON snapshots
	/// deserializable: missing field decodes as an empty map, which
	/// matches the legacy "no L7 listeners" graph shape.
	#[serde(default)]
	pub short_circuit_response_entry: std::collections::BTreeMap<NodeId, NodeId>,

	/// Per-listener cert pool. Symbolic — each entry is the aggregated
	/// `(default, sni_certs)` view across every rule on the bind
	/// address that carried a `tls` block; the engine's `link` stage
	/// reads PEM files referenced here and builds a `rustls::ServerConfig`
	/// with an SNI resolver that falls back to `default` for unmatched
	/// SNI. Listeners absent from this map are cleartext. See
	/// `spec/crates/engine-tls.md` § _Termination flow (L4 → L7 upgrade)_ and § _SNI peek (L4, no decrypt)_.
	///
	/// `#[serde(default)]` for the same wire-compat reason as the map
	/// above.
	#[serde(default)]
	pub listener_tls: std::collections::BTreeMap<SocketAddr, crate::rule::ListenerTlsSpec>,

	/// Per-listener dispatch posture, derived from each entry's
	/// reachable-terminator set. Populated by the lower pass; the
	/// engine reads it in [`crate::ir::ListenerKind`]-aware dispatch
	/// (`spec/crates/engine.md` § _Dispatch table_).
	/// Listeners absent from this map are treated as `Http` by the
	/// engine's defensive accessor — but the lower pass guarantees
	/// every entry address has an explicit kind.
	#[serde(default)]
	pub listener_kinds: std::collections::BTreeMap<SocketAddr, ListenerKind>,

	/// Per-listener transport, derived from each entry's reachable
	/// fetches. A listener with any reachable `L4Forward` whose
	/// `args.transport == "udp"` is `Transport::Udp`; everything else
	/// is `Transport::Tcp`. Mixing UDP `L4Forward` with any other
	/// fetch kind on the same listener is a compile error — the
	/// physical socket is single-protocol and cannot serve both
	/// transports concurrently. See `spec/crates/engine.md`
	/// § _`udp_dispatch`_. `#[serde(default)]` keeps older dry-run
	/// snapshots loadable; absent listeners are treated as `Tcp`.
	#[serde(default)]
	pub listener_transports: std::collections::BTreeMap<SocketAddr, Transport>,

	/// Compile-time annotations the lower pass emits as observations
	/// about the produced graph — surfaced in `vane compile --dry-run`
	/// so operators see synthetic-route insertions and rule-shadowing
	/// warnings without grepping logs. Stable wire format keyed by
	/// `kind` (e.g. `"acme-injected"`, `"shadowed-by-acme"`).
	///
	/// `#[serde(default)]` keeps older snapshots loadable: an absent
	/// field decodes to an empty Vec, matching pre-ACME graph shape.
	#[serde(default)]
	pub annotations: Vec<DryRunAnnotation>,
}

/// One observation about the compiled graph, surfaced through
/// `compile_dry_run` for operator visibility. Currently used by the
/// ACME inject pass to mark synthesised `:80` challenge routes and
/// any operator-defined rule whose path overlaps the injected one.
///
/// Intentionally schemaless on `target` — different annotation
/// kinds describe different things (a listener address, a rule
/// name, a node id). `kind` plus `message` is the human-readable
/// surface; structured fields can land in a follow-up if a tool
/// needs them programmatically.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct DryRunAnnotation {
	/// Annotation taxonomy — currently `"acme-injected"` (a route
	/// the lower pass synthesised) or `"shadowed-by-acme"` (an
	/// operator rule whose match is preempted by an injected one).
	pub kind: String,
	/// Operator-readable explanation of the annotation, including
	/// the listener address and any relevant identifiers.
	pub message: String,
}

const fn empty_feature_set() -> &'static [&'static str] {
	&[]
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct SymbolicFlowGraph {
	pub nodes: Vec<Node>,
	pub predicates: Vec<PredicateInst>,
	pub middlewares: Vec<SymbolicMiddlewareRef>,
	pub fetches: Vec<SymbolicFetchRef>,
	pub terminators: Vec<Terminator>,
	pub entries: HashMap<SocketAddr, NodeId>,
	pub meta: FlowGraphMeta,
}

impl Index<NodeId> for SymbolicFlowGraph {
	type Output = Node;
	fn index(&self, id: NodeId) -> &Node {
		&self.nodes[id.get() as usize]
	}
}

impl Index<PredicateId> for SymbolicFlowGraph {
	type Output = PredicateInst;
	fn index(&self, id: PredicateId) -> &PredicateInst {
		&self.predicates[id.get() as usize]
	}
}

impl Index<MiddlewareId> for SymbolicFlowGraph {
	type Output = SymbolicMiddlewareRef;
	fn index(&self, id: MiddlewareId) -> &SymbolicMiddlewareRef {
		&self.middlewares[id.get() as usize]
	}
}

impl Index<FetchId> for SymbolicFlowGraph {
	type Output = SymbolicFetchRef;
	fn index(&self, id: FetchId) -> &SymbolicFetchRef {
		&self.fetches[id.get() as usize]
	}
}

impl Index<TerminatorId> for SymbolicFlowGraph {
	type Output = Terminator;
	fn index(&self, id: TerminatorId) -> &Terminator {
		&self.terminators[id.get() as usize]
	}
}

#[cfg(test)]
mod tests {
	use std::collections::hash_map::DefaultHasher;
	use std::hash::{Hash, Hasher};
	use std::sync::Arc;

	use serde_json::Value;

	use super::*;
	use crate::fetch::{FetchKind, SymbolicFetchRef, Terminator};
	use crate::middleware::{MiddlewareKind, SymbolicMiddlewareRef};
	use crate::predicate::{CompiledOperator, CompiledValue, FieldPath, PredicateInst};

	#[test]
	fn new_then_get_round_trips_raw_u32() {
		for raw in [0_u32, 1, 42, u32::MAX] {
			assert_eq!(NodeId::new(raw).get(), raw);
		}
	}

	#[test]
	fn node_id_equality_is_structural() {
		assert_eq!(NodeId::new(7), NodeId::new(7));
		assert_ne!(NodeId::new(7), NodeId::new(8));
	}

	#[test]
	fn node_id_ordering_follows_raw_u32() {
		assert!(NodeId::new(1) < NodeId::new(2));
		assert!(NodeId::new(u32::MAX) > NodeId::new(0));
	}

	#[test]
	fn node_id_serde_round_trip() {
		let id = NodeId::new(0x0bad_f00d);
		let encoded = serde_json::to_string(&id).expect("serialize");
		let decoded: NodeId = serde_json::from_str(&encoded).expect("deserialize");
		assert_eq!(decoded, id);
	}

	#[test]
	fn body_side_serde_round_trip_per_variant() {
		for s in [BodySide::Request, BodySide::Response] {
			let encoded = serde_json::to_string(&s).expect("serialize");
			let decoded: BodySide = serde_json::from_str(&encoded).expect("deserialize");
			assert_eq!(decoded, s);
		}
	}

	fn hash_of<T: Hash>(t: &T) -> u64 {
		let mut h = DefaultHasher::new();
		t.hash(&mut h);
		h.finish()
	}

	#[test]
	fn predicate_id_new_get_round_trip_and_hash_eq() {
		for raw in [0_u32, 1, 42, u32::MAX] {
			let a = PredicateId::new(raw);
			let b = PredicateId::new(raw);
			assert_eq!(a.get(), raw);
			assert_eq!(a, b);
			assert_eq!(hash_of(&a), hash_of(&b));
			let encoded = serde_json::to_string(&a).expect("serialize");
			let decoded: PredicateId = serde_json::from_str(&encoded).expect("deserialize");
			assert_eq!(decoded, a);
		}
	}

	#[test]
	fn middleware_id_new_get_round_trip_and_hash_eq() {
		for raw in [0_u32, 1, 42, u32::MAX] {
			let a = MiddlewareId::new(raw);
			let b = MiddlewareId::new(raw);
			assert_eq!(a.get(), raw);
			assert_eq!(a, b);
			assert_eq!(hash_of(&a), hash_of(&b));
			let encoded = serde_json::to_string(&a).expect("serialize");
			let decoded: MiddlewareId = serde_json::from_str(&encoded).expect("deserialize");
			assert_eq!(decoded, a);
		}
	}

	#[test]
	fn fetch_id_new_get_round_trip_and_hash_eq() {
		for raw in [0_u32, 1, 42, u32::MAX] {
			let a = FetchId::new(raw);
			let b = FetchId::new(raw);
			assert_eq!(a.get(), raw);
			assert_eq!(a, b);
			assert_eq!(hash_of(&a), hash_of(&b));
			let encoded = serde_json::to_string(&a).expect("serialize");
			let decoded: FetchId = serde_json::from_str(&encoded).expect("deserialize");
			assert_eq!(decoded, a);
		}
	}

	#[test]
	fn terminator_id_new_get_round_trip_and_hash_eq() {
		for raw in [0_u32, 1, 42, u32::MAX] {
			let a = TerminatorId::new(raw);
			let b = TerminatorId::new(raw);
			assert_eq!(a.get(), raw);
			assert_eq!(a, b);
			assert_eq!(hash_of(&a), hash_of(&b));
			let encoded = serde_json::to_string(&a).expect("serialize");
			let decoded: TerminatorId = serde_json::from_str(&encoded).expect("deserialize");
			assert_eq!(decoded, a);
		}
	}

	// The newtype wrappers are distinct types — a function accepting `NodeId`
	// refuses a `PredicateId` at compile time. `_id_types_are_distinct` is a
	// compile-only witness that the signatures pin the right types; any mix-up
	// at a call site would fail to type-check.
	fn _id_types_are_distinct(
		_n: NodeId,
		_p: PredicateId,
		_m: MiddlewareId,
		_f: FetchId,
		_t: TerminatorId,
	) {
	}

	#[test]
	fn node_check_collect_body_before_returns_stored_flag() {
		let some = Node::Check {
			predicate: PredicateId::new(0),
			on_match: NodeId::new(0),
			on_miss: NodeId::new(0),
			collect_body_before: Some(BodySide::Request),
			body_limit: 0,
		};
		assert_eq!(some.collect_body_before(), Some(BodySide::Request));

		let none = Node::Check {
			predicate: PredicateId::new(0),
			on_match: NodeId::new(0),
			on_miss: NodeId::new(0),
			collect_body_before: None,
			body_limit: 0,
		};
		assert_eq!(none.collect_body_before(), None);
	}

	#[test]
	fn node_middleware_collect_body_before_returns_stored_flag() {
		let some = Node::Middleware {
			id: MiddlewareId::new(0),
			next: NodeId::new(0),
			on_error: None,
			collect_body_before: Some(BodySide::Response),
			body_limit: 0,
		};
		assert_eq!(some.collect_body_before(), Some(BodySide::Response));

		let none = Node::Middleware {
			id: MiddlewareId::new(0),
			next: NodeId::new(0),
			on_error: None,
			collect_body_before: None,
			body_limit: 0,
		};
		assert_eq!(none.collect_body_before(), None);
	}

	#[test]
	fn node_fetch_collect_body_before_returns_stored_flag() {
		let some = Node::Fetch {
			id: FetchId::new(0),
			next_response: None,
			next_tunnel: None,
			collect_body_before: Some(BodySide::Request),
			body_limit: 0,
		};
		assert_eq!(some.collect_body_before(), Some(BodySide::Request));

		let none = Node::Fetch {
			id: FetchId::new(0),
			next_response: None,
			next_tunnel: None,
			collect_body_before: None,
			body_limit: 0,
		};
		assert_eq!(none.collect_body_before(), None);
	}

	#[test]
	fn node_upgrade_collect_body_before_is_always_none() {
		let n = Node::Upgrade { next: NodeId::new(0) };
		assert_eq!(n.collect_body_before(), None);
	}

	#[test]
	fn node_terminate_collect_body_before_is_always_none() {
		let n = Node::Terminate(TerminatorId::new(0));
		assert_eq!(n.collect_body_before(), None);
	}

	fn sample_predicate() -> PredicateInst {
		PredicateInst {
			path: FieldPath::TlsSni,
			op: CompiledOperator::Equals(CompiledValue::Str(Arc::from("a"))),
		}
	}

	fn sample_middleware() -> SymbolicMiddlewareRef {
		SymbolicMiddlewareRef {
			name: Arc::from("noop"),
			args: Value::Null,
			kind: MiddlewareKind::L7Request,
			stateless: true,
			needs_body: false,
			on_error: None,
		}
	}

	fn sample_fetch() -> SymbolicFetchRef {
		SymbolicFetchRef {
			kind: FetchKind::HttpProxy,
			args: Value::Null,
			retry_buffer_required: false,
			allow_zero_rtt: None,
		}
	}

	fn sample_meta() -> FlowGraphMeta {
		FlowGraphMeta {
			version_hash: [0; 32],
			compiled_at: SystemTime::UNIX_EPOCH,
			source_files: vec![],
			feature_set: &[],
			short_circuit_response_entry: std::collections::BTreeMap::new(),
			listener_tls: std::collections::BTreeMap::new(),
			listener_kinds: std::collections::BTreeMap::new(),
			listener_transports: std::collections::BTreeMap::new(),
			annotations: Vec::new(),
		}
	}

	fn one_of_each_graph() -> SymbolicFlowGraph {
		SymbolicFlowGraph {
			nodes: vec![Node::Terminate(TerminatorId::new(0))],
			predicates: vec![sample_predicate()],
			middlewares: vec![sample_middleware()],
			fetches: vec![sample_fetch()],
			terminators: vec![Terminator::WriteHttpResponse],
			entries: HashMap::new(),
			meta: sample_meta(),
		}
	}

	#[test]
	fn index_by_node_id_returns_matching_node() {
		let g = one_of_each_graph();
		match &g[NodeId::new(0)] {
			Node::Terminate(t) => assert_eq!(*t, TerminatorId::new(0)),
			other => panic!("expected Terminate, got {other:?}"),
		}
	}

	#[test]
	fn index_by_predicate_id_returns_matching_predicate() {
		let g = one_of_each_graph();
		assert_eq!(g[PredicateId::new(0)], sample_predicate());
	}

	#[test]
	fn index_by_middleware_id_returns_matching_middleware() {
		let g = one_of_each_graph();
		assert_eq!(g[MiddlewareId::new(0)], sample_middleware());
	}

	#[test]
	fn index_by_fetch_id_returns_matching_fetch() {
		let g = one_of_each_graph();
		assert_eq!(g[FetchId::new(0)].kind, FetchKind::HttpProxy);
	}

	#[test]
	fn index_by_terminator_id_returns_matching_terminator() {
		let g = one_of_each_graph();
		assert_eq!(g[TerminatorId::new(0)], Terminator::WriteHttpResponse);
	}

	fn node_round_trip(n: &Node) -> Node {
		let encoded = serde_json::to_string(n).expect("serialize node");
		serde_json::from_str(&encoded).expect("deserialize node")
	}

	#[test]
	fn node_check_serde_round_trip_with_and_without_collect_flag() {
		let with = Node::Check {
			predicate: PredicateId::new(3),
			on_match: NodeId::new(4),
			on_miss: NodeId::new(5),
			collect_body_before: Some(BodySide::Request),
			body_limit: 0,
		};
		match node_round_trip(&with) {
			Node::Check { predicate, on_match, on_miss, collect_body_before, .. } => {
				assert_eq!(predicate, PredicateId::new(3));
				assert_eq!(on_match, NodeId::new(4));
				assert_eq!(on_miss, NodeId::new(5));
				assert_eq!(collect_body_before, Some(BodySide::Request));
			}
			other => panic!("expected Check, got {other:?}"),
		}

		let without = Node::Check {
			predicate: PredicateId::new(0),
			on_match: NodeId::new(0),
			on_miss: NodeId::new(0),
			collect_body_before: None,
			body_limit: 0,
		};
		match node_round_trip(&without) {
			Node::Check { collect_body_before, .. } => assert_eq!(collect_body_before, None),
			other => panic!("expected Check, got {other:?}"),
		}
	}

	#[test]
	fn node_middleware_serde_round_trip_with_and_without_collect_flag() {
		let with = Node::Middleware {
			id: MiddlewareId::new(1),
			next: NodeId::new(2),
			on_error: Some(NodeId::new(9)),
			collect_body_before: Some(BodySide::Response),
			body_limit: 0,
		};
		match node_round_trip(&with) {
			Node::Middleware { id, next, on_error, collect_body_before, .. } => {
				assert_eq!(id, MiddlewareId::new(1));
				assert_eq!(next, NodeId::new(2));
				assert_eq!(on_error, Some(NodeId::new(9)));
				assert_eq!(collect_body_before, Some(BodySide::Response));
			}
			other => panic!("expected Middleware, got {other:?}"),
		}

		let without = Node::Middleware {
			id: MiddlewareId::new(0),
			next: NodeId::new(0),
			on_error: None,
			collect_body_before: None,
			body_limit: 0,
		};
		match node_round_trip(&without) {
			Node::Middleware { on_error, collect_body_before, .. } => {
				assert_eq!(on_error, None);
				assert_eq!(collect_body_before, None);
			}
			other => panic!("expected Middleware, got {other:?}"),
		}
	}

	#[test]
	fn node_fetch_serde_round_trip_with_and_without_collect_flag() {
		let with = Node::Fetch {
			id: FetchId::new(7),
			next_response: Some(NodeId::new(8)),
			next_tunnel: Some(NodeId::new(9)),
			collect_body_before: Some(BodySide::Request),
			body_limit: 0,
		};
		match node_round_trip(&with) {
			Node::Fetch { id, next_response, next_tunnel, collect_body_before, .. } => {
				assert_eq!(id, FetchId::new(7));
				assert_eq!(next_response, Some(NodeId::new(8)));
				assert_eq!(next_tunnel, Some(NodeId::new(9)));
				assert_eq!(collect_body_before, Some(BodySide::Request));
			}
			other => panic!("expected Fetch, got {other:?}"),
		}

		let without = Node::Fetch {
			id: FetchId::new(0),
			next_response: None,
			next_tunnel: None,
			collect_body_before: None,
			body_limit: 0,
		};
		match node_round_trip(&without) {
			Node::Fetch { next_response, next_tunnel, collect_body_before, .. } => {
				assert_eq!(next_response, None);
				assert_eq!(next_tunnel, None);
				assert_eq!(collect_body_before, None);
			}
			other => panic!("expected Fetch, got {other:?}"),
		}
	}

	#[test]
	fn node_upgrade_serde_round_trip() {
		let n = Node::Upgrade { next: NodeId::new(11) };
		match node_round_trip(&n) {
			Node::Upgrade { next } => assert_eq!(next, NodeId::new(11)),
			other => panic!("expected Upgrade, got {other:?}"),
		}
	}

	#[test]
	fn node_terminate_serde_round_trip() {
		let n = Node::Terminate(TerminatorId::new(13));
		match node_round_trip(&n) {
			Node::Terminate(t) => assert_eq!(t, TerminatorId::new(13)),
			other => panic!("expected Terminate, got {other:?}"),
		}
	}

	// `FlowGraphMeta` derives `Serialize` but not `Deserialize` — the
	// version-hash + feature-set fields are populated by compile, never
	// reconstructed from JSON. Assert the forward direction only.
	#[test]
	fn flow_graph_meta_serializes_and_emits_version_hash_field() {
		let meta = sample_meta();
		let encoded = serde_json::to_string(&meta).expect("serialize meta");
		assert!(encoded.contains("version_hash"), "expected version_hash field in {encoded}");
	}

	#[test]
	fn flow_graph_meta_round_trip_preserves_all_but_feature_set() {
		// spec/flow-model.md § _The compiled form_: feature_set is a compile-time
		// slice the daemon fills in at link and is NOT emitted to dry-run JSON.
		// version_hash / compiled_at / source_files must round-trip.
		use std::time::Duration;
		let meta = FlowGraphMeta {
			version_hash: [0x42; 32],
			compiled_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000_000),
			source_files: vec![PathBuf::from("/a.json"), PathBuf::from("/b.json")],
			feature_set: &["h3", "wasm"],
			short_circuit_response_entry: std::collections::BTreeMap::new(),
			listener_tls: std::collections::BTreeMap::new(),
			listener_kinds: std::collections::BTreeMap::new(),
			listener_transports: std::collections::BTreeMap::new(),
			annotations: Vec::new(),
		};
		let encoded = serde_json::to_string(&meta).expect("serialize meta");
		assert!(
			!encoded.contains("feature_set"),
			"feature_set must be skipped in dry-run JSON, got: {encoded}",
		);
		let decoded: FlowGraphMeta = serde_json::from_str(&encoded).expect("deserialize meta");
		assert_eq!(decoded.version_hash, meta.version_hash);
		assert_eq!(decoded.compiled_at, meta.compiled_at);
		assert_eq!(decoded.source_files, meta.source_files);
		// feature_set is restored to the empty slice by #[serde(skip, default=...)].
		assert!(decoded.feature_set.is_empty(), "feature_set must default to empty on deserialize");
	}
}