Skip to main content

tilo_resource/
recording.rs

1//! A stretch of a resource's history as a document of its own: what a report
2//! carries so its reader can step through the states the reporter saw
3//! (`docs/architecture/session-replay.md`).
4//!
5//! A resource's document already records every change with its author, time
6//! and action. [`record`] takes the changes of a window of time and writes
7//! them into a new document: the first change writes the resource's state at
8//! the start of the window, and each later one is an original change's
9//! effect, read as Automerge's own diff between the two frontiers and
10//! written with the original's actor, timestamp and action entry. Nothing
11//! from before the window is in it; an Automerge change graph cannot be
12//! served in part, so handing out the resource itself would hand out all of
13//! its history.
14//!
15//! The recording is a document of the same shape as the resource, so the
16//! app's views draw it and History steps through it: its [`history`]
17//! entries are the steps, and [`Recording::heads_at`] is the state at one.
18//!
19//! [`history`]: crate::history
20
21use std::collections::{BTreeMap, HashMap, HashSet};
22
23use automerge::marks::{ExpandMark, Mark};
24use automerge::transaction::{CommitOptions, Transactable};
25use automerge::{
26    ActorId, Automerge, ChangeHash, ObjId, ObjType, Patch, PatchAction, Prop, ROOT, ReadDoc,
27    ScalarValue, Value,
28};
29use tilo_actions::{ActionContext, ChangeKind, EntryReader};
30use tilo_sort::CompactSort as _;
31
32use crate::history::{Version, committed_versions};
33use crate::model::Doc;
34
35/// Root keys a recording leaves out: the recorded record's own identity and
36/// the records it indexes. A recording is not that record.
37const LEFT_OUT: [&str; 2] = ["tilo:record", "tilo:records"];
38
39/// How large a recording may be.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub struct Limits {
42    /// Changes after the start state. A longer window starts later, so the
43    /// last changes before the end are always kept.
44    pub steps: usize,
45    /// Saved bytes of the whole recording.
46    pub bytes: usize,
47}
48
49impl Default for Limits {
50    fn default() -> Self {
51        Self {
52            steps: 2_000,
53            bytes: 16 * 1024 * 1024,
54        }
55    }
56}
57
58#[derive(Debug, thiserror::Error, PartialEq, Eq)]
59pub enum RecordingError {
60    #[error("the end of the recording is not in this document's history")]
61    UnknownEnd,
62    #[error("the recording would take {0} bytes, more than it may")]
63    TooLarge(usize),
64    #[error("the recording holds more steps than it may")]
65    TooManySteps,
66    #[error("this is not a recording: {0}")]
67    Invalid(String),
68    #[error("could not write the recording: {0}")]
69    Write(String),
70    #[error("the recording does not reproduce the recorded state")]
71    Diverged,
72}
73
74impl From<automerge::AutomergeError> for RecordingError {
75    fn from(error: automerge::AutomergeError) -> Self {
76        Self::Write(error.to_string())
77    }
78}
79
80/// One step of a recording, by the change it reproduces.
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct Step {
83    /// The recorded document's change.
84    pub original: ChangeHash,
85    /// The recording's change that reproduces it.
86    pub recorded: ChangeHash,
87}
88
89/// A recording: its document and what it covers.
90pub struct Recording {
91    doc: Doc,
92    /// Milliseconds since the Unix epoch at which the start state stands.
93    pub from_ms: i64,
94    /// Milliseconds since the Unix epoch of the last step, or `from_ms`.
95    pub to_ms: i64,
96    /// The steps after the start, oldest first. Empty for a loaded
97    /// recording, whose original changes are not known.
98    pub steps: Vec<Step>,
99}
100
101/// The changes of `source` that `upto` holds, from the first at or after
102/// `from_ms` (milliseconds since the Unix epoch), recorded on the state
103/// before them.
104///
105/// # Errors
106///
107/// [`RecordingError::UnknownEnd`] when `source` lacks a change of `upto`;
108/// [`RecordingError::TooLarge`] past `limits.bytes`;
109/// [`RecordingError::Diverged`] when the written recording does not end in
110/// `source`'s state at `upto`.
111pub fn record(
112    source: &Doc,
113    from_ms: i64,
114    upto: &[ChangeHash],
115    limits: &Limits,
116) -> Result<Recording, RecordingError> {
117    let document = source.committed_document();
118    let ordered = ancestry(document, upto)?;
119    let Window { start, from_ms, .. } = window(&ordered, from_ms, limits);
120    let mut writer = Writer {
121        source: document,
122        target: Doc::new(),
123        objects: HashMap::from([(ROOT, ROOT)]),
124        authored: HashSet::new(),
125    };
126    let mut entries = EntryReader::default();
127    for change in ordered.iter().take(start) {
128        entries.read(&change.actor, change.message.as_deref());
129    }
130    let start_heads = frontier(ordered.get(..start).unwrap_or(&[]));
131    writer.write(&[], &start_heads)?;
132    let begun = ActionContext::default().with_change(ChangeKind::External);
133    let start_time = from_ms.div_euclid(1000);
134    writer.commit(start_time, begun.change_message().as_deref());
135    let mut steps = Vec::new();
136    let mut before = start_heads;
137    for (at, change) in ordered.iter().enumerate().skip(start) {
138        let after = frontier(ordered.get(..=at).unwrap_or(&[]));
139        writer.target.set_actor(change.actor.clone());
140        writer.write(&before, &after)?;
141        let entry = entries.read(&change.actor, change.message.as_deref());
142        let message = match change.message.as_deref() {
143            Some(text) if ActionContext::continued_gesture(text).is_some() => {
144                entry.and_then(|entry| entry.change_message())
145            }
146            text => text.map(str::to_owned),
147        };
148        steps.push(Step {
149            original: change.hash,
150            recorded: writer.commit(change.time_s, message.as_deref()),
151        });
152        before = after;
153    }
154    let mut doc = writer.target;
155    let heads = doc.get_heads();
156    if !same_state(document, &before, doc.committed_document(), &heads)? {
157        return Err(RecordingError::Diverged);
158    }
159    let size = doc
160        .save()
161        .len()
162        .saturating_add(tilo_content::RECORDING_MAGIC.len());
163    if size > limits.bytes {
164        return Err(RecordingError::TooLarge(size));
165    }
166    let to_ms = window(&ordered, from_ms, limits).to_ms;
167    Ok(Recording {
168        doc,
169        from_ms,
170        to_ms,
171        steps,
172    })
173}
174
175/// What [`record`] would record of `source` with the same arguments, read
176/// from the changes' metadata alone: nothing is written.
177///
178/// # Errors
179///
180/// [`RecordingError::UnknownEnd`] when `source` lacks a change of `upto`.
181pub fn plan(
182    source: &Doc,
183    from_ms: i64,
184    upto: &[ChangeHash],
185    limits: &Limits,
186) -> Result<Planned, RecordingError> {
187    let ordered = ancestry(source.committed_document(), upto)?;
188    let window = window(&ordered, from_ms, limits);
189    Ok(Planned {
190        from_ms: window.from_ms,
191        to_ms: window.to_ms,
192        steps: ordered.len().saturating_sub(window.start),
193    })
194}
195
196/// What a recording would hold, before it is made ([`plan`]).
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
198pub struct Planned {
199    pub from_ms: i64,
200    pub to_ms: i64,
201    pub steps: usize,
202}
203
204/// Where a recording of `ordered` from `from_ms` starts within `limits`.
205struct Window {
206    /// The first change recorded as a step.
207    start: usize,
208    from_ms: i64,
209    to_ms: i64,
210}
211
212fn window(ordered: &[Change], from_ms: i64, limits: &Limits) -> Window {
213    let times: Vec<i64> = ordered
214        .iter()
215        .map(|change| change.time_s.saturating_mul(1000))
216        .collect();
217    let mut start = times.iter().take_while(|time| **time < from_ms).count();
218    let mut from_ms = from_ms;
219    if ordered.len().saturating_sub(start) > limits.steps {
220        start = ordered.len().saturating_sub(limits.steps);
221        from_ms = times.get(start).copied().unwrap_or(from_ms);
222    }
223    let to_ms = times
224        .last()
225        .copied()
226        .filter(|_| ordered.len() > start)
227        .unwrap_or(from_ms);
228    Window {
229        start,
230        from_ms,
231        to_ms: to_ms.max(from_ms),
232    }
233}
234
235impl Recording {
236    /// Read a recording from its saved `bytes`, within `limits`.
237    ///
238    /// # Errors
239    ///
240    /// Refuses bytes past `limits.bytes`, a document that does not start
241    /// with a recording's start state, or one with more steps than
242    /// `limits.steps`.
243    pub fn load(bytes: &[u8], limits: &Limits) -> Result<Self, RecordingError> {
244        if bytes.len() > limits.bytes {
245            return Err(RecordingError::TooLarge(bytes.len()));
246        }
247        let saved = bytes
248            .strip_prefix(tilo_content::RECORDING_MAGIC)
249            .ok_or_else(|| RecordingError::Invalid("it has no recording header".into()))?;
250        let doc = Doc::load(saved).map_err(|error| RecordingError::Invalid(error.to_string()))?;
251        let versions = committed_versions(&doc);
252        let (first, rest) = versions
253            .split_first()
254            .ok_or_else(|| RecordingError::Invalid("it has no start".into()))?;
255        let begins = first
256            .context
257            .as_ref()
258            .is_some_and(|context| context.change == ChangeKind::External);
259        let has_deps = doc
260            .committed_document()
261            .get_change_meta_by_hash(&first.hash)
262            .is_none_or(|meta| !meta.deps.is_empty());
263        if !begins || has_deps {
264            return Err(RecordingError::Invalid(
265                "it does not start with a state".into(),
266            ));
267        }
268        if rest.len() > limits.steps {
269            return Err(RecordingError::TooManySteps);
270        }
271        Ok(Self {
272            from_ms: first.time_ms,
273            to_ms: rest.last().map_or(first.time_ms, |last| last.time_ms),
274            doc,
275            steps: Vec::new(),
276        })
277    }
278
279    /// The recording's document: a document of the recorded resource's
280    /// shape whose history is the recording.
281    #[must_use]
282    pub fn doc(&self) -> &Doc {
283        &self.doc
284    }
285
286    /// The saved bytes, behind the recording header
287    /// ([`tilo_content::RECORDING_MAGIC`]) that says what they are: what a
288    /// report carries and what the recorded app opens.
289    #[must_use]
290    pub fn bytes(&self) -> Vec<u8> {
291        let mut bytes = tilo_content::RECORDING_MAGIC.to_vec();
292        bytes.extend(self.doc.clone().save());
293        bytes
294    }
295
296    /// The start state and every step after it, oldest first, as History
297    /// lists them.
298    #[must_use]
299    pub fn versions(&self) -> Vec<Version> {
300        committed_versions(&self.doc)
301    }
302
303    /// How many steps follow the start state.
304    #[must_use]
305    pub fn step_count(&self) -> usize {
306        self.versions().len().saturating_sub(1)
307    }
308
309    /// The heads of the state at `step`: 0 is the start state, `n` the
310    /// state after the `n`th step. `None` past the last step.
311    #[must_use]
312    pub fn heads_at(&self, step: usize) -> Option<Vec<ChangeHash>> {
313        let versions = self.versions();
314        // Each step depends on the one before it: the frontier is the step.
315        versions.get(step).map(|version| vec![version.hash])
316    }
317}
318
319/// One change of the recorded window, as its metadata reads.
320struct Change {
321    hash: ChangeHash,
322    deps: Vec<ChangeHash>,
323    actor: ActorId,
324    time_s: i64,
325    message: Option<String>,
326}
327
328/// The changes `upto` holds, in causal order.
329fn ancestry(document: &Automerge, upto: &[ChangeHash]) -> Result<Vec<Change>, RecordingError> {
330    let mut held = HashSet::new();
331    let mut pending = upto.to_vec();
332    while let Some(hash) = pending.pop() {
333        if !held.insert(hash) {
334            continue;
335        }
336        let meta = document
337            .get_change_meta_by_hash(&hash)
338            .ok_or(RecordingError::UnknownEnd)?;
339        pending.extend(meta.deps.iter().copied());
340    }
341    Ok(document
342        .get_changes_meta(&[])
343        .into_iter()
344        .filter(|meta| held.contains(&meta.hash))
345        .map(|meta| Change {
346            hash: meta.hash,
347            deps: meta.deps.clone(),
348            actor: meta.actor.clone().into_owned(),
349            time_s: meta.timestamp,
350            message: meta.message.as_deref().map(str::to_owned),
351        })
352        .collect())
353}
354
355/// The heads of a causally closed run of changes: those no other change of
356/// the run depends on.
357fn frontier(changes: &[Change]) -> Vec<ChangeHash> {
358    let depended: HashSet<ChangeHash> = changes
359        .iter()
360        .flat_map(|change| change.deps.iter().copied())
361        .collect();
362    let mut heads: Vec<ChangeHash> = changes
363        .iter()
364        .map(|change| change.hash)
365        .filter(|hash| !depended.contains(hash))
366        .collect();
367    heads.compact_sort();
368    heads
369}
370
371/// Writes the effect of the source's changes into the recording.
372struct Writer<'a> {
373    source: &'a Automerge,
374    target: Doc,
375    /// Each source object the recording holds, by its id in the source.
376    objects: HashMap<ObjId, ObjId>,
377    /// Source objects written whole in the current step.
378    authored: HashSet<ObjId>,
379}
380
381impl Writer<'_> {
382    /// Write what changes from the source's state at `before` to its state
383    /// at `after`.
384    fn write(&mut self, before: &[ChangeHash], after: &[ChangeHash]) -> Result<(), RecordingError> {
385        self.authored.clear();
386        for patch in self.source.diff(before, after) {
387            self.apply(patch, after)?;
388        }
389        Ok(())
390    }
391
392    /// Commit what was written as one change at `time_s` with `message`,
393    /// an empty change when nothing was.
394    fn commit(&mut self, time_s: i64, message: Option<&str>) -> ChangeHash {
395        let options = || {
396            let options = CommitOptions::default().with_time(time_s);
397            match &message {
398                Some(message) => options.with_message((*message).to_owned()),
399                None => options,
400            }
401        };
402        if self.target.pending_ops() > 0
403            && let Some(hash) = self.target.commit_with(options())
404        {
405            return hash;
406        }
407        self.target.rollback();
408        self.target.empty_change(options())
409    }
410
411    fn left_out(patch: &Patch) -> bool {
412        let at_root =
413            |prop: &Prop| matches!(prop, Prop::Map(key) if LEFT_OUT.contains(&key.as_str()));
414        if let Some((obj, prop)) = patch.path.first() {
415            return *obj == ROOT && at_root(prop);
416        }
417        patch.obj == ROOT
418            && match &patch.action {
419                PatchAction::PutMap { key, .. } | PatchAction::DeleteMap { key } => {
420                    LEFT_OUT.contains(&key.as_str())
421                }
422                PatchAction::Increment { prop, .. } | PatchAction::Conflict { prop } => {
423                    at_root(prop)
424                }
425                _ => false,
426            }
427    }
428
429    fn apply(&mut self, patch: Patch, after: &[ChangeHash]) -> Result<(), RecordingError> {
430        if Self::left_out(&patch)
431            || self.authored.contains(&patch.obj)
432            || patch
433                .path
434                .iter()
435                .any(|(obj, _)| self.authored.contains(obj))
436        {
437            return Ok(());
438        }
439        let obj = self
440            .objects
441            .get(&patch.obj)
442            .cloned()
443            .ok_or_else(|| RecordingError::Write("a change names an unknown object".into()))?;
444        match patch.action {
445            PatchAction::PutMap { key, value, .. } => {
446                self.put(&obj, Prop::Map(key), value, false, after)?;
447            }
448            PatchAction::PutSeq { index, value, .. } => {
449                self.put(&obj, Prop::Seq(index), value, false, after)?;
450            }
451            PatchAction::Insert { index, values } => {
452                for (offset, (value, id, _)) in values.iter().enumerate() {
453                    let at = index.checked_add(offset).ok_or_else(overflow)?;
454                    let value = (value.clone(), id.clone());
455                    self.put(&obj, Prop::Seq(at), value, true, after)?;
456                }
457            }
458            PatchAction::SpliceText {
459                index,
460                value,
461                marks,
462            } => {
463                let before = self.target.length(&obj);
464                self.target
465                    .splice_text(&obj, index, 0, &value.make_string())?;
466                let inserted = self.target.length(&obj).saturating_sub(before);
467                let wanted = marks
468                    .map(|set| {
469                        set.iter()
470                            .map(|(name, value)| (name.to_owned(), value.clone()))
471                            .collect::<BTreeMap<_, _>>()
472                    })
473                    .unwrap_or_default();
474                self.settle_marks(&obj, index, inserted, &wanted)?;
475            }
476            PatchAction::Increment { prop, value } => self.target.increment(&obj, prop, value)?,
477            PatchAction::Conflict { .. } => {}
478            PatchAction::DeleteMap { key } => self.target.delete(&obj, key.as_str())?,
479            PatchAction::DeleteSeq { index, length } => {
480                if self.target.object_type(&obj)? == ObjType::Text {
481                    let length = isize::try_from(length).map_err(|_| overflow())?;
482                    self.target.splice_text(&obj, index, length, "")?;
483                } else {
484                    for _ in 0..length {
485                        self.target.delete(&obj, index)?;
486                    }
487                }
488            }
489            PatchAction::Mark { marks } => {
490                for mark in marks {
491                    self.target.mark(&obj, mark, ExpandMark::None)?;
492                }
493            }
494        }
495        Ok(())
496    }
497
498    /// Give the `len` characters just inserted at `index` exactly the marks
499    /// `wanted`, whatever they took from their neighbours.
500    fn settle_marks(
501        &mut self,
502        obj: &ObjId,
503        index: usize,
504        len: usize,
505        wanted: &BTreeMap<String, ScalarValue>,
506    ) -> Result<(), RecordingError> {
507        if len == 0 {
508            return Ok(());
509        }
510        let end = index.checked_add(len).ok_or_else(overflow)?;
511        let have = self
512            .target
513            .get_marks(obj, index, None)?
514            .iter()
515            .map(|(name, value)| (name.to_owned(), value.clone()))
516            .collect::<BTreeMap<_, _>>();
517        for (name, value) in wanted {
518            if have.get(name) != Some(value) {
519                let mark = Mark::new(name.clone(), value.clone(), index, end);
520                self.target.mark(obj, mark, ExpandMark::None)?;
521            }
522        }
523        for name in have.keys().filter(|name| !wanted.contains_key(*name)) {
524            self.target
525                .unmark(obj, name, index, end, ExpandMark::None)?;
526        }
527        Ok(())
528    }
529
530    /// Write one value at `prop` of `parent`: a scalar as itself, an object
531    /// as a new object holding the source's whole copy of it at `after`.
532    fn put(
533        &mut self,
534        parent: &ObjId,
535        prop: Prop,
536        (value, source): (Value<'_>, ObjId),
537        insert: bool,
538        after: &[ChangeHash],
539    ) -> Result<(), RecordingError> {
540        match (value, insert, prop) {
541            (Value::Scalar(scalar), true, Prop::Seq(index)) => {
542                self.target.insert(parent, index, scalar.into_owned())?;
543            }
544            (Value::Scalar(scalar), _, prop) => {
545                self.target.put(parent, prop, scalar.into_owned())?;
546            }
547            (Value::Object(kind), true, Prop::Seq(index)) => {
548                let made = self.target.insert_object(parent, index, kind)?;
549                self.author(source, made, kind, after)?;
550            }
551            (Value::Object(kind), _, prop) => {
552                let made = self.target.put_object(parent, prop, kind)?;
553                self.author(source, made, kind, after)?;
554            }
555        }
556        Ok(())
557    }
558
559    /// Fill the new object `made` with the whole content `source` has at
560    /// `after`.
561    fn author(
562        &mut self,
563        source: ObjId,
564        made: ObjId,
565        kind: ObjType,
566        after: &[ChangeHash],
567    ) -> Result<(), RecordingError> {
568        let mut pending = vec![(source, made, kind)];
569        while let Some((from, into, kind)) = pending.pop() {
570            self.authored.insert(from.clone());
571            self.objects.insert(from.clone(), into.clone());
572            match kind {
573                ObjType::Map | ObjType::Table => {
574                    let keys = self.source.keys_at(&from, after).collect::<Vec<_>>();
575                    for key in keys {
576                        match entry(self.source, &from, key.as_str(), after)? {
577                            Some(Entry::Scalar(scalar)) => {
578                                self.target.put(&into, key.as_str(), scalar)?;
579                            }
580                            Some(Entry::Object(kind, child)) => {
581                                let made = self.target.put_object(&into, key.as_str(), kind)?;
582                                pending.push((child, made, kind));
583                            }
584                            None => {}
585                        }
586                    }
587                }
588                ObjType::List => {
589                    for index in 0..self.source.length_at(&from, after) {
590                        match entry(self.source, &from, index, after)? {
591                            Some(Entry::Scalar(scalar)) => {
592                                self.target.insert(&into, index, scalar)?;
593                            }
594                            Some(Entry::Object(kind, child)) => {
595                                let made = self.target.insert_object(&into, index, kind)?;
596                                pending.push((child, made, kind));
597                            }
598                            None => {}
599                        }
600                    }
601                }
602                ObjType::Text => {
603                    let text = self.source.text_at(&from, after)?;
604                    self.target.splice_text(&into, 0, 0, &text)?;
605                    for mark in self.source.marks_at(&from, after)? {
606                        self.target.mark(&into, mark, ExpandMark::None)?;
607                    }
608                }
609            }
610        }
611        Ok(())
612    }
613}
614
615fn overflow() -> RecordingError {
616    RecordingError::Write("an index overflowed".into())
617}
618
619/// One value of an object, owned.
620#[derive(PartialEq)]
621enum Entry {
622    Scalar(ScalarValue),
623    Object(ObjType, ObjId),
624}
625
626fn entry(
627    doc: &Automerge,
628    obj: &ObjId,
629    prop: impl Into<Prop>,
630    at: &[ChangeHash],
631) -> Result<Option<Entry>, RecordingError> {
632    Ok(doc.get_at(obj, prop, at)?.map(|(value, id)| match value {
633        Value::Object(kind) => Entry::Object(kind, id),
634        Value::Scalar(scalar) => Entry::Scalar(scalar.into_owned()),
635    }))
636}
637
638/// Whether `left` at `left_at` and `right` at `right_at` hold the same
639/// keys, values, sequences, text and marks, whatever their objects' ids,
640/// leaving out the root keys a recording leaves out.
641pub fn same_state(
642    left: &Automerge,
643    left_at: &[ChangeHash],
644    right: &Automerge,
645    right_at: &[ChangeHash],
646) -> Result<bool, RecordingError> {
647    let mut pending = vec![(ROOT, ROOT, ObjType::Map)];
648    while let Some((one, other, kind)) = pending.pop() {
649        match kind {
650            ObjType::Map | ObjType::Table => {
651                let keys = |doc: &Automerge, obj: &ObjId, at: &[ChangeHash]| {
652                    let mut keys = doc
653                        .keys_at(obj, at)
654                        .filter(|key| !(*obj == ROOT && LEFT_OUT.contains(&key.as_str())))
655                        .collect::<Vec<_>>();
656                    keys.compact_sort();
657                    keys
658                };
659                let mine = keys(left, &one, left_at);
660                if mine != keys(right, &other, right_at) {
661                    return Ok(false);
662                }
663                for key in mine {
664                    let a = entry(left, &one, key.as_str(), left_at)?;
665                    let b = entry(right, &other, key.as_str(), right_at)?;
666                    if !same_entry(a, b, &mut pending) {
667                        return Ok(false);
668                    }
669                }
670            }
671            ObjType::List => {
672                let len = left.length_at(&one, left_at);
673                if len != right.length_at(&other, right_at) {
674                    return Ok(false);
675                }
676                for index in 0..len {
677                    let a = entry(left, &one, index, left_at)?;
678                    let b = entry(right, &other, index, right_at)?;
679                    if !same_entry(a, b, &mut pending) {
680                        return Ok(false);
681                    }
682                }
683            }
684            ObjType::Text => {
685                if left.text_at(&one, left_at)? != right.text_at(&other, right_at)?
686                    || marks(left, &one, left_at)? != marks(right, &other, right_at)?
687                {
688                    return Ok(false);
689                }
690            }
691        }
692    }
693    Ok(true)
694}
695
696/// The marks of a text, as spans that say what they mark.
697fn marks(
698    doc: &Automerge,
699    obj: &ObjId,
700    at: &[ChangeHash],
701) -> Result<Vec<(usize, usize, String, ScalarValue)>, RecordingError> {
702    Ok(doc
703        .marks_at(obj, at)?
704        .into_iter()
705        .map(|mark| {
706            (
707                mark.start,
708                mark.end,
709                mark.name().to_owned(),
710                mark.value().clone(),
711            )
712        })
713        .collect())
714}
715
716fn same_entry(
717    left: Option<Entry>,
718    right: Option<Entry>,
719    pending: &mut Vec<(ObjId, ObjId, ObjType)>,
720) -> bool {
721    match (left, right) {
722        (Some(Entry::Object(kind, one)), Some(Entry::Object(other_kind, other)))
723            if kind == other_kind =>
724        {
725            pending.push((one, other, kind));
726            true
727        }
728        (left, right) => left == right,
729    }
730}
731
732#[cfg(test)]
733#[allow(
734    clippy::arithmetic_side_effects,
735    reason = "a test generator and the positions it picks"
736)]
737#[path = "recording_tests.rs"]
738mod tests;