1use super::AiError;
2
3pub const MAX_DECISION_STATES: u16 = 64;
4pub const MAX_DECISION_EDGES: usize = 256;
5#[derive(Clone, Copy, Debug)]
9pub struct DecisionEdge {
10 pub from: Option<u16>,
11 pub to: u16,
12 pub all: u64,
13 pub none: u64,
14 pub after: f32,
15}
16
17impl DecisionEdge {
18 fn inspect(
19 &self,
20 index: usize,
21 state: u16,
22 flags: u64,
23 elapsed: f64,
24 ) -> DecisionEdgeExplanation {
25 DecisionEdgeExplanation {
26 index,
27 source_matches: self.from.is_none_or(|source| source == state),
28 missing_flags: self.all & !flags,
29 forbidden_flags: self.none & flags,
30 remaining_seconds: (f64::from(self.after) - elapsed).max(0.),
31 outcome: DecisionEdgeOutcome::Rejected,
32 }
33 }
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum DecisionGraphError {
41 InvalidStateCount { states: u16 },
43 InvalidInitialState { initial: u16, states: u16 },
45 TooManyEdges { len: usize },
47 InvalidDestination { edge: usize, to: u16, states: u16 },
49 InvalidSource { edge: usize, from: u16, states: u16 },
51 SelfTransition { edge: usize, state: u16 },
53 ConflictingGuards { edge: usize, flags: u64 },
55 InvalidDelay { edge: usize },
57}
58
59impl std::fmt::Display for DecisionGraphError {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 match self {
62 Self::InvalidStateCount { states } => write!(
63 f,
64 "decision state count {states} must be in 1..={MAX_DECISION_STATES}"
65 ),
66 Self::InvalidInitialState { initial, states } => {
67 write!(f, "initial state {initial} must be below {states}")
68 }
69 Self::TooManyEdges { len } => {
70 write!(f, "decision edge count {len} exceeds {MAX_DECISION_EDGES}")
71 }
72 Self::InvalidDestination { edge, to, states } => {
73 write!(f, "edge {edge} destination {to} must be below {states}")
74 }
75 Self::InvalidSource { edge, from, states } => {
76 write!(f, "edge {edge} source {from} must be below {states}")
77 }
78 Self::SelfTransition { edge, state } => {
79 write!(
80 f,
81 "edge {edge} explicitly transitions state {state} to itself"
82 )
83 }
84 Self::ConflictingGuards { edge, flags } => write!(
85 f,
86 "edge {edge} requires and forbids sensor bits {flags:#018x}"
87 ),
88 Self::InvalidDelay { edge } => {
89 write!(
90 f,
91 "edge {edge} delay must be finite and in 0..=3600 seconds"
92 )
93 }
94 }
95 }
96}
97
98impl std::error::Error for DecisionGraphError {}
99
100impl From<DecisionGraphError> for AiError {
101 fn from(_: DecisionGraphError) -> Self {
102 Self::InvalidConfiguration
103 }
104}
105
106#[derive(Debug)]
109pub struct DecisionGraph {
110 states: u16,
111 initial: u16,
112 edges: Vec<DecisionEdge>,
113}
114impl DecisionGraph {
115 pub fn new(states: u16, initial: u16, edges: &[DecisionEdge]) -> Result<Self, AiError> {
118 Self::new_checked(states, initial, edges).map_err(AiError::from)
119 }
120
121 pub fn validate(
139 states: u16,
140 initial: u16,
141 edges: &[DecisionEdge],
142 ) -> Result<(), DecisionGraphError> {
143 if states == 0 || states > MAX_DECISION_STATES {
144 return Err(DecisionGraphError::InvalidStateCount { states });
145 }
146 if initial >= states {
147 return Err(DecisionGraphError::InvalidInitialState { initial, states });
148 }
149 if edges.len() > MAX_DECISION_EDGES {
150 return Err(DecisionGraphError::TooManyEdges { len: edges.len() });
151 }
152 for (edge, e) in edges.iter().enumerate() {
153 if e.to >= states {
154 return Err(DecisionGraphError::InvalidDestination {
155 edge,
156 to: e.to,
157 states,
158 });
159 }
160 if let Some(from) = e.from {
161 if from >= states {
162 return Err(DecisionGraphError::InvalidSource { edge, from, states });
163 }
164 if from == e.to {
165 return Err(DecisionGraphError::SelfTransition { edge, state: from });
166 }
167 }
168 if e.all & e.none != 0 {
169 return Err(DecisionGraphError::ConflictingGuards {
170 edge,
171 flags: e.all & e.none,
172 });
173 }
174 if !e.after.is_finite() || !(0. ..=3600.).contains(&e.after) {
175 return Err(DecisionGraphError::InvalidDelay { edge });
176 }
177 }
178 Ok(())
179 }
180
181 pub fn new_checked(
195 states: u16,
196 initial: u16,
197 edges: &[DecisionEdge],
198 ) -> Result<Self, DecisionGraphError> {
199 Self::validate(states, initial, edges)?;
200 Ok(Self {
201 states,
202 initial,
203 edges: edges.to_vec(),
204 })
205 }
206
207 pub fn edges(&self) -> &[DecisionEdge] {
211 &self.edges
212 }
213
214 pub fn initial(&self) -> DecisionState {
215 DecisionState {
216 state: self.initial,
217 elapsed: 0.,
218 }
219 }
220}
221#[derive(Clone, Copy, Debug, PartialEq)]
222pub struct DecisionState {
223 state: u16,
224 elapsed: f64,
225}
226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
227pub struct DecisionChange {
228 pub from: u16,
229 pub to: u16,
230}
231
232#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub enum DecisionEdgeOutcome {
235 Rejected,
237 Transition,
239 Hold,
241 Shadowed { by: usize },
243}
244
245#[derive(Clone, Copy, Debug, PartialEq)]
249pub struct DecisionEdgeExplanation {
250 pub index: usize,
252 pub source_matches: bool,
254 pub missing_flags: u64,
256 pub forbidden_flags: u64,
258 pub remaining_seconds: f64,
260 pub outcome: DecisionEdgeOutcome,
262}
263
264impl DecisionEdgeExplanation {
265 fn matches(&self) -> bool {
266 self.source_matches
267 && self.missing_flags == 0
268 && self.forbidden_flags == 0
269 && self.remaining_seconds == 0.
270 }
271}
272
273#[derive(Clone, Copy, Debug)]
278pub struct DecisionExplanation<'a> {
279 edges: &'a [DecisionEdge],
280 state: u16,
281 flags: u64,
282 elapsed: f64,
283 selected_edge: Option<usize>,
284}
285
286impl DecisionExplanation<'_> {
287 pub fn elapsed(&self) -> f64 {
290 self.elapsed
291 }
292
293 pub fn selected_edge(&self) -> Option<usize> {
296 self.selected_edge
297 }
298
299 pub fn change(&self) -> Option<DecisionChange> {
303 let to = self.edges[self.selected_edge?].to;
304 (to != self.state).then_some(DecisionChange {
305 from: self.state,
306 to,
307 })
308 }
309
310 pub fn edges(
315 &self,
316 ) -> impl ExactSizeIterator<Item = DecisionEdgeExplanation> + DoubleEndedIterator + '_ {
317 self.edges.iter().enumerate().map(|(index, edge)| {
318 let mut result = edge.inspect(index, self.state, self.flags, self.elapsed);
319 if result.matches() {
320 result.outcome = match self.selected_edge {
321 Some(by) if by != index => DecisionEdgeOutcome::Shadowed { by },
322 _ if edge.to == self.state => DecisionEdgeOutcome::Hold,
323 _ => DecisionEdgeOutcome::Transition,
324 };
325 }
326 result
327 })
328 }
329}
330
331impl DecisionState {
332 pub fn state(&self) -> u16 {
333 self.state
334 }
335 pub fn elapsed(&self) -> f64 {
336 self.elapsed
337 }
338 pub fn reset(&mut self, graph: &DecisionGraph) {
339 *self = graph.initial();
340 }
341
342 pub fn explain<'a>(
379 &self,
380 graph: &'a DecisionGraph,
381 flags: u64,
382 dt: f32,
383 ) -> Result<DecisionExplanation<'a>, AiError> {
384 if self.state >= graph.states {
385 return Err(AiError::InvalidState);
386 }
387 if !dt.is_finite() || !(0. ..=60.).contains(&dt) {
388 return Err(AiError::InvalidInput);
389 }
390 let elapsed = (self.elapsed + f64::from(dt)).min(3600.);
391 let selected_edge = graph.edges.iter().enumerate().find_map(|(index, edge)| {
392 edge.inspect(index, self.state, flags, elapsed)
393 .matches()
394 .then_some(index)
395 });
396 Ok(DecisionExplanation {
397 edges: &graph.edges,
398 state: self.state,
399 flags,
400 elapsed,
401 selected_edge,
402 })
403 }
404
405 pub fn update(
408 &mut self,
409 graph: &DecisionGraph,
410 flags: u64,
411 dt: f32,
412 ) -> Result<Option<DecisionChange>, AiError> {
413 let explanation = self.explain(graph, flags, dt)?;
414 let change = explanation.change();
415 self.elapsed = explanation.elapsed();
416 if let Some(change) = change {
417 self.state = change.to;
418 self.elapsed = 0.;
419 }
420 Ok(change)
421 }
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427
428 fn edge(from: Option<u16>, to: u16) -> DecisionEdge {
429 DecisionEdge {
430 from,
431 to,
432 all: 0,
433 none: 0,
434 after: 0.,
435 }
436 }
437
438 fn assert_invalid(
439 states: u16,
440 initial: u16,
441 edges: &[DecisionEdge],
442 expected: DecisionGraphError,
443 ) {
444 assert_eq!(
445 DecisionGraph::validate(states, initial, edges),
446 Err(expected)
447 );
448 assert_eq!(
449 DecisionGraph::new_checked(states, initial, edges).unwrap_err(),
450 expected
451 );
452 assert_eq!(
453 DecisionGraph::new(states, initial, edges).unwrap_err(),
454 AiError::InvalidConfiguration
455 );
456 assert!(!expected.to_string().is_empty());
457 }
458
459 #[test]
460 fn configuration_diagnostics_keep_legacy_bounds_and_error_category() {
461 for states in [0, MAX_DECISION_STATES + 1, u16::MAX] {
462 assert_invalid(
463 states,
464 0,
465 &[],
466 DecisionGraphError::InvalidStateCount { states },
467 );
468 }
469 assert_invalid(
470 2,
471 2,
472 &[],
473 DecisionGraphError::InvalidInitialState {
474 initial: 2,
475 states: 2,
476 },
477 );
478 let edges = [edge(None, 0); MAX_DECISION_EDGES + 1];
479 assert_invalid(
480 1,
481 0,
482 &edges,
483 DecisionGraphError::TooManyEdges {
484 len: MAX_DECISION_EDGES + 1,
485 },
486 );
487 let graph = DecisionGraph::new_checked(
488 MAX_DECISION_STATES,
489 MAX_DECISION_STATES - 1,
490 &edges[..MAX_DECISION_EDGES],
491 )
492 .unwrap();
493 assert_eq!(graph.edges().len(), MAX_DECISION_EDGES);
494 assert_eq!(graph.initial().state(), MAX_DECISION_STATES - 1);
495 assert!(DecisionGraph::validate(1, 0, &[]).is_ok());
496 }
497
498 #[test]
499 fn edge_diagnostics_identify_indices_and_all_invalid_edge_kinds() {
500 let valid = edge(Some(0), 1);
501 for (invalid, error) in [
502 (
503 edge(Some(2), 2),
504 DecisionGraphError::InvalidDestination {
505 edge: 1,
506 to: 2,
507 states: 2,
508 },
509 ),
510 (
511 edge(Some(2), 0),
512 DecisionGraphError::InvalidSource {
513 edge: 1,
514 from: 2,
515 states: 2,
516 },
517 ),
518 (
519 edge(Some(1), 1),
520 DecisionGraphError::SelfTransition { edge: 1, state: 1 },
521 ),
522 (
523 DecisionEdge {
524 all: 5 | (1 << 63),
525 none: 4 | (1 << 63),
526 ..valid
527 },
528 DecisionGraphError::ConflictingGuards {
529 edge: 1,
530 flags: 4 | (1 << 63),
531 },
532 ),
533 ] {
534 assert_invalid(2, 0, &[valid, invalid], error);
535 }
536 for after in [
537 -f32::EPSILON,
538 3600.25,
539 f32::NAN,
540 f32::INFINITY,
541 f32::NEG_INFINITY,
542 ] {
543 assert_invalid(
544 2,
545 0,
546 &[valid, DecisionEdge { after, ..valid }],
547 DecisionGraphError::InvalidDelay { edge: 1 },
548 );
549 }
550 for after in [-0., 0., 3600.] {
551 assert!(DecisionGraph::validate(2, 0, &[DecisionEdge { after, ..valid }]).is_ok());
552 }
553 }
554
555 #[test]
556 fn diagnostics_choose_the_first_failure_in_documented_order() {
557 let invalid = DecisionEdge {
558 all: 1,
559 none: 1,
560 after: f32::NAN,
561 ..edge(Some(0), 0)
562 };
563 let too_many = [invalid; MAX_DECISION_EDGES + 1];
564 assert_eq!(
565 DecisionGraph::validate(0, 2, &too_many),
566 Err(DecisionGraphError::InvalidStateCount { states: 0 })
567 );
568 assert_eq!(
569 DecisionGraph::validate(2, 2, &too_many),
570 Err(DecisionGraphError::InvalidInitialState {
571 initial: 2,
572 states: 2
573 })
574 );
575 assert_eq!(
576 DecisionGraph::validate(2, 0, &too_many),
577 Err(DecisionGraphError::TooManyEdges {
578 len: MAX_DECISION_EDGES + 1
579 })
580 );
581 assert_eq!(
582 DecisionGraph::validate(2, 0, &[invalid, edge(None, 9)]),
583 Err(DecisionGraphError::SelfTransition { edge: 0, state: 0 })
584 );
585 assert_eq!(
586 DecisionGraph::validate(2, 0, &[DecisionEdge { to: 1, ..invalid }]),
587 Err(DecisionGraphError::ConflictingGuards { edge: 0, flags: 1 })
588 );
589 }
590
591 #[test]
592 fn zero_delta_cycles_follow_one_edge_and_preview_is_read_only() {
593 let graph = DecisionGraph::new_checked(
594 3,
595 0,
596 &[edge(Some(0), 1), edge(Some(1), 2), edge(Some(2), 0)],
597 )
598 .unwrap();
599 let mut state = graph.initial();
600 for index in [0, 1, 2, 0, 1, 2] {
601 let before = state;
602 let explanation = state.explain(&graph, 0, 0.).unwrap();
603 assert_eq!(state, before);
604 assert_eq!(explanation.selected_edge(), Some(index));
605 let expected = Some(DecisionChange {
606 from: index as u16,
607 to: (index as u16 + 1) % 3,
608 });
609 assert_eq!(explanation.change(), expected);
610 assert_eq!(
611 explanation.edges().nth(index).unwrap().outcome,
612 DecisionEdgeOutcome::Transition
613 );
614 assert_eq!(state.update(&graph, 0, 0.).unwrap(), expected);
615 assert_eq!(explanation.change(), expected); assert_eq!(state.elapsed(), 0.);
617 }
618 }
619
620 #[test]
621 fn wildcard_hold_blocks_lower_priority_without_resetting_time() {
622 let graph = DecisionGraph::new_checked(
623 2,
624 0,
625 &[
626 DecisionEdge {
627 all: 1,
628 ..edge(None, 0)
629 },
630 edge(Some(0), 1),
631 ],
632 )
633 .unwrap();
634 let mut state = graph.initial();
635 state.update(&graph, 1, 0.25).unwrap();
636 let explanation = state.explain(&graph, 1, 0.5).unwrap();
637 assert_eq!(explanation.selected_edge(), Some(0));
638 assert_eq!(explanation.change(), None);
639 assert_eq!(explanation.elapsed(), 0.75);
640 assert_eq!(
641 explanation.edges().next().unwrap().outcome,
642 DecisionEdgeOutcome::Hold
643 );
644 assert_eq!(
645 explanation.edges().nth(1).unwrap().outcome,
646 DecisionEdgeOutcome::Shadowed { by: 0 }
647 );
648 assert_eq!(state.update(&graph, 1, 0.5).unwrap(), None);
649 assert_eq!(state.elapsed(), 0.75);
650 assert_eq!(
651 state.update(&graph, 0, 0.).unwrap(),
652 Some(DecisionChange { from: 0, to: 1 })
653 );
654 assert_eq!(state.elapsed(), 0.);
655 }
656
657 #[test]
658 fn explanations_report_all_guards_even_after_a_priority_winner() {
659 let high = 1 << 63;
660 let graph = DecisionGraph::new_checked(
661 3,
662 0,
663 &[
664 edge(None, 0),
665 DecisionEdge {
666 all: high | 1,
667 none: 2 | 4,
668 after: 0.5,
669 ..edge(Some(1), 2)
670 },
671 edge(Some(0), 2),
672 ],
673 )
674 .unwrap();
675 let state = graph.initial();
676 let explanation = state.explain(&graph, 2, 0.25).unwrap();
677 assert_eq!(explanation.edges().len(), 3);
678 assert_eq!(
679 explanation.edges().nth(1).unwrap(),
680 DecisionEdgeExplanation {
681 index: 1,
682 source_matches: false,
683 missing_flags: high | 1,
684 forbidden_flags: 2,
685 remaining_seconds: 0.25,
686 outcome: DecisionEdgeOutcome::Rejected,
687 }
688 );
689 assert_eq!(
690 explanation.edges().next_back().unwrap().outcome,
691 DecisionEdgeOutcome::Shadowed { by: 0 }
692 );
693 assert_eq!(state.elapsed(), 0.);
694 }
695
696 #[test]
697 fn unmatched_and_empty_graphs_advance_only_when_updated() {
698 let graphs = [
699 DecisionGraph::new_checked(1, 0, &[]).unwrap(),
700 DecisionGraph::new_checked(
701 2,
702 0,
703 &[DecisionEdge {
704 all: 1,
705 ..edge(Some(0), 1)
706 }],
707 )
708 .unwrap(),
709 ];
710 for graph in graphs {
711 let mut state = graph.initial();
712 let explanation = state.explain(&graph, 0, 0.5).unwrap();
713 assert_eq!(explanation.selected_edge(), None);
714 assert_eq!(explanation.change(), None);
715 assert_eq!(explanation.elapsed(), 0.5);
716 assert!(
717 explanation
718 .edges()
719 .all(|e| e.outcome == DecisionEdgeOutcome::Rejected)
720 );
721 assert_eq!(state.elapsed(), 0.);
722 assert_eq!(state.update(&graph, 0, 0.5).unwrap(), None);
723 assert_eq!(state.elapsed(), 0.5);
724 }
725 }
726
727 #[test]
728 fn invalid_preview_and_update_inputs_preserve_state_and_error_order() {
729 let graph = DecisionGraph::new_checked(2, 1, &[edge(None, 0)]).unwrap();
730 let smaller = DecisionGraph::new_checked(1, 0, &[]).unwrap();
731 let mut state = graph.initial();
732 let original = state;
733 for dt in [
734 -f32::EPSILON,
735 60.25,
736 f32::NAN,
737 f32::INFINITY,
738 f32::NEG_INFINITY,
739 ] {
740 assert_eq!(
741 state.explain(&graph, 0, dt).unwrap_err(),
742 AiError::InvalidInput
743 );
744 assert_eq!(state.update(&graph, 0, dt), Err(AiError::InvalidInput));
745 assert_eq!(
746 state.explain(&smaller, 0, dt).unwrap_err(),
747 AiError::InvalidState
748 );
749 assert_eq!(state.update(&smaller, 0, dt), Err(AiError::InvalidState));
750 assert_eq!(state, original);
751 }
752 assert_eq!(
753 state.explain(&smaller, 0, 0.).unwrap_err(),
754 AiError::InvalidState
755 );
756 state.reset(&smaller);
757 assert_eq!(
758 state.explain(&smaller, 0, 0.).unwrap().selected_edge(),
759 None
760 );
761 }
762
763 #[test]
764 fn cap_and_transition_overshoot_match_the_proposed_elapsed_time() {
765 let graph = DecisionGraph::new_checked(
766 2,
767 0,
768 &[DecisionEdge {
769 after: 3600.,
770 all: 1,
771 ..edge(Some(0), 1)
772 }],
773 )
774 .unwrap();
775 let mut state = graph.initial();
776 for _ in 0..59 {
777 state.update(&graph, 0, 60.).unwrap();
778 }
779 state.update(&graph, 0, 59.75).unwrap();
780 assert_eq!(state.elapsed(), 3599.75);
781 let waiting = state.explain(&graph, 1, 0.).unwrap();
782 assert_eq!(waiting.edges().next().unwrap().remaining_seconds, 0.25);
783 assert_eq!(waiting.selected_edge(), None);
784 let ready = state.explain(&graph, 1, 0.25).unwrap();
785 assert_eq!(ready.selected_edge(), Some(0));
786 assert_eq!(ready.elapsed(), 3600.);
787 state.update(&graph, 0, 60.).unwrap();
788 state.update(&graph, 0, 60.).unwrap();
789 assert_eq!(state.elapsed(), 3600.);
790 assert_eq!(state.update(&graph, 1, 60.).unwrap(), ready.change());
791 assert_eq!(state.elapsed(), 0.);
792
793 let short = DecisionGraph::new_checked(
794 2,
795 0,
796 &[DecisionEdge {
797 after: 0.5,
798 ..edge(Some(0), 1)
799 }],
800 )
801 .unwrap();
802 state.reset(&short);
803 let preview = state.explain(&short, 0, 60.).unwrap();
804 assert_eq!(preview.elapsed(), 60.);
805 assert_eq!(state.update(&short, 0, 60.).unwrap(), preview.change());
806 assert_eq!(state.elapsed(), 0.);
807 }
808
809 #[test]
810 fn previews_match_legacy_selection_across_sensor_and_time_combinations() {
811 let high = 1 << 63;
812 let graph = DecisionGraph::new_checked(
813 3,
814 0,
815 &[
816 DecisionEdge {
817 all: high | 1,
818 none: 2,
819 after: 0.5,
820 ..edge(None, 2)
821 },
822 DecisionEdge {
823 all: 2,
824 none: 1,
825 after: 0.25,
826 ..edge(Some(0), 1)
827 },
828 DecisionEdge {
829 none: 2,
830 after: 0.5,
831 ..edge(Some(1), 0)
832 },
833 DecisionEdge {
834 none: high,
835 ..edge(Some(2), 0)
836 },
837 DecisionEdge {
838 after: 1.,
839 ..edge(None, 1)
840 },
841 ],
842 )
843 .unwrap();
844 for source in 0..3 {
845 for bits in 0..16 {
846 let flags = (bits & 7) | if bits & 8 != 0 { high } else { 0 };
847 for elapsed in [0., 0.25, 0.5, 1., 3599.75, 3600.] {
848 for dt in [0., 0.25, 60.] {
849 let mut state = DecisionState {
850 state: source,
851 elapsed,
852 };
853 let proposed = (elapsed + f64::from(dt)).min(3600.);
854 let selected = graph.edges().iter().position(|e| {
856 e.from.is_none_or(|s| s == source)
857 && flags & e.all == e.all
858 && flags & e.none == 0
859 && proposed >= f64::from(e.after)
860 });
861 let change = selected.and_then(|index| {
862 let to = graph.edges()[index].to;
863 (source != to).then_some(DecisionChange { from: source, to })
864 });
865 let explanation = state.explain(&graph, flags, dt).unwrap();
866 assert_eq!(explanation.selected_edge(), selected);
867 assert_eq!(explanation.change(), change);
868 assert_eq!(explanation.elapsed(), proposed);
869 let repeated = state.explain(&graph, flags, dt).unwrap();
870 assert!(explanation.edges().eq(repeated.edges()));
871 assert_eq!(
872 state,
873 DecisionState {
874 state: source,
875 elapsed
876 }
877 );
878 assert_eq!(state.update(&graph, flags, dt).unwrap(), change);
879 assert_eq!(state.state(), change.map_or(source, |c| c.to));
880 assert_eq!(
881 state.elapsed(),
882 if change.is_some() { 0. } else { proposed }
883 );
884 }
885 }
886 }
887 }
888 }
889}