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
//! The order frames are dropped in when a trace would pass its size cap.
//!
//! A frame is identified by the step that produced it: a step's frame after is the next step's
//! frame before, so dropping a frame clears both slots. The order depends only on the steps,
//! and the writer drops the shortest prefix of it that fits, so the result depends only on
//! sizes.

use std::collections::BTreeSet;

/// Where a frame came from: the boot render, or the end of a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum Producer {
    Boot,
    Step(u32),
}

/// What the drop order needs to know about one step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StepFrames {
    pub(crate) tree_changed: bool,
    pub(crate) failed: bool,
    pub(crate) before: Option<Producer>,
    pub(crate) after: Option<Producer>,
}

/// Every droppable frame in the order it goes: frames of steps whose tree did not change,
/// then every other remaining frame, pass after pass. Frames of the first step, the last step,
/// each failing step and the step before it are never in the order.
pub(crate) fn drop_order(steps: &[StepFrames]) -> Vec<Producer> {
    let Some(last) = steps.len().checked_sub(1) else {
        return Vec::new();
    };
    let mut protected_steps = BTreeSet::from([0, last]);
    for (index, step) in steps.iter().enumerate() {
        if step.failed {
            protected_steps.insert(index);
            protected_steps.insert(index.saturating_sub(1));
        }
    }
    let protected: BTreeSet<Producer> = protected_steps
        .iter()
        .filter_map(|index| steps.get(*index))
        .flat_map(|step| [step.before, step.after])
        .flatten()
        .collect();
    let candidates: BTreeSet<Producer> = steps
        .iter()
        .flat_map(|step| [step.before, step.after])
        .flatten()
        .filter(|producer| !protected.contains(producer))
        .collect();

    let unchanged = |producer: &Producer| match producer {
        Producer::Boot => false,
        Producer::Step(index) => usize::try_from(*index)
            .ok()
            .and_then(|index| steps.get(index))
            .is_some_and(|step| !step.tree_changed),
    };
    let (mut order, mut rest): (Vec<Producer>, Vec<Producer>) =
        candidates.into_iter().partition(unchanged);
    while !rest.is_empty() {
        if let [only] = rest.as_slice() {
            order.push(*only);
            break;
        }
        let (kept, dropped): (Vec<_>, Vec<_>) = rest
            .iter()
            .enumerate()
            .partition(|(position, _)| position % 2 == 0);
        order.extend(dropped.into_iter().map(|(_, producer)| *producer));
        rest = kept.into_iter().map(|(_, producer)| *producer).collect();
    }
    order
}

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

    /// Steps where each step's frame before is the previous step's frame after.
    fn chain(changed: &[bool], failed: &[usize]) -> Vec<StepFrames> {
        (0..changed.len())
            .map(|index| StepFrames {
                tree_changed: changed[index],
                failed: failed.contains(&index),
                before: Some(match index {
                    0 => Producer::Boot,
                    _ => Producer::Step(index as u32 - 1),
                }),
                after: Some(Producer::Step(index as u32)),
            })
            .collect()
    }

    fn steps(indices: &[u32]) -> Vec<Producer> {
        indices.iter().map(|index| Producer::Step(*index)).collect()
    }

    #[test]
    fn nothing_to_drop_without_steps() {
        assert!(drop_order(&[]).is_empty());
    }

    #[test]
    fn unchanged_trees_go_first_then_every_other_frame() {
        let mut changed = vec![true; 12];
        changed[4] = false;
        changed[8] = false;
        let order = drop_order(&chain(&changed, &[7]));
        // Protected: step 0 (boot, 0), step 11 (10, 11), failing step 7 (6, 7) and step 6 (5, 6).
        // Unchanged: 4 and 8. Remaining 1, 2, 3, 9: every other is 2, 9, then 3, then 1.
        assert_eq!(order, steps(&[4, 8, 2, 9, 3, 1]));
    }

    #[test]
    fn a_single_remaining_frame_is_dropped_last() {
        let order = drop_order(&chain(&[true; 4], &[]));
        // Protected: step 0 (boot, 0) and step 3 (2, 3). Remaining: 1.
        assert_eq!(order, steps(&[1]));
    }

    #[test]
    fn frames_without_a_step_are_not_ordered() {
        let mut frames = chain(&[true; 6], &[]);
        for step in &mut frames {
            step.before = None;
        }
        frames[2].after = None;
        // Protected: 0 and 5. Remaining 1, 3, 4: drop 3, then 4, then 1.
        assert_eq!(drop_order(&frames), steps(&[3, 4, 1]));
    }

    #[test]
    fn every_unprotected_frame_appears_once() {
        let frames = chain(&[true; 50], &[30]);
        let order = drop_order(&frames);
        let unique: BTreeSet<_> = order.iter().collect();
        assert_eq!(unique.len(), order.len());
        // 51 frames (boot and 50 steps), minus boot, 0, 48, 49, 28, 29 and 30.
        assert_eq!(order.len(), 51 - 7);
    }
}