transforms 2.0.0

A transform library to track reference frames and provide transforms between them.
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
#[cfg(test)]
mod buffer_tests {
    use crate::{
        core::{
            Buffer,
            buffer::{GetError, InsertError},
        },
        errors::TransformError,
        geometry::{Quaternion, Transform, Vector3},
        time::{Stamp, Timestamp},
    };
    use core::time::Duration;

    fn create_transform(t: Timestamp) -> Transform {
        stamped_transform(Stamp::At(t))
    }

    fn create_static_transform() -> Transform {
        stamped_transform(Stamp::Static)
    }

    fn stamped_transform(timestamp: Stamp) -> Transform {
        frames_transform("map", "base", Vector3::new(1.0, 2.0, 3.0), timestamp)
    }

    /// A valid transform between the named frames, for the tests that vary
    /// frames or translation. `Transform`'s fields are private, so a variant
    /// is built, not edited into existence.
    fn frames_transform(
        parent: &str,
        child: &str,
        translation: Vector3,
        timestamp: Stamp,
    ) -> Transform {
        Transform::new(
            parent,
            child,
            translation,
            Quaternion::identity(),
            timestamp,
        )
        .unwrap()
    }

    #[test]
    fn insert_and_get() {
        let mut buffer = Buffer::dynamic();
        let t = Timestamp::from_nanos(1_000_000_000);

        let transform = create_transform(t);
        buffer.insert(transform.clone()).unwrap();

        let mut r = buffer.get(t);

        assert!(r.is_ok(), "expected transform, got {r:?}");
        assert_eq!(r.unwrap(), transform);

        r = buffer.get((t + Duration::from_secs(1)).unwrap());
        assert!(r.is_err(), "expected no transform, got {r:?}");

        r = buffer.get((t - Duration::from_secs(1)).unwrap());
        assert!(r.is_err(), "expected no transform, got {r:?}");
    }

    #[test]
    fn get_out_of_range_reports_covered_range() {
        let mut buffer = Buffer::dynamic();
        let t1 = Timestamp::from_nanos(1_000_000_000);
        let t2 = Timestamp::from_nanos(2_000_000_000);
        buffer.insert(create_transform(t1)).unwrap();
        buffer.insert(create_transform(t2)).unwrap();

        // Too new: past the latest sample. The error carries the covered
        // range in the buffer's own timestamp type, so latency ("just too
        // new") is distinguishable from stale data without further queries
        // and without a lossy conversion to seconds.
        let result = buffer.get(Timestamp::from_nanos(3_000_000_000));
        assert!(
            matches!(
                &result,
                Err(GetError::OutOfRange { start, end }) if *start == t1 && *end == t2
            ),
            "expected OutOfRange with the covered range, got {result:?}"
        );

        // Too old: before the earliest sample.
        let result = buffer.get(Timestamp::from_nanos(500_000_000));
        assert!(
            matches!(
                &result,
                Err(GetError::OutOfRange { start, end }) if *start == t1 && *end == t2
            ),
            "expected OutOfRange with the covered range, got {result:?}"
        );
    }

    #[test]
    fn get_on_empty_buffer_reports_no_transforms() {
        let buffer = Buffer::<Timestamp>::dynamic();

        let result = buffer.get(Timestamp::from_nanos(1_000_000_000));
        assert!(
            matches!(result, Err(GetError::NoTransformAvailable)),
            "expected NoTransformAvailable on an empty dynamic buffer, got {result:?}"
        );

        let buffer = Buffer::<Timestamp>::static_edge();
        let result = buffer.get(Timestamp::from_nanos(1_000_000_000));
        assert!(
            matches!(result, Err(GetError::NoTransformAvailable)),
            "expected NoTransformAvailable on an empty static buffer, got {result:?}"
        );

        let buffer = Buffer::<Timestamp>::dynamic_with_max_age(Duration::from_secs(10));
        let result = buffer.get(Timestamp::from_nanos(1_000_000_000));
        assert!(
            matches!(result, Err(GetError::NoTransformAvailable)),
            "expected NoTransformAvailable on an empty max-age buffer, got {result:?}"
        );
    }

    #[test]
    fn insert_and_get_static() {
        let mut buffer = Buffer::static_edge();

        let transform = create_static_transform();

        buffer.insert(transform.clone()).unwrap();

        // A static buffer serves any requested instant.
        let mut r = buffer.get(Timestamp::from_nanos(1_000_000_000));

        assert!(r.is_ok(), "expected transform, got {r:?}");
        assert_eq!(r.unwrap(), transform);

        r = buffer.get(Timestamp::zero());
        assert!(r.is_ok(), "expected transform, got {r:?}");
        assert_eq!(r.unwrap(), transform);
    }

