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