vsrg 0.6.0

Data structures for vertical scrolling rhythm games
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
use crate::notes::relations::{AssignParterToNote, AssignPartnersToNote};
use crate::notes::{NoteState, NotesStorage, NotesStorageEditHook};

// For future users:
// - It's not immediately clear whether storing parent-child relationship in an auxiliary
//   field in notes storage is useful. Therefore we skip it for now to simplify the API.
// - These relationship cannot represent relationship between notes of the same type,
//   or circular relationship, since those would cause an infinite loop when removing the
//   notes. A separate dedicated relationship is necessary.
//
// If you need these features, then let us know by opening an issue.

/// Reads the parent of a note.
///
/// # Requirements
/// Returns [`Some`] with the parent's id if the note declares itself a child
/// of that note, or [`None`] if it has no parent.
pub type ParentIdOf<S> = fn(&<S as NotesStorage>::NoteEnum) -> Option<u64>;

/// Remove any parent linking from a child note.
///
/// # Requirements
/// - This operation must be *stateless*: how it writes should not depend on the current runtime
///   state of the note.
/// - This operation must be *idempotent*: multiple applications of this callback on the same note
///   is the same as only one application.
pub type DetachNote<S> = fn(<S as NotesStorage>::NoteMutEnum<'_>);

/// What happens to a child note whose parent is removed.
#[derive(Debug, Clone, Copy)]
pub enum OrphanPolicy<S: NotesStorage> {
    /// Detach the child notes from its parent, without removing the note.
    ///
    /// # Remarks
    /// You must provide a callback to detach the note.
    ///
    /// # Requirements
    /// - This operation must be *stateless*: how it writes should not depend on the current runtime
    ///   state of the note.
    /// - This operation must be *idempotent*: multiple applications of this callback on the same note
    ///   is the same as only one application.
    Detach(DetachNote<S>),

    /// Remove the orphaned children from the notes storage.
    Remove,
}

/// Parent-child relationship.
///
/// # Remarks
/// This assumes each child note stores the id of its parent note (and not the reverse where parent
/// stores ids of its children notes), and wants to cache data from its parent notes into its
/// runtime state. For example: tap notes belonging to a parent curve caching the parent curve's position
/// at its time.
pub struct ParentChild<S: NotesStorage> {
    parent_note_type: S::NoteTypeEnum,
    child_note_type: S::NoteTypeEnum,

    parent_id_of: ParentIdOf<S>,
    link_parent_to_child: Option<AssignParterToNote<S>>,
    link_children_to_parent: Option<AssignPartnersToNote<S>>,
    orphan_policy: OrphanPolicy<S>,

    scratch_children: Vec<S::NoteSnapshotEnum>,
}

impl<S: NotesStorage> ParentChild<S> {
    /// Creates a relationship with no linking callbacks.
    ///
    /// # Remarks
    /// Continue configuring the relationship by calling its builder methods.
    ///
    /// Removing a parent removes its children by default; use [Self::orphan_policy] to configure
    /// detachment instead.
    pub const fn new(
        parent_note_type: S::NoteTypeEnum,
        child_note_type: S::NoteTypeEnum,
        parent_id_of: ParentIdOf<S>,
    ) -> Self {
        Self {
            parent_note_type,
            child_note_type,
            parent_id_of,
            link_parent_to_child: None,
            link_children_to_parent: None,
            orphan_policy: OrphanPolicy::Remove,
            scratch_children: Vec::new(),
        }
    }

    /// Assign the parent to the child.
    ///
    /// # Remarks
    /// The note can copy any data from the partner note as needed. For example: copying the
    /// parent curve's position to the child note.
    ///
    /// # Requirements
    /// - This operation must be *stateless*: how it writes should not depend on the current runtime
    ///   state of the note.
    /// - This operation must be *idempotent*: multiple applications of this callback on the same note
    ///   is the same as only one application.
    ///
    /// Effectively, it should sets the parent rather than appending the parent to the note.
    pub const fn link_parent_to_child(mut self, callback: AssignParterToNote<S>) -> Self {
        self.link_parent_to_child = Some(callback);
        self
    }

    /// Assign the children to the parent.
    ///
    /// # Remarks
    /// The note can copy any data from the partner notes as needed.
    /// The slice contains the all children notes whose stored parent id is the parent note.
    /// Empty slice means it no longer has any children.
    ///
    /// # Requirements
    /// - This operation must be *stateless*: how it writes should not depend on the current runtime
    ///   state of the note.
    /// - This operation must be *idempotent*: multiple applications of this callback on the same note
    ///   is the same as only one application.
    ///
    /// Effectively, it should sets the children rather than appending the children to the note.
    pub const fn link_children_to_parent(mut self, callback: AssignPartnersToNote<S>) -> Self {
        self.link_children_to_parent = Some(callback);
        self
    }

    /// Sets whether removing a parent removes or detaches its children.
    pub const fn orphan_policy(mut self, value: OrphanPolicy<S>) -> Self {
        self.orphan_policy = value;
        self
    }
}
impl<S: NotesStorage> ParentChild<S> {
    fn post_add_one(&mut self, storage: &mut S, note_type: S::NoteTypeEnum, note_id: u64) {
        if note_type != self.child_note_type {
            return;
        }

        let Some(just_added) = storage
            .query_notes_ref([(note_id, note_type)].into_iter())
            .map(|x| S::NoteEnum::from(&x))
            .next()
        else {
            return;
        };

        let Some(parent_id) = (self.parent_id_of)(&just_added) else {
            return;
        };
        drop(just_added);

        let Some(parent) = storage
            .query_notes([(parent_id, self.parent_note_type)].into_iter())
            .next()
        else {
            return;
        };

        if let Some(link) = self.link_parent_to_child {
            storage.query_notes_mut([(note_id, note_type)].into_iter(), |note| {
                link(note, parent.clone());
            })
        }

        if let Some(link) = self.link_children_to_parent {
            self.scratch_children.clear();
            self.scratch_children.extend(
                storage
                    .all_notes_ref_of_type(self.child_note_type)
                    .filter_map(|n| {
                        (self.parent_id_of)(&S::NoteEnum::from(&n))
                            .is_some_and(|i| parent_id == i)
                            .then_some(n.to_snapshot())
                    }),
            );
            storage.query_notes_mut([(parent_id, self.parent_note_type)].into_iter(), |parent| {
                link(parent, &self.scratch_children)
            });
        }
    }

    fn pre_remove_one(
        &mut self,
        storage: &mut S,
        note_type: <S as NotesStorage>::NoteTypeEnum,
        note_id: u64,
        removal_batch: &[S::NoteSnapshotEnum],
    ) {
        if note_type != self.child_note_type {
            return;
        }

        let Some(link) = self.link_children_to_parent else {
            return;
        };

        let Some(removing) = storage
            .query_notes_ref([(note_id, note_type)].into_iter())
            .map(|x| S::NoteEnum::from(&x))
            .next()
        else {
            return;
        };

        let Some(parent_id) = (self.parent_id_of)(&removing) else {
            return;
        };
        drop(removing);

        self.scratch_children.clear();
        self.scratch_children.extend(
            storage
                .all_notes_ref_of_type(self.child_note_type)
                .filter_map(|n| {
                    let matching_parent =
                        (self.parent_id_of)(&S::NoteEnum::from(&n)).is_some_and(|i| parent_id == i);
                    let is_removing = removal_batch.iter().any(|removed| {
                        removed.id() == n.id()
                            && S::NoteTypeEnum::from(removed) == self.child_note_type
                    });
                    (matching_parent && !is_removing).then(|| n.to_snapshot())
                }),
        );
        storage.query_notes_mut([(parent_id, self.parent_note_type)].into_iter(), |parent| {
            link(parent, &self.scratch_children)
        });
    }

    fn post_remove_one(&mut self, storage: &mut S, just_removed: &S::NoteSnapshotEnum) {
        if S::NoteTypeEnum::from(just_removed) != self.parent_note_type {
            return;
        }

        match self.orphan_policy {
            OrphanPolicy::Remove => {
                // remove_notes consumes its input, so this buffer cannot be reused.
                let children = storage
                    .all_notes_ref_of_type(self.child_note_type)
                    .filter_map(|n| {
                        let id = n.id();
                        (self.parent_id_of)(&S::NoteEnum::from(&n))
                            .is_some_and(|id| id == just_removed.id())
                            .then_some((id, self.child_note_type))
                    })
                    .collect::<Vec<_>>();
                storage.remove_notes(children);
            }

            OrphanPolicy::Detach(detach) => {
                storage.all_notes_mut_of_type(self.child_note_type, |candidate| {
                    if (self.parent_id_of)(&(&candidate).into())
                        .is_some_and(|id| id == just_removed.id())
                    {
                        detach(candidate);
                    }
                })
            }
        }
    }

    fn pre_update_one(
        &mut self,
        storage: &mut S,
        replacing_id: u64,
        replacing_note: &<S as NotesStorage>::NoteEnum,
        replacements: &[(u64, S::NoteEnum)],
    ) {
        // If a note has changed its parent id, then we need to notify the previous parent.
        let Some(link) = self.link_children_to_parent else {
            return;
        };

        let note_type = S::NoteTypeEnum::from(replacing_note);
        if note_type != self.child_note_type {
            return;
        }

        let Some(note_ref) = storage
            .query_notes_ref([(replacing_id, note_type)].into_iter())
            .map(|x| S::NoteEnum::from(&x))
            .next()
        else {
            return;
        };

        let Some(current_parent_id) = (self.parent_id_of)(&note_ref) else {
            return;
        };
        drop(note_ref);

        let new_parent_id = (self.parent_id_of)(replacing_note);
        if new_parent_id == Some(current_parent_id) {
            return;
        }

        self.scratch_children.clear();
        self.scratch_children.extend(
            storage
                .all_notes_ref_of_type(self.child_note_type)
                .filter_map(|n| {
                    let matching_parent = (self.parent_id_of)(&S::NoteEnum::from(&n))
                        .is_some_and(|i| current_parent_id == i);
                    let will_change_parent = replacements.iter().any(|(id, replacement)| {
                        *id == n.id()
                            && S::NoteTypeEnum::from(replacement) == self.child_note_type
                            && (self.parent_id_of)(replacement) != Some(current_parent_id)
                    });
                    (matching_parent && !will_change_parent).then(|| n.to_snapshot())
                }),
        );
        storage.query_notes_mut(
            [(current_parent_id, self.parent_note_type)].into_iter(),
            |parent| link(parent, &self.scratch_children),
        );
    }

    fn post_update_one(
        &mut self,
        storage: &mut S,
        _before: &S::NoteSnapshotEnum,
        after: &S::NoteSnapshotEnum,
    ) {
        let note_type = S::NoteTypeEnum::from(after);
        if note_type == self.child_note_type {
            // Unconditionally link child to the new parent, which is the same as adding the note.
            // Unlinking is already handled in pre_update
            self.post_add_one(storage, note_type, after.id());
        } else if note_type == self.parent_note_type {
            // Scan all notes of children note type, for any notes whose parent id matches the
            // updated note. Then link them
            let Some(link) = self.link_parent_to_child else {
                return;
            };
            let Some(parent) = storage
                .query_notes([(after.id(), note_type)].into_iter())
                .next()
            else {
                return;
            };

            let children = storage
                .all_notes_ref_of_type(self.child_note_type)
                .filter_map(|child| {
                    let child_note = S::NoteEnum::from(&child);
                    ((self.parent_id_of)(&child_note) == Some(after.id())).then_some(child.id())
                })
                .collect::<Vec<_>>();

            for child_id in children {
                storage.query_notes_mut([(child_id, self.child_note_type)].into_iter(), |child| {
                    link(child, parent.clone())
                });
            }
        }
    }
}

impl<S: NotesStorage> NotesStorageEditHook<S> for ParentChild<S> {
    fn post_add(&mut self, storage: &mut S, notes: &[(u64, S::NoteTypeEnum)]) {
        for &(id, ty) in notes {
            self.post_add_one(storage, ty, id);
        }
    }
    fn pre_remove(&mut self, storage: &mut S, notes: &[S::NoteSnapshotEnum]) {
        for note in notes {
            self.pre_remove_one(storage, S::NoteTypeEnum::from(note), note.id(), notes);
        }
    }
    fn post_remove(&mut self, storage: &mut S, notes: &[S::NoteSnapshotEnum]) {
        for note in notes {
            self.post_remove_one(storage, note);
        }
    }
    fn pre_update(&mut self, storage: &mut S, notes: &mut [(u64, S::NoteEnum)]) {
        for (id, note) in notes.iter() {
            self.pre_update_one(storage, *id, note, notes);
        }
    }
    fn post_update(
        &mut self,
        storage: &mut S,
        notes: &[(S::NoteSnapshotEnum, S::NoteSnapshotEnum)],
    ) {
        for (before, after) in notes {
            self.post_update_one(storage, before, after);
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::notes::relations::test_common::{RelLong, RelShort, World, long_at, short_at};
    use crate::notes::{LongNoteTypeStorage, ShortNoteTypeStorage};

    crate::generate_notes_storage! {
        enum Kind,
        enum Note,
        enum Snapshot,
        enum NoteRef,
        enum NoteMut,
        struct Storage {
            note_type Child(RelShort) => children: ShortNoteTypeStorage<RelShort>,
            note_type Parent(RelLong) => parents: LongNoteTypeStorage<RelLong>,
            edit_hook ParentChild::<Storage>::new(Kind::Parent, Kind::Child, |note| match note {
                    Note::Child(child) => Some(child.pos as u64),
                    _ => None,
                }).link_parent_to_child(|child, parent| {
                    if let (NoteMut::Child(child), Snapshot::Parent(parent)) = (child, parent) {
                        *child.runtime_data.parent_id = Some(parent.id());
                        *child.runtime_data.matching_ids = vec![(parent.note.pos as u64, false)];
                    }
                }).link_children_to_parent(|parent, children| {
                    if let NoteMut::Parent(parent) = parent {
                        *parent.runtime_data.matching_ids = children.iter().map(|n| (n.id(), false)).collect();
                    }
                }),
        }
    }

    fn fixture(world: &mut World) -> Storage {
        Storage::with_notes(
            vec![
                Note::Parent(long_at(0.0, 10.0, 0)),
                Note::Parent(long_at(20.0, 10.0, 0)),
                Note::Child(short_at(1.0, 1)),
                Note::Child(short_at(2.0, 1)),
            ],
            &world.note_groups,
            &world.tempo_tracks,
            &world.scroll_tracks,
        )
    }

    fn children(storage: &Storage, id: u64) -> Vec<u64> {
        match storage
            .query_notes_ref([(id, Kind::Parent)].into_iter())
            .next()
            .unwrap()
        {
            NoteRef::Parent(parent) => parent
                .runtime_data
                .matching_ids
                .iter()
                .map(|(id, _)| *id)
                .collect(),
            _ => unreachable!(),
        }
    }

    #[test]
    fn removing_children_together_excludes_the_entire_batch() {
        let mut world = World::new(0);
        let mut storage = fixture(&mut world);
        assert_eq!(children(&storage, 1), vec![1, 2]);
        storage.remove_notes(vec![(1, Kind::Child), (2, Kind::Child)]);
        assert!(children(&storage, 1).is_empty());
    }

    #[test]
    fn moving_children_together_refreshes_both_parents() {
        let mut world = World::new(0);
        let mut storage = fixture(&mut world);
        storage.replace_notes(
            &world.note_groups,
            &world.tempo_tracks,
            &world.scroll_tracks,
            vec![
                (1, Note::Child(short_at(1.0, 2))),
                (2, Note::Child(short_at(2.0, 2))),
            ],
        );
        assert!(children(&storage, 1).is_empty());
        assert_eq!(children(&storage, 2), vec![1, 2]);
    }

    #[test]
    fn removing_parent_and_child_together_cascades_remaining_children() {
        let mut world = World::new(0);
        let mut storage = fixture(&mut world);
        storage.remove_notes(vec![(1, Kind::Parent), (1, Kind::Child)]);
        assert_eq!(storage.all_notes_of_type(Kind::Child).count(), 0);
        assert_eq!(storage.all_notes_of_type(Kind::Parent).count(), 1);
    }

    fn add(world: &mut World, storage: &mut Storage, note: Note) {
        storage.add_note(
            &world.note_groups,
            &world.tempo_tracks,
            &world.scroll_tracks,
            note,
        );
    }

    fn child_parent(storage: &Storage, id: u64) -> (Option<u64>, Vec<(u64, bool)>) {
        match storage
            .query_notes_ref([(id, Kind::Child)].into_iter())
            .next()
            .unwrap()
        {
            NoteRef::Child(child) => (
                *child.runtime_data.parent_id,
                child.runtime_data.matching_ids.clone(),
            ),
            _ => unreachable!(),
        }
    }

    #[test]
    fn adding_child_copies_the_selected_parents_position() {
        let mut world = World::new(0);
        let mut storage = Storage::new();
        add(
            &mut world,
            &mut storage,
            Note::Parent(long_at(0.0, 10.0, 17)),
        );
        add(
            &mut world,
            &mut storage,
            Note::Parent(long_at(20.0, 10.0, 42)),
        );
        add(&mut world, &mut storage, Note::Child(short_at(1.0, 2)));
        assert_eq!(child_parent(&storage, 1), (Some(2), vec![(42, false)]));
        assert!(children(&storage, 1).is_empty());
        assert_eq!(children(&storage, 2), vec![1]);
    }

    #[test]
    fn replacing_child_parent_refreshes_its_position_and_both_parents() {
        let mut world = World::new(0);
        let mut storage = Storage::new();
        add(
            &mut world,
            &mut storage,
            Note::Parent(long_at(0.0, 10.0, 17)),
        );
        add(
            &mut world,
            &mut storage,
            Note::Parent(long_at(20.0, 10.0, 42)),
        );
        add(&mut world, &mut storage, Note::Child(short_at(1.0, 1)));
        assert_eq!(child_parent(&storage, 1), (Some(1), vec![(17, false)]));
        storage.replace_note(
            &world.note_groups,
            &world.tempo_tracks,
            &world.scroll_tracks,
            1,
            Note::Child(short_at(1.0, 2)),
        );
        assert_eq!(child_parent(&storage, 1), (Some(2), vec![(42, false)]));
        assert!(children(&storage, 1).is_empty());
        assert_eq!(children(&storage, 2), vec![1]);
    }

    #[test]
    fn replacing_parent_children_refreshes() {
        let mut world = World::new(0);
        let mut storage = Storage::new();
        add(
            &mut world,
            &mut storage,
            Note::Parent(long_at(0.0, 10.0, 17)),
        );
        add(&mut world, &mut storage, Note::Child(short_at(1.0, 1)));
        assert_eq!(child_parent(&storage, 1), (Some(1), vec![(17, false)]));
        storage.replace_note(
            &world.note_groups,
            &world.tempo_tracks,
            &world.scroll_tracks,
            1,
            Note::Parent(long_at(0.0, 10.0, 42)),
        );
        assert_eq!(child_parent(&storage, 1), (Some(1), vec![(42, false)]));
        assert_eq!(children(&storage, 1), vec![1]);
    }

    #[test]
    fn removing_parent_cascades_only_its_children() {
        let mut world = World::new(0);
        let mut storage = fixture(&mut world);
        add(&mut world, &mut storage, Note::Child(short_at(3.0, 2)));
        storage.remove_note(Kind::Parent, 1);
        assert!(
            storage
                .query_notes([(1, Kind::Child), (2, Kind::Child)].into_iter())
                .next()
                .is_none()
        );
        assert_eq!(child_parent(&storage, 3).0, Some(2));
        assert_eq!(children(&storage, 2), vec![3]);
    }

    #[test]
    fn removing_one_child_preserves_the_other_link() {
        let mut world = World::new(0);
        let mut storage = fixture(&mut world);
        storage.remove_note(Kind::Child, 1);
        assert!(
            storage
                .query_notes([(1, Kind::Child)].into_iter())
                .next()
                .is_none()
        );
        assert_eq!(children(&storage, 1), vec![2]);
        assert_eq!(child_parent(&storage, 2).0, Some(1));
        storage.remove_note(Kind::Child, 2);
        assert!(children(&storage, 1).is_empty());
    }

    mod detach {
        use super::*;
        crate::generate_notes_storage! {
            enum Kind,
            enum Note,
            enum Snapshot,
            enum NoteRef,
            enum NoteMut,
            struct Storage {
                note_type Child(RelShort) => children: ShortNoteTypeStorage<RelShort>,
                note_type Parent(RelLong) => parents: LongNoteTypeStorage<RelLong>,
                edit_hook ParentChild::<Storage>::new(Kind::Parent, Kind::Child, |note| match note {
                        Note::Child(child) if child.pos != 0 => Some(child.pos as u64),
                        _ => None,
                    }).link_parent_to_child(|child, parent| {
                        if let NoteMut::Child(child) = child {
                            *child.runtime_data.parent_id = Some(parent.id());
                        }
                    }).orphan_policy(OrphanPolicy::Detach(|child| {
                        if let NoteMut::Child(child) = child {
                            // Detachment clears runtime linkage; authored parent IDs are immutable here.
                            *child.runtime_data.parent_id = None;
                        }
                    })),
            }
        }

        #[test]
        fn removing_parent_detaches_children_and_preserves_unrelated_links() {
            let world = World::new(0);
            let mut storage = Storage::with_notes(
                vec![
                    Note::Parent(long_at(0.0, 10.0, 17)),
                    Note::Parent(long_at(20.0, 10.0, 42)),
                    Note::Child(short_at(1.0, 1)),
                    Note::Child(short_at(2.0, 2)),
                ],
                &world.note_groups,
                &world.tempo_tracks,
                &world.scroll_tracks,
            );
            storage.remove_note(Kind::Parent, 1);
            assert_eq!(storage.all_notes_of_type(Kind::Child).count(), 2);
            for (id, expected) in [(1, None), (2, Some(2))] {
                match storage
                    .query_notes_ref([(id, Kind::Child)].into_iter())
                    .next()
                    .unwrap()
                {
                    NoteRef::Child(child) => {
                        assert_eq!(*child.runtime_data.parent_id, expected);
                        assert_eq!(*child.value_data.0 as u64, id);
                    }
                    _ => unreachable!(),
                }
            }
        }
    }

    fn assert_matches_scan(storage: &Storage) {
        for snapshot in storage.all_notes_of_type(Kind::Parent) {
            let parent = snapshot.id();
            let position = match snapshot {
                Snapshot::Parent(n) => n.note.pos,
                _ => unreachable!(),
            };
            let mut expected: Vec<_> = storage
                .all_notes_of_type(Kind::Child)
                .filter_map(|n| match n {
                    Snapshot::Child(n) if n.note.pos as u64 == parent => Some(n.id()),
                    _ => None,
                })
                .collect();
            expected.sort_unstable();
            let mut actual = children(storage, parent);
            actual.sort_unstable();
            assert_eq!(actual, expected.clone());
            for id in expected {
                assert_eq!(
                    child_parent(storage, id),
                    (Some(parent), vec![(position as u64, false)])
                );
            }
        }
    }

    use proptest::prelude::*;

    proptest! {
        #[test]
        fn random_child_edits_match_manual_scan(
            ops in prop::collection::vec((0u8..6, 0usize..20, 1u32..=2), 1..40)
        ) {
            let mut world = World::new(0);
            let mut storage = fixture(&mut world);
            for (op, index, parent_index) in ops {
                let parents: Vec<_> = storage.all_notes_of_type(Kind::Parent).map(|n| n.id()).collect();
                if op == 5 || parents.is_empty() {
                    add(&mut world, &mut storage, Note::Parent(long_at(index as f64, 10.0, index as u32)));
                } else if op == 4 {
                    let parent = parents[index % parents.len()];
                    let removed_children = children(&storage, parent);
                    storage.remove_note(Kind::Parent, parent);
                    for id in removed_children {
                        prop_assert!(storage.query_notes([(id, Kind::Child)].into_iter()).next().is_none());
                    }
                } else {
                let parent = parents[parent_index as usize % parents.len()] as u32;
                let ids: Vec<_> = storage.all_notes_of_type(Kind::Child).map(|n| n.id()).collect();
                if op == 0 || ids.is_empty() {
                    add(&mut world, &mut storage, Note::Child(short_at(index as f64, parent)));
                } else {
                    let id = ids[index % ids.len()];
                    if op == 1 {
                        storage.remove_note(Kind::Child, id);
                    } else if op == 2 {
                        storage.replace_note(
                            &world.note_groups,
                            &world.tempo_tracks,
                            &world.scroll_tracks,
                            id,
                            Note::Child(short_at(index as f64, parent))
                        );
                    } else {
                        storage.remove_notes(ids.into_iter().take(2).map(|id| (id, Kind::Child)).collect());
                    }
                }
                }
                assert_matches_scan(&storage);
                storage.children.health_check();
                storage.parents.health_check();
            }
        }
    }
}