    #[test]
    // The compared values are exactly representable; the assertion is on
    // reported payloads, not on float arithmetic.
    #[allow(clippy::float_cmp)]
    fn static_insert_is_a_last_write_wins_upsert() {
        let mut buffer = Buffer::static_edge();

        buffer.insert(create_static_transform()).unwrap();

        let recalibrated =
            frames_transform("map", "base", Vector3::new(9.0, 9.0, 9.0), Stamp::Static);
        buffer.insert(recalibrated).unwrap();

        assert_eq!(buffer.get(Timestamp::zero()).unwrap().translation().x, 9.0);
        // The replacement is served at every instant, so the original is
        // stored nowhere: a static buffer holds one transform, not a history.
        assert_eq!(
            buffer
                .get(Timestamp::from_nanos(9_000_000_000))
                .unwrap()
                .translation()
                .x,
            9.0
        );
    }

    #[test]
    fn zero_is_an_ordinary_dynamic_timestamp() {
        // The most natural loop there is: samples at t = 0, 1, 2, ... The
        // old design reserved t = 0 as the static sentinel, so the very
        // first iteration silently created a static buffer and the second
        // failed with StaticDynamicConflict. With staticness in the Stamp,
        // zero needs no special handling.
        let mut buffer = Buffer::dynamic();
        for i in 0..3u64 {
            let t = Timestamp::from_nanos(i * 1_000_000_000);
            buffer.insert(create_transform(t)).unwrap();
        }

        // All three samples are stored and served exactly, the t = 0 one
        // included.
        for i in 0..3u64 {
            let t = Timestamp::from_nanos(i * 1_000_000_000);
            assert_eq!(buffer.get(t).unwrap().timestamp(), Stamp::At(t));
        }

        // Interpolation across t = 0 works like any other span.
        let midpoint = Timestamp::from_nanos(500_000_000);
        let interpolated = buffer.get(midpoint).unwrap();
        assert_eq!(interpolated.timestamp(), Stamp::At(midpoint));
    }

    #[test]
    fn remove_before_resets_the_expiry_reference() {
        // Regression test: remove_before used to clear only the sample map,
        // leaving the max_age expiry reference at the pre-wipe maximum. A
        // restarted stream at earlier timestamps was then evicted by the
        // very insert that added it — Ok(()) returned, buffer stayed empty.
        let mut buffer = Buffer::dynamic_with_max_age(Duration::from_secs(1));
        buffer
            .insert(create_transform(Timestamp::from_nanos(1_000_000_000_000)))
            .unwrap();

        buffer.remove_before(Timestamp::from_nanos(2_000_000_000_000));
        assert!(matches!(
            buffer.get(Timestamp::from_nanos(1_000_000_000_000)),
            Err(GetError::NoTransformAvailable)
        ));

        // A restarted stream from t = 0 must be retained again.
        let t = Timestamp::zero();
        buffer.insert(create_transform(t)).unwrap();
        assert!(buffer.get(t).is_ok());
    }

    #[test]
    fn emptied_dynamic_buffer_keeps_its_kind() {
        // Regression test: the kind used to be a flag re-decided whenever
        // the buffer was empty, so a dynamic buffer emptied by
        // remove_before accepted a static insert, silently flipped kind,
        // and then rejected dynamic inserts. The kind is now declared at
        // construction and structural: it cannot flip.
        let t = Timestamp::from_nanos(1_000_000_000);
        let mut buffer = Buffer::dynamic();
        buffer.insert(create_transform(t)).unwrap();

        buffer.remove_before((t + Duration::from_secs(1)).unwrap());
        assert!(matches!(buffer.get(t), Err(GetError::NoTransformAvailable)));

        let result = buffer.insert(create_static_transform());
        assert!(
            matches!(result, Err(InsertError::StaticDynamicConflict)),
            "an emptied dynamic buffer must stay dynamic, got {result:?}"
        );

        // Dynamic inserts keep working.
        buffer.insert(create_transform(t)).unwrap();
        assert!(buffer.get(t).is_ok());
    }

