icedwright-trace 0.0.2

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! [`TraceWriter`]: builds a trace step by step and writes the archive.

use std::collections::{BTreeMap, BTreeSet};
use std::io::Write;
use std::time::SystemTime;

use icedwright_types::VirtualDuration;

use crate::archive::{self, Member, Packing};
use crate::blob::{BlobHash, BlobRef, Png, Yaml, member_name};
use crate::budget::{Producer, StepFrames, drop_order};
use crate::config::{ByteSize, FramePolicy, TraceConfig};
use crate::error::TraceError;
use crate::ids::{RawId, Renumbering, StepIndex};
use crate::meta::{FORMAT, MetaFile, TraceMeta, WRITER};
use crate::normalise::{self, BootInstant};
use crate::step::{
    Attempt, LogLine, RealSpan, RealTiming, RealTimings, SourceLocation, Step, StepKind,
    StepOutcome, TraceEvent, TraceMessage, TraceTask,
};

/// What the app looked like when the harness booted, before any step.
#[derive(Debug, Clone)]
pub struct TraceStart {
    /// The boot instant, for rewriting instants printed in message and state text.
    pub boot: Option<BootInstant>,
    /// The semantic tree at boot, as YAML, which is the first step's tree before.
    pub tree: String,
    /// The frame at boot, which is the first step's frame before.
    pub frame: Option<Png>,
}

/// What [`TraceWriter::write`] wrote.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WriteSummary {
    /// The archive's size in bytes.
    pub bytes: u64,
    /// How many steps it holds.
    pub steps: u32,
    /// How many distinct trees it holds.
    pub trees: u32,
    /// How many distinct frames it holds.
    pub frames: u32,
    /// How many frames were dropped to fit the size cap.
    pub frames_dropped: u32,
}

/// Builds a trace step by step and writes the archive. It takes plain values and knows nothing
/// about iced; the harness's step observer drives it. A step is open between
/// [`begin_step`](TraceWriter::begin_step) and [`StepBuilder::end`].
#[must_use]
#[derive(Debug)]
pub struct TraceWriter {
    meta: TraceMeta,
    cap: ByteSize,
    policy: FramePolicy,
    boot: Option<BootInstant>,
    ids: Renumbering,
    entries: Vec<Entry>,
    real: RealTimings,
    trees: BTreeMap<BlobHash, String>,
    frames: BTreeMap<BlobHash, Png>,
    frame_refs: BTreeMap<BlobHash, usize>,
    frame_bytes: u64,
    tree: BlobRef<Yaml>,
    latest_frame: Option<(Producer, Png)>,
    dropped: BTreeSet<Producer>,
    sources: BTreeMap<String, String>,
    attachments: BTreeMap<String, Vec<u8>>,
}

#[derive(Debug)]
struct Entry {
    step: Step,
    before_from: Option<Producer>,
    after_from: Option<Producer>,
}

impl TraceWriter {
    /// A writer for one test, starting from what the app showed at boot.
    pub fn new(meta: TraceMeta, config: &TraceConfig, start: TraceStart) -> Self {
        let mut writer = Self {
            meta,
            cap: config.size_cap(),
            policy: config.frame_policy(),
            boot: start.boot,
            ids: Renumbering::default(),
            entries: Vec::new(),
            real: RealTimings::default(),
            trees: BTreeMap::new(),
            frames: BTreeMap::new(),
            frame_refs: BTreeMap::new(),
            frame_bytes: 0,
            tree: BlobRef::new(BlobHash::of(start.tree.as_bytes())),
            latest_frame: start.frame.map(|frame| (Producer::Boot, frame)),
            dropped: BTreeSet::new(),
            sources: BTreeMap::new(),
            attachments: BTreeMap::new(),
        };
        writer.tree = writer.store_tree(start.tree);
        writer
    }

