mnesis-store 0.3.1

Event store edge layer for the Mnesis event-sourcing framework
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! Relocated inline test mod of `src/projection.rs` (mnesis-inmemory is a
//! dev-dependency; type unification with it requires an integration test).

#![cfg(feature = "projection")]

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        reason = "test module"
    )]

    use core::num::{NonZeroU32, NonZeroU64};

    use mnesis::{DomainEvent, Message, Version, version};

    use mnesis_inmemory::{InMemoryAllPos, InMemorySnapshotStore};
    use mnesis_store::StreamKey;
    use mnesis_store::decoded::Decoded;
    use mnesis_store::projection::{Projection, ProjectionError, Projector};
    use mnesis_store::state::{
        AfterEventTypes, EveryNEvents, Hydrated, PersistTrigger, SnapshotStore,
    };

    // ── fixtures ────────────────────────────────────────────────────────────

    #[derive(Debug, Clone, Hash, PartialEq, Eq)]
    struct TestId(&'static str);
    impl core::fmt::Display for TestId {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.write_str(self.0)
        }
    }
    impl AsRef<[u8]> for TestId {
        fn as_ref(&self) -> &[u8] {
            self.0.as_bytes()
        }
    }

    #[derive(Debug, Clone, PartialEq)]
    struct CountState {
        count: u64,
        total: u64,
    }

    #[derive(Debug)]
    enum TestEvent {
        Added(u64),
        Removed(u64),
    }
    impl Message for TestEvent {}
    impl DomainEvent for TestEvent {
        fn name(&self) -> &'static str {
            match self {
                Self::Added(_) => "Added",
                Self::Removed(_) => "Removed",
            }
        }
    }

    #[derive(Debug, thiserror::Error)]
    #[error("projection overflow")]
    struct TestProjectionError;

    struct CountingProjector;
    impl Projector for CountingProjector {
        type Event = TestEvent;
        type State = CountState;
        type Error = TestProjectionError;

        fn initial(&self) -> CountState {
            CountState { count: 0, total: 0 }
        }
        fn apply(
            &self,
            state: CountState,
            event: &TestEvent,
        ) -> Result<CountState, TestProjectionError> {
            let count = state.count.checked_add(1).ok_or(TestProjectionError)?;
            let total = match event {
                TestEvent::Added(n) => state.total.checked_add(*n).ok_or(TestProjectionError)?,
                TestEvent::Removed(n) => state.total.checked_sub(*n).ok_or(TestProjectionError)?,
            };
            Ok(CountState { count, total })
        }
    }

    /// Build a `Decoded` event at a given version, the way `.decoded()` would.
    const fn decoded(event: TestEvent, ver: u64) -> Decoded<TestEvent> {
        Decoded {
            event,
            version: Version::new(ver).expect("nonzero version"),
            metadata: None,
        }
    }

    fn store() -> InMemorySnapshotStore<CountState, Version> {
        InMemorySnapshotStore::new()
    }

    // ── 1. Sequence/Protocol: load → advance×n commits and folds ────────────

    #[tokio::test]
    async fn advance_folds_and_commits_each_event_when_trigger_always_fires() {
        let ss = store();
        let id = TestId("s");
        let (mut p, mut state) = Projection::load(
            id.clone(),
            CountingProjector,
            EveryNEvents(NonZeroU64::MIN),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();

        assert_eq!(p.checkpoint(), None);
        state = p
            .advance(state, decoded(TestEvent::Added(10), 1))
            .await
            .unwrap();
        state = p
            .advance(state, decoded(TestEvent::Added(20), 2))
            .await
            .unwrap();
        state = p
            .advance(state, decoded(TestEvent::Added(30), 3))
            .await
            .unwrap();

        assert_eq!(p.checkpoint(), Some(version!(3)));
        assert_eq!(
            state,
            CountState {
                count: 3,
                total: 60
            }
        );

        // Persisted together, atomically.
        let (pos, st) = ss
            .hydrate(&id, NonZeroU32::MIN)
            .await
            .unwrap()
            .into_found()
            .unwrap();
        assert_eq!(pos, version!(3));
        assert_eq!(
            st,
            CountState {
                count: 3,
                total: 60
            }
        );
    }

    // ── 2. Lifecycle: commit → reload → resume from checkpoint ───────────────

    #[tokio::test]
    async fn load_resumes_state_and_checkpoint_from_snapshot() {
        let ss = store();
        let id = TestId("s");

        {
            let (mut p, mut state) = Projection::load(
                id.clone(),
                CountingProjector,
                EveryNEvents(NonZeroU64::MIN),
                &ss,
                NonZeroU32::MIN,
            )
            .await
            .unwrap();
            state = p
                .advance(state, decoded(TestEvent::Added(10), 1))
                .await
                .unwrap();
            state = p
                .advance(state, decoded(TestEvent::Added(20), 2))
                .await
                .unwrap();
            let _ = p
                .advance(state, decoded(TestEvent::Added(30), 3))
                .await
                .unwrap();
        }

        // Fresh stepper over the same snapshot store: state + checkpoint restored.
        let (mut p2, state2) = Projection::load(
            id.clone(),
            CountingProjector,
            EveryNEvents(NonZeroU64::MIN),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();
        assert_eq!(p2.checkpoint(), Some(version!(3)));
        assert_eq!(
            state2,
            CountState {
                count: 3,
                total: 60
            }
        );

        // Resume: the next event folds onto the restored state.
        let resumed = p2
            .advance(state2, decoded(TestEvent::Added(40), 4))
            .await
            .unwrap();
        assert_eq!(p2.checkpoint(), Some(version!(4)));
        assert_eq!(
            resumed,
            CountState {
                count: 4,
                total: 100
            }
        );
    }

    // ── 3. Defensive boundary: a failing apply surfaces as ::Apply ───────────

    #[tokio::test]
    async fn advance_surfaces_projector_apply_error() {
        let ss = store();
        let (mut p, state) = Projection::load(
            TestId("s"),
            CountingProjector,
            EveryNEvents(NonZeroU64::MIN),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();

        // Removed(1) from total 0 underflows in the projector.
        let err = p
            .advance(state, decoded(TestEvent::Removed(1), 1))
            .await
            .unwrap_err();
        assert!(
            matches!(err, ProjectionError::Apply(_)),
            "expected Apply, got {err:?}"
        );
        // Nothing was committed on the failed fold.
        assert_eq!(p.checkpoint(), None);
    }

    // ── flush semantics: tail is committed once on shutdown ──────────────────

    #[tokio::test]
    async fn flush_commits_folded_but_unpersisted_tail() {
        let ss = store();
        let id = TestId("s");
        // Trigger never fires (bucket of 100) — only flush persists.
        let (mut p, mut state) = Projection::load(
            id.clone(),
            CountingProjector,
            EveryNEvents(NonZeroU64::new(100).unwrap()),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();

        state = p
            .advance(state, decoded(TestEvent::Added(10), 1))
            .await
            .unwrap();
        state = p
            .advance(state, decoded(TestEvent::Added(20), 2))
            .await
            .unwrap();
        assert_eq!(p.checkpoint(), None, "trigger must not have fired");
        assert_eq!(
            ss.hydrate(&id, NonZeroU32::MIN).await.unwrap(),
            Hydrated::Absent
        );

        p.flush(&state).await.unwrap();
        assert_eq!(p.checkpoint(), Some(version!(2)));
        let (pos, st) = ss
            .hydrate(&id, NonZeroU32::MIN)
            .await
            .unwrap()
            .into_found()
            .unwrap();
        assert_eq!(pos, version!(2));
        assert_eq!(
            st,
            CountState {
                count: 2,
                total: 30
            }
        );
    }

    #[tokio::test]
    async fn flush_is_a_noop_when_nothing_is_pending() {
        let ss = store();
        let id = TestId("s");
        let (mut p, state) = Projection::load(
            id.clone(),
            CountingProjector,
            EveryNEvents(NonZeroU64::MIN),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();

        // Never advanced: flush must not write a spurious snapshot.
        p.flush(&state).await.unwrap();
        assert_eq!(p.checkpoint(), None);
        assert_eq!(
            ss.hydrate(&id, NonZeroU32::MIN).await.unwrap(),
            Hydrated::Absent
        );
    }

    // ── defensive: a schema-mismatched snapshot starts fresh, but flags a rebuild ─

    #[tokio::test]
    async fn load_stale_schema_starts_from_initial_and_signals_rebuild() {
        let ss = store();
        let id = TestId("s");
        // Pre-commit a v1 snapshot.
        ss.commit(
            &id,
            NonZeroU32::MIN,
            version!(5),
            &CountState {
                count: 99,
                total: 999,
            },
        )
        .await
        .unwrap();

        // Load with schema v2 — the v1 snapshot must not be restored...
        let (p, state) = Projection::load(
            id,
            CountingProjector,
            EveryNEvents(NonZeroU64::MIN),
            &ss,
            NonZeroU32::new(2).unwrap(),
        )
        .await
        .unwrap();
        assert_eq!(p.checkpoint(), None);
        assert_eq!(state, CountState { count: 0, total: 0 });
        // ...but the rebuild is *visible*: a host can tell this apart from a
        // fresh start (which reports `None`) — the whole point of the Stale
        // signal. The invalidated schema version (v1) is reported.
        assert_eq!(p.rebuilding_from(), Some(NonZeroU32::MIN));
    }

    #[tokio::test]
    async fn load_fresh_does_not_signal_rebuild() {
        let ss = store();
        let (p, _state) = Projection::load(
            TestId("s"),
            CountingProjector,
            EveryNEvents(NonZeroU64::MIN),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();
        // A genuinely-new projection is not a rebuild.
        assert_eq!(p.rebuilding_from(), None);
    }

    // ── $all duality (#327): the SAME stepper drives an $all projection ─────
    //
    // The $all position rides beside the item as `(P, StreamKey, Decoded<E>)`
    // — exactly what `.decoded()` yields on a subscribe_all stream — and feeds
    // `advance` whole (the stepper drops the key). `InMemoryAllPos` stands in
    // for fjall's `GlobalSeq`.

    /// `$all` trigger that always fires — the per-event-commit dual of
    /// `EveryNEvents(1)`, which is deliberately `Version`-only (#328).
    struct Always;
    impl PersistTrigger<InMemoryAllPos> for Always {
        fn should_persist(
            &self,
            _old_position: Option<InMemoryAllPos>,
            _new_position: InMemoryAllPos,
            _event_names: impl Iterator<Item: AsRef<str>>,
        ) -> bool {
            true
        }
    }

    fn all_pos(v: u64) -> InMemoryAllPos {
        InMemoryAllPos::new(v).expect("nonzero position")
    }

    /// Stand-in origin key for hand-built `$all` items — the stepper drops it.
    fn all_key() -> StreamKey {
        StreamKey::from_slice(b"origin")
    }

    fn all_store() -> InMemorySnapshotStore<CountState, InMemoryAllPos> {
        InMemorySnapshotStore::new()
    }

    // ── 1. Sequence/Protocol ($all): advance folds and checkpoints the tag ──

    #[tokio::test]
    async fn all_advance_accepts_tuple_items_and_checkpoints_the_all_tag() {
        let ss = all_store();
        let id = TestId("all");
        let (mut p, mut state) =
            Projection::load(id.clone(), CountingProjector, Always, &ss, NonZeroU32::MIN)
                .await
                .unwrap();
        assert_eq!(p.checkpoint(), None);

        // Gappy positions on purpose: $all is monotonic but NOT gapless
        // (aborted appends burn values) — the stepper checkpoints whatever
        // tag arrives. Inner versions are per-stream (two streams, both v1).
        state = p
            .advance(
                state,
                (all_pos(3), all_key(), decoded(TestEvent::Added(10), 1)),
            )
            .await
            .unwrap();
        state = p
            .advance(
                state,
                (all_pos(7), all_key(), decoded(TestEvent::Added(20), 1)),
            )
            .await
            .unwrap();

        assert_eq!(p.checkpoint(), Some(all_pos(7)));
        assert_eq!(
            state,
            CountState {
                count: 2,
                total: 30
            }
        );

        // Persisted together, atomically, under the $all position type.
        let (pos, st) = ss
            .hydrate(&id, NonZeroU32::MIN)
            .await
            .unwrap()
            .into_found()
            .unwrap();
        assert_eq!(pos, all_pos(7));
        assert_eq!(
            st,
            CountState {
                count: 2,
                total: 30
            }
        );
    }

    // ── 2. Lifecycle ($all): commit → reload → resume from the $all tag ─────

    #[tokio::test]
    async fn all_load_resumes_state_and_checkpoint_from_snapshot() {
        let ss = all_store();
        let id = TestId("all");
        {
            let (mut p, state) =
                Projection::load(id.clone(), CountingProjector, Always, &ss, NonZeroU32::MIN)
                    .await
                    .unwrap();
            let _ = p
                .advance(
                    state,
                    (all_pos(9), all_key(), decoded(TestEvent::Added(10), 1)),
                )
                .await
                .unwrap();
        }

        let (mut p2, state2) =
            Projection::load(id, CountingProjector, Always, &ss, NonZeroU32::MIN)
                .await
                .unwrap();
        assert_eq!(
            p2.checkpoint(),
            Some(all_pos(9)),
            "resume point is the $all tag, not a Version"
        );
        assert_eq!(
            state2,
            CountState {
                count: 1,
                total: 10
            }
        );

        // Resume folds onto the restored state at a later (gappy) position.
        let resumed = p2
            .advance(
                state2,
                (all_pos(12), all_key(), decoded(TestEvent::Added(5), 2)),
            )
            .await
            .unwrap();
        assert_eq!(p2.checkpoint(), Some(all_pos(12)));
        assert_eq!(
            resumed,
            CountState {
                count: 2,
                total: 15
            }
        );
    }

    // ── flush semantics ($all) + AfterEventTypes genericity in the stepper ──

    #[tokio::test]
    async fn all_flush_commits_tail_under_a_generic_after_event_types_trigger() {
        let ss = all_store();
        let id = TestId("all");
        // AfterEventTypes is position-generic (#328); "Removed" never arrives,
        // so only flush persists.
        let (mut p, mut state) = Projection::load(
            id.clone(),
            CountingProjector,
            AfterEventTypes::new(&["Removed"]),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();

        state = p
            .advance(
                state,
                (all_pos(2), all_key(), decoded(TestEvent::Added(10), 1)),
            )
            .await
            .unwrap();
        assert_eq!(p.checkpoint(), None, "trigger must not have fired");
        assert_eq!(
            ss.hydrate(&id, NonZeroU32::MIN).await.unwrap(),
            Hydrated::Absent
        );

        p.flush(&state).await.unwrap();
        assert_eq!(p.checkpoint(), Some(all_pos(2)));
        let (pos, st) = ss
            .hydrate(&id, NonZeroU32::MIN)
            .await
            .unwrap()
            .into_found()
            .unwrap();
        assert_eq!(pos, all_pos(2));
        assert_eq!(
            st,
            CountState {
                count: 1,
                total: 10
            }
        );
    }

    // ── attributed fold (#345): the stepper forwards the $all StreamKey ────

    /// Routes each event's value into a per-origin-stream bucket. State maps
    /// raw key bytes → running total. `apply` (keyless) is unreachable for a
    /// correctly driven $all fold and returns `Unattributed`.
    struct RoutingProjector;

    #[derive(Debug, PartialEq, thiserror::Error)]
    enum RoutingError {
        #[error("attributed fold invoked without a stream key")]
        Unattributed,
        #[error("overflow")]
        Overflow,
    }

    impl Projector for RoutingProjector {
        type Event = TestEvent;
        type State = std::collections::HashMap<Vec<u8>, u64>;
        type Error = RoutingError;

        fn initial(&self) -> Self::State {
            std::collections::HashMap::new()
        }

        fn apply(
            &self,
            _state: Self::State,
            _event: &TestEvent,
        ) -> Result<Self::State, RoutingError> {
            Err(RoutingError::Unattributed)
        }

        fn apply_attributed(
            &self,
            mut state: Self::State,
            stream_key: Option<&StreamKey>,
            event: &TestEvent,
        ) -> Result<Self::State, RoutingError> {
            let k = stream_key.ok_or(RoutingError::Unattributed)?;
            let slot = state.entry(k.as_bytes().to_vec()).or_insert(0);
            *slot = match event {
                TestEvent::Added(n) => slot.checked_add(*n).ok_or(RoutingError::Overflow)?,
                TestEvent::Removed(n) => slot.checked_sub(*n).ok_or(RoutingError::Overflow)?,
            };
            Ok(state)
        }
    }

    fn routing_store()
    -> InMemorySnapshotStore<std::collections::HashMap<Vec<u8>, u64>, InMemoryAllPos> {
        InMemorySnapshotStore::new()
    }

    // ── 1. Sequence/protocol (#345): $all items route by origin stream ─────

    #[tokio::test]
    async fn advance_routes_all_items_by_origin_stream() {
        let ss = routing_store();
        let id = TestId("routed");
        let (mut p, mut state) =
            Projection::load(id, RoutingProjector, Always, &ss, NonZeroU32::MIN)
                .await
                .unwrap();

        // Interleaved origins, gappy $all positions: a:Added(10), b:Added(5),
        // a:Added(20).
        state = p
            .advance(
                state,
                (
                    all_pos(3),
                    StreamKey::from_slice(b"a"),
                    decoded(TestEvent::Added(10), 1),
                ),
            )
            .await
            .unwrap();
        state = p
            .advance(
                state,
                (
                    all_pos(7),
                    StreamKey::from_slice(b"b"),
                    decoded(TestEvent::Added(5), 1),
                ),
            )
            .await
            .unwrap();
        state = p
            .advance(
                state,
                (
                    all_pos(12),
                    StreamKey::from_slice(b"a"),
                    decoded(TestEvent::Added(20), 2),
                ),
            )
            .await
            .unwrap();

        assert_eq!(p.checkpoint(), Some(all_pos(12)));
        assert_eq!(
            state,
            std::collections::HashMap::from([(b"a".to_vec(), 30), (b"b".to_vec(), 5)])
        );
    }

    // ── 2. Defensive (#345): the default seam ignores the key ───────────────

    #[tokio::test]
    async fn default_projector_ignores_the_key_on_all_items() {
        let ss = all_store();
        let id = TestId("default-seam");
        let (mut p, mut state) =
            Projection::load(id, CountingProjector, Always, &ss, NonZeroU32::MIN)
                .await
                .unwrap();

        // Same interleaved two-key shape as the routing test; the key must be
        // inert for a projector that does not override `apply_attributed`.
        state = p
            .advance(
                state,
                (
                    all_pos(3),
                    StreamKey::from_slice(b"a"),
                    decoded(TestEvent::Added(10), 1),
                ),
            )
            .await
            .unwrap();
        state = p
            .advance(
                state,
                (
                    all_pos(7),
                    StreamKey::from_slice(b"b"),
                    decoded(TestEvent::Added(5), 1),
                ),
            )
            .await
            .unwrap();
        state = p
            .advance(
                state,
                (
                    all_pos(12),
                    StreamKey::from_slice(b"a"),
                    decoded(TestEvent::Added(20), 2),
                ),
            )
            .await
            .unwrap();

        // Identical to the keyless fold of the same three events.
        assert_eq!(p.checkpoint(), Some(all_pos(12)));
        assert_eq!(
            state,
            CountState {
                count: 3,
                total: 35
            }
        );
    }

    // ── 3. Defensive (#345): None is observable on per-stream items ─────────

    #[tokio::test]
    async fn attributed_projector_sees_none_on_per_stream_items() {
        let ss: InMemorySnapshotStore<std::collections::HashMap<Vec<u8>, u64>, Version> =
            InMemorySnapshotStore::new();
        let (mut p, state) = Projection::load(
            TestId("per-stream"),
            RoutingProjector,
            EveryNEvents(NonZeroU64::MIN),
            &ss,
            NonZeroU32::MIN,
        )
        .await
        .unwrap();

        // A bare Decoded item carries no tag, so the routing projector sees
        // None and surfaces its typed error — absence is not swallowed.
        let err = p
            .advance(state, decoded(TestEvent::Added(1), 1))
            .await
            .unwrap_err();
        assert!(
            matches!(err, ProjectionError::Apply(RoutingError::Unattributed)),
            "expected Apply(Unattributed), got {err:?}"
        );
        assert_eq!(p.checkpoint(), None);
    }

    // ── 4. Lifecycle (#345): attributed fold resumes from the checkpoint ────

    #[tokio::test]
    async fn attributed_projection_resumes_from_committed_checkpoint() {
        let ss = routing_store();
        let id = TestId("routed");

        {
            let (mut p, mut state) =
                Projection::load(id.clone(), RoutingProjector, Always, &ss, NonZeroU32::MIN)
                    .await
                    .unwrap();
            state = p
                .advance(
                    state,
                    (
                        all_pos(3),
                        StreamKey::from_slice(b"a"),
                        decoded(TestEvent::Added(10), 1),
                    ),
                )
                .await
                .unwrap();
            let _ = p
                .advance(
                    state,
                    (
                        all_pos(7),
                        StreamKey::from_slice(b"b"),
                        decoded(TestEvent::Added(5), 1),
                    ),
                )
                .await
                .unwrap();
        }

        // Fresh stepper over the same snapshot store: routed state and the
        // $all checkpoint are restored.
        let (mut p2, state2) = Projection::load(id, RoutingProjector, Always, &ss, NonZeroU32::MIN)
            .await
            .unwrap();
        assert_eq!(p2.checkpoint(), Some(all_pos(7)));
        assert_eq!(
            state2,
            std::collections::HashMap::from([(b"a".to_vec(), 10), (b"b".to_vec(), 5)])
        );

        // Resume: the third event routes onto the restored buckets.
        let resumed = p2
            .advance(
                state2,
                (
                    all_pos(12),
                    StreamKey::from_slice(b"a"),
                    decoded(TestEvent::Added(20), 2),
                ),
            )
            .await
            .unwrap();
        assert_eq!(p2.checkpoint(), Some(all_pos(12)));
        assert_eq!(
            resumed,
            std::collections::HashMap::from([(b"a".to_vec(), 30), (b"b".to_vec(), 5)])
        );
    }
}