fxprof_processed_profile/
sample_table.rs

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
use std::fmt::{Display, Formatter};

use serde::ser::{Serialize, SerializeMap, Serializer};

use crate::cpu_delta::CpuDelta;
use crate::serialization_helpers::SerializableSingleValueColumn;
use crate::Timestamp;

/// The sample table contains stacks with timestamps and some extra information.
///
/// In the most common case, this is used for time-based sampling: At a fixed but
/// configurable rate, a profiler samples the current stack of each thread and records
/// it in the profile.
#[derive(Debug, Clone)]
pub struct SampleTable {
    sample_weight_type: WeightType,
    sample_weights: Vec<i32>,
    sample_timestamps: Vec<Timestamp>,
    /// An index into the thread's stack table for each sample. `None` means the empty stack.
    sample_stack_indexes: Vec<Option<usize>>,
    /// CPU usage delta since the previous sample for this thread, for each sample.
    sample_cpu_deltas: Vec<CpuDelta>,
    sorted_by_time: bool,
    last_sample_timestamp: Timestamp,
}

/// Specifies the meaning of the "weight" value of a thread's samples.
#[derive(Debug, Clone)]
pub enum WeightType {
    /// The weight is an integer multiplier. For example, "this stack was
    /// observed n times when sampling at the specified interval."
    ///
    /// This affects the total + self score of each call node in the call tree,
    /// and the order in the tree because the tree is ordered from large "totals"
    /// to small "totals".
    /// It also affects the width of the sample's stack's box in the flame graph.
    Samples,
    /// The weight is a duration in (fractional) milliseconds.
    ///
    /// Note that, since [`Profile::add_sample`](crate::Profile::add_sample) currently
    /// only accepts integer weight values, the usefulness of `TracingMs` is
    /// currently limited.
    TracingMs,
    /// The weight of each sample is a value in bytes.
    ///
    /// This can be used for profiles with allocation stacks. It can also be used
    /// for "size" profiles which give a bytes breakdown of the contents of a file.
    Bytes,
}

impl Display for WeightType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            WeightType::Samples => write!(f, "samples"),
            WeightType::TracingMs => write!(f, "tracing-ms"),
            WeightType::Bytes => write!(f, "bytes"),
        }
    }
}

impl Serialize for WeightType {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            WeightType::Samples => serializer.serialize_str("samples"),
            WeightType::TracingMs => serializer.serialize_str("tracing-ms"),
            WeightType::Bytes => serializer.serialize_str("bytes"),
        }
    }
}

impl SampleTable {
    pub fn new() -> Self {
        Self {
            sample_weight_type: WeightType::Samples,
            sample_weights: Vec::new(),
            sample_timestamps: Vec::new(),
            sample_stack_indexes: Vec::new(),
            sample_cpu_deltas: Vec::new(),
            sorted_by_time: true,
            last_sample_timestamp: Timestamp::from_nanos_since_reference(0),
        }
    }

    pub fn add_sample(
        &mut self,
        timestamp: Timestamp,
        stack_index: Option<usize>,
        cpu_delta: CpuDelta,
        weight: i32,
    ) {
        self.sample_weights.push(weight);
        self.sample_timestamps.push(timestamp);
        self.sample_stack_indexes.push(stack_index);
        self.sample_cpu_deltas.push(cpu_delta);
        if timestamp < self.last_sample_timestamp {
            self.sorted_by_time = false;
        }
        self.last_sample_timestamp = timestamp;
    }

    pub fn set_weight_type(&mut self, t: WeightType) {
        self.sample_weight_type = t;
    }

    pub fn modify_last_sample(&mut self, timestamp: Timestamp, weight: i32) {
        *self.sample_weights.last_mut().unwrap() += weight;
        *self.sample_timestamps.last_mut().unwrap() = timestamp;
    }
}

impl Serialize for SampleTable {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let len = self.sample_timestamps.len();
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("length", &len)?;
        map.serialize_entry("weightType", &self.sample_weight_type.to_string())?;

        if self.sorted_by_time {
            map.serialize_entry("stack", &self.sample_stack_indexes)?;
            map.serialize_entry("time", &self.sample_timestamps)?;
            map.serialize_entry("weight", &self.sample_weights)?;
            map.serialize_entry("threadCPUDelta", &self.sample_cpu_deltas)?;
        } else {
            let mut indexes: Vec<usize> = (0..self.sample_timestamps.len()).collect();
            indexes.sort_unstable_by_key(|index| self.sample_timestamps[*index]);
            map.serialize_entry(
                "stack",
                &SliceWithPermutation(&self.sample_stack_indexes, &indexes),
            )?;
            map.serialize_entry(
                "time",
                &SliceWithPermutation(&self.sample_timestamps, &indexes),
            )?;
            map.serialize_entry(
                "weight",
                &SliceWithPermutation(&self.sample_weights, &indexes),
            )?;
            map.serialize_entry(
                "threadCPUDelta",
                &SliceWithPermutation(&self.sample_cpu_deltas, &indexes),
            )?;
        }
        map.end()
    }
}

