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
use crate::{
    NanoSecond, Reader, Result, Scope, ScopeCollection, ScopeId, Stream, ThreadInfo,
    UnpackedFrameData,
};
use std::{collections::BTreeMap, hash::Hash};

/// Temporary structure while building a [`MergeScope`].
#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
struct MergeId<'s> {
    id: ScopeId,
    data: &'s str,
}

/// Temporary structure while building a [`MergeScope`].
#[derive(Default)]
struct MergeNode<'s> {
    /// These are the raw scopes that got merged into us.
    /// All these scopes have the same `id`.
    pieces: Vec<MergePiece<'s>>,

    /// indexed by their id+data
    children: BTreeMap<MergeId<'s>, MergeNode<'s>>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct MergePiece<'s> {
    /// The start of the scope relative to its *parent* [`Scope`].
    pub relative_start_ns: NanoSecond,
    /// The raw scope, just like it is found in the input stream
    pub scope: Scope<'s>,
}

/// A scope that has been merged from many different sources
#[derive(Clone, Debug, PartialEq)]
pub struct MergeScope<'s> {
    /// Relative to parent.
    pub relative_start_ns: NanoSecond,
    /// Sum of all durations over all frames
    pub total_duration_ns: NanoSecond,
    /// [`Self::total_duration_ns`] divided by number of frames.
    pub duration_per_frame_ns: NanoSecond,
    /// The slowest individual piece.
    pub max_duration_ns: NanoSecond,
    /// Number of pieces that got merged together to us.
    pub num_pieces: usize,
    /// The common identifier that we merged using.
    pub id: ScopeId,
    /// only set if all children had the same
    pub data: std::borrow::Cow<'s, str>,
    /// The merged children of this merged scope.
    pub children: Vec<MergeScope<'s>>,
}

impl<'s> MergeScope<'s> {
    /// Clones the merge scope.
    pub fn into_owned(self) -> MergeScope<'static> {
        MergeScope::<'static> {
            relative_start_ns: self.relative_start_ns,
            total_duration_ns: self.total_duration_ns,
            duration_per_frame_ns: self.duration_per_frame_ns,
            max_duration_ns: self.max_duration_ns,
            num_pieces: self.num_pieces,
            id: self.id,
            data: std::borrow::Cow::Owned(self.data.into_owned()),
            children: self.children.into_iter().map(Self::into_owned).collect(),
        }
    }
}

impl<'s> MergeNode<'s> {
    fn add<'slf>(&'slf mut self, stream: &'s Stream, piece: MergePiece<'s>) -> Result<()> {
        self.pieces.push(piece);

        for child in Reader::with_offset(stream, piece.scope.child_begin_position)? {
            let child = child?;

            self.children
                .entry(MergeId {
                    id: child.id,
                    data: child.record.data,
                })
                .or_default()
                .add(
                    stream,
                    MergePiece {
                        relative_start_ns: child.record.start_ns - piece.scope.record.start_ns,
                        scope: child,
                    },
                )?;
        }

        Ok(())
    }

    fn build(self, scope_collection: &ScopeCollection, num_frames: i64) -> MergeScope<'s> {
        assert!(!self.pieces.is_empty());
        let mut relative_start_ns = self.pieces[0].relative_start_ns;
        let mut total_duration_ns = 0;
        let mut slowest_ns = 0;
        let num_pieces = self.pieces.len();
        let id = self.pieces[0].scope.id;
        let mut data = self.pieces[0].scope.record.data;

        for piece in &self.pieces {
            // Merged scope should start at the earliest piece:
            relative_start_ns = relative_start_ns.min(piece.relative_start_ns);
            total_duration_ns += piece.scope.record.duration_ns;
            slowest_ns = slowest_ns.max(piece.scope.record.duration_ns);

            assert_eq!(id, piece.scope.id);
            if data != piece.scope.record.data {
                data = ""; // different in different pieces
            }
        }

        MergeScope {
            relative_start_ns,
            total_duration_ns,
            duration_per_frame_ns: total_duration_ns / num_frames,
            max_duration_ns: slowest_ns,
            num_pieces,
            id,
            data: data.into(),
            children: build(scope_collection, self.children, num_frames),
        }
    }
}

fn build<'s>(
    scope_collection: &ScopeCollection,
    nodes: BTreeMap<MergeId<'s>, MergeNode<'s>>,
    num_frames: i64,
) -> Vec<MergeScope<'s>> {
    let mut scopes: Vec<_> = nodes
        .into_values()
        .map(|node| node.build(scope_collection, num_frames))
        .collect();

    // Earliest first:
    scopes.sort_by_key(|scope| scope.relative_start_ns);

    // Make sure sibling scopes do not overlap:
    let mut relative_ns = 0;
    for scope in &mut scopes {
        scope.relative_start_ns = scope.relative_start_ns.max(relative_ns);
        relative_ns = scope.relative_start_ns + scope.duration_per_frame_ns;
    }

    scopes
}

