1use crate::{CalibrationEvidenceState, ReplayArtifact, StudioSource, ViewerError, ViewerResult};
9
10pub const FULL_BAG_MAPPING_STATE_VERSION: u32 = 1;
12
13#[derive(Clone, Debug, PartialEq, Eq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
17pub struct MappingSourceSummary {
18 pub front_topic: String,
20 pub rear_topic: String,
22 pub front_bag_message_count: u64,
24 pub rear_bag_message_count: u64,
26 pub front_chunk_count: u64,
28 pub rear_chunk_count: u64,
30 pub front_record_count: u64,
32 pub rear_record_count: u64,
34 pub total_record_count: u64,
36 pub total_point_count: u64,
38 pub retained_bytes: u64,
40 pub peak_source_bytes: u64,
42 pub start_nanos: Option<u64>,
44 pub end_nanos: Option<u64>,
46 pub full_bag_processed: bool,
48 pub truncated: bool,
50}
51
52impl MappingSourceSummary {
53 pub fn validate(&self) -> ViewerResult<()> {
55 let expected_total =
56 self.front_record_count.checked_add(self.rear_record_count).ok_or_else(|| {
57 ViewerError::InvalidState("mapping source record total overflow".into())
58 })?;
59 if self.front_topic.trim().is_empty()
60 || self.rear_topic.trim().is_empty()
61 || self.front_topic == self.rear_topic
62 || self.front_bag_message_count < self.front_record_count
63 || self.rear_bag_message_count < self.rear_record_count
64 || self.front_chunk_count < self.front_record_count
65 || self.rear_chunk_count < self.rear_record_count
66 || self.total_record_count != expected_total
67 || (self.total_record_count == 0 && self.total_point_count != 0)
68 || self.truncated && self.full_bag_processed
69 {
70 return Err(ViewerError::InvalidState(
71 "mapping source summary has invalid topic or bounded totals".into(),
72 ));
73 }
74 if let (Some(start), Some(end)) = (self.start_nanos, self.end_nanos) {
75 if start > end {
76 return Err(ViewerError::InvalidState(
77 "mapping source timestamp bounds are reversed".into(),
78 ));
79 }
80 } else if self.start_nanos.is_some() != self.end_nanos.is_some() {
81 return Err(ViewerError::InvalidState(
82 "mapping source timestamp bounds must be complete".into(),
83 ));
84 }
85 if self.full_bag_processed
86 && (self.total_record_count == 0
87 || self.total_point_count == 0
88 || self.retained_bytes == 0
89 || self.peak_source_bytes == 0)
90 {
91 return Err(ViewerError::InvalidState(
92 "a completed full-bag mapping run must retain source records and points".into(),
93 ));
94 }
95 if self.full_bag_processed
96 && (self.front_bag_message_count != self.front_record_count
97 || self.rear_bag_message_count != self.rear_record_count
98 || self.total_point_count < self.total_record_count
99 || self.start_nanos.is_none()
100 || self.end_nanos.is_none())
101 {
102 return Err(ViewerError::InvalidState(
103 "completed mapping source requires one nonempty scan per message and corrected time bounds"
104 .into(),
105 ));
106 }
107 Ok(())
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Eq)]
113#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
114#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
115pub struct MappingOdometrySummary {
116 pub topic: String,
118 pub source_frame: String,
120 pub root_frame: String,
122 pub clock_id: String,
124 pub clock_domain: String,
126 pub matcher: String,
128 pub scan_count: u64,
130 pub motion_count: u64,
132 pub pose_graph_node_count: u64,
134 pub pose_graph_edge_count: u64,
136 pub complete: bool,
138 pub truncated: bool,
140}
141
142impl MappingOdometrySummary {
143 pub fn validate(&self) -> ViewerResult<()> {
145 if self.topic.trim().is_empty()
146 || self.source_frame.trim().is_empty()
147 || self.root_frame.trim().is_empty()
148 || self.clock_id.trim().is_empty()
149 || self.clock_domain.trim().is_empty()
150 || self.matcher.trim().is_empty()
151 || self.motion_count > self.scan_count
152 || self.pose_graph_node_count != self.scan_count
153 || self.pose_graph_edge_count != self.motion_count
154 || self.truncated && self.complete
155 {
156 return Err(ViewerError::InvalidState(
157 "mapping odometry summary has invalid identity or graph totals".into(),
158 ));
159 }
160 if self.complete
161 && (self.scan_count < 2 || self.motion_count.checked_add(1) != Some(self.scan_count))
162 {
163 return Err(ViewerError::InvalidState(
164 "completed mapping odometry requires a connected scan trajectory".into(),
165 ));
166 }
167 Ok(())
168 }
169}
170
171#[derive(Clone, Debug, PartialEq)]
173#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
174#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
175pub struct MappingTsdfSummary {
176 pub frame_id: String,
178 pub origin: [f32; 3],
180 pub voxel_size: f32,
182 pub dims: [usize; 3],
184 pub truncation: f32,
186 pub integrated_record_count: u64,
188 pub integrated_point_count: u64,
190 pub mesh_vertex_count: u64,
192 pub mesh_triangle_count: u64,
194 pub complete: bool,
196}
197
198impl MappingTsdfSummary {
199 pub fn validate(&self) -> ViewerResult<()> {
201 if self.frame_id.trim().is_empty()
202 || self.origin.iter().any(|value| !value.is_finite())
203 || !self.voxel_size.is_finite()
204 || self.voxel_size <= 0.0
205 || self.dims.contains(&0)
206 || !self.truncation.is_finite()
207 || self.truncation <= 0.0
208 || self.mesh_vertex_count == 0 && self.mesh_triangle_count != 0
209 {
210 return Err(ViewerError::InvalidState(
211 "mapping TSDF summary has invalid volume or mesh values".into(),
212 ));
213 }
214 if self.complete && (self.integrated_record_count == 0 || self.integrated_point_count == 0)
215 {
216 return Err(ViewerError::InvalidState(
217 "completed mapping TSDF requires integrated records and points".into(),
218 ));
219 }
220 Ok(())
221 }
222}
223
224#[derive(Clone, Debug, PartialEq, Eq)]
226#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
227#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
228pub struct MappingGateSummary {
229 pub calibration_registered: bool,
231 pub clock_applied: bool,
233 pub frame_graph_applied: bool,
235 pub full_bag_processed: bool,
237 pub odometry_complete: bool,
239 pub tsdf_complete: bool,
241 pub mapping_admitted: bool,
243}
244
245#[derive(Clone, Debug, PartialEq)]
247#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
248#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
249pub struct FullBagMappingState {
250 pub version: u32,
252 pub title: String,
254 pub source: StudioSource,
256 pub calibration: Option<CalibrationEvidenceState>,
258 pub source_summary: MappingSourceSummary,
260 pub odometry: Option<MappingOdometrySummary>,
262 pub tsdf: Option<MappingTsdfSummary>,
264 pub artifacts: Vec<ReplayArtifact>,
266 pub summary: MappingGateSummary,
268 pub blockers: Vec<String>,
270}
271
272impl FullBagMappingState {
273 #[allow(clippy::too_many_arguments)]
275 pub fn try_new(
276 title: impl Into<String>,
277 source: StudioSource,
278 calibration: Option<CalibrationEvidenceState>,
279 source_summary: MappingSourceSummary,
280 odometry: Option<MappingOdometrySummary>,
281 tsdf: Option<MappingTsdfSummary>,
282 artifacts: Vec<ReplayArtifact>,
283 clock_applied: bool,
284 frame_graph_applied: bool,
285 mut blockers: Vec<String>,
286 ) -> ViewerResult<Self> {
287 let calibration_registered = calibration.as_ref().is_some_and(|calibration| {
288 calibration.registration_ready
289 && calibration.source.identity_matches
290 && calibration.source.path == source.path
291 && calibration.source.observed_sha256 == source.observed_sha256
292 });
293 let full_bag_processed = source_summary.full_bag_processed && !source_summary.truncated;
294 let odometry_complete =
295 odometry.as_ref().is_some_and(|odometry| odometry.complete && !odometry.truncated);
296 let tsdf_complete = tsdf.as_ref().is_some_and(|tsdf| tsdf.complete);
297
298 if !source.identity_matches {
299 push_blocker(
300 &mut blockers,
301 "mapping input source identity does not match expected SHA-256",
302 );
303 }
304 if calibration.is_none() {
305 push_blocker(&mut blockers, "source-bound calibration evidence was not supplied");
306 } else if !calibration_registered {
307 push_blocker(
308 &mut blockers,
309 "source-bound calibration evidence registration is incomplete",
310 );
311 }
312 if !full_bag_processed {
313 push_blocker(
314 &mut blockers,
315 "full-bag ingest was not completed because an admission gate blocked execution or a configured bound was reached",
316 );
317 }
318 if !clock_applied {
319 push_blocker(
320 &mut blockers,
321 "registered clock model was not applied to the mapping timeline",
322 );
323 }
324 if !frame_graph_applied {
325 push_blocker(
326 &mut blockers,
327 "registered frame graph was not applied to sensor geometry",
328 );
329 }
330 if !odometry_complete {
331 push_blocker(&mut blockers, "full-bag frame-aware odometry did not complete");
332 }
333 if !tsdf_complete {
334 push_blocker(&mut blockers, "full-bag TSDF integration did not complete");
335 }
336
337 let summary = MappingGateSummary {
338 calibration_registered,
339 clock_applied,
340 frame_graph_applied,
341 full_bag_processed,
342 odometry_complete,
343 tsdf_complete,
344 mapping_admitted: source.identity_matches
345 && calibration_registered
346 && clock_applied
347 && frame_graph_applied
348 && full_bag_processed
349 && odometry_complete
350 && tsdf_complete
351 && blockers.is_empty(),
352 };
353 let state = Self {
354 version: FULL_BAG_MAPPING_STATE_VERSION,
355 title: title.into(),
356 source,
357 calibration,
358 source_summary,
359 odometry,
360 tsdf,
361 artifacts,
362 summary,
363 blockers,
364 };
365 state.validate()?;
366 Ok(state)
367 }
368
369 pub fn validate(&self) -> ViewerResult<()> {
374 if self.version != FULL_BAG_MAPPING_STATE_VERSION {
375 return Err(ViewerError::InvalidState(format!(
376 "unsupported full-bag mapping state version {}",
377 self.version
378 )));
379 }
380 if self.title.trim().is_empty() {
381 return Err(ViewerError::InvalidState(
382 "full-bag mapping title must not be empty".into(),
383 ));
384 }
385 self.source.validate()?;
386 self.source_summary.validate()?;
387 if let Some(calibration) = &self.calibration {
388 calibration.validate()?;
389 }
390 if let Some(odometry) = &self.odometry {
391 odometry.validate()?;
392 }
393 if let Some(tsdf) = &self.tsdf {
394 tsdf.validate()?;
395 }
396 self.validate_stage_bindings()?;
397 let mut roles = std::collections::BTreeSet::new();
398 let mut paths = std::collections::BTreeSet::new();
399 for artifact in &self.artifacts {
400 artifact.validate()?;
401 if !roles.insert(&artifact.role) || !paths.insert(&artifact.path) {
402 return Err(ViewerError::InvalidState(
403 "full-bag mapping artifacts must have unique roles and paths".into(),
404 ));
405 }
406 }
407
408 let calculated_calibration = self.calibration.as_ref().is_some_and(|calibration| {
409 calibration.registration_ready
410 && calibration.source.identity_matches
411 && calibration.source.path == self.source.path
412 && calibration.source.observed_sha256 == self.source.observed_sha256
413 });
414 let calculated_full =
415 self.source_summary.full_bag_processed && !self.source_summary.truncated;
416 let calculated_odometry =
417 self.odometry.as_ref().is_some_and(|odometry| odometry.complete && !odometry.truncated);
418 let calculated_tsdf = self.tsdf.as_ref().is_some_and(|tsdf| tsdf.complete);
419 if self.summary.calibration_registered != calculated_calibration
420 || self.summary.full_bag_processed != calculated_full
421 || self.summary.odometry_complete != calculated_odometry
422 || self.summary.tsdf_complete != calculated_tsdf
423 || (self.summary.clock_applied && !calculated_calibration)
424 || (self.summary.frame_graph_applied && !calculated_calibration)
425 {
426 return Err(ViewerError::InvalidState(
427 "full-bag mapping summary disagrees with source or stage receipts".into(),
428 ));
429 }
430 let calculated_mapping = self.source.identity_matches
431 && calculated_calibration
432 && self.summary.clock_applied
433 && self.summary.frame_graph_applied
434 && calculated_full
435 && calculated_odometry
436 && calculated_tsdf
437 && self.blockers.is_empty();
438 if self.summary.mapping_admitted != calculated_mapping {
439 return Err(ViewerError::InvalidState(
440 "mapping_admitted disagrees with full-bag mapping gates".into(),
441 ));
442 }
443 if self.summary.mapping_admitted && !self.blockers.is_empty() {
444 return Err(ViewerError::InvalidState(
445 "admitted full-bag mapping cannot contain blockers".into(),
446 ));
447 }
448 if !self.summary.mapping_admitted && self.blockers.is_empty() {
449 return Err(ViewerError::InvalidState(
450 "blocked full-bag mapping must expose at least one blocker".into(),
451 ));
452 }
453 if self.blockers.iter().any(|blocker| blocker.trim().is_empty()) {
454 return Err(ViewerError::InvalidState(
455 "full-bag mapping blockers must not be empty".into(),
456 ));
457 }
458 Ok(())
459 }
460
461 fn validate_stage_bindings(&self) -> ViewerResult<()> {
462 if let Some(odometry) = &self.odometry {
463 let front = &self.source_summary;
464 if odometry.topic != front.front_topic
465 || odometry.scan_count > front.front_record_count
466 || (odometry.complete
467 && (odometry.scan_count != front.front_record_count
468 || odometry.scan_count != front.front_bag_message_count))
469 {
470 return Err(ViewerError::InvalidState(
471 "mapping odometry topic or scan count differs from the selected front source"
472 .into(),
473 ));
474 }
475 if let Some(calibration) = &self.calibration {
476 if calibration.frame.required_frames.get("front") != Some(&odometry.source_frame)
477 || odometry.root_frame != calibration.frame.root_frame
478 || odometry.clock_id != calibration.clock.target_domain
479 {
480 return Err(ViewerError::InvalidState(
481 "mapping odometry frame or clock identity differs from registered calibration"
482 .into(),
483 ));
484 }
485 }
486 }
487 if let Some(tsdf) = &self.tsdf {
488 let calibration_mismatch = self
489 .calibration
490 .as_ref()
491 .is_some_and(|calibration| tsdf.frame_id != calibration.frame.root_frame);
492 let odometry_mismatch =
493 self.odometry.as_ref().is_some_and(|odometry| tsdf.frame_id != odometry.root_frame);
494 if calibration_mismatch || odometry_mismatch {
495 return Err(ViewerError::InvalidState(
496 "mapping TSDF frame differs from calibration or odometry root".into(),
497 ));
498 }
499 }
500 Ok(())
501 }
502}
503
504fn push_blocker(blockers: &mut Vec<String>, blocker: impl Into<String>) {
505 let blocker = blocker.into();
506 if !blockers.iter().any(|existing| existing == &blocker) {
507 blockers.push(blocker);
508 }
509}
510
511#[cfg(test)]
512#[path = "mapping_gate_consistency_tests.rs"]
513mod consistency_tests;
514
515#[cfg(test)]
516mod tests {
517 use super::*;
518 use crate::{
519 CalibrationArtifact, CalibrationEvidenceClock, CalibrationEvidenceFrame, ClockCalibration,
520 FrameTransform,
521 };
522
523 const SHA: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
524
525 fn source() -> StudioSource {
526 StudioSource::try_new("fixture", "/media/fixture.db3", SHA, SHA, true).unwrap()
527 }
528
529 fn source_summary() -> MappingSourceSummary {
530 MappingSourceSummary {
531 front_topic: "/front".into(),
532 rear_topic: "/rear".into(),
533 front_bag_message_count: 0,
534 rear_bag_message_count: 0,
535 front_chunk_count: 0,
536 rear_chunk_count: 0,
537 front_record_count: 0,
538 rear_record_count: 0,
539 total_record_count: 0,
540 total_point_count: 0,
541 retained_bytes: 0,
542 peak_source_bytes: 0,
543 start_nanos: None,
544 end_nanos: None,
545 full_bag_processed: false,
546 truncated: false,
547 }
548 }
549
550 #[test]
551 fn missing_calibration_is_a_valid_blocked_state() {
552 let state = FullBagMappingState::try_new(
553 "fixture mapping",
554 source(),
555 None,
556 source_summary(),
557 None,
558 None,
559 Vec::new(),
560 false,
561 false,
562 Vec::new(),
563 )
564 .unwrap();
565 assert!(!state.summary.mapping_admitted);
566 assert!(state.blockers.iter().any(|blocker| blocker.contains("calibration")));
567 state.validate().unwrap();
568 }
569
570 pub(super) fn complete_state() -> FullBagMappingState {
571 let calibration = CalibrationEvidenceState::try_new(
572 "fixture calibration",
573 source(),
574 CalibrationArtifact::try_new(
575 "clock_evidence",
576 "registered",
577 Some("/media/clock.json".into()),
578 Some(SHA.into()),
579 true,
580 )
581 .unwrap(),
582 CalibrationArtifact::try_new(
583 "frame_evidence",
584 "registered",
585 Some("/media/frame.json".into()),
586 Some(SHA.into()),
587 true,
588 )
589 .unwrap(),
590 CalibrationEvidenceClock::try_new(
591 "sensor",
592 "external",
593 "fixture clock fit",
594 ClockCalibration::try_new(
595 "registered",
596 "anchored external clock",
597 2,
598 Some(1.0),
599 Some(2.0),
600 Some(0.0),
601 Some(3.0),
602 true,
603 false,
604 )
605 .unwrap(),
606 )
607 .unwrap(),
608 CalibrationEvidenceFrame::try_new(
609 "fixture extrinsic fit",
610 "base_link",
611 std::collections::BTreeMap::from([
612 ("front".into(), "front_frame".into()),
613 ("rear".into(), "rear_frame".into()),
614 ]),
615 vec!["base_link".into(), "front_frame".into(), "rear_frame".into()],
616 vec![
617 FrameTransform::try_new(
618 "base_link",
619 "front_frame",
620 [0.0, 0.0, 0.0],
621 [0.0, 0.0, 0.0, 1.0],
622 None,
623 true,
624 true,
625 )
626 .unwrap(),
627 FrameTransform::try_new(
628 "base_link",
629 "rear_frame",
630 [0.0, 0.0, 0.0],
631 [0.0, 0.0, 0.0, 1.0],
632 None,
633 true,
634 true,
635 )
636 .unwrap(),
637 ],
638 )
639 .unwrap(),
640 Vec::new(),
641 )
642 .unwrap();
643 FullBagMappingState::try_new(
644 "fixture mapping",
645 source(),
646 Some(calibration),
647 MappingSourceSummary {
648 front_topic: "/front".into(),
649 rear_topic: "/rear".into(),
650 front_bag_message_count: 2,
651 rear_bag_message_count: 2,
652 front_chunk_count: 2,
653 rear_chunk_count: 2,
654 front_record_count: 2,
655 rear_record_count: 2,
656 total_record_count: 4,
657 total_point_count: 12,
658 retained_bytes: 48,
659 peak_source_bytes: 256,
660 start_nanos: Some(1),
661 end_nanos: Some(2),
662 full_bag_processed: true,
663 truncated: false,
664 },
665 Some(MappingOdometrySummary {
666 topic: "/front".into(),
667 source_frame: "front_frame".into(),
668 root_frame: "base_link".into(),
669 clock_id: "external".into(),
670 clock_domain: "external-calibrated".into(),
671 matcher: "fixture".into(),
672 scan_count: 2,
673 motion_count: 1,
674 pose_graph_node_count: 2,
675 pose_graph_edge_count: 1,
676 complete: true,
677 truncated: false,
678 }),
679 Some(MappingTsdfSummary {
680 frame_id: "base_link".into(),
681 origin: [0.0, 0.0, 0.0],
682 voxel_size: 0.5,
683 dims: [8, 8, 8],
684 truncation: 1.0,
685 integrated_record_count: 4,
686 integrated_point_count: 12,
687 mesh_vertex_count: 3,
688 mesh_triangle_count: 1,
689 complete: true,
690 }),
691 vec![ReplayArtifact::try_new("mesh", "/media/mesh.gltf", 1, SHA).unwrap()],
692 true,
693 true,
694 Vec::new(),
695 )
696 .unwrap()
697 }
698
699 #[test]
700 fn complete_source_bound_stages_are_admitted() {
701 let state = complete_state();
702 assert!(state.summary.mapping_admitted);
703 state.validate().unwrap();
704 }
705
706 #[test]
707 fn summary_rejects_reversed_source_bounds() {
708 let mut summary = source_summary();
709 summary.start_nanos = Some(20);
710 summary.end_nanos = Some(10);
711 assert!(summary.validate().is_err());
712 }
713}