tightbeam-rs 0.6.2

A secure, high-performance messaging protocol library
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
//! FDR refinement checking subsystem
//!
//! This module contains the RefinementChecker trait implementation.

use std::cell::RefCell;
use std::collections::{HashSet, VecDeque};
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::testing::fdr::config::{Failure, FdrConfig, Trace};
use crate::testing::fdr::explorer::{MemoizationCache, RefinementChecker};
use crate::testing::specs::csp::{Action, Event, Process, State};

/// Timeout checker helper
struct TimeoutChecker {
	start: Instant,
	timeout: Duration,
}

impl TimeoutChecker {
	fn new(timeout_ms: u64) -> Self {
		Self { start: Instant::now(), timeout: Duration::from_millis(timeout_ms) }
	}

	fn is_expired(&self) -> bool {
		self.start.elapsed() >= self.timeout
	}
}

/// Default refinement checker implementation
pub struct DefaultRefinementChecker<'a, M>
where
	M: MemoizationCache,
{
	/// Configuration
	config: Arc<FdrConfig>,
	/// Process being verified
	process: &'a Process,
	/// Shared memoization cache
	cache: Rc<RefCell<M>>,
}

impl<'a, M> DefaultRefinementChecker<'a, M>
where
	M: MemoizationCache,
{
	/// Create new refinement checker with shared cache
	pub fn new(process: &'a Process, config: Arc<FdrConfig>, cache: Rc<RefCell<M>>) -> Self {
		Self { config, process, cache }
	}

	/// Get configuration
	pub fn config(&self) -> &FdrConfig {
		&self.config
	}

	/// Get process
	pub fn process(&self) -> &Process {
		self.process
	}

	/// Helper methods to access trait constants
	fn max_traces() -> usize {
		<Self as RefinementChecker>::MAX_TRACES
	}

	fn max_queue_size() -> usize {
		<Self as RefinementChecker>::MAX_QUEUE_SIZE
	}

	fn max_visited() -> usize {
		<Self as RefinementChecker>::MAX_VISITED
	}

	/// Check if limits are exceeded before enqueueing
	fn check_limits(queue_len: usize, visited_len: usize, traces_count: usize) -> bool {
		queue_len >= Self::max_queue_size() || visited_len >= Self::max_visited() || traces_count >= Self::max_traces()
	}

	/// Check if a state is stable (no Ï„-transitions enabled)
	fn is_stable_state(process: &Process, state: State) -> bool {
		let enabled_actions = process.enabled(state);
		!enabled_actions.iter().any(|action| process.hidden.contains(&action.event))
	}

	/// Process a transition, handling Ï„-transitions vs observable events
	/// Process a transition, handling Ï„-transitions vs observable events
	fn process_transition(process: &Process, event: &Event, trace: Trace, depth: usize) -> (Trace, usize) {
		if process.hidden.contains(event) {
			// Ï„-transition: don't extend trace
			(trace, depth)
		} else {
			// Observable event: extend trace
			let mut new_trace = trace;
			new_trace.push(*event);
			(new_trace, depth + 1)
		}
	}

	/// Extract trace from a linear process (single deterministic path)
	/// Returns None if the process is not linear (has branching)
	fn extract_linear_trace(process: &Process, max_depth: usize) -> Option<Trace> {
		let mut trace = Vec::new();
		let mut current_state = process.initial;
		let mut visited_states = HashSet::new();
		visited_states.insert(current_state);

		loop {
			// Check if we've reached a terminal state
			if process.terminal.contains(&current_state) {
				return Some(trace);
			}

			// Check depth limit
			if trace.len() >= max_depth {
				return None; // Not linear if we hit depth limit
			}

			// Check for cycles
			if visited_states.len() > 1000 {
				return None; // Likely not linear if we've visited many states
			}

			// First, follow any Ï„-transitions (hidden events) - they don't extend the trace
			// Process all Ï„-transitions in sequence until we reach a state with no Ï„-transitions
			let mut has_tau_transitions = true;
			while has_tau_transitions {
				has_tau_transitions = false;
				let current_enabled = process.enabled(current_state);
				for action in &current_enabled {
					if process.hidden.contains(&action.event) {
						let next_states = process.step(current_state, &action.event);
						if next_states.len() != 1 {
							return None; // Non-deterministic Ï„-transition
						}
						current_state = next_states[0];

						// Check for cycles
						if !visited_states.insert(current_state) {
							return None; // Cycle detected
						}

						has_tau_transitions = true;
						break; // Restart check from new state
					}
				}

				// Check terminal after Ï„-transitions
				if process.terminal.contains(&current_state) {
					return Some(trace);
				}
			}

			// Now check for observable actions at the stable state
			let stable_enabled = process.enabled(current_state);
			let observable_actions: Vec<_> = stable_enabled
				.iter()
				.filter(|action| !process.hidden.contains(&action.event))
				.collect();

			// Linear process: at most one observable action
			if observable_actions.len() > 1 {
				return None; // Not linear - has branching in observable events
			}

			// If we have an observable action, follow it
			if let Some(action) = observable_actions.first() {
				let next_states = process.step(current_state, &action.event);

				// Linear process must have exactly one next state
				if next_states.len() != 1 {
					return None; // Not linear - has non-determinism
				}

				// Add event to trace
				trace.push(action.event);
				current_state = next_states[0];

				// Check for cycles
				if !visited_states.insert(current_state) {
					return None; // Cycle detected - not a simple linear trace
				}
			} else {
				// No enabled actions - deadlock or terminal state
				if process.terminal.contains(&current_state) {
					return Some(trace);
				}
				return None; // Deadlock - not a valid linear trace
			}
		}
	}

	/// Generic BFS helper for trace and failure computation
	fn bfs_with_callbacks<T, FState, FTransition>(
		&self,
		process: &Process,
		max_depth: usize,
		mut data: T,
		mut on_state: FState,
		mut on_transition: FTransition,
	) -> T
	where
		FState: FnMut(&mut T, State, &Trace, usize) -> bool,
		FTransition: FnMut(&mut T, &mut VecDeque<(State, Trace, usize)>, State, Trace, usize, &Event, State),
	{
		let mut queue = VecDeque::new();
		let mut visited = HashSet::new();
		queue.push_back((process.initial, Vec::new(), 0usize));

		while let Some((state, trace, depth)) = queue.pop_front() {
			if queue.len() >= Self::max_queue_size() || visited.len() >= Self::max_visited() {
				break;
			}

			if trace.len() >= max_depth {
				continue;
			}

			let visit_key = (state, trace.clone());
			if visited.contains(&visit_key) {
				continue;
			}
			visited.insert(visit_key);

			let skip_transitions = on_state(&mut data, state, &trace, depth);
			if skip_transitions {
				continue;
			}

			for action in process.enabled(state) {
				for next_state in process.step(state, &action.event) {
					on_transition(&mut data, &mut queue, state, trace.clone(), depth, &action.event, next_state);
				}
			}
		}

		data
	}

	/// Check if a Ï„-transition would create a cycle
	fn has_tau_cycle(&self, tau_states_seen: &HashSet<(State, Trace)>, next_state: State, trace: &Trace) -> bool {
		let next_key = (next_state, trace.clone());
		tau_states_seen.contains(&next_key)
	}

	/// Process observable events matching the next event in target trace.
	/// Returns false if timeout or resource limits exceeded.
	#[allow(clippy::too_many_arguments)]
	fn process_observable_events(
		spec: &Process,
		state: State,
		next_event: &Event,
		enabled_actions: &[Action],
		queue: &mut VecDeque<(State, usize)>,
		visited: &mut HashSet<(State, usize)>,
		trace_idx: usize,
		max_queue_size: usize,
		max_visited: usize,
		timeout_checker: &TimeoutChecker,
	) -> bool {
		for action in enabled_actions {
			if timeout_checker.is_expired() {
				return false;
			}
			if &action.event == next_event {
				for next_state in spec.step(state, &action.event) {
					if timeout_checker.is_expired() {
						return false;
					}
					if queue.len() >= max_queue_size || visited.len() >= max_visited {
						break;
					}
					queue.push_back((next_state, trace_idx + 1));
				}
			}
		}
		true
	}

	/// Process Ï„-transitions (hidden events) with exploration limits.
	/// Returns false if timeout or resource limits exceeded.
	#[allow(clippy::too_many_arguments)]
	fn process_tau_transitions(
		spec: &Process,
		state: State,
		enabled_actions: &[Action],
		queue: &mut VecDeque<(State, usize)>,
		visited: &mut HashSet<(State, usize)>,
		trace_idx: usize,
		max_queue_size: usize,
		max_visited: usize,
		timeout_checker: &TimeoutChecker,
	) -> bool {
		let mut tau_count = 0;
		const MAX_TAU_PER_STATE: usize = 10; // Limit Ï„-transition exploration

		for action in enabled_actions {
			if timeout_checker.is_expired() {
				return false;
			}
			if spec.hidden.contains(&action.event) {
				if tau_count >= MAX_TAU_PER_STATE {
					break; // Limit Ï„-transition exploration
				}
				tau_count += 1;
				for next_state in spec.step(state, &action.event) {
					if timeout_checker.is_expired() {
						return false;
					}
					if queue.len() >= max_queue_size || visited.len() >= max_visited {
						break;
					}
					queue.push_back((next_state, trace_idx));
				}
			}
		}
		true
	}

	/// Check if an implementation failure exists in the specification failures.
	/// Returns true if a matching spec failure is found where impl_refusal ⊆ spec_refusal.
	fn failure_exists_in_spec(spec_failures: &[Failure], impl_trace: &Trace, impl_refusal: &HashSet<Event>) -> bool {
		for (spec_trace, spec_refusal) in spec_failures {
			if spec_trace == impl_trace && impl_refusal.is_subset(spec_refusal) {
				return true;
			}
		}
		false
	}

	/// Check if a specific trace exists in a spec without computing all traces
	fn trace_exists_in_spec(
		spec: &Process,
		target_trace: &Trace,
		max_depth: usize,
		max_queue_size: usize,
		max_visited: usize,
		timeout_ms: u64,
	) -> bool {
		if target_trace.len() > max_depth {
			return false;
		}

		let timeout_checker = TimeoutChecker::new(timeout_ms);
		let mut queue = VecDeque::new();
		let mut visited = HashSet::new();
		queue.push_back((spec.initial, 0usize));

		while let Some((state, trace_idx)) = queue.pop_front() {
			if timeout_checker.is_expired() {
				return false;
			}

			if queue.len() >= max_queue_size || visited.len() >= max_visited {
				return false;
			}

			let visit_key = (state, trace_idx);
			if visited.contains(&visit_key) {
				continue;
			}
			visited.insert(visit_key);

			if trace_idx >= target_trace.len() {
				return true;
			}

			// Process observable events first (matching the next event in target trace)
			let next_event = &target_trace[trace_idx];
			let enabled_actions = spec.enabled(state);
			if !Self::process_observable_events(
				spec,
				state,
				next_event,
				&enabled_actions,
				&mut queue,
				&mut visited,
				trace_idx,
				max_queue_size,
				max_visited,
				&timeout_checker,
			) {
				return false;
			}

			// Explore Ï„-transitions (limit exploration to avoid state explosion)
			if !Self::process_tau_transitions(
				spec,
				state,
				&enabled_actions,
				&mut queue,
				&mut visited,
				trace_idx,
				max_queue_size,
				max_visited,
				&timeout_checker,
			) {
				return false;
			}
		}

		false
	}
}