struct SliceWithPermutation<'a, T: Serialize>(&'a [T], &'a [usize]);

impl<T: Serialize> Serialize for SliceWithPermutation<'_, T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_seq(self.1.iter().map(|i| &self.0[*i]))
    }
}

/// JS documentation of the native allocations table:
///
/// ```ignore
/// /**
///  * This variant is the original version of the table, before the memory address
///  * and threadId were added.
///  */
/// export type UnbalancedNativeAllocationsTable = {|
///   time: Milliseconds[],
///   // "weight" is used here rather than "bytes", so that this type will match the
///   // SamplesLikeTableShape.
///   weight: Bytes[],
///   weightType: 'bytes',
///   stack: Array<IndexIntoStackTable | null>,
///   length: number,
/// |};
///
/// /**
///  * The memory address and thread ID were added later.
///  */
/// export type BalancedNativeAllocationsTable = {|
///   ...UnbalancedNativeAllocationsTable,
///   memoryAddress: number[],
///   threadId: number[],
/// |};
/// ```
///
/// In this crate we always create a `BalancedNativeAllocationsTable`. We require
/// a memory address for each allocation / deallocation sample.
#[derive(Debug, Clone, Default)]
pub struct NativeAllocationsTable {
    /// The timstamps for each sample
    time: Vec<Timestamp>,
    /// The stack index for each sample
    stack: Vec<Option<usize>>,
    /// The size in bytes (positive for allocations, negative for deallocations) for each sample
    allocation_size: Vec<i64>,
    /// The memory address of the allocation for each sample
    allocation_address: Vec<u64>,
}

impl NativeAllocationsTable {
    /// Add a sample to the [`NativeAllocations`] table.
    pub fn add_sample(
        &mut self,
        timestamp: Timestamp,
        stack_index: Option<usize>,
        allocation_address: u64,
        allocation_size: i64,
    ) {
        self.time.push(timestamp);
        self.stack.push(stack_index);
        self.allocation_address.push(allocation_address);
        self.allocation_size.push(allocation_size);
    }
}

impl Serialize for NativeAllocationsTable {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let len = self.time.len();
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("time", &self.time)?;
        map.serialize_entry("weight", &self.allocation_size)?;
        map.serialize_entry("weightType", &WeightType::Bytes)?;
        map.serialize_entry("stack", &self.stack)?;
        map.serialize_entry("memoryAddress", &self.allocation_address)?;

        // The threadId column is currently unused by the Firefox Profiler.
        // Fill the column with zeros because the type definitions require it to be a number.
        // A better alternative would be to use thread indexes or the threads' string TIDs.
        map.serialize_entry("threadId", &SerializableSingleValueColumn(0, len))?;

        map.serialize_entry("length", &len)?;
        map.end()
    }
}

#[cfg(test)]
mod tests {
    use assert_json_diff::assert_json_eq;
    use serde_json::json;

    use super::*;

    #[test]
    fn test_serialize_native_allocations() {
        // example of `nativeAllocations`:
        //
        // "nativeAllocations": {
        //     "time": [
        //         274364.1082197344,
        //         274364.17226073437,
        //         274364.2063027344,
        //         274364.2229277344,
        //         274364.44117773435,
        //         274366.4713027344,
        //         274366.48871973436,
        //         274366.6601777344,
        //         274366.6705107344
        //     ],
        //     "weight": [
        //         4096,
        //         -4096,
        //         4096,
        //         -4096,
        //         147456,
        //         4096,
        //         -4096,
        //         96,
        //         -96
        //     ],
        //     "weightType": "bytes",
        //     "stack": [
        //         71,
        //         88,
        //         119,
        //         138,
        //         null,
        //         171,
        //         190,
        //         210,
        //         214
        //     ],
        //     "memoryAddress": [
        //         4388749312,
        //         4388749312,
        //         4388749312,
        //         4388749312,
        //         4376330240,
        //         4388749312,
        //         4388749312,
        //         4377576256,
        //         4377576256
        //     ],
        //     "threadId": [
        //         0,
        //         0,
        //         0,
        //         0,
        //         0,
        //         0,
        //         0,
        //         0,
        //         0
        //     ],
        //     "length": 9
        // },

        let mut native_allocations_table = NativeAllocationsTable::default();
        native_allocations_table.add_sample(
            Timestamp::from_millis_since_reference(274_363.248_375),
            None,
            5969772544,
            147456,
        );

        assert_json_eq!(
            native_allocations_table,
            json!({
              "time": [
                274363.248375
              ],
              "weight": [
                147456
              ],
              "weightType": "bytes",
              "stack": [
                null
              ],
              "memoryAddress": [
                5969772544u64
              ],
              "threadId": [
                0
              ],
              "length": 1
            })
        );
    }
}