    #[test]
    fn get_nearest() {
        let mut buffer = Buffer::dynamic();
        let t = Timestamp::from_nanos(1_000_000_000);

        let t1 = (t + Duration::from_secs(1)).unwrap();
        let t2 = (t + Duration::from_secs(2)).unwrap();
        let t3 = (t + Duration::from_secs(3)).unwrap();
        let p1 = create_transform(t1);
        let p2 = create_transform(t2);
        let p3 = create_transform(t3);

        buffer.insert(p1.clone()).unwrap();
        buffer.insert(p2.clone()).unwrap();
        buffer.insert(p3.clone()).unwrap();

        // Exact match
        let (before, after) = buffer.get_nearest(&t2);
        assert_eq!(before.unwrap(), (&t2, &p2));
        assert_eq!(after.unwrap(), (&t2, &p2));

        // Between two points
        let p_mid = (t1 + Duration::from_millis(500)).unwrap();
        let (before, after) = buffer.get_nearest(&p_mid);
        assert_eq!(before.unwrap(), (&t1, &p1));
        assert_eq!(after.unwrap(), (&t2, &p2));

        // Before first point
        let p_0 = (t1 - Duration::from_secs(1)).unwrap();
        let (before, after) = buffer.get_nearest(&p_0);
        assert_eq!(before, None);
        assert_eq!(after.unwrap(), (&t1, &p1));

        // After last point
        let p_4 = (t3 + Duration::from_secs(1)).unwrap();
        let (before, after) = buffer.get_nearest(&p_4);
        assert_eq!(before.unwrap(), (&t3, &p3));
        assert_eq!(after, None);

        // Exactly at first point
        let (before, after) = buffer.get_nearest(&t1);
        assert_eq!(before.unwrap(), (&t1, &p1));
        assert_eq!(after.unwrap(), (&t1, &p1));

        // Exactly at last point
        let (before, after) = buffer.get_nearest(&t3);
        assert_eq!(before.unwrap(), (&t3, &p3));
        assert_eq!(after.unwrap(), (&t3, &p3));
    }

    #[test]
    fn empty_buffer() {
        let buffer = Buffer::dynamic();

        assert!(buffer.get(Timestamp::from_nanos(1000)).is_err());

        let (before, after) = buffer.get_nearest(&Timestamp::from_nanos(1000));
        assert!(before.is_none());
        assert!(after.is_none());
    }

    #[test]
    fn remove_before() {
        let mut buffer = Buffer::dynamic();
        let t1 = Timestamp::from_nanos(1_000_000_000);
        let t2 = (t1 + Duration::from_secs(2)).unwrap();

        buffer.insert(create_transform(t1)).unwrap();
        buffer.insert(create_transform(t2)).unwrap();

        assert!(buffer.get(t1).is_ok());
        assert!(buffer.get(t2).is_ok());

        buffer.remove_before(Timestamp::from_nanos(2_000_000_000));

        assert!(buffer.get(t1).is_err());
        assert!(buffer.get(t2).is_ok());
    }

    #[test]
    fn remove_expired() {
        let mut buffer = Buffer::dynamic_with_max_age(Duration::from_secs(10));
        let t = Timestamp::from_nanos(20_000_000_000);

        buffer.insert(create_transform(t)).unwrap();
        buffer
            .insert(create_transform((t + Duration::from_secs(1)).unwrap()))
            .unwrap();
        buffer
            .insert(create_transform((t + Duration::from_secs(2)).unwrap()))
            .unwrap();

        let get_1 = buffer.get((t - Duration::from_secs(2)).unwrap());
        let get_2 = buffer.get((t - Duration::from_secs(1)).unwrap());
        let get_3 = buffer.get(t);

        assert!(get_1.is_err());
        // Before the earliest stored sample: nothing to interpolate from.
        assert!(get_2.is_err());
        assert!(get_3.is_ok());
    }

    #[test]
    fn single_point_buffer() {
        let mut buffer = Buffer::dynamic();
        let t = Timestamp::from_nanos(1_000_000_000);

        let point = create_transform(t);
        buffer.insert(point.clone()).unwrap();

        // Before the point
        let (before, after) = buffer.get_nearest(&(t - Duration::from_secs(1)).unwrap());
        assert!(before.is_none());
        assert_eq!(after.unwrap(), (&t, &point));

        // Exact match
        let (before, after) = buffer.get_nearest(&t);
        assert_eq!(before.unwrap(), (&t, &point));
        assert_eq!(after.unwrap(), (&t, &point));

        // After the point
        let (before, after) = buffer.get_nearest(&(t + Duration::from_secs(1)).unwrap());
        assert_eq!(before.unwrap(), (&t, &point));
        assert!(after.is_none());
    }