impl<'a, M> RefinementChecker for DefaultRefinementChecker<'a, M>
where
	M: MemoizationCache,
{
	fn check_trace_refinement(&mut self, spec: &Process, impl_process: &Process) -> (bool, Option<Trace>) {
		// Trace refinement: impl ⊑ spec means traces(impl) ⊆ traces(spec)
		// For deterministic linear processes, we only check the longest trace.
		// Reference: Pedersen & Chalmers (2024)
		let impl_traces = self.compute_traces(impl_process, self.config.max_depth);
		let longest_trace = impl_traces.iter().max_by_key(|t| t.len()).cloned();
		if let Some(full_trace) = longest_trace {
			let max_queue = Self::max_queue_size();
			let max_visited = Self::max_visited();

			if !Self::trace_exists_in_spec(
				spec,
				&full_trace,
				self.config.max_depth,
				max_queue,
				max_visited,
				self.config.timeout_ms,
			) {
				return (false, Some(full_trace));
			}

			(true, None)
		} else {
			(false, Some(Vec::new()))
		}
	}

	fn check_failures_refinement(&mut self, spec: &Process, impl_process: &Process) -> (bool, Option<Failure>) {
		// Failures refinement: impl ⊑ spec means failures(impl) ⊆ failures(spec)
		// For each impl failure (trace, impl_refusal), there must exist a spec failure
		// (trace, spec_refusal) where impl_refusal ⊆ spec_refusal.
		// Reference: Roscoe (1998, 2010)
		let spec_failures = self.compute_failures(spec, self.config.max_depth);
		let impl_failures = self.compute_failures(impl_process, self.config.max_depth);

		for (impl_trace, impl_refusal) in &impl_failures {
			if !<DefaultRefinementChecker<'a, M>>::failure_exists_in_spec(&spec_failures, impl_trace, impl_refusal) {
				return (false, Some((impl_trace.clone(), impl_refusal.clone())));
			}
		}

		(true, None)
	}

	fn check_divergence_refinement(&mut self, spec: &Process, impl_process: &Process) -> (bool, Option<Trace>) {
		// Divergence refinement: impl ⊑ spec means divergences(impl) ⊆ divergences(spec)
		// Reference: Roscoe (1998, 2010)
		let spec_divergences = self.compute_divergences(spec, self.config.max_depth);
		let impl_divergences = self.compute_divergences(impl_process, self.config.max_depth);
		for impl_div in &impl_divergences {
			if !spec_divergences.contains(impl_div) {
				return (false, Some(impl_div.clone()));
			}
		}

		(true, None)
	}

	fn compute_traces(&mut self, process: &Process, max_depth: usize) -> HashSet<Trace> {
		if let Some(cached) = self.cache.borrow().get_cached_traces(process.name) {
			return cached.into_iter().collect();
		}

		// Fast path: For linear trace processes, extract trace directly
		if let Some(linear_trace) = Self::extract_linear_trace(process, max_depth) {
			let mut traces = HashSet::new();
			traces.insert(linear_trace);
			return traces;
		}

		let timeout_checker = TimeoutChecker::new(self.config.timeout_ms);
		let mut traces = HashSet::new();
		traces.insert(Vec::new());

		let mut queue = VecDeque::new();
		let mut visited = HashSet::new();
		queue.push_back((process.initial, Vec::new(), 0usize));

		while let Some((state, trace, depth)) = queue.pop_front() {
			if timeout_checker.is_expired() {
				break;
			}

			if Self::check_limits(queue.len(), visited.len(), traces.len()) {
				break;
			}

			if trace.len() >= max_depth {
				continue;
			}

			let visit_key = (state, trace.clone());
			if visited.contains(&visit_key) {
				continue;
			}
			visited.insert(visit_key);

			let enabled_actions = process.enabled(state);
			for action in enabled_actions {
				let next_states = process.step(state, &action.event);
				for next_state in next_states {
					if Self::check_limits(queue.len(), visited.len(), traces.len()) {
						break;
					}

					let (new_trace, new_depth) = Self::process_transition(process, &action.event, trace.clone(), depth);
					if !process.hidden.contains(&action.event) {
						traces.insert(new_trace.clone());
					}
					queue.push_back((next_state, new_trace, new_depth));
				}
			}
		}

		let traces_vec: Vec<Trace> = traces.iter().cloned().collect();
		self.cache.borrow_mut().cache_traces(process.name.to_string(), traces_vec);

		traces
	}

	fn compute_failures(&mut self, process: &Process, max_depth: usize) -> Vec<Failure> {
		if let Some(cached) = self.cache.borrow().get_cached_failures(process.name) {
			return cached;
		}

		// Failures are only recorded at stable states (no Ï„-transitions enabled)
		// Reference: Roscoe (1998, 2010)
		let failures = Vec::new();
		let visited = HashSet::new();
		let data = (failures, visited);
		let (failures, _) = self.bfs_with_callbacks(
			process,
			max_depth,
			data,
			|(failures, visited), state, trace, _depth| {
				let visit_key = (state, trace.clone());
				if visited.contains(&visit_key) {
					return true;
				}
				visited.insert(visit_key);

				if Self::is_stable_state(process, state) {
					let refusals = self.compute_refusals(process, state);
					let failure = (trace.clone(), refusals);
					if !failures.contains(&failure) {
						failures.push(failure);
					}
				}

				false
			},
			|(_failures, _visited), queue, _state, trace, depth, event, next_state| {
				let (new_trace, new_depth) = Self::process_transition(process, event, trace, depth);
				queue.push_back((next_state, new_trace, new_depth));
			},
		);

		self.cache
			.borrow_mut()
			.cache_failures(process.name.to_string(), failures.clone());

		failures
	}

	fn compute_divergences(&mut self, process: &Process, max_depth: usize) -> HashSet<Trace> {
		if let Some(cached) = self.cache.borrow().get_cached_divergences(process.name) {
			return cached.into_iter().collect();
		}

		let mut divergences = HashSet::new();
		let mut queue = VecDeque::new();
		let mut initial_tau_seen = HashSet::new();
		initial_tau_seen.insert((process.initial, Vec::new()));
		queue.push_back((process.initial, Vec::new(), initial_tau_seen));

		let mut global_visited = HashSet::new();
		while let Some((state, trace, tau_states_seen)) = queue.pop_front() {
			if trace.len() >= max_depth {
				continue;
			}

			let visit_key = (state, trace.clone());
			if global_visited.contains(&visit_key) {
				continue;
			}

			for action in process.enabled(state) {
				for next_state in process.step(state, &action.event) {
					if process.hidden.contains(&action.event) {
						if self.has_tau_cycle(&tau_states_seen, next_state, &trace) {
							divergences.insert(trace.clone());
							continue;
						}

						let mut new_tau_seen = tau_states_seen.clone();
						new_tau_seen.insert((next_state, trace.clone()));
						queue.push_back((next_state, trace.clone(), new_tau_seen));
					} else {
						let mut new_trace = trace.clone();
						new_trace.push(action.event);
						let mut new_tau_seen = HashSet::new();
						new_tau_seen.insert((next_state, new_trace.clone()));
						queue.push_back((next_state, new_trace, new_tau_seen));
					}
				}
			}

			global_visited.insert(visit_key);
		}

		let divergences_vec: Vec<Trace> = divergences.iter().cloned().collect();
		self.cache
			.borrow_mut()
			.cache_divergences(process.name.to_string(), divergences_vec);

		divergences
	}

	/// Compute refusal set for a stable state.
	/// Refusal set = all observable events minus enabled events.
	/// Reference: Roscoe (1998, 2010)
	fn compute_refusals(&self, process: &Process, state: State) -> HashSet<Event> {
		let enabled_events: HashSet<Event> = process
			.enabled(state)
			.iter()
			.filter_map(|action| {
				if !process.hidden.contains(&action.event) {
					Some(action.event)
				} else {
					None
				}
			})
			.collect();

		process
			.observable
			.iter()
			.filter(|&event| !enabled_events.contains(event))
			.cloned()
			.collect()
	}
}