buildprof 0.2.5

Records every process and file access in a build and shows it as an interactive timeline
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
// Copyright 2026 The Buildprof Authors.
// SPDX-License-Identifier: Apache-2.0

use crate::model::{FileOpen, Process, Rename, Segment};
use proto::AttributeValue;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::path::Path;
use wire::Encoder;
use zstd::stream::write::Encoder as Compressor;

mod proto;
mod wire;

const OUTPUT_BUFFER_BYTES: usize = 64 * 1024;
/// zstd level for the whole-file stream. Level 3 already shrinks a build trace
/// about nine times over and compresses at well over a gigabyte a second, so
/// it costs the recorder nothing measurable; higher levels gain little.
const COMPRESSION_LEVEL: i32 = 3;
/// Bumped whenever the UI needs to tell traces apart to read them correctly.
pub const TRACE_FORMAT_VERSION: i64 = 1;
const VERSION_ATTRIBUTE: &str = "buildprof.version";
const TRACE_FORMAT_ATTRIBUTE: &str = "buildprof.trace_format";
const PROCESS_MERGE_KEY: &str = "buildprof.processes";
const FILE_MERGE_KEY: &str = "buildprof.files";
const PROCESS_CATEGORY: &str = "buildprof.process";
const FILE_CATEGORY: &str = "buildprof.file";
const RENAME_CATEGORY: &str = "buildprof.rename";
const COMPILER_CATEGORY: &str = "buildprof.compiler";
const TRACK_UUID_PID_SHIFT: u32 = 2;
const PROCESS_TRACK_DISCRIMINATOR: u64 = 1;
const FILE_TRACK_DISCRIMINATOR: u64 = 2;
const COMPILER_TRACK_NAMESPACE: u64 = 1 << 63;
const COMPILER_TRACK_PID_SHIFT: u32 = 31;
const COMPILER_TRACK_BACKEND_SHIFT: u32 = 29;
const COMPILER_TRACK_THREAD_MASK: u64 = (1 << COMPILER_TRACK_BACKEND_SHIFT) - 1;
const MINIMUM_SLICE_DURATION_NS: u64 = 1;

/// Incrementally writes trace packets to a zstd-compressed file.
///
/// The whole file is one zstd stream around an ordinary Perfetto protobuf
/// trace; Trace Processor detects the compression from the magic bytes. No
/// protobuf message tree or encoded packet is retained. Nested message lengths
/// are obtained with an allocation-free counting pass immediately before the
/// bytes are written.
pub struct Writer {
    output: Compressor<'static, BufWriter<File>>,
    event_categories: HashMap<String, u64>,
    event_names: HashMap<String, u64>,
    annotation_names: HashMap<String, u64>,
    annotation_values: HashMap<String, u64>,
}

impl Writer {
    pub fn create(path: &Path) -> io::Result<Self> {
        let file = File::create(path)?;
        let buffered = BufWriter::with_capacity(OUTPUT_BUFFER_BYTES, file);
        let mut writer = Self {
            output: Compressor::new(buffered, COMPRESSION_LEVEL)?,
            event_categories: HashMap::new(),
            event_names: HashMap::new(),
            annotation_names: HashMap::new(),
            annotation_values: HashMap::new(),
        };
        writer.write_preamble()?;
        Ok(writer)
    }

    /// Preserve collection settings so an absent layer is not mistaken for no activity.
    pub fn collection_options(
        &mut self,
        file_events: bool,
        compiler_traces: bool,
    ) -> io::Result<()> {
        self.with_encoder(|trace| {
            trace.packet(&mut |packet| {
                packet.trace_attributes(&[
                    (
                        "buildprof.file_events",
                        AttributeValue::Long(i64::from(file_events)),
                    ),
                    (
                        "buildprof.compiler_traces",
                        AttributeValue::Long(i64::from(compiler_traces)),
                    ),
                ])
            })
        })
    }

    pub fn process_started(&mut self, pid: i32) -> io::Result<()> {
        self.with_encoder(|trace| {
            trace.packet(&mut |packet| {
                packet.sequence()?;
                packet.track_descriptor(
                    process_track_uuid(pid),
                    Some(proto::ROOT_TRACK_UUID),
                    "Processes",
                    Some(PROCESS_MERGE_KEY),
                )
            })?;
            trace.packet(&mut |packet| {
                packet.sequence()?;
                packet.track_descriptor(
                    file_track_uuid(pid),
                    Some(proto::ROOT_TRACK_UUID),
                    "File opens",
                    Some(FILE_MERGE_KEY),
                )
            })
        })
    }

