Skip to main content

icedwright_trace/
writer.rs

1//! [`TraceWriter`]: builds a trace step by step and writes the archive.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::io::Write;
5use std::time::SystemTime;
6
7use icedwright_types::VirtualDuration;
8
9use crate::archive::{self, Member, Packing};
10use crate::blob::{BlobHash, BlobRef, Png, Yaml, member_name};
11use crate::budget::{Producer, StepFrames, drop_order};
12use crate::config::{ByteSize, FramePolicy, TraceConfig};
13use crate::error::TraceError;
14use crate::ids::{RawId, Renumbering, StepIndex};
15use crate::meta::{FORMAT, MetaFile, TraceMeta, WRITER};
16use crate::normalise::{self, BootInstant};
17use crate::step::{
18    Attempt, LogLine, RealSpan, RealTiming, RealTimings, SourceLocation, Step, StepKind,
19    StepOutcome, TraceEvent, TraceMessage, TraceTask,
20};
21
22/// What the app looked like when the harness booted, before any step.
23#[derive(Debug, Clone)]
24pub struct TraceStart {
25    /// The boot instant, for rewriting instants printed in message and state text.
26    pub boot: Option<BootInstant>,
27    /// The semantic tree at boot, as YAML, which is the first step's tree before.
28    pub tree: String,
29    /// The frame at boot, which is the first step's frame before.
30    pub frame: Option<Png>,
31}
32
33/// What [`TraceWriter::write`] wrote.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct WriteSummary {
36    /// The archive's size in bytes.
37    pub bytes: u64,
38    /// How many steps it holds.
39    pub steps: u32,
40    /// How many distinct trees it holds.
41    pub trees: u32,
42    /// How many distinct frames it holds.
43    pub frames: u32,
44    /// How many frames were dropped to fit the size cap.
45    pub frames_dropped: u32,
46}
47
48/// Builds a trace step by step and writes the archive. It takes plain values and knows nothing
49/// about iced; the harness's step observer drives it. A step is open between
50/// [`begin_step`](TraceWriter::begin_step) and [`StepBuilder::end`].
51#[must_use]
52#[derive(Debug)]
53pub struct TraceWriter {
54    meta: TraceMeta,
55    cap: ByteSize,
56    policy: FramePolicy,
57    boot: Option<BootInstant>,
58    ids: Renumbering,
59    entries: Vec<Entry>,
60    real: RealTimings,
61    trees: BTreeMap<BlobHash, String>,
62    frames: BTreeMap<BlobHash, Png>,
63    frame_refs: BTreeMap<BlobHash, usize>,
64    frame_bytes: u64,
65    tree: BlobRef<Yaml>,
66    latest_frame: Option<(Producer, Png)>,
67    dropped: BTreeSet<Producer>,
68    sources: BTreeMap<String, String>,
69    attachments: BTreeMap<String, Vec<u8>>,
70}
71
72#[derive(Debug)]
73struct Entry {
74    step: Step,
75    before_from: Option<Producer>,
76    after_from: Option<Producer>,
77}
78
79impl TraceWriter {
80    /// A writer for one test, starting from what the app showed at boot.
81    pub fn new(meta: TraceMeta, config: &TraceConfig, start: TraceStart) -> Self {
82        let mut writer = Self {
83            meta,
84            cap: config.size_cap(),
85            policy: config.frame_policy(),
86            boot: start.boot,
87            ids: Renumbering::default(),
88            entries: Vec::new(),
89            real: RealTimings::default(),
90            trees: BTreeMap::new(),
91            frames: BTreeMap::new(),
92            frame_refs: BTreeMap::new(),
93            frame_bytes: 0,
94            tree: BlobRef::new(BlobHash::of(start.tree.as_bytes())),
95            latest_frame: start.frame.map(|frame| (Producer::Boot, frame)),
96            dropped: BTreeSet::new(),
97            sources: BTreeMap::new(),
98            attachments: BTreeMap::new(),
99        };
100        writer.tree = writer.store_tree(start.tree);
101        writer
102    }
103
104    /// Opens a step that began at `at`, measured from boot.
105    pub fn begin_step(
106        &mut self,
107        kind: StepKind,
108        location: SourceLocation,
109        at: VirtualDuration,
110    ) -> StepBuilder<'_> {
111        StepBuilder {
112            writer: self,
113            kind,
114            location,
115            start: at,
116            events: Vec::new(),
117            messages: Vec::new(),
118            tasks: Vec::new(),
119            attempts: Vec::new(),
120            log: Vec::new(),
121            state_diff: None,
122            tree: None,
123            frame: None,
124        }
125    }
126
127    /// Renumbers a raw id to a per-trace ordinal, in order of first appearance. The ordinal's
128    /// type follows from the raw id's.
129    pub fn ordinal<I: RawId>(&mut self, raw: I) -> I::Ordinal {
130        self.ids.ordinal(raw)
131    }
132
133    /// The step most recently ended, as the archive will hold it, for streaming a trace while
134    /// it is recorded.
135    #[must_use]
136    pub fn last_step(&self) -> Option<&Step> {
137        self.entries.last().map(|entry| &entry.step)
138    }
139
140    /// The metadata, for filling in what is known only later, such as the failure message.
141    pub fn meta_mut(&mut self) -> &mut TraceMeta {
142        &mut self.meta
143    }
144
145    /// Records the wall-clock time the test started, which goes in `real.json` only.
146    pub fn wall_clock_start(&mut self, started: SystemTime) {
147        self.real.wall_clock_start = started.duration_since(SystemTime::UNIX_EPOCH).ok();
148    }
149
150    /// Every source file a step's location names, so the caller can add each one.
151    #[must_use]
152    pub fn referenced_sources(&self) -> BTreeSet<&str> {
153        self.entries
154            .iter()
155            .map(|entry| entry.step.location.file.as_str())
156            .collect()
157    }
158
159    /// Stores the text of a source file under `source/`, so the trace can show the line of a
160    /// step without a checkout.
161    pub fn add_source(&mut self, file: &str, text: String) -> Result<(), TraceError> {
162        let member = source_member(file)?;
163        self.sources.insert(member, text);
164        Ok(())
165    }
166
167    /// Stores a file the test attached under `attachments/`. `name` is a plain file name; a
168    /// second attachment with the same name replaces the first. Attachments are never dropped
169    /// to fit the size cap.
170    pub fn attach(&mut self, name: &str, bytes: Vec<u8>) -> Result<(), TraceError> {
171        let member = attachment_member(name)?;
172        self.attachments.insert(member, bytes);
173        Ok(())
174    }
175
176    /// How many frames have been dropped so far to keep memory under the size cap.
177    #[must_use]
178    pub fn frames_dropped(&self) -> u32 {
179        u32::try_from(self.dropped.len()).unwrap_or(u32::MAX)
180    }
181
182    /// Writes the archive to `sink`. When it would pass the size cap, frames are dropped in
183    /// the documented order until it fits; trees and steps are never dropped.
184    pub fn write(self, sink: &mut impl Write) -> Result<WriteSummary, TraceError> {
185        let order = drop_order(&self.step_frames());
186        let mut chosen = self.render(&[])?;
187        if !self.fits(&chosen.bytes) {
188            chosen = self.smallest_fitting(&order)?;
189        }
190        sink.write_all(&chosen.bytes)?;
191        Ok(WriteSummary {
192            bytes: u64::try_from(chosen.bytes.len()).unwrap_or(u64::MAX),
193            steps: u32::try_from(self.entries.len()).unwrap_or(u32::MAX),
194            trees: u32::try_from(self.trees.len()).unwrap_or(u32::MAX),
195            frames: chosen.frames,
196            frames_dropped: chosen.frames_dropped,
197        })
198    }
199
200    /// The render that drops the shortest prefix of `order` that fits, or all of it when
201    /// nothing does.
202    fn smallest_fitting(&self, order: &[Producer]) -> Result<Rendered, TraceError> {
203        let (mut low, mut high) = (1, order.len());
204        let mut found = None;
205        while low <= high {
206            let middle = low + (high - low) / 2;
207            let attempt = self.render(order.get(..middle).unwrap_or(order))?;
208            if self.fits(&attempt.bytes) {
209                found = Some(attempt);
210                high = middle - 1;
211            } else {
212                low = middle + 1;
213            }
214        }
215        match found {
216            Some(rendered) => Ok(rendered),
217            None => self.render(order),
218        }
219    }
220
221    fn fits(&self, bytes: &[u8]) -> bool {
222        u64::try_from(bytes.len()).is_ok_and(|len| len <= self.cap.get())
223    }
224
225    /// The archive with the frames of `drop` left out as well as those already dropped.
226    fn render(&self, drop: &[Producer]) -> Result<Rendered, TraceError> {
227        let drop: BTreeSet<Producer> = drop.iter().copied().collect();
228        let dropped = |from: Option<Producer>| from.is_some_and(|p| drop.contains(&p));
229        let mut steps = Vec::new();
230        let mut kept = BTreeSet::new();
231        for entry in &self.entries {
232            let mut step = entry.step.clone();
233            if dropped(entry.before_from) {
234                step.frame_before = None;
235            }
236            if dropped(entry.after_from) {
237                step.frame_after = None;
238            }
239            kept.extend(
240                step.frame_before
241                    .iter()
242                    .chain(&step.frame_after)
243                    .map(|r| r.hash),
244            );
245            serde_json::to_writer(&mut steps, &step).map_err(std::io::Error::from)?;
246            steps.push(b'\n');
247        }
248        let frames_dropped = u32::try_from(self.dropped.len() + drop.len()).unwrap_or(u32::MAX);
249        let meta = MetaFile {
250            format: FORMAT,
251            written_by: WRITER.to_owned(),
252            frames_dropped,
253            trace: self.meta.clone(),
254        };
255        let mut meta = serde_json::to_vec_pretty(&meta).map_err(std::io::Error::from)?;
256        meta.push(b'\n');
257        let real = serde_json::to_vec(&self.real).map_err(std::io::Error::from)?;
258
259        let mut blobs: BTreeMap<String, (&[u8], Packing)> = BTreeMap::new();
260        for (hash, yaml) in &self.trees {
261            blobs.insert(
262                member_name::<Yaml>(*hash),
263                (yaml.as_bytes(), Packing::Deflate),
264            );
265        }
266        for hash in &kept {
267            if let Some(png) = self.frames.get(hash) {
268                blobs.insert(member_name::<Png>(*hash), (png.as_bytes(), Packing::Store));
269            }
270        }
271
272        let mut members = vec![
273            Member {
274                name: archive::META.to_owned(),
275                bytes: &meta,
276                packing: Packing::Deflate,
277            },
278            Member {
279                name: archive::STEPS.to_owned(),
280                bytes: &steps,
281                packing: Packing::Deflate,
282            },
283        ];
284        members.extend(blobs.into_iter().map(|(name, (bytes, packing))| Member {
285            name,
286            bytes,
287            packing,
288        }));
289        members.extend(self.sources.iter().map(|(name, text)| Member {
290            name: name.clone(),
291            bytes: text.as_bytes(),
292            packing: Packing::Deflate,
293        }));
294        members.extend(self.attachments.iter().map(|(name, bytes)| Member {
295            name: name.clone(),
296            bytes,
297            packing: if name.ends_with(".png") {
298                Packing::Store
299            } else {
300                Packing::Deflate
301            },
302        }));
303        members.push(Member {
304            name: archive::REAL.to_owned(),
305            bytes: &real,
306            packing: Packing::Deflate,
307        });
308        Ok(Rendered {
309            bytes: archive::pack(&members)?,
310            frames: u32::try_from(kept.len()).unwrap_or(u32::MAX),
311            frames_dropped,
312        })
313    }
314
315    fn step_frames(&self) -> Vec<StepFrames> {
316        self.entries
317            .iter()
318            .map(|entry| StepFrames {
319                tree_changed: entry.step.tree_before != entry.step.tree_after,
320                failed: entry.step.outcome.is_failure(),
321                before: entry.before_from,
322                after: entry.after_from,
323            })
324            .collect()
325    }
326
327    fn store_tree(&mut self, yaml: String) -> BlobRef<Yaml> {
328        let hash = BlobHash::of(yaml.as_bytes());
329        self.trees.entry(hash).or_insert(yaml);
330        BlobRef::new(hash)
331    }
332
333    fn store_frame(&mut self, png: &Png) -> BlobRef<Png> {
334        let hash = BlobHash::of(png.as_bytes());
335        if !self.frames.contains_key(&hash) {
336            self.frame_bytes = self
337                .frame_bytes
338                .saturating_add(u64::try_from(png.len()).unwrap_or(u64::MAX));
339            self.frames.insert(hash, png.clone());
340        }
341        *self.frame_refs.entry(hash).or_insert(0) += 1;
342        BlobRef::new(hash)
343    }
344
345    fn release_frame(&mut self, frame: Option<BlobRef<Png>>) {
346        let Some(frame) = frame else {
347            return;
348        };
349        let Some(count) = self.frame_refs.get_mut(&frame.hash) else {
350            return;
351        };
352        *count = count.saturating_sub(1);
353        if *count > 0 {
354            return;
355        }
356        self.frame_refs.remove(&frame.hash);
357        if let Some(png) = self.frames.remove(&frame.hash) {
358            self.frame_bytes = self
359                .frame_bytes
360                .saturating_sub(u64::try_from(png.len()).unwrap_or(u64::MAX));
361        }
362    }
363
364    fn drop_frame(&mut self, producer: Producer) {
365        let mut released = Vec::new();
366        for entry in &mut self.entries {
367            if entry.before_from == Some(producer) {
368                released.push(entry.step.frame_before.take());
369                entry.before_from = None;
370            }
371            if entry.after_from == Some(producer) {
372                released.push(entry.step.frame_after.take());
373                entry.after_from = None;
374            }
375        }
376        released
377            .into_iter()
378            .for_each(|frame| self.release_frame(frame));
379        self.dropped.insert(producer);
380    }
381
382    /// Drops frames by the documented order, over the steps so far, while the frames held in
383    /// memory pass twice the cap. The slack lets `write` choose from the whole trace whenever
384    /// the frames are no more than twice the cap.
385    fn enforce_cap(&mut self) {
386        let limit = self.cap.get().saturating_mul(2);
387        if self.frame_bytes <= limit {
388            return;
389        }
390        for producer in drop_order(&self.step_frames()) {
391            self.drop_frame(producer);
392            if self.frame_bytes <= limit {
393                return;
394            }
395        }
396    }
397
398    /// The latest frame, stored for a step, unless the cap already dropped it.
399    fn latest_stored(&mut self) -> (Option<BlobRef<Png>>, Option<Producer>) {
400        let Some((producer, png)) = self.latest_frame.take() else {
401            return (None, None);
402        };
403        let stored = if self.dropped.contains(&producer) {
404            (None, None)
405        } else {
406            (Some(self.store_frame(&png)), Some(producer))
407        };
408        self.latest_frame = Some((producer, png));
409        stored
410    }
411}
412
413#[derive(Debug)]
414struct Rendered {
415    bytes: Vec<u8>,
416    frames: u32,
417    frames_dropped: u32,
418}
419
420/// The member a source file is stored under, refusing paths that would leave `source/`.
421pub(crate) fn source_member(file: &str) -> Result<String, TraceError> {
422    let normal = file.replace('\\', "/");
423    let escapes = normal.is_empty()
424        || normal.starts_with('/')
425        || normal.contains(':')
426        || normal
427            .split('/')
428            .any(|part| part.is_empty() || part == "." || part == "..");
429    if escapes {
430        return Err(TraceError::BadSourcePath(file.to_owned()));
431    }
432    Ok(format!("{}{normal}", archive::SOURCE_PREFIX))
433}
434
435/// Refuses an attachment name that is not a plain file name, as [`TraceWriter::attach`] would.
436pub fn check_attachment_name(name: &str) -> Result<(), TraceError> {
437    attachment_member(name).map(|_| ())
438}
439
440/// The member an attachment is stored under: a plain file name, with no directories.
441pub(crate) fn attachment_member(name: &str) -> Result<String, TraceError> {
442    let plain = !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\', ':']);
443    if !plain {
444        return Err(TraceError::BadAttachmentName(name.to_owned()));
445    }
446    Ok(format!("{}{name}", archive::ATTACHMENT_PREFIX))
447}
448
449/// One open step. Recording into it after [`end`](StepBuilder::end) does not compile, because
450/// `end` takes it by value.
451#[must_use = "a step is only recorded when `end` is called"]
452#[derive(Debug)]
453pub struct StepBuilder<'w> {
454    writer: &'w mut TraceWriter,
455    kind: StepKind,
456    location: SourceLocation,
457    start: VirtualDuration,
458    events: Vec<TraceEvent>,
459    messages: Vec<TraceMessage>,
460    tasks: Vec<TraceTask>,
461    attempts: Vec<Attempt>,
462    log: Vec<LogLine>,
463    state_diff: Option<String>,
464    tree: Option<String>,
465    frame: Option<Png>,
466}
467
468impl StepBuilder<'_> {
469    /// Records an input event.
470    pub fn event(&mut self, event: TraceEvent) {
471        self.events.push(event);
472    }
473
474    /// Records a message. Instants in its `Debug` text become offsets from boot, and text
475    /// past 4 KiB is cut with its full length recorded.
476    pub fn message(&mut self, mut message: TraceMessage) {
477        let debug = match self.writer.boot {
478            Some(boot) => normalise::rewrite_instants(&message.debug, boot),
479            None => message.debug,
480        };
481        let (debug, full_len) = normalise::truncate(debug, normalise::MESSAGE_LIMIT);
482        message.debug = debug;
483        message.full_len = full_len;
484        self.messages.push(message);
485    }
486
487    /// Records a task lifecycle change.
488    pub fn task(&mut self, task: TraceTask) {
489        self.tasks.push(task);
490    }
491
492    /// Records one evaluation of an `expect`.
493    pub fn attempt(&mut self, attempt: Attempt) {
494        self.attempts.push(attempt);
495    }
496
497    /// Adds a line to the step's call log.
498    pub fn log(&mut self, line: LogLine) {
499        self.log.push(line);
500    }
501
502    /// Records the state's `{:#?}` text before and after the step as a unified diff, or a
503    /// note when either is over 256 KiB.
504    pub fn state(&mut self, before: &str, after: &str) {
505        self.state_diff = match self.writer.boot {
506            Some(boot) => normalise::state_diff(
507                &normalise::rewrite_instants(before, boot),
508                &normalise::rewrite_instants(after, boot),
509            ),
510            None => normalise::state_diff(before, after),
511        };
512    }
513
514    /// Sets the semantic tree, as YAML, once the step settled. Without one, the tree is
515    /// unchanged from the step before.
516    pub fn tree(&mut self, yaml: String) {
517        self.tree = Some(yaml);
518    }
519
520    /// Sets the frame once the step settled. Without one, the frame is unchanged from the step
521    /// before, and the step's frame after is that frame.
522    pub fn frame(&mut self, png: Png) {
523        self.frame = Some(png);
524    }
525
526    /// Renumbers a raw id, as [`TraceWriter::ordinal`] does.
527    pub fn ordinal<I: RawId>(&mut self, raw: I) -> I::Ordinal {
528        self.writer.ordinal(raw)
529    }
530
531    /// Closes the step at `at`, with its real-clock span kept apart in `real.json`.
532    pub fn end(self, outcome: StepOutcome, at: VirtualDuration, real: RealSpan) -> StepIndex {
533        let writer = self.writer;
534        let index = u32::try_from(writer.entries.len()).unwrap_or(u32::MAX);
535        let step_index = StepIndex::from_index(index);
536
537        let tree_before = writer.tree;
538        let tree_after = match self.tree {
539            Some(yaml) => writer.store_tree(yaml),
540            None => tree_before,
541        };
542        writer.tree = tree_after;
543
544        let keeps_frames = match writer.policy {
545            FramePolicy::None => false,
546            FramePolicy::EveryStep => true,
547            FramePolicy::ActionsOnly => self.kind.is_action(),
548        };
549        let (frame_before, before_from) = if keeps_frames {
550            writer.latest_stored()
551        } else {
552            (None, None)
553        };
554        if let Some(png) = self.frame {
555            writer.latest_frame = Some((Producer::Step(index), png));
556        }
557        // A step that drew nothing new shows the frame it started from.
558        let (frame_after, after_from) = if keeps_frames {
559            writer.latest_stored()
560        } else {
561            (None, None)
562        };
563
564        writer.entries.push(Entry {
565            step: Step {
566                index: step_index,
567                kind: self.kind,
568                location: self.location,
569                virtual_start: self.start,
570                virtual_end: at,
571                events: self.events,
572                messages: self.messages,
573                tasks: self.tasks,
574                state_diff: self.state_diff,
575                attempts: self.attempts,
576                log: self.log,
577                tree_before,
578                tree_after,
579                frame_before,
580                frame_after,
581                outcome,
582            },
583            before_from,
584            after_from,
585        });
586        writer.real.steps.push(RealTiming {
587            step: step_index,
588            real_start: real.start,
589            real_end: real.end,
590        });
591        writer.enforce_cap();
592        step_index
593    }
594}