    /// Opens a step that began at `at`, measured from boot.
    pub fn begin_step(
        &mut self,
        kind: StepKind,
        location: SourceLocation,
        at: VirtualDuration,
    ) -> StepBuilder<'_> {
        StepBuilder {
            writer: self,
            kind,
            location,
            start: at,
            events: Vec::new(),
            messages: Vec::new(),
            tasks: Vec::new(),
            attempts: Vec::new(),
            log: Vec::new(),
            state_diff: None,
            tree: None,
            frame: None,
        }
    }

    /// Renumbers a raw id to a per-trace ordinal, in order of first appearance. The ordinal's
    /// type follows from the raw id's.
    pub fn ordinal<I: RawId>(&mut self, raw: I) -> I::Ordinal {
        self.ids.ordinal(raw)
    }

    /// The step most recently ended, as the archive will hold it, for streaming a trace while
    /// it is recorded.
    #[must_use]
    pub fn last_step(&self) -> Option<&Step> {
        self.entries.last().map(|entry| &entry.step)
    }

    /// The metadata, for filling in what is known only later, such as the failure message.
    pub fn meta_mut(&mut self) -> &mut TraceMeta {
        &mut self.meta
    }

    /// Records the wall-clock time the test started, which goes in `real.json` only.
    pub fn wall_clock_start(&mut self, started: SystemTime) {
        self.real.wall_clock_start = started.duration_since(SystemTime::UNIX_EPOCH).ok();
    }

    /// Every source file a step's location names, so the caller can add each one.
    #[must_use]
    pub fn referenced_sources(&self) -> BTreeSet<&str> {
        self.entries
            .iter()
            .map(|entry| entry.step.location.file.as_str())
            .collect()
    }

    /// Stores the text of a source file under `source/`, so the trace can show the line of a
    /// step without a checkout.
    pub fn add_source(&mut self, file: &str, text: String) -> Result<(), TraceError> {
        let member = source_member(file)?;
        self.sources.insert(member, text);
        Ok(())
    }

    /// Stores a file the test attached under `attachments/`. `name` is a plain file name; a
    /// second attachment with the same name replaces the first. Attachments are never dropped
    /// to fit the size cap.
    pub fn attach(&mut self, name: &str, bytes: Vec<u8>) -> Result<(), TraceError> {
        let member = attachment_member(name)?;
        self.attachments.insert(member, bytes);
        Ok(())
    }

    /// How many frames have been dropped so far to keep memory under the size cap.
    #[must_use]
    pub fn frames_dropped(&self) -> u32 {
        u32::try_from(self.dropped.len()).unwrap_or(u32::MAX)
    }

    /// Writes the archive to `sink`. When it would pass the size cap, frames are dropped in
    /// the documented order until it fits; trees and steps are never dropped.
    pub fn write(self, sink: &mut impl Write) -> Result<WriteSummary, TraceError> {
        let order = drop_order(&self.step_frames());
        let mut chosen = self.render(&[])?;
        if !self.fits(&chosen.bytes) {
            chosen = self.smallest_fitting(&order)?;
        }
        sink.write_all(&chosen.bytes)?;
        Ok(WriteSummary {
            bytes: u64::try_from(chosen.bytes.len()).unwrap_or(u64::MAX),
            steps: u32::try_from(self.entries.len()).unwrap_or(u32::MAX),
            trees: u32::try_from(self.trees.len()).unwrap_or(u32::MAX),
            frames: chosen.frames,
            frames_dropped: chosen.frames_dropped,
        })
    }

    /// The render that drops the shortest prefix of `order` that fits, or all of it when
    /// nothing does.
    fn smallest_fitting(&self, order: &[Producer]) -> Result<Rendered, TraceError> {
        let (mut low, mut high) = (1, order.len());
        let mut found = None;
        while low <= high {
            let middle = low + (high - low) / 2;
            let attempt = self.render(order.get(..middle).unwrap_or(order))?;
            if self.fits(&attempt.bytes) {
                found = Some(attempt);
                high = middle - 1;
            } else {
                low = middle + 1;
            }
        }
        match found {
            Some(rendered) => Ok(rendered),
            None => self.render(order),
        }
    }

    fn fits(&self, bytes: &[u8]) -> bool {
        u64::try_from(bytes.len()).is_ok_and(|len| len <= self.cap.get())
    }

    /// The archive with the frames of `drop` left out as well as those already dropped.
    fn render(&self, drop: &[Producer]) -> Result<Rendered, TraceError> {
        let drop: BTreeSet<Producer> = drop.iter().copied().collect();
        let dropped = |from: Option<Producer>| from.is_some_and(|p| drop.contains(&p));
        let mut steps = Vec::new();
        let mut kept = BTreeSet::new();
        for entry in &self.entries {
            let mut step = entry.step.clone();
            if dropped(entry.before_from) {
                step.frame_before = None;
            }
            if dropped(entry.after_from) {
                step.frame_after = None;
            }
            kept.extend(
                step.frame_before
                    .iter()
                    .chain(&step.frame_after)
                    .map(|r| r.hash),
            );
            serde_json::to_writer(&mut steps, &step).map_err(std::io::Error::from)?;
            steps.push(b'\n');
        }
        let frames_dropped = u32::try_from(self.dropped.len() + drop.len()).unwrap_or(u32::MAX);
        let meta = MetaFile {
            format: FORMAT,
            written_by: WRITER.to_owned(),
            frames_dropped,
            trace: self.meta.clone(),
        };
        let mut meta = serde_json::to_vec_pretty(&meta).map_err(std::io::Error::from)?;
        meta.push(b'\n');
        let real = serde_json::to_vec(&self.real).map_err(std::io::Error::from)?;

        let mut blobs: BTreeMap<String, (&[u8], Packing)> = BTreeMap::new();
        for (hash, yaml) in &self.trees {
            blobs.insert(
                member_name::<Yaml>(*hash),
                (yaml.as_bytes(), Packing::Deflate),
            );
        }
        for hash in &kept {
            if let Some(png) = self.frames.get(hash) {
                blobs.insert(member_name::<Png>(*hash), (png.as_bytes(), Packing::Store));
            }
        }

        let mut members = vec![
            Member {
                name: archive::META.to_owned(),
                bytes: &meta,
                packing: Packing::Deflate,
            },
            Member {
                name: archive::STEPS.to_owned(),
                bytes: &steps,
                packing: Packing::Deflate,
            },
        ];
        members.extend(blobs.into_iter().map(|(name, (bytes, packing))| Member {
            name,
            bytes,
            packing,
        }));
        members.extend(self.sources.iter().map(|(name, text)| Member {
            name: name.clone(),
            bytes: text.as_bytes(),
            packing: Packing::Deflate,
        }));
        members.extend(self.attachments.iter().map(|(name, bytes)| Member {
            name: name.clone(),
            bytes,
            packing: if name.ends_with(".png") {
                Packing::Store
            } else {
                Packing::Deflate
            },
        }));
        members.push(Member {
            name: archive::REAL.to_owned(),
            bytes: &real,
            packing: Packing::Deflate,
        });
        Ok(Rendered {
            bytes: archive::pack(&members)?,
            frames: u32::try_from(kept.len()).unwrap_or(u32::MAX),
            frames_dropped,
        })
    }

    fn step_frames(&self) -> Vec<StepFrames> {
        self.entries
            .iter()
            .map(|entry| StepFrames {
                tree_changed: entry.step.tree_before != entry.step.tree_after,
                failed: entry.step.outcome.is_failure(),
                before: entry.before_from,
                after: entry.after_from,
            })
            .collect()
    }

    fn store_tree(&mut self, yaml: String) -> BlobRef<Yaml> {
        let hash = BlobHash::of(yaml.as_bytes());
        self.trees.entry(hash).or_insert(yaml);
        BlobRef::new(hash)
    }

    fn store_frame(&mut self, png: &Png) -> BlobRef<Png> {
        let hash = BlobHash::of(png.as_bytes());
        if !self.frames.contains_key(&hash) {
            self.frame_bytes = self
                .frame_bytes
                .saturating_add(u64::try_from(png.len()).unwrap_or(u64::MAX));
            self.frames.insert(hash, png.clone());
        }
        *self.frame_refs.entry(hash).or_insert(0) += 1;
        BlobRef::new(hash)
    }

    fn release_frame(&mut self, frame: Option<BlobRef<Png>>) {
        let Some(frame) = frame else {
            return;
        };
        let Some(count) = self.frame_refs.get_mut(&frame.hash) else {
            return;
        };
        *count = count.saturating_sub(1);
        if *count > 0 {
            return;
        }
        self.frame_refs.remove(&frame.hash);
        if let Some(png) = self.frames.remove(&frame.hash) {
            self.frame_bytes = self
                .frame_bytes
                .saturating_sub(u64::try_from(png.len()).unwrap_or(u64::MAX));
        }
    }

    fn drop_frame(&mut self, producer: Producer) {
        let mut released = Vec::new();
        for entry in &mut self.entries {
            if entry.before_from == Some(producer) {
                released.push(entry.step.frame_before.take());
                entry.before_from = None;
            }
            if entry.after_from == Some(producer) {
                released.push(entry.step.frame_after.take());
                entry.after_from = None;
            }
        }
        released
            .into_iter()
            .for_each(|frame| self.release_frame(frame));
        self.dropped.insert(producer);
    }

    /// Drops frames by the documented order, over the steps so far, while the frames held in
    /// memory pass twice the cap. The slack lets `write` choose from the whole trace whenever
    /// the frames are no more than twice the cap.
    fn enforce_cap(&mut self) {
        let limit = self.cap.get().saturating_mul(2);
        if self.frame_bytes <= limit {
            return;
        }
        for producer in drop_order(&self.step_frames()) {
            self.drop_frame(producer);
            if self.frame_bytes <= limit {
                return;
            }
        }
    }

    /// The latest frame, stored for a step, unless the cap already dropped it.
    fn latest_stored(&mut self) -> (Option<BlobRef<Png>>, Option<Producer>) {
        let Some((producer, png)) = self.latest_frame.take() else {
            return (None, None);
        };
        let stored = if self.dropped.contains(&producer) {
            (None, None)
        } else {
            (Some(self.store_frame(&png)), Some(producer))
        };
        self.latest_frame = Some((producer, png));
        stored
    }
}