    #[test]
    fn insert_rejects_static_dynamic_mixing() {
        let t_dynamic = Timestamp::from_nanos(1_000_000_000);

        let static_tf = create_static_transform();
        let dynamic_tf = create_transform(t_dynamic);

        // A static buffer rejects dynamic transforms.
        let mut buffer = Buffer::static_edge();

        buffer.insert(static_tf.clone()).unwrap();
        assert!(matches!(
            buffer.insert(dynamic_tf.clone()),
            Err(InsertError::StaticDynamicConflict)
        ));

        // The static transform is still served after the rejected insert.
        assert_eq!(buffer.get(t_dynamic).unwrap(), static_tf);

        // A dynamic buffer rejects static transforms.
        let mut buffer = Buffer::dynamic();

        buffer.insert(dynamic_tf.clone()).unwrap();
        assert!(matches!(
            buffer.insert(static_tf),
            Err(InsertError::StaticDynamicConflict)
        ));

        // The dynamic transform is still served after the rejected insert.
        assert_eq!(buffer.get(t_dynamic).unwrap(), dynamic_tf);
    }

    #[test]
    fn insert_kind_mismatch_on_fresh_buffer_pins_no_frames() {
        // A first insert rejected for the wrong kind must leave the buffer
        // untouched: no frames pinned, nothing stored.
        let mut buffer = Buffer::static_edge();
        let result = buffer.insert(create_transform(Timestamp::zero()));
        assert!(matches!(result, Err(InsertError::StaticDynamicConflict)));
        assert_eq!(buffer.parent(), None);
        assert!(matches!(
            buffer.get(Timestamp::zero()),
            Err(GetError::NoTransformAvailable)
        ));

        // Neither frame was pinned: a static transform for an entirely
        // different frame pair is still accepted.
        let other = frames_transform("odom", "lidar", Vector3::zero(), Stamp::Static);
        buffer.insert(other).unwrap();
        assert_eq!(buffer.parent(), Some("odom"));
    }

    #[test]
    fn insert_expires_entries_older_than_max_age() {
        let mut buffer = Buffer::dynamic_with_max_age(Duration::from_secs(1));

        let t1 = Timestamp::from_nanos(1_000_000_000);
        let t2 = Timestamp::from_nanos(6_000_000_000);

        buffer.insert(create_transform(t1)).unwrap();
        buffer.insert(create_transform(t2)).unwrap();

        // t1 is more than max_age older than the latest inserted timestamp,
        // so it must have been expired by the second insert.
        assert!(
            buffer.get(t1).is_err(),
            "entry older than max_age must expire on insert"
        );
        assert!(buffer.get(t2).is_ok());
    }

    #[test]
    fn dynamic_buffer_never_expires_entries() {
        let mut buffer: Buffer = Buffer::dynamic();

        let t1 = Timestamp::from_nanos(1_000_000_000);
        let t2 = Timestamp::from_nanos(3_600_000_000_000);

        buffer.insert(create_transform(t1)).unwrap();
        buffer.insert(create_transform(t2)).unwrap();

        assert!(
            buffer.get(t1).is_ok(),
            "Buffer::dynamic must not expire entries"
        );
        assert!(buffer.get(t2).is_ok());
    }

    #[test]
    fn remove_before_preserves_static_transforms() {
        let mut buffer: Buffer = Buffer::static_edge();

        let static_tf = create_static_transform();
        buffer.insert(static_tf.clone()).unwrap();

        // Manual cleanup with any cutoff must not destroy a static transform:
        // it is valid for all time, not just before the cutoff.
        buffer.remove_before(Timestamp::from_nanos(5_000_000_000));

        assert_eq!(
            buffer.get(Timestamp::from_nanos(9_000_000_000)).unwrap(),
            static_tf,
            "static transforms must survive manual cleanup"
        );
    }