    pub fn segment(&mut self, process: Process, segment: &Segment) -> io::Result<()> {
        {
            self.write_event(
                segment.start_ns,
                proto::TYPE_SLICE_BEGIN,
                process_track_uuid(process.pid),
                Some(PROCESS_CATEGORY),
                Some(&segment.name),
                None,
                &mut |args| {
                    args.command(&segment.command)?;
                    args.cwd(&segment.cwd)?;
                    args.pid(process.pid)?;
                    args.parent_pid(process.parent_pid)?;
                    args.build_parent_pid(process.build_parent_pid)?;
                    args.execed(process.execed)?;
                    if let Some(exit_code) = segment.exit_code {
                        args.exit_code(exit_code)?;
                    }
                    Ok(())
                },
            )?;

            let end_ns = segment
                .end_ns
                .max(segment.start_ns.saturating_add(MINIMUM_SLICE_DURATION_NS));
            self.write_event(
                end_ns,
                proto::TYPE_SLICE_END,
                process_track_uuid(process.pid),
                None,
                None,
                None,
                &mut |_| Ok(()),
            )
        }
    }

    pub fn file_open(&mut self, pid: i32, open: &FileOpen) -> io::Result<()> {
        {
            self.write_event(
                open.timestamp_ns,
                proto::TYPE_INSTANT,
                file_track_uuid(pid),
                Some(FILE_CATEGORY),
                Some("open"),
                None,
                &mut |args| {
                    args.path(&open.path)?;
                    args.owner_pid(pid)?;
                    args.flags(open.flags)?;
                    args.fd(open.fd)
                },
            )
        }
    }

    pub fn rename(&mut self, pid: i32, rename: &Rename) -> io::Result<()> {
        {
            self.write_event(
                rename.timestamp_ns,
                proto::TYPE_INSTANT,
                file_track_uuid(pid),
                Some(RENAME_CATEGORY),
                Some("rename"),
                None,
                &mut |args| {
                    args.from(&rename.from)?;
                    args.to(&rename.to)?;
                    args.owner_pid(pid)
                },
            )
        }
    }