#[derive(Debug)]
struct Rendered {
    bytes: Vec<u8>,
    frames: u32,
    frames_dropped: u32,
}

/// The member a source file is stored under, refusing paths that would leave `source/`.
pub(crate) fn source_member(file: &str) -> Result<String, TraceError> {
    let normal = file.replace('\\', "/");
    let escapes = normal.is_empty()
        || normal.starts_with('/')
        || normal.contains(':')
        || normal
            .split('/')
            .any(|part| part.is_empty() || part == "." || part == "..");
    if escapes {
        return Err(TraceError::BadSourcePath(file.to_owned()));
    }
    Ok(format!("{}{normal}", archive::SOURCE_PREFIX))
}

/// Refuses an attachment name that is not a plain file name, as [`TraceWriter::attach`] would.
pub fn check_attachment_name(name: &str) -> Result<(), TraceError> {
    attachment_member(name).map(|_| ())
}

/// The member an attachment is stored under: a plain file name, with no directories.
pub(crate) fn attachment_member(name: &str) -> Result<String, TraceError> {
    let plain = !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\', ':']);
    if !plain {
        return Err(TraceError::BadAttachmentName(name.to_owned()));
    }
    Ok(format!("{}{name}", archive::ATTACHMENT_PREFIX))
}

/// One open step. Recording into it after [`end`](StepBuilder::end) does not compile, because
/// `end` takes it by value.
#[must_use = "a step is only recorded when `end` is called"]
#[derive(Debug)]
pub struct StepBuilder<'w> {
    writer: &'w mut TraceWriter,
    kind: StepKind,
    location: SourceLocation,
    start: VirtualDuration,
    events: Vec<TraceEvent>,
    messages: Vec<TraceMessage>,
    tasks: Vec<TraceTask>,
    attempts: Vec<Attempt>,
    log: Vec<LogLine>,
    state_diff: Option<String>,
    tree: Option<String>,
    frame: Option<Png>,
}