    #[test]
    fn insert_rejects_invalid_transforms() {
        let mut buffer: Buffer = Buffer::dynamic();

        let t = Timestamp::from_nanos(1_000_000_000);

        // The constructors reject both of these, so the only way one reaches
        // an insert is the way a caller produces it: derived from valid
        // transforms by `*`, `interpolate`, `inverse` or a lookup, none of
        // which re-validate. `unvalidated` stands in for that derivation.
        let non_unit = Transform::unvalidated(
            "map".into(),
            "base".into(),
            Vector3::new(1.0, 0.0, 0.0),
            Quaternion::from_wxyz(2.0, 0.0, 0.0, 0.0),
            Stamp::At(t),
        );
        assert!(matches!(
            buffer.insert(non_unit),
            Err(InsertError::Invalid(TransformError::NonUnitRotation(_)))
        ));

        let non_finite = Transform::unvalidated(
            "map".into(),
            "base".into(),
            Vector3::new(f64::NAN, 0.0, 0.0),
            Quaternion::identity(),
            Stamp::At(t),
        );
        assert!(matches!(
            buffer.insert(non_finite),
            Err(InsertError::Invalid(TransformError::NonFiniteValues))
        ));

        // A rejected insert stores nothing and pins nothing.
        assert!(matches!(buffer.get(t), Err(GetError::NoTransformAvailable)));
        assert_eq!(buffer.parent(), None);

        // Unit-norm rotations with f32-grade precision loss must still be
        // accepted — the tolerance exists for exactly them.
        let f32_grade = Transform::new(
            "map",
            "base",
            Vector3::new(1.0, 0.0, 0.0),
            Quaternion::from_wxyz(1.0 + 1e-8, 0.0, 0.0, 0.0),
            Stamp::At(t),
        )
        .unwrap();
        assert!(buffer.insert(f32_grade).is_ok());
    }

    #[test]
    fn frame_pins_survive_the_buffer_being_emptied() {
        let mut buffer = Buffer::dynamic();
        assert_eq!(buffer.parent(), None);

        let t = Timestamp::from_nanos(1_000_000_000);
        buffer.insert(create_transform(t)).unwrap();
        assert_eq!(buffer.parent(), Some("map"));

        // The pins survive the buffer being emptied, matching the documented
        // parent behavior: dropping the buffer is the only release.
        buffer.remove_before((t + Duration::from_secs(1)).unwrap());
        assert!(matches!(buffer.get(t), Err(GetError::NoTransformAvailable)));
        assert_eq!(buffer.parent(), Some("map"));

        // The child pin survives too, so a drained buffer still refuses a
        // transform for another child frame.
        let other = frames_transform("map", "lidar", Vector3::zero(), Stamp::At(t));
        let result = buffer.insert(other);
        assert!(
            matches!(result, Err(InsertError::ChildFrameMismatch { ref pinned, ref found }) if pinned == "base" && found == "lidar"),
            "expected ChildFrameMismatch, got {result:?}"
        );
    }

    #[test]
    fn insert_rejects_child_frame_mismatch_static() {
        let mut buffer = Buffer::static_edge();

        // Static calibration transform for map -> base.
        let original = create_static_transform();
        buffer.insert(original.clone()).unwrap();

        // Same parent, different child (a frame-naming bug): without child
        // pinning this key collision silently overwrote the stored data.
        let other = frames_transform("map", "lidar", Vector3::new(9.0, 9.0, 9.0), Stamp::Static);
        let result = buffer.insert(other);
        assert!(
            matches!(result, Err(InsertError::ChildFrameMismatch { ref pinned, ref found }) if pinned == "base" && found == "lidar"),
            "expected ChildFrameMismatch, got {result:?}"
        );

        // The original static transform must be untouched and retrievable.
        assert_eq!(
            buffer.get(Timestamp::from_nanos(1_000_000_000)).unwrap(),
            original,
            "the pinned child's static transform must survive the rejected insert"
        );
    }

    #[test]
    fn insert_rejects_child_frame_mismatch_dynamic() {
        let mut buffer = Buffer::dynamic();
        let t1 = Timestamp::from_nanos(1_000_000_000);
        let t2 = Timestamp::from_nanos(2_000_000_000);
        let t3 = Timestamp::from_nanos(3_000_000_000);

        buffer.insert(create_transform(t1)).unwrap();
        buffer.insert(create_transform(t3)).unwrap();

        // A different child between the stored samples: without child pinning
        // this insert succeeded and made interpolating lookups fail with
        // IncompatibleFrames while exact-hit lookups kept working.
        let other = frames_transform("map", "lidar", Vector3::zero(), Stamp::At(t2));
        assert!(matches!(
            buffer.insert(other),
            Err(InsertError::ChildFrameMismatch { .. })
        ));

        // Interpolation over the pinned child's samples must keep working.
        let result = buffer.get(t2).unwrap();
        assert_eq!(result.child(), "base");
        assert_eq!(result.timestamp(), Stamp::At(t2));
    }