    pub fn compiler_track(&mut self, pid: i32, thread_id: u32, backend: &str) -> io::Result<()> {
        let name = format!("{backend} compiler [pid {pid}] · thread {thread_id}");
        self.with_encoder(|trace| {
            trace.packet(&mut |packet| {
                packet.sequence()?;
                packet.track_descriptor(
                    compiler_track_uuid(pid, thread_id, backend),
                    Some(proto::ROOT_TRACK_UUID),
                    &name,
                    None,
                )
            })
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn compiler_slice(
        &mut self,
        pid: i32,
        thread_id: u32,
        backend: &str,
        event_category: &str,
        name: &str,
        start_ns: u64,
        duration_ns: u64,
        detail: Option<&str>,
    ) -> io::Result<()> {
        let track_uuid = compiler_track_uuid(pid, thread_id, backend);
        let annotation = detail
            .map(|detail| self.intern_debug_annotation("detail", detail))
            .transpose()?;
        {
            self.write_event(
                start_ns,
                proto::TYPE_SLICE_BEGIN,
                track_uuid,
                Some(COMPILER_CATEGORY),
                Some(name),
                annotation,
                &mut |args| {
                    args.owner_pid(pid)?;
                    args.backend(backend)?;
                    args.compiler_category(event_category)
                },
            )?;
            self.write_event(
                start_ns.saturating_add(duration_ns),
                proto::TYPE_SLICE_END,
                track_uuid,
                None,
                None,
                None,
                &mut |_| Ok(()),
            )
        }
    }

    pub fn finish(self) -> io::Result<()> {
        self.output.finish()?.flush()
    }

    fn write_preamble(&mut self) -> io::Result<()> {
        self.with_encoder(|trace| {
            trace.packet(&mut |packet| packet.extension_descriptor())?;
            trace.packet(&mut |packet| {
                packet.trace_attributes(&[
                    (
                        VERSION_ATTRIBUTE,
                        AttributeValue::Str(env!("CARGO_PKG_VERSION")),
                    ),
                    (
                        TRACE_FORMAT_ATTRIBUTE,
                        AttributeValue::Long(TRACE_FORMAT_VERSION),
                    ),
                ])
            })?;
            trace.packet(&mut |packet| {
                packet.sequence_start()?;
                packet.track_descriptor(proto::ROOT_TRACK_UUID, None, "Build", None)
            })
        })
    }

    fn intern_debug_annotation(&mut self, name: &str, value: &str) -> io::Result<(u64, u64)> {
        let (name_iid, new_name) = intern(&mut self.annotation_names, name);
        let (value_iid, new_value) = intern(&mut self.annotation_values, value);
        if new_name || new_value {
            self.with_encoder(|trace| {
                trace.packet(&mut |packet| {
                    packet.sequence()?;
                    packet.intern_debug_annotation(
                        new_name.then_some((name_iid, name)),
                        new_value.then_some((value_iid, value)),
                    )
                })
            })?;
        }
        Ok((name_iid, value_iid))
    }

    fn with_encoder(
        &mut self,
        encode: impl FnOnce(&mut proto::Trace<'_, '_>) -> io::Result<()>,
    ) -> io::Result<()> {
        let mut encoder = Encoder::writer(&mut self.output);
        encode(&mut proto::Trace::new(&mut encoder))
    }
}

impl Writer {
    /// Writes one track event. Categories and names are interned on first
    /// use, so the trace carries them once and every event refers to them by
    /// id; the reader then resolves them with a table lookup instead of
    /// hashing the string for every event.
    #[allow(clippy::too_many_arguments)]
    fn write_event(
        &mut self,
        timestamp_ns: u64,
        event_type: u32,
        track_uuid: u64,
        category: Option<&str>,
        name: Option<&str>,
        annotation: Option<(u64, u64)>,
        args: &mut dyn FnMut(&mut proto::BuildprofEvent<'_, '_>) -> io::Result<()>,
    ) -> io::Result<()> {
        let category_iid = category.map(|c| intern(&mut self.event_categories, c));
        let name_iid = name.map(|n| intern(&mut self.event_names, n));
        let new_category = category_iid.filter(|(_, new)| *new).map(|(iid, _)| iid);
        let new_name = name_iid.filter(|(_, new)| *new).map(|(iid, _)| iid);
        if new_category.is_some() || new_name.is_some() {
            self.with_encoder(|trace| {
                trace.packet(&mut |packet| {
                    packet.sequence()?;
                    packet.sequence_needs_incremental_state()?;
                    packet.intern_event_strings(
                        new_category.map(|iid| (iid, category.unwrap_or_default())),
                        new_name.map(|iid| (iid, name.unwrap_or_default())),
                    )
                })
            })?;
        }
        self.with_encoder(|trace| {
            trace.packet(&mut |packet| {
                packet.timestamp(timestamp_ns)?;
                packet.sequence()?;
                packet.sequence_needs_incremental_state()?;
                packet.track_event(
                    event_type,
                    track_uuid,
                    category_iid.map(|(iid, _)| iid),
                    name_iid.map(|(iid, _)| iid),
                    annotation,
                    args,
                )
            })
        })
    }
}

fn intern(table: &mut HashMap<String, u64>, value: &str) -> (u64, bool) {
    if let Some(iid) = table.get(value) {
        return (*iid, false);
    }
    let iid = table.len() as u64 + 1;
    table.insert(value.to_owned(), iid);
    (iid, true)
}

fn process_track_uuid(pid: i32) -> u64 {
    (u64::from(pid as u32) << TRACK_UUID_PID_SHIFT) | PROCESS_TRACK_DISCRIMINATOR
}

fn file_track_uuid(pid: i32) -> u64 {
    (u64::from(pid as u32) << TRACK_UUID_PID_SHIFT) | FILE_TRACK_DISCRIMINATOR
}

fn compiler_track_uuid(pid: i32, thread_id: u32, backend: &str) -> u64 {
    COMPILER_TRACK_NAMESPACE
        | (u64::from(pid as u32) << COMPILER_TRACK_PID_SHIFT)
        | (compiler_backend_discriminator(backend) << COMPILER_TRACK_BACKEND_SHIFT)
        | (u64::from(thread_id) & COMPILER_TRACK_THREAD_MASK)
}

fn compiler_backend_discriminator(backend: &str) -> u64 {
    match backend {
        "Rust" => 0,
        "Clang" => 1,
        "LLD" => 2,
        _ => 3,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];
    const TRACE_PACKET_TAG: u8 = 0x0a;

    #[test]
    fn writes_a_zstd_stream_carrying_the_provenance_attributes() {
        let path = std::env::temp_dir().join(format!(
            "buildprof-writer-test-{}-{}.buildprof",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let mut writer = Writer::create(&path).unwrap();
        writer.collection_options(false, true).unwrap();
        writer.process_started(42).unwrap();
        writer.finish().unwrap();

        let compressed = std::fs::read(&path).unwrap();
        std::fs::remove_file(&path).unwrap();
        assert_eq!(&compressed[..4], &ZSTD_MAGIC);

        let trace = zstd::decode_all(compressed.as_slice()).unwrap();
        assert_eq!(trace[0], TRACE_PACKET_TAG);
        let contains = |needle: &[u8]| trace.windows(needle.len()).any(|w| w == needle);
        assert!(contains(VERSION_ATTRIBUTE.as_bytes()));
        assert!(contains(env!("CARGO_PKG_VERSION").as_bytes()));
        assert!(contains(TRACE_FORMAT_ATTRIBUTE.as_bytes()));
        assert!(contains(b"Processes"));
        assert!(contains(b"buildprof.file_events"));
        assert!(contains(b"buildprof.compiler_traces"));
    }
}