When bytes go bad¶
Stored bytes go bad: a failing sector flips a bit, a torn write leaves half a block. Two questions follow: what the damage costs, and how a reader says exactly what it lost instead of guessing. A tape's checks confine the damage, a reader reads past a bad block, and it salvages the good parts of a damaged chunk.
The examples damage the drive's last piece, the one that holds the fault at minute 52, one copy per kind of damage.
Checks at three levels¶
A tape finds damage before it can contain it. Every block ends with a CRC-32C, a CRC over all its bytes. A chunk adds two finer checks inside its body, and a closed piece adds one coarse check over all its blocks.
The chunk head carries the chunk's length, track, item numbers and ticks, and its own CRC. It also holds one CRC per segment, a fixed stretch of the payload that writers make 64 KiB long. The chunk head's CRC is what keeps damage small. With a good chunk head and a damaged payload, a reader still trusts the chunk's length. It finds the next block and knows which segments failed.
| Check | Covers | Damage there costs |
|---|---|---|
| block CRC-32C | each whole block | that block |
| the chunk head's CRC | a chunk's header and chunk head | the chunk; the index still says what it held |
| segment CRC-32C | each segment of a chunk's payload | one segment of one chunk |
| content hash, BLAKE3 | every byte of a closed piece before its close record | nothing; it proves the piece unchanged |
The checks detect damage and never repair it. Correction is the medium's job: the error correction of a disk, of a flash controller or of a file system. A tape catches only what that correction missed.
Every CRC is CRC-32C. The processor's CRC instructions compute it where they exist. Elsewhere, such as in a browser or on a microcontroller, a table computes it, with the same result.
Checks on bytes kept in memory¶
A tape kept in memory by the process that writes it is read without its payload CRCs by default. No disk or wire
touched those bytes. OpenOptions::check_payloads decides. PayloadCheck::BySource checks a file and skips a
ByteSource::trusted source, such as a memory tape. PayloadCheck::Always also catches memory faults.
An unchecked read keeps every other check: header, chunk head CRC, lengths and records. Block::checked says
how far a block was checked. The bench read_check times TapeReader::read_block from memory both ways:
| Block | Payload CRCs | Bytes per block | ns per block | GB/s |
|---|---|---|---|---|
| chunk | checked | 1 048 775 | 57 401 | 18.27 |
| records | checked | 4043 | 295 | 13.71 |
| chunk | not checked | 1 048 775 | 26 789 | 39.15 |
| records | not checked | 4043 | 98 | 41.24 |
just bench-read-check on gpd-omarchy, load average 3.32 before, 3.32 after.
An unchecked read takes 47 % of the time of a checked one for a chunk, mostly its copy, and 33 % for a records block.
The bench ran on gpd-omarchy, a machine with 24 logical CPUs (AMD Ryzen AI 9 HX 370 w/ Radeon 890M, x86_64) and 30 GiB of memory. It was a release build at opt-level 3 of commit 026660e71, built with 24 jobs. The load average ran from 3.32 to 3.32 across the tables.
A writer may skip checks too, and a seal adds them later: Fewer checks, sealed later.
What the flipped bit costs¶
In the drive's last piece, a flipped bit about 9.7 MB in lands in the chunk of phase_a that starts at 50:00. The chunk
holds one second of samples, 25 000 of them, in about 28 KB. That is less than one segment, so the chunk has one
segment, and its CRC fails.
The cost is that segment: one second of phase_a, 25 000 of the run's 90 million samples. Every other block of the
piece reads, and so does every other track in the same second. The fault at minute 52 is untouched. cargo run -p
example_drive prints these numbers, and examples/example_drive/src/damage.rs makes the damage.
A reader meets the flip in two places. TapeReader::verify checks the piece against its content hash and
finds that it no longer holds. Reading by the final index, TapeReader::read_block fails for that one chunk and
succeeds for the other 3444 blocks the index lists. The reader thus knows which track and which items it lost, since the
index entry names them, while the bytes themselves do not read.
A chunk longer than one segment loses less. The sample codecs code samples in groups that decode alone, and
Chunk::range_damaged says whether a group's bytes lie in a bad segment. A reader then decodes the groups of the good
segments and marks the rest lost. Damage thus costs the samples of the bad segment, not the whole chunk.
Reading past damage¶
FileBlocks walks the blocks of a byte stream in order. What it does at damage depends on its recovery mode, a
Recovery value given to FileBlocks::with_recovery. The two modes answer different questions, and the figure
walks the drive's last piece both ways.
ww_tape_figures from the drive's last piece at 1/1000 of its data, a bit flipped in a chunk of
phase_a and one in a records block.Recovery::Prefix, the default, reads the longest valid prefix of the bytes. It stops at the first block with a bad
magic, length or CRC, or at a block cut short. It also stops at a sequence number going backwards, and at a good block
of another session where none may start. It reports where it stopped and why (FileError::Cut).
A crash leaves good blocks, then a torn block, which is what Prefix expects. In the flipped piece, Prefix reads 1154 blocks and stops where the damaged chunk starts, about 9.7 MB in.
Recovery::Resync reads on. At a bad block it reports FileError::Bad and looks for the next block's magic one
byte after the bad block's start. Any byte may start a block, so Resync takes a block only when its CRCs match. It hands
out a chunk with a good chunk head and a damaged payload instead of skipping it, with Block::is_intact false and
Chunk::bad_segments naming the failed segments. In the flipped piece, Resync hands out all 3455 blocks, the damaged
chunk among them, and reports nothing else.
This walk counts what a flipped bit costs, as a test or a salvage tool would:
use ww_tape::{FileBlocks, Recovery};
let drive = example_drive::Drive::scaled(1000).expect("1000 divides the rates");
let recording = drive.record().expect("the run records");
let (piece, byte) = recording.story_flip().expect("the run reaches minute 50");
let damaged = recording.flip(piece, byte).expect("the byte lies in the piece");
let mut walk = FileBlocks::with_recovery(&damaged.bytes[..], Recovery::Resync);
let (mut good, mut bad_segments, mut reports) = (0, 0, 0);
while let Some(block) = walk.next_block() {
match block {
Ok(b) if b.is_intact() => good += 1,
Ok(b) => bad_segments += b.chunk().map_or(0, |c| c.bad_segments().count()),
Err(_) => reports += 1,
}
}
// Every block reads but one chunk, which has one bad segment.
assert_eq!((bad_segments, reports), (1, 0));
assert!(good > 50);
Resync has no sequence number check, since damage can hide any block, and guards against a repeated number instead. It
remembers the latest blocks of data it handed out, as many as the format reference states. A
good block with the session and sequence number of one of them but other bytes is a conflict
(FileError::Conflict). Resync never hands out the second block of a conflict as a block of its own.
The first block of a conflict went out already when Resync meets the second. An application that keeps what Resync gives therefore holds blocks back since the last damage, or can take one back.
Salvaging the items of an events chunk¶
An events chunk usually has one segment, so a flipped bit in it fails that segment whole. Its columns still carry
enough structure to salvage most items: read every item it can and mark the rest suspect.
EventTimes::salvage and Payloads::salvage do this.
The chunk stores the time codec and the payload lengths per group of 128 items. Each group's record must agree with its neighbours: its offsets chain, its ticks are in order and its widths are in range. A group that breaks the chain is suspect, and so are its items only.
The cost depends on where the damage lands:
- A flipped bit in one time residual damages one item.
- A flipped bit in a group record damages one group or two.
- A payload column coded with lz4 is the exception: it decodes as a whole, so one bad byte makes every item of the chunk suspect.
What a damaged piece still gives¶
Damage to a piece lands in one of three places: the start, the end or somewhere between. The drive's last piece shows all three, each on its own copy: the flipped bit, the first 4 KiB lost, the last 4 KiB lost. A lost stretch here reads as zeros, as sectors that a disk could not read.
ww_tape_figures from the drive's last piece at 1/1000 of its
data, where 4 KiB is a larger share.At full scale, the piece holds 3445 blocks that its index lists. cargo run -p example_drive prints what each damage
leaves:
| Damage | The reader finds the piece by | Content hash | Blocks that read | Definitions found |
|---|---|---|---|---|
| a flipped bit | its tail | does not hold | 3444 | 10 of 10 |
| the first 4 KiB lost | its tail | does not hold | 3441 | 10 of 10 |
| the last 4 KiB lost | its final index, with no scan after it | no close to check | 3445 | 10 of 10 |
The first 4 KiB lost¶
These bytes hold the piece head, the first definitions and the first blocks of data. The reader still opens the piece from its tail. By the final index it reads every block outside the lost bytes, 3441 of the 3445. Four blocks are lost:
- the puts of the layout and the producer;
- the puts of the definitions the piece carries for the tracks its head carries, with the mode's newest item;
- the chunk of frames of minute 45's first second;
- the chunk of samples that the lost bytes reach into.
Each definition comes from its newest record that reads. The writer copies a definition at a use 1 MiB or more after its first record. Every call that puts a definition or an item uses the layout and the producer's name too, so the writer copies them the same way. Every definition of the drive is thus found again, the layout and the producer among them. A reader scanning past the newest checkpoint takes its gap rules from the layout's copy.
The mode is a state track, and a cut carries its newest item beside its definition. That item lay in the lost bytes. A reader thus finds no mode in force over the piece's first 35 seconds, 45:00 to 45:34. The mode's copy at 45:35 gives it again from there.
A raw-media walk that starts past the lost bytes knows no gap rules until it reaches that copy. Over the first MiB or so
of the piece, only the rules a medium layer gives (OpenOptions::layout) read past a gap. Without them a blank
stretch there ends the data.
The piece head named the piece before it, so the chain's link back from this piece can no longer be checked. The last piece of a chain names no next piece, so it has no link forward to lose.
The last 4 KiB lost¶
These bytes hold the tail, the close and the padding up to a multiple of 4 KiB. The final index before them is whole. The reader finds no tail and reads the piece as unclosed. It takes the final index as the newest index block, with no byte to scan after it. Every one of the 3445 blocks of data reads, and so does every definition, but the piece loses its content hash.
Lost bytes that reach into the final index make the reader take the newest checkpoint and scan the stretch after it.
A piece in the middle of a chain would also lose its close's link to the next piece.
One block in the middle lost¶
In a closed piece the reader reads blocks by the final index, so a lost block in the middle costs that block alone. What that block held decides the cost:
| Lost block | Cost |
|---|---|
| series chunk, chunk head good | one segment per hit, the samples of the groups in it |
| series or events chunk, chunk head damaged | the chunk; the index still says which track, items and ticks it held |
| events chunk, payload damaged | the items of the groups it hits, marked suspect |
| records block | its records; the index says how many, the sequence numbers how many blocks |
| summary | nothing: a summary derives from its track's data, and ww_tape_summary builds it again |
| definitions or state records | nothing once a copy or a later put of each item reads |
| checkpoint | in an unclosed piece, the stretch to the next good checkpoint is scanned instead |
| final index | in a closed piece, the list of all blocks: TapeReader::entries fails, while TapeReader::track_entries still reads each track whose own list reads |
In an unclosed piece the same holds before the newest checkpoint. After it, the reader's scan stops at the lost block, and a Resync walk reads what follows.
What the checks cannot do¶
The checks bound what damage costs, but some damage costs more than one segment. These limits follow from the design.
The checks detect damage and never repair it. The block kind BlockKind::Parity is reserved for parity blocks: no
writer writes one, and a reader skips one as a kind it does not know.
A damaged chunk head costs the whole chunk. Its CRC finds the damage, but no second copy of the chunk head exists to read instead.
Salvage can miss small shifts. A flipped bit in a group record can shift a tick or a slope without breaking the order. The group then reads shifted and is not marked suspect.
The content hash needs a close, so an unclosed piece has no hash to check it by.
A reader scans an unclosed piece without a checkpoint yet, under about 4 MiB, from its start. The scan stops at the first bad block, and only a Resync walk reads past it.
An unclosed piece shorter than 1 MiB holds each definition once, so one bad sector can take a definition. Chunks then still place themselves by track id, item number and tick. Without clock rates and item types, a reader cannot turn ticks into seconds or bytes into values.
The layout and the producer have the same limit, and one more. Their copy takes two state entries of the piece's index policy. In a piece whose state entries are full, the writer skips the copy rather than refuse a call. Such a piece names the layout and the producer once, after its head.
The state lookups go by index entries. A damaged block where a scan stopped has no known kind and no entries. The lookups therefore take the newest record before it and report the stretch after it as uncovered by the index.
A resume cuts only a torn end. Damage with good blocks behind it therefore stops a resume and leaves the piece unclosed, and a Resync walk reads it.
Session tags have 32 bits. Data of an earlier recording thus matches the current session by chance with a probability of 2⁻³² per earlier session.
The format reference states the walks and their reports as rules. Damage on a raw card brings one more question, where the data ends, which Raw media answers.
TapeReader.pub check_payloads: PayloadCheck,
Whether TapeReader::read_block and TapeReader::range_hash check the CRCs over payloads.
BySource,
Check unless the source is trusted: a memory tape a writer of this process wrote is read unchecked, a file checked.
fn trusted(&self) -> bool {
false
}
Whether a writer in this process made the bytes and kept them in its memory, so no disk or wire touched them: a reader with PayloadCheck::BySource then skips the CRCs over payloads (Block::read_unverified).
Always,
Check every payload: a reader that looks for memory faults too.
pub fn checked(&self) -> Checked {
self.checked
}
How far the bytes were checked when the block was read.
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).
//! Damage to an archived piece of the drive's recording: a flipped bit, lost sectors at the start or the end, and
//! what each reader still gets from the piece.
use core::ops::Range;
use ww_tape::reader::Found;
use ww_tape::{BlockKind, ColumnKind, FileBlocks, FileError, Recovery, Samples, Slot, TapeReader};
use crate::defs::{key, phase_def};
use crate::record::Recording;
use crate::signals::US_PER_MS;
use crate::{Drive, Error};
/// The minute whose first chunk of `phase_a` the story's flipped bit lands in: in the last piece, which holds the
/// fault.
pub const FLIP_MINUTE: u32 = 50;
pub fn verify(&self, i: usize) -> R<Verification, S>
Whether closed piece i holds up as a whole: its bytes before its close record hash to the close's content
hash (each block that reads whole as it is, a chunk's payload by its hash, other bytes as they are,
piece docs); its final index and the blocks walked are the same set: each block walked that
its writer lists has exactly the entries its writer made of it, field for field (offset, length, kind, track,
items, ticks, a chunk's unit hash of its bytes and its range relation's range from its column), but a
byte-identical copy of the listed block before it; each entry names a block walked, or a block that doesn't
read whole in bytes no block explains, ending before the close and before the next block walked; and each
close row states the hash its track's blocks fold to from the head row's, or says it incomplete exactly where
a damaged block kept or the head leaves units out.
pub fn range_damaged(&self, range: core::ops::Range<usize>) -> bool {
if range.is_empty() {
return false;
}
let Some(last_byte) = range.end.checked_sub(1) else {
return false;
};
let first = range.start / self.seg_len;
let last = last_byte / self.seg_len;
(first..=last)
.take_while(|i| *i < self.segment_count())
.any(|i| self.segment_bad(i))
}
Whether any byte in range of the payload lies in a bad segment.
pub struct FileBlocks<R>
Reads blocks one after the other from a byte stream into one reused buffer, see Recovery for what happens at damage and Medium for where a new session may start.
pub enum Recovery
What a reader does at damage.
pub fn with_recovery(rd: R, recovery: Recovery) -> Self
Prefix,
The longest valid prefix: stop at the first block with a bad magic, length or CRC, a cut one, one of a session that may not start there, or a seq that goes backwards, and report where (FileError::Cut).
Cut {
offset: u64,
why: Cut,
},
[Recovery::Prefix]: the file is read up to offset, the bytes from there on are left out, for why. Comes
once, the walk ends after it.
Resync,
Salvage: report a bad block and read on at the next block magic one byte after its start (FileError::Bad); no seq check, but a data block with the session and seq of one handed out before (of the last RESYNC_SEQS_MAX) and other bytes is a conflict (FileError::Conflict): it comes only in the report, which names both (a copy with the same bytes is no conflict).
Bad {
offset: u64,
error: BlockError,
skipped: u64,
},
[Recovery::Resync]: bytes at offset are not a good block (error); skipped bytes were passed over to the
next block magic.
pub fn is_intact(&self) -> bool {
self.checked != Checked::Damaged
}
Whether the block is good throughout, as far as it was checked. Only Self::salvage hands out one that isn't.
pub fn bad_segments(&self) -> impl Iterator<Item = usize> + '_ {
self.segments()
.enumerate()
.filter(|(_, (s, c))| !self.unchecked && CRC.checksum(s) != *c)
.map(|(i, _)| i)
}
The segments whose bytes don't match their CRC, ascending. Empty for an intact block.
Conflict {
first: u64,
offset: u64,
session: SessionTag,
seq: u64,
block: Vec<u8>,
},
[Recovery::Resync]: two good blocks of session session and seq seq with other bytes, the one handed out at
first and block, met at offset, however far apart (the last RESYNC_SEQS_MAX data blocks handed out are
remembered).
pub fn salvage(chunk: &Chunk<'b>) -> Result<Self, TimesError> {
Self::open(chunk, |c| chunk.column_damaged(c))
}
Read the time columns of a chunk whose payload may be damaged (Chunk::bad_segments): columns with a byte in a bad segment are read group by group, and the items of a group that doesn't hold up are suspect (Self::is_suspect).
pub fn salvage(chunk: &Chunk<'b>) -> Result<Option<Self>, PayloadsError>
Read the payload columns of a chunk whose payload may be damaged (Chunk::bad_segments): group records are checked one by one and only the items of a group that doesn't hold up, or whose bytes are in a bad segment, are suspect (Self::is_suspect).
mode; the writer keeps its items near their uses.pub layout: Option<Layout>,
The gap rules of a Medium::Raw from its start, before the definitions say them; None: none until then.
Parity,
Reserved for parity blocks (one per group of blocks, for archives on poor media); none are written yet, and a reader skips them like a kind it doesn't know.
pub fn entries(&self, i: usize) -> R<Vec<IndexEntry>, S> {
let p = self.piece(i)?;
if let Some(e) = &p.entries {
return in_order(p, e.clone());
}
let mut out = Vec::new();
self.for_final(p, |ix| {
out.extend(ix.entries());
})?;
in_order(p, out)
}
Every block of piece i its index or scan knows, in file order; offsets from the piece's start. Entries
that overlap, but for a block's state records, are refused (IndexError::BadEntries): from a final index,
checkpoints or a scan alike.
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.