Reading a tape¶
A recording can run to gigabytes, 3.7 GB for a minute of a radio capture. The question asked of it is often about one second. A reader answers it with a few small reads. It opens a file or a chain, finds the blocks of one track in a time range, and looks up the state in force there. Each step uses what a closed piece says about itself at its end and in its index.
The example is a query on the drive's recording for the second around the fault at minute 52 of its hour. The recording
is a chain of four pieces, about 116 MB in all. Every number below comes from src/fault.rs. This program
runs each step on that recording and counts the bytes it reads. cargo run -p example_drive prints them.
Byte sources¶
A reader, TapeReader, reads a tape through a byte source: anything with a length that reads bytes at an
offset. The trait is ByteSource, and the crate provides it for these:
- a byte slice or a
Vec<u8>, such as a whole file read into memory; - a file on disk, through
FileSource::open, which reads only what the reader asks for; - a tape still being written into memory, through
MemSink::tape.
An HTTP resource read by range requests can be a byte source too. The reader itself needs no file system and no threads, so it builds for WebAssembly and runs in a browser or a tool. It needs an allocator, like the writer, and it is not meant for firmware. A small device reads its own log with logring.
In the example, the drive's four pieces lie back to back in one file. The program wraps that file in a byte source that counts each read, and so measures what each step costs.
Opening from the tails¶
A closed piece describes itself at its end. Its last 164 bytes are the tail, which gives the piece's length
and the offset of its close record. TapeReader::open therefore starts at the end of the bytes and works
backwards:
- It reads the tail of the last piece, and from it the piece's start.
- It reads that piece's close, which lists every track the piece holds with its items and ticks, and its piece head.
- The tail of the piece before lies just before that start, so the reader steps back piece by piece.
For the drive's chain, opening reads about 17 KB in 28 reads, and TapeReader::pieces lists four pieces. Each
PieceInfo holds the piece's start and end, its head and its close with a row per track. The row of phase_a says
which ticks the track's chunks cover in that piece. The program picks the piece whose row reaches 52:00, without
another read:
let reader = TapeReader::open(src)?; // the tails, the closes and the heads, last piece first
let fault = fault_us(); // 52:00 on the board's µs clock
// the piece whose close says phase_a reaches the fault: no read beyond what opening read
let piece = reader
.pieces()
.iter()
.position(|p| {
p.close.as_ref().is_some_and(|(_, tracks)| {
tracks.iter().any(|t| {
t.track_id == key("phase_a").id()
&& t.first_tick <= fault
&& fault <= t.last_tick
})
})
})
.ok_or(FaultError::Missing("piece holding the fault"))?;
What the example uses here: fault_us, key, Opened
/// The ticks of the fault on the board's clock, µs since boot.
pub const fn fault_us() -> i64 {
FAULT_MINUTE as i64 * US_PER_MINUTE
}
/// 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)])
}
/// What [open] found: the pieces, and the one that holds the fault.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Opened {
pub pieces: usize,
pub piece: usize,
}
The fault lies in piece 3, the last one. A piece that a crash left without a tail is found from its newest
checkpoint instead, as When the power fails shows. A piece still being
written, or closed more than once, reads as Reading a growing piece explains. A raw medium such
as a card is read forwards from its start, since an older recording's tail there may pass for the newest one. Open it
with TapeReader::open_with and Medium::Raw; Where the data ends on a raw card explains why.
Finding blocks through the index¶
The final index of a closed piece lists every block with an index entry, and the entries of one track lie together. An entry says where the block is and what it holds, so a reader picks blocks before it reads any:
Field of IndexEntry |
What it says |
|---|---|
offset, len |
where the block lies in the piece |
kind, track_id |
a records block, a chunk or a summary block, and of which track |
first_item, count |
the item numbers the block holds |
first_tick, last_tick, latest_end |
the ticks of its first and last item, and the latest end of any item |
TapeReader::track_entries gives the entries of one track in file order. In a closed piece it reads the final
index's directory and that track's list, each checked by its own CRC. It never walks the
file. The example asks for phase_a in the second either side of the fault:
let (from, to) = (fault - 1_000_000, fault + 1_000_000); // a second either side
let entries = reader.track_entries(piece, key("phase_a").id())?; // the directory and one track's list
let chunks: Vec<IndexEntry> = entries
.iter()
.filter(|e| e.kind == BlockKind::Series && e.first_tick < to && e.last_tick >= from)
.copied()
.collect();
What the example uses here: fault_us, key, Found
/// The ticks of the fault on the board's clock, µs since boot.
pub const fn fault_us() -> i64 {
FAULT_MINUTE as i64 * US_PER_MINUTE
}
/// 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)])
}
/// What [find] found: the blocks of `phase_a` in the piece and those within a second of the fault.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Found {
/// Entries in the track's list: its chunks and summary blocks.
pub listed: usize,
/// The chunks of the second before the fault and of the second after it, in file order.
pub chunks: Vec<IndexEntry>,
}
phase_a's list in the last piece holds 1 638 entries, its chunks and its summary blocks. The query keeps two of
them, the chunks from 51:59.000 to 51:59.999 and from 52:00.000 to 52:00.999. It reads about 210 KB in 3 reads,
almost all of them the track's list. A track with a chunk every second has a long list, and a reader that queries it
often keeps the list in memory.
phase_a and can0 in the drive's last piece, each over
the ticks it covers, and the entries a query for the stretch around the fault reads. Drawn by
ww_tape_figures from the drive's recording at 1/1000 of its data, where a chunk covers a minute instead of
a second.