    #[test]
    fn out_of_order_insert_does_not_regress_latest_timestamp() {
        let mut buffer = Buffer::dynamic_with_max_age(Duration::from_secs(1));

        let t_new = Timestamp::from_nanos(5_000_000_000);
        let t_old = Timestamp::from_nanos(1_000_000_000);

        buffer.insert(create_transform(t_new)).unwrap();
        // Late-arriving old sample: the expiry reference must remain t_new,
        // so this entry is already outside max_age and gets dropped.
        buffer.insert(create_transform(t_old)).unwrap();

        assert!(
            buffer.get(t_old).is_err(),
            "expiry must be measured against the latest timestamp, not the last insert"
        );
        assert!(buffer.get(t_new).is_ok());
    }

    /// A transform translated by `x`, distinguishable from `create_transform`.
    fn transform_with_x(
        t: Timestamp,
        x: f64,
    ) -> Transform {
        frames_transform("a", "b", Vector3::new(x, 0.0, 0.0), Stamp::At(t))
    }

    #[test]
    // The compared values are exactly representable; the assertion is on
    // reported payloads, not on float arithmetic.
    #[allow(clippy::float_cmp)]
    fn duplicate_timestamp_insert_is_a_last_write_wins_upsert() {
        let t = Timestamp::from_nanos(5_000_000_000);
        let mut buffer = Buffer::dynamic();
        buffer.insert(transform_with_x(t, 1.0)).unwrap();
        // Same timestamp, different payload: Ok, silently replaces.
        buffer.insert(transform_with_x(t, 2.0)).unwrap();
        assert_eq!(buffer.get(t).unwrap().translation().x, 2.0);
    }

    #[test]
    // The compared values are exactly representable; the assertion is on
    // reported payloads, not on float arithmetic.
    #[allow(clippy::float_cmp)]
    fn zero_max_age_out_of_order_insert_is_ok_but_immediately_evicted() {
        // Inserting an OLDER sample after a newer one with max_age == ZERO
        // returns Ok, but the same insert call evicts it: the expiry
        // threshold stays pinned to the latest timestamp seen.
        let t1 = Timestamp::from_nanos(1_000_000_000);
        let t2 = Timestamp::from_nanos(2_000_000_000);
        let mut buffer = Buffer::dynamic_with_max_age(Duration::ZERO);
        buffer.insert(transform_with_x(t2, 2.0)).unwrap();
        buffer.insert(transform_with_x(t1, 1.0)).unwrap();
        assert_eq!(buffer.get(t2).unwrap().translation().x, 2.0);
        assert!(buffer.get(t1).is_err(), "older insert must be evicted");
    }

    #[test]
    // The compared values are exactly representable; the assertion is on
    // reported payloads, not on float arithmetic.
    #[allow(clippy::float_cmp)]
    fn eviction_boundary_retains_a_sample_exactly_max_age_old() {
        let max_age = Duration::from_secs(10);
        let t0 = Timestamp::from_nanos(100_000_000_000);
        let t0_plus_max_age = Timestamp::from_nanos(110_000_000_000);

        let mut buffer = Buffer::dynamic_with_max_age(max_age);
        buffer.insert(transform_with_x(t0, 1.0)).unwrap();
        buffer
            .insert(transform_with_x(t0_plus_max_age, 2.0))
            .unwrap();

        // threshold = (t0 + max_age) - max_age = t0; eviction keeps
        // k >= threshold, so the sample exactly max_age old survives.
        assert_eq!(buffer.get(t0).unwrap().translation().x, 1.0);
    }

    #[test]
    // The compared values are exactly representable; the assertion is on
    // reported payloads, not on float arithmetic.
    #[allow(clippy::float_cmp)]
    fn eviction_boundary_evicts_one_nanosecond_past_max_age() {
        let max_age = Duration::from_secs(10);
        let t0 = Timestamp::from_nanos(100_000_000_000);
        let t_past = Timestamp::from_nanos(110_000_000_001);

        let mut buffer = Buffer::dynamic_with_max_age(max_age);
        buffer.insert(transform_with_x(t0, 1.0)).unwrap();
        buffer.insert(transform_with_x(t_past, 2.0)).unwrap();

        assert!(
            buffer.get(t0).is_err(),
            "sample older than max_age must be evicted"
        );
        assert_eq!(buffer.get(t_past).unwrap().translation().x, 2.0);
    }
}