impl StepBuilder<'_> {
    /// Records an input event.
    pub fn event(&mut self, event: TraceEvent) {
        self.events.push(event);
    }

    /// Records a message. Instants in its `Debug` text become offsets from boot, and text
    /// past 4 KiB is cut with its full length recorded.
    pub fn message(&mut self, mut message: TraceMessage) {
        let debug = match self.writer.boot {
            Some(boot) => normalise::rewrite_instants(&message.debug, boot),
            None => message.debug,
        };
        let (debug, full_len) = normalise::truncate(debug, normalise::MESSAGE_LIMIT);
        message.debug = debug;
        message.full_len = full_len;
        self.messages.push(message);
    }

    /// Records a task lifecycle change.
    pub fn task(&mut self, task: TraceTask) {
        self.tasks.push(task);
    }

    /// Records one evaluation of an `expect`.
    pub fn attempt(&mut self, attempt: Attempt) {
        self.attempts.push(attempt);
    }

    /// Adds a line to the step's call log.
    pub fn log(&mut self, line: LogLine) {
        self.log.push(line);
    }

    /// Records the state's `{:#?}` text before and after the step as a unified diff, or a
    /// note when either is over 256 KiB.
    pub fn state(&mut self, before: &str, after: &str) {
        self.state_diff = match self.writer.boot {
            Some(boot) => normalise::state_diff(
                &normalise::rewrite_instants(before, boot),
                &normalise::rewrite_instants(after, boot),
            ),
            None => normalise::state_diff(before, after),
        };
    }

    /// Sets the semantic tree, as YAML, once the step settled. Without one, the tree is
    /// unchanged from the step before.
    pub fn tree(&mut self, yaml: String) {
        self.tree = Some(yaml);
    }

    /// Sets the frame once the step settled. Without one, the frame is unchanged from the step
    /// before, and the step's frame after is that frame.
    pub fn frame(&mut self, png: Png) {
        self.frame = Some(png);
    }

    /// Renumbers a raw id, as [`TraceWriter::ordinal`] does.
    pub fn ordinal<I: RawId>(&mut self, raw: I) -> I::Ordinal {
        self.writer.ordinal(raw)
    }

    /// Closes the step at `at`, with its real-clock span kept apart in `real.json`.
    pub fn end(self, outcome: StepOutcome, at: VirtualDuration, real: RealSpan) -> StepIndex {
        let writer = self.writer;
        let index = u32::try_from(writer.entries.len()).unwrap_or(u32::MAX);
        let step_index = StepIndex::from_index(index);

        let tree_before = writer.tree;
        let tree_after = match self.tree {
            Some(yaml) => writer.store_tree(yaml),
            None => tree_before,
        };
        writer.tree = tree_after;

        let keeps_frames = match writer.policy {
            FramePolicy::None => false,
            FramePolicy::EveryStep => true,
            FramePolicy::ActionsOnly => self.kind.is_action(),
        };
        let (frame_before, before_from) = if keeps_frames {
            writer.latest_stored()
        } else {
            (None, None)
        };
        if let Some(png) = self.frame {
            writer.latest_frame = Some((Producer::Step(index), png));
        }
        // A step that drew nothing new shows the frame it started from.
        let (frame_after, after_from) = if keeps_frames {
            writer.latest_stored()
        } else {
            (None, None)
        };

        writer.entries.push(Entry {
            step: Step {
                index: step_index,
                kind: self.kind,
                location: self.location,
                virtual_start: self.start,
                virtual_end: at,
                events: self.events,
                messages: self.messages,
                tasks: self.tasks,
                state_diff: self.state_diff,
                attempts: self.attempts,
                log: self.log,
                tree_before,
                tree_after,
                frame_before,
                frame_after,
                outcome,
            },
            before_from,
            after_from,
        });
        writer.real.steps.push(RealTiming {
            step: step_index,
            real_start: real.start,
            real_end: real.end,
        });
        writer.enforce_cap();
        step_index
    }
}