081 follows the fault. A screenshot rendered by
eventfull_book_shots from the recording at full rate.An entry also carries what a query by item number needs. A reader that wants item 3 120 000 of can0 takes the
entry whose first_item and count hold it. Item j of a chunk is item first_item + j of its track. An item number
counts a track's items over the whole recording, across pieces. It therefore names the same item in the recording
however its pieces are stored, in one file or in many.
State at a place¶
Data often needs a state to mean something. The items of a state track stay in force until the next one replaces
them. A tape therefore has no "current state" of a whole file: what is in force depends on the place. A reader asks
for the state in force where its data starts. The two chunks of the example give the drive's current, for instance,
and the mode track says what the controller was doing.
TapeReader::state_at finds the newest record of a slot whose block starts before a place. Every state record
has an index entry of its own, which holds its slot and the hash of its item. The lookup therefore goes through the
index to the one block it needs:
let lookup = reader.state_at(piece, Slot::State { track: mode }, chunk.offset)?;
let record = lookup.item.as_ref().ok_or(FaultError::Missing("mode"))?;
// record.item is the mode in force; record.offset is where its block starts
What the example uses here: number_of, InForce
/// The number of the drive's track `name` among the definitions in force at `offset` of piece `piece`: a reader
/// finds a track by its key.
fn number_of<S: ByteSource>(
reader: &TapeReader<S>,
piece: usize,
offset: u64,
name: &'static str,
) -> Result<TrackNum, FaultError<S::Error>> {
reader
.definitions_at(piece, offset)?
.track_number(key(name).id(), [0; 32])
.ok_or(FaultError::Missing(name))
}
/// The mode in force at a place, as [mode] found it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InForce {
/// The item in force.
pub item: Vec<u8>,
/// Bytes between the record and the place.
pub behind: u64,
/// The record's time, µs since boot.
pub at_us: i64,
/// Nothing newer can hide: no block lost, every stretch covered.
pub whole: bool,
}
At the chunk before the fault, the mode is run, 31 A limit, and its record from 45:35 lies about 12 MB behind. That
record is the state copy which the writer adds after the record the cut carried into the last piece. At the chunk
from 52:00, the mode is fault: overcurrent, from 52:00, and lies about 2 KB behind.
The number of mode is only the file's name for the track, so the reader first finds it by its key among the
definitions in force. With that, both lookups together read about 4.2 KB in 10 reads. Each record lies within near,
32 MiB, so a reader of the last piece alone finds both.
TapeReader::definitions_at answers the same question for every definition at once: the clocks, the clock map
and each track's definition in force at a place. The program uses it to learn phase_a's period before it reads the
samples. TapeReader::item_by_hash finds a state item by the hash of its bytes, for an application that refers to
an item that way.
When a lookup meets damage¶
Damage is a reason to look further back, never an error. When the newest record of a slot does not read, the lookup lists it as lost and takes the next older record. It also names the stretches the index does not cover, because a newer record may lie there. Such a stretch is a gap a scan read past, or the bytes after a torn end.
A Lookup carries the record, the lost blocks, the uncovered stretches and whether its read budget ran out.
Lookup::is_whole says that none of these happened, so no newer record can hide. Both lookups of the example are
whole. A viewer that shows a state from a lookup that is not whole marks it as uncertain.
Reading the items of a block¶
Once the reader has an entry, TapeReader::read_block reads the block and checks its CRC-32C.
TapeReader::read_chunk_head reads only a chunk's head, up to its payload, which gives a series chunk's
grid without its samples. What comes next depends on the kind of block:
| Block | Read with | Chapter |
|---|---|---|
| a records block | Block::records: each record's track, time and item |
Blocks |
| an events chunk | its time columns and payloads, in place | Events |
| a series chunk | its samples, from any sample on | Series |
| a [[summary block | summary]] | its nodes, a coarse view of a track |
A block that fails its CRC is damaged, and a reader skips it. Its index entry still says what it held: which track,
which items and which ticks. When bytes go bad shows how much of a damaged chunk still reads. The next
chapter reads an events chunk in place, such as the frames on can0 around the fault.
TapeReader.//! The fault at minute 52 found in code: the program of the book's Part IV.
//!
//! An engineer opens the drive's chain ([open]), finds the blocks of `phase_a` around the fault and the mode in force
//! there ([find], [mode]), reads the CAN frames after it ([frames]) and the current before it ([current]). A viewer
//! draws the hour of `phase_a` from its summaries and zooms to the fault ([overview]). The chain's links, each
//! piece's hash and a range of frames in a copy are checked ([check]). The chapters include the marked sections of
//! this file; [Fault::find] runs them all and counts the bytes each step reads ([Counted]).
use core::cell::Cell;
use ww_tape::ItemNum;
use ww_tape::TrackNum;
use shrink_wrap::prelude::*;
use ww_tape::chunk::ColumnKind;
use ww_tape::index::{ENTRY_READ_LEN, IndexEntry};
use ww_tape::payloads::{Payloads, PayloadsError};
pub struct TapeReader<S> {
src: S,
len: u64,
/// [ByteSource::start]: no piece is looked for before it
front: u64,
/// [OpenOptions::check_payloads] as it applies to the source
check_payloads: bool,
pieces: Vec<PieceInfo>,
/// [OpenOptions::state_read_max]
state_read_max: u64,
/// The pieces' state entries sorted, shared by the reader's lookups
states: state::StateCache,
}
A tape read by positional reads, see the module docs.
pub trait ByteSource
Bytes that read at an offset.
pub fn open(src: S) -> R<Self, S> {
Self::open_with(src, OpenOptions::default())
}
Find the pieces of src with the default OpenOptions.
pub fn pieces(&self) -> &[PieceInfo] {
&self.pieces
}
The pieces, in file order.
pub struct PieceInfo
A piece of the tape.
pub fn open_with(src: S, options: OpenOptions) -> R<Self, S>
Raw,
A raw medium (SD card, NAND, a partition) that may hold stale blocks of earlier lives behind the end of data: a new session starts only at a piece head naming the session just ended (crate::PieceHead::prev_session), and a reader walks forward from the start or a hint, never from the medium's end.
pub fn track_entries(&self, i: usize, track_id: TrackId) -> R<Vec<IndexEntry>, S> {
let p = self.piece(i)?;
let entries = self.track_entries_unordered(p, track_id)?;
ranges_in_order(p, &entries)?;
Ok(entries)
}
The blocks of track track_id in piece i (0: record blocks of data, STATE_TRACK_ID:
state records, one entry each), in file order. A closed piece
reads only the final index's head and that track's entries.
mode; the writer keeps its items near their uses.pub fn state_at(&self, i: usize, slot: Slot, offset: u64) -> R<Lookup, S> {
let ix = self.state_index(i)?;
let candidates: Vec<&(IndexEntry, StateEntry)> = ix.of_slot(slot, offset).rev().collect();
let mut found = self.first_good(i, &candidates)?;
let from = found.item.as_ref().map_or(0, |s| s.offset);
found.uncovered = uncovered(self.piece(i)?, from..offset);
Ok(found)
}
The record of slot in force at offset in piece i: the newest one whose block starts before offset.
TapeWriter.pub fn definitions_at(&self, i: usize, offset: u64) -> R<DefinitionsAt, S> {
self.definitions_of(i, offset, Slot::is_definition)
}
Every definition in force at offset in piece i (u64::MAX: at its end): each definition slot's newest
record whose block starts before offset, an older one where that block doesn't read.
pub fn item_by_hash(&self, i: usize, hash: ItemHash) -> R<Lookup, S> {
let ix = self.state_index(i)?;
let candidates: Vec<&(IndexEntry, StateEntry)> = ix.of_hash(hash).rev().collect();
let mut found = self.first_good(i, &candidates)?;
let from = found.item.as_ref().map_or(0, |s| s.offset);
found.uncovered = uncovered(self.piece(i)?, from..u64::MAX);
Ok(found)
}
The newest record of piece i whose item hashes to hash, of any slot. Its uncovered stretches run from
the record to the piece's end.
pub struct Lookup {
/// The record, None when no entry led to one.
pub item: Option<StateItem>,
/// The newer blocks of the slot that didn't read.
pub lost: Vec<Lost>,
/// Stretches of the piece between the record (the piece's start when none was found) and the place that the
/// index doesn't cover, as offsets in the piece: a newer record may lie there.
pub uncovered: Vec<Range<u64>>,
/// The lookup's budget ([OpenOptions::state_read_max](super::OpenOptions::state_read_max)) ran out before it found a record that reads: older candidates were
/// not read.
pub spent: bool,
}
What a lookup of one record found.
pub fn is_whole(&self) -> bool {
self.lost.is_empty() && self.uncovered.is_empty() && !self.spent
}
Whether nothing newer can hide: every block read, the budget lasted and the index covers the stretch to the place.
pub fn read_block<'b>(
&self,
i: usize,
entry: &IndexEntry,
buf: &'b mut Vec<u8>,
) -> R<Block<'b>, S> {
let (offset, len) = self.place(i, entry)?;
buf.resize(len, 0);
self.src.read_at(offset, buf).map_err(ReadError::Source)?;
self.read_payload(buf)
.map_err(|error| ReadError::Block { offset, error })
}
Read the block of entry in piece i into buf and check it, its payload as OpenOptions::check_payloads
says (Block::checked tells which).
pub fn read_chunk_head(
&self,
i: usize,
entry: &IndexEntry,
buf: &mut Vec<u8>,
) -> R<ChunkHead, S>
Read the head of the chunk block of entry in piece i, using buf: its header, then its bytes up to the
payload, head CRC and ranges checked (ChunkHead::read_head).
pub fn open(path: &Path) -> Result<Self, FsError> {
let file = File::open(path).map_err(io_err("opening the file", path))?;
Ok(Self {
file,
path: path.to_path_buf(),
})
}
The file at path, opened to read.
pub fn tape(&self) -> MemPiece<K> {
self.tape.clone()
}
The bytes, for readers.
pub struct IndexEntry
Where a block is in its piece and what it holds.
pub fn records(&self) -> Records<'b> {
let (slots, body) = self
.clock_table()
.and_then(|(slots, at)| Some((slots, self.covered.get(at..)?)))
.unwrap_or((Slots::NONE, &[]));
Records {
body,
slots,
failed: false,
coded: self.has_records() && self.plain_body().is_none(),
}
}
The records, none for a chunk block or a block whose body this reader doesn't know (Self::body_known).