Summaries¶
A plot of a long track has a few hundred pixels across, and the track may hold millions of items. Reading them all for one picture costs far too much. A writer therefore keeps summaries beside the data, a coarse view built while the run is recorded. A viewer draws the whole track from them and zooms in to the items where it needs them.
A viewer, for example, opens on the whole hour of phase_a, 90 million samples, in a plot 600 pixels wide. The
track's chunks hold about 100 MB, and the viewer draws the hour from the summaries instead.
A tree over item numbers¶
A summary node covers a run of a track's items and holds what a viewer needs to draw them. A node at level 0 covers a power of two of items, 1 024 samples for the drive's current. Each level up, a node covers 16 nodes of the level below: at level 1, 16 384 samples. The nodes run over item numbers, not time. A sparse track therefore has no empty nodes, and the nodes of two pieces of one track line up.
A track has one of two kinds of tree:
| Tree | Level 0 | A node holds |
|---|---|---|
| events | 2 048 items | the first and last item's start, the OR of the items' flags, and for spans the latest end |
| series | a power of two of samples, which the track picks | per channel, the statistics the track declares |
A series declares its statistics in its definition, a SeriesSummarySpec. The drive's phase_a keeps the minimum,
the maximum, the sum and the sum of squares. From them a viewer draws the envelope and the root mean square:
SeriesSummarySpec {
base_shift: 10,
stats: SeriesStats {
min: true,
max: true,
sum: true,
sum_sq: true,
clipped: false,
flags: false,
power_mean: false,
power_max: false,
},
clip: None,
}
What the example uses here: phase_def, phase_shape
/// The `phase_a` series definition at `hz` samples a second.
pub fn phase_def(hz: u32, summaries: bool) -> Option<GridDef<'static>> {
let mut def = GridDef::of::<i16>(1, Ratio64::new(1_000_000, u64::from(hz))?);
def.scale = Magnitude::pow10(-3);
def.summaries = summaries.then(phase_summaries);
Some(def)
}
/// The shape of `phase_a`'s samples: its track's items are i16 numbers, one channel.
pub fn phase_shape(def: &GridDef<'_>) -> SampleShape {
def.shape(<i16 as SeriesValue>::ELEMENT)
}
A node holds no ticks, since the chunks' grids give every sample's tick. A summary block holds the nodes of one level over a stretch of the track. The index lists it like any block, with its level.
phase_a over its item numbers: each node at level 1 merges 16 nodes of level
0, and each bar spans its node's minimum and maximum. The viewer's pixel columns take the nodes of the coarsest level
that still has a node per column. Drawn by ww_tape_figures from the summary blocks of the drive's
recording at 1/1000 of its data.Drawing the hour¶
The viewer picks the coarsest level whose nodes still outnumber its 600 columns. Every column then gets several nodes, and no column falls between two:
// the coarsest level whose nodes still outnumber the columns: a level up, a node covers 16 times as many samples
let mut level = 0u8;
while total >> (spec.base_shift + 4 * (level + 1)) >= COLUMNS as u64 {
level += 1;
}
What the example uses here: the fault's constants, series_def, column_of, nodes
/// Microseconds of the board's clock in a minute.
const US_PER_MINUTE: i64 = 60_000_000;
/// Pixel columns of the viewer's plot of the hour.
pub const COLUMNS: usize = 600;
/// [COLUMNS] as a number of µs to divide.
const COLUMNS_I64: i64 = 600;
/// Microseconds of the current before the fault that [current] reads.
pub const BEFORE_US: i64 = 20_000;
/// Microseconds of frames after the fault that [frames] lists.
pub const AFTER_US: i64 = 5_000;
/// The period and the summaries of `phase_a`, found by its key among the definitions in force at `offset` of piece
/// `piece`.
fn series_def<S: ByteSource>(
reader: &TapeReader<S>,
piece: usize,
offset: u64,
) -> Result<(Ratio64, Option<SeriesSummarySpec>), FaultError<S::Error>> {
let defs = reader.definitions_at(piece, offset)?;
let number = defs
.track_number(key("phase_a").id(), [0; 32])
.ok_or(FaultError::Missing("phase_a"))?;
let state = defs
.items
.get(&Slot::Track { number })
.ok_or(FaultError::Missing("definition of phase_a"))?;
let Ok(Describe::Track(def)) = Describe::from_ww_bytes(&state.item) else {
return Err(FaultError::Missing("track definition that decodes"));
};
let TrackKind::Series(series) = def.kind else {
return Err(FaultError::Missing("series definition"));
};
Ok((series.period, series.summaries))
}
/// The column of sample `i` of `total`.
fn column_of(i: u64, total: u64) -> usize {
let c = u128::from(i) * COLUMNS as u128 / u128::from(total.max(1));
usize::try_from(c).map_or(COLUMNS - 1, |c| c.min(COLUMNS - 1))
}
/// The nodes of the summary blocks of `phase_a` at `level` in every piece that cover any sample of `items`, each with
/// its first sample and the samples it covers.
fn nodes<S: ByteSource>(
reader: &TapeReader<S>,
entries: &[Vec<IndexEntry>],
level: u8,
items: core::ops::Range<u64>,
mut take: impl FnMut(u64, u64, ChannelStats),
) -> Result<(u64, u64), FaultError<S::Error>> {
let (mut blocks, mut count) = (0, 0);
let mut buf = Vec::new();
for (i, entries) in entries.iter().enumerate() {
for e in entries {
// entries: phase_a's index entries in piece i
let wanted =
e.first_item < ItemNum::new(items.end) && e.end_item() > ItemNum::new(items.start);
if e.kind != BlockKind::Summary || e.level != level || !wanted {
continue; // another block, another level, or outside the range drawn
}
let block = reader.read_block(i, e, &mut buf)?;
let summary = Summary::of_block(&block).ok_or(FaultError::Missing("summary"))?;
let span = 1u64 << summary.head().node_shift; // samples a node covers
for n in 0..summary.node_count() {
let stats = summary
.channel_stats(0, n)
.ok_or(FaultError::Missing("node"))?;
let first = summary.head().first_item.saturating_add(n as u64 * span);
let samples = span.min(first.saturating_offset_to(e.end_item())); // the last node may be partial
take(first.get(), samples, stats);
}
blocks += 1;
count += summary.node_count() as u64;
}
}
Ok((blocks, count))
}
For the hour of phase_a that is level 1, nodes of 16 384 samples. The viewer reads the summary blocks of that level
in each piece, and merges each node into the column its first sample falls in:
for e in entries {
// entries: phase_a's index entries in piece i
let wanted =
e.first_item < ItemNum::new(items.end) && e.end_item() > ItemNum::new(items.start);
if e.kind != BlockKind::Summary || e.level != level || !wanted {
continue; // another block, another level, or outside the range drawn
}
let block = reader.read_block(i, e, &mut buf)?;
let summary = Summary::of_block(&block).ok_or(FaultError::Missing("summary"))?;
let span = 1u64 << summary.head().node_shift; // samples a node covers
for n in 0..summary.node_count() {
let stats = summary
.channel_stats(0, n)
.ok_or(FaultError::Missing("node"))?;
let first = summary.head().first_item.saturating_add(n as u64 * span);
let samples = span.min(first.saturating_offset_to(e.end_item())); // the last node may be partial
take(first.get(), samples, stats);
}
What the example uses here: column_of
The overview reads 175 summary blocks with 5 497 nodes: about 194 KB in 175 reads, and no sample. Finding those
blocks costs more than reading them. phase_a's index entries in the four pieces take about 843 KB in 19 reads,
since the track has a chunk a second. A viewer that opens the recording once keeps the entries in memory.
All 600 columns get nodes. The column with the highest peak is column 519, from 51:54.000, at 31 873 mA. It holds the seconds just before the current stops at 52:00.
Zooming in¶
Next the viewer zooms into that column. It reads the level-0 nodes of the column alone, from the summary blocks whose items overlap it, with the same loop. The node with the highest peak covers the 1 024 samples from item 77 999 104, at 51:59.964. The zoom reads about 6.8 KB in 6 reads.
That node lies in the chunk from 51:59.000, which Series reads, sample by sample. The way from the hour to the 500 samples before the trip thus runs through summaries and one chunk. Events reads the frames after the trip, and Reading a tape the mode on either side.

eventfull_book_shots from the recording at full
rate.How nodes merge¶
Every statistic merges: a parent is its 16 children merged in item order, with ChannelStats::merge for a series
and EventNode::merge for events. A reader that builds coarser bins of its own, such as the viewer's columns, gets
exactly what the writer would have stored. A minimum of minimums is the minimum, and sums add.
Nodes of two scales merge at their common scale, as Changing scale mid-run shows. A summary block states its scale, so it reads without the chunks.
Writing summaries¶
The crate ww_tape_summary builds the trees as the items arrive: an EventTree for an event track, a
SeriesSummaries for a series. A recorder that writes the file itself starts one for phase_a with the track's first grid and
period:
let start = SeriesStart {
track_id: key("phase_a").id(),
track_number: numbers.phase_a,
shape: crate::defs::phase_shape(&def),
first_item: ItemNum::new(0),
grid: def.first_grid(0),
period: def.period,
tile: ww_tape::TileCoords::NONE,
tile_cells: 1,
};
Some(SeriesSummaries::new(start, crate::defs::phase_summaries())?)
What the example uses here: DriveNumbers, key, phase_def, phase_shape
/// The numbers the drive's definitions were given ([Definitions::define_clock], [Definitions::define_track]): what its
/// records, chunks and maps name each clock and track by.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DriveNumbers {
/// The board's microsecond timer since boot: the clock of every track.
pub board_clock: ClockNum,
/// The host's wall clock in ns since the Unix epoch, which the board's clock maps to.
pub host_clock: ClockNum,
/// The firmware's log lines.
pub log: TrackNum,
/// The controller's mode, a state track.
pub mode: TrackNum,
/// CAN frames on the vehicle bus.
pub can0: TrackNum,
/// Phase current, 16-bit fixed point in mA.
pub phase_a: TrackNum,
/// Board temperature.
pub temp: TrackNum,
}
/// The key of a track at `name` in the drive's API.
pub fn key(name: &str) -> TrackKey {
track_key(API_ROOT, &[Segment::Name(name)])
}
/// The `phase_a` series definition at `hz` samples a second.
pub fn phase_def(hz: u32, summaries: bool) -> Option<GridDef<'static>> {
let mut def = GridDef::of::<i16>(1, Ratio64::new(1_000_000, u64::from(hz))?);
def.scale = Magnitude::pow10(-3);
def.summaries = summaries.then(phase_summaries);
Some(def)
}
/// The shape of `phase_a`'s samples: its track's items are i16 numbers, one channel.
pub fn phase_shape(def: &GridDef<'_>) -> SampleShape {
def.shape(<i16 as SeriesValue>::ELEMENT)
}
Each second, the recorder pushes the second's samples. A level that fills a block gives that block, and the recorder
hands it to the writer with TapeWriter::defer_block. The writer places a deferred block where it fits, in
an aligned file into the gap before a chunk's payload:
if let Some(s) = &mut self.summaries {
s.push(&values, 0)?; // a second of samples, flags 0
// the blocks of the levels that filled, for the writer's defer_block
self.queue
.extend(s.take_blocks().into_iter().map(Act::Summary));
}
What the example uses here: Act
/// One thing the recorder hands the chain.
#[derive(Clone, Debug, PartialEq)]
pub enum Act {
/// A put of the mode in force from `ticks` on.
Put { ticks: i64, mode: Mode },
/// A records block: log lines and temperatures, (track, ticks, item) in time order.
Records(Vec<(TrackNum, i64, Vec<u8>)>),
/// A chunk of `can0` or `phase_a`: its head and columns.
Chunk {
head: Box<ChunkHead>,
columns: Vec<(ColumnSpec, Vec<u8>)>,
},
/// A summary block of `phase_a`.
Summary(Vec<u8>),
}
At the end of the run, SeriesSummaries::finish gives the blocks of the partial nodes. The first piece of the
drive's recording holds 735 summary blocks of about 825 KB, beside about 25 MB of samples. A lost summary block
costs nothing that a reader cannot rebuild from the chunks.
A recorder that writes through a TapeMux builds no tree of its own. Its GridHandle computes the leaves of the
samples it takes, as its summaries option says (Samples into columns shows
it). The writing thread builds the levels above them, one tree per piece, ended before each cut and at the close. A mux
resumed after a crash rebuilds the tree of the torn piece from the chunks the piece kept. The resumed file then holds
the bytes of the run without the crash.
The crate ww_tape itself reads only a summary block's head, with Block::summary_head, which is enough to list
the block in the index. Summary::of_block in ww_tape_summary reads the nodes. Checks and range hashes
shows how a copy proves that it holds the same frames as the recording.
pub struct SeriesSummarySpec {
/// A level-0 node holds `2^base_shift` samples, [Self::BASE_SHIFT_MIN] to [Self::BASE_SHIFT_MAX]; each level up 16
/// times more. A raw format field: log2 of a sample count.
pub base_shift: u8,
pub stats: SeriesStats,
/// Where samples clip; None: at the scalar type's ends for integers, infinities for floats.
pub clip: Option<ClipRange>,
}
What summaries a series track keeps: its declaration, as the track definition carries it.
pub fn merge(&mut self, next: &Self, samples: u64, next_samples: u64)
Merge next (next_samples samples, right after this one's samples) into this one. Merging in item order,
one node at a time, gives the same bits as the writer's parent node.
pub fn merge(&mut self, next: &Self) {
self.last_tick = next.last_tick;
self.flags |= next.flags;
self.latest_end = self.latest_end.max(next.latest_end);
}
Merge next, the node right after this one, into this one.
pub struct EventTree {
track_id: TrackId,
track_number: TrackNum,
fields: EventFields,
origin: u64,
next_item: u64,
/// The open level-0 node
acc: Option<EventNode>,
levels: Levels<EventNode>,
blocks: Vec<Vec<u8>>,
/// Last start of the last closed level-0 node
last_tick: Option<i64>,
}
Builds the item tree of one event track as items are completed, and encodes its summary blocks.
pub struct SeriesSummaries<T: Scalar> {
leaves: SeriesLeaves<T>,
tree: SeriesTree,
}
Builds the summary tree of one series track as samples come, and encodes its summary blocks.
pub fn defer_block(
&mut self,
defs: &Definitions,
block: Vec<u8>,
) -> Result<(), WriteError<S::Error>>
A small summary or data block that may wait for the gap in front of the next aligned chunk payload: checked
against defs and the definitions it needs put now, as for a block written now; when it is placed, nothing
is put.
TapeWriter.pub fn finish(&mut self) -> Result<(), BuildError> {
self.leaves.complete()?;
self.take_leaves()?;
self.tree.finish()
}
Write the open nodes of every level, partial ones included, as blocks. Call it once, after the last sample.
pub struct TapeMux<T: PieceStore> {
shared: Arc<Shared<T>>,
thread: Option<JoinHandle<()>>,
}
Writes one chain from a thread of its own, for producers on any thread; see the crate docs.
pub struct GridHandle<T: PieceStore, S: Scalar + Sample + Send + 'static> {
s: Sender<T>,
open: Arc<Open<T, GridChunks<S>>>,
backlog: Backlog<T>,
track: TrackNum,
}
Writes the time steps of one grid track from one producer: the whole grid, or one box of its tiles.
pub fn summary_head(&self) -> Option<SummaryHead> {
if !self.is_summary() {
return None;
}
SummaryHead::read(self.bytes).ok().map(|(head, _, _)| head)
}
The head of a summary block whose body this reader knows: what an index lists, without the nodes.
pub fn of_block(block: &Block<'b>) -> Option<Self> {
if !block.body_known() || block.kind != BlockKind::Summary {
return None;
}
Self::read(block.bytes()).ok()
}
The summary of a summary block whose body this reader knows (Block::body_known); None for another block, or one whose head or body length breaks the format.