/// For the given thread, merge all scopes with the same id+data path.
pub fn merge_scopes_for_thread<'s>(
    scope_collection: &ScopeCollection,
    frames: &'s [std::sync::Arc<UnpackedFrameData>],
    thread_info: &ThreadInfo,
) -> Result<Vec<MergeScope<'s>>> {
    let mut top_nodes: BTreeMap<MergeId<'s>, MergeNode<'s>> = Default::default();

    for frame in frames {
        if let Some(stream_info) = frame.thread_streams.get(thread_info) {
            let offset_ns = frame.meta.range_ns.0 - frames[0].meta.range_ns.0; // make everything relative to first frame

            let top_scopes = Reader::from_start(&stream_info.stream).read_top_scopes()?;
            for scope in top_scopes {
                top_nodes
                    .entry(MergeId {
                        id: scope.id,
                        data: scope.record.data,
                    })
                    .or_default()
                    .add(
                        &stream_info.stream,
                        MergePiece {
                            relative_start_ns: scope.record.start_ns - offset_ns,
                            scope,
                        },
                    )?;
            }
        }
    }

    Ok(build(scope_collection, top_nodes, frames.len() as _))
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, sync::Arc};

    #[test]
    fn test_merge() {
        use crate::*;

        let mut scope_collection = ScopeCollection::default();
        // top scopes
        scope_collection.insert(Arc::new(
            ScopeDetails::from_scope_id(ScopeId::new(1)).with_function_name("a"),
        ));
        scope_collection.insert(Arc::new(
            ScopeDetails::from_scope_id(ScopeId::new(2)).with_function_name("b"),
        ));

        // middle scopes
        scope_collection.insert(Arc::new(
            ScopeDetails::from_scope_id(ScopeId::new(3)).with_function_name("ba"),
        ));
        scope_collection.insert(Arc::new(
            ScopeDetails::from_scope_id(ScopeId::new(4)).with_function_name("bb"),
        ));
        scope_collection.insert(Arc::new(
            ScopeDetails::from_scope_id(ScopeId::new(5)).with_function_name("bba"),
        ));

        let stream = {
            let mut stream = Stream::default();

            for i in 0..2 {
                let ns = 1000 * i;

                let (a, _) = stream.begin_scope(|| ns + 100, ScopeId::new(1), "");
                stream.end_scope(a, ns + 200);

                let (b, _) = stream.begin_scope(|| ns + 200, ScopeId::new(2), "");

                let (ba, _) = stream.begin_scope(|| ns + 400, ScopeId::new(3), "");
                stream.end_scope(ba, ns + 600);

                let (bb, _) = stream.begin_scope(|| ns + 600, ScopeId::new(4), "");
                let (bba, _) = stream.begin_scope(|| ns + 600, ScopeId::new(5), "");
                stream.end_scope(bba, ns + 700);
                stream.end_scope(bb, ns + 800);
                stream.end_scope(b, ns + 900);
            }

            stream
        };

        let stream_info = StreamInfo::parse(stream).unwrap();
        let mut thread_streams = BTreeMap::new();
        let thread_info = ThreadInfo {
            start_time_ns: Some(0),
            name: "main".to_owned(),
        };
        thread_streams.insert(thread_info.clone(), stream_info);
        let frame = UnpackedFrameData::new(0, thread_streams).unwrap();
        let frames = [Arc::new(frame)];
        let merged = merge_scopes_for_thread(&scope_collection, &frames, &thread_info).unwrap();

        let expected = vec![
            MergeScope {
                relative_start_ns: 100,
                total_duration_ns: 2 * 100,
                duration_per_frame_ns: 2 * 100,
                max_duration_ns: 100,
                num_pieces: 2,
                id: ScopeId::new(1),
                data: "".into(),
                children: vec![],
            },
            MergeScope {
                relative_start_ns: 300, // moved forward to make place for "a" (as are all children)
                total_duration_ns: 2 * 700,
                duration_per_frame_ns: 2 * 700,
                max_duration_ns: 700,
                num_pieces: 2,
                id: ScopeId::new(2),
                data: "".into(),
                children: vec![
                    MergeScope {
                        relative_start_ns: 200,
                        total_duration_ns: 2 * 200,
                        duration_per_frame_ns: 2 * 200,
                        max_duration_ns: 200,
                        num_pieces: 2,
                        id: ScopeId::new(3),
                        data: "".into(),
                        children: vec![],
                    },
                    MergeScope {
                        relative_start_ns: 600,
                        total_duration_ns: 2 * 200,
                        duration_per_frame_ns: 2 * 200,
                        max_duration_ns: 200,
                        num_pieces: 2,
                        id: ScopeId::new(4),
                        data: "".into(),
                        children: vec![MergeScope {
                            relative_start_ns: 0,
                            total_duration_ns: 2 * 100,
                            duration_per_frame_ns: 2 * 100,
                            max_duration_ns: 100,
                            num_pieces: 2,
                            id: ScopeId::new(5),
                            data: "".into(),
                            children: vec![],
                        }],
                    },
                ],
            },
        ];

        assert_eq!(
            merged, expected,
            "\nGot:\n{merged:#?}\n\n!=\nExpected:\n{expected:#?}",
        );
    }
}