Skip to content
Basic

Pieces and chains

A recording that runs for days does not fit one file well. A crash costs only the bytes it touched, in a file of any size. A file of hundreds of gigabytes, though, is slow to copy, and its old data cannot go without rewriting the rest. How does a writer cut a long recording into pieces, how do the pieces find each other, and how do old ones go? The examples cut the drive's hour every 15 minutes into four pieces.

Why pieces

A piece is a complete tape: it has its own definitions, index, content hash and tail, and it reads without any other piece. A chain is the pieces of one recording in order, each piece head naming the piece before it. Cutting a recording into a chain gives three things:

  • Files of a handy size. A piece of 256 MiB copies, uploads or moves to an archive on its own. A tool that needs one stretch of the recording takes only the pieces that hold it.
  • Simple retention. Deleting the oldest piece frees space without rewriting anything.
  • Closed history. The pieces before the one being written are closed and hashed. A later crash or a bug in the writer cannot touch them.

A crash inside a piece costs only the bytes it touched there, as When the power fails shows. A chain is therefore not what bounds the loss. A reader also opens a piece of any size with a few small reads at its end.

A piece reads alone because the writer measures near inside the piece. A new piece carries the definition of every track the chain has used, even when the piece before held it a few bytes earlier. It also carries each state track's newest state item. A reader of piece 7 alone therefore decodes everything piece 7 holds.

Pieces know each other

Each piece says by itself where it belongs. Its piece head holds its id, the owner id and its piece number, which counts from 0 in each chain. The head also names the piece before it by that piece's content hash and id. The close names the next piece's id. The ids follow from the owner id and the chain number, so a reader tells two chains apart.

A program therefore never trusts a file's name. Files renamed by hand, copied into one directory from several disks or listed in any order still form their chain. A scan opens each file from its end, a few small reads, and learns which piece it is and which items it holds. check_chain then orders the pieces and checks every link both ways:

// Copied by hand under names that sort in the wrong order: piece 0 becomes d.wwt, piece 3 a.wwt.
let mixed = scratch("chains_mixed");
for seq in 0..pieces {
    let name = ["d.wwt", "c.wwt", "b.wwt", "a.wwt"][seq as usize];
    std::fs::copy(
        dir.join(ww_tape_fs::chain::piece_name(seq)),
        mixed.join(name),
    )?;
}

// A scan opens each file from its end and asks the piece where it belongs and what it holds.
let mut found = Vec::new(); // (file, piece number, the items of the track)
let mut summaries = Vec::new();
for file in std::fs::read_dir(&mixed)? {
    let path = file?.path();
    let reader = TapeReader::open(ww_tape_fs::FileSource::open(&path)?)?;
    let piece = &reader.pieces()[0];
    let summary = piece.summary().ok_or("a closed piece")?;
    let (_, ranges) = piece.close.as_ref().ok_or("a close")?;
    let items = ranges[0].first_item.get()..ranges[0].end_item().get();
    found.push((
        path.file_name().ok_or("a name")?.to_owned(),
        summary.ident.seq,
        items,
    ));
    summaries.push(summary);
}

// The heads put the pieces in order, whatever their names, and every link holds.
let report = check_chain(&summaries);
assert!(report.is_whole());
found.sort_by_key(|(_, seq, _)| *seq);
assert_eq!(
    found,
    [
        ("d.wwt".into(), 0, 0..1600),
        ("c.wwt".into(), 1, 1600..3150),
        ("b.wwt".into(), 2, 3150..4700),
        ("a.wwt".into(), 3, 4700..6000),
    ]
);

The scan needs no index of the directory and no database beside the files. The close of each piece lists every track it holds with its first and last item number and tick. A viewer thus knows which file to open for a given second before it reads any data.

A chain in a directory

A PieceChain writes a chain and cuts it by itself. On files, ww_tape_fs::chain::create makes one file per piece in a directory, named 00000000.wwt, 00000001.wwt and so on, so that the names sort in chain order. The test below cuts a piece once it holds 16 KiB:

let options = ChainOptions {
    cut: CutPolicy {
        bytes: exact_units::Bytes::new(16 << 10), // a new piece once one holds 16 KiB
        ..CutPolicy::default()
    },
    tapes: PieceTapes::Each, // a file per piece: 00000000.wwt, 00000001.wwt, ...
    writer: WriterOptions {
        index: IndexPolicy {
            bytes: exact_units::Bytes::new(4 << 10),
            ..IndexPolicy::default()
        },
        ..WriterOptions::default()
    },
};
let mut chain = ww_tape_fs::chain::create(&dir, owner, 0, &[], options)?;
for k in 0..120 {
    let (head, starts) = chunk(0, k);
    chain.write_chunk(defs, &head, &column(&starts))?; // cuts first when the piece is full
}
let pieces = chain.close()?;

The chain takes an owner id and a chain number. The owner id is a 32-byte id that the application chooses and ww_tape does not interpret, such as a project's id. One owner may have several chains, such as one for events and one for a high-rate stream. Each chain then gets its own piece ids and session tag. Tracks of several owners can share one chain (Track owners and hashes).

When to cut

A CutPolicy has three limits, and the first one reached cuts:

Limit Cuts when the piece holds
bytes that many bytes, such as 256 MiB
chunks that many chunks
interval data for that long, counted from its start or its resume

A limit of 0 or None is off. The chain checks the policy before each chunk, so a cut never comes after the last chunk and never leaves a piece without data. The chain also cuts before a write that the piece's index has no room left for. PieceChain::cut_now cuts at once.

A cut by age makes the file's bytes depend on the clock. The drive's recorder counts chunks instead, as many as 15 minutes of the run make:

let definitions = StatePolicy {
    near: drive.near_bytes,
    copies: exact_units::Count::new(1),
};
ChainOptions {
    writer: WriterOptions {
        sync: SyncPolicy::default(),
        index: IndexPolicy {
            bytes: drive.checkpoint_bytes,
            interval: None,
            ..IndexPolicy::default()
        },
        layout: drive.layout.with_definitions(definitions),
        producer: PRODUCER.to_owned(),
        near: NearPolicy {
            copy_spacing: drive.copy_spacing,
            ..NearPolicy::default()
        },
        // no clock: no sync, checkpoint or cut is due by time, so the bytes follow from the acts alone
        clock: ClockRef::NONE,
        // every CRC and hash: the drive's log is kept and handed on
        integrity: ww_tape::Integrity::Full,
    },
    cut: CutPolicy {
        bytes: exact_units::Bytes::new(0),
        chunks: exact_units::Count::new(drive.piece_chunks()),
        interval: None,
    },
    tapes: PieceTapes::Each,
}
What the example uses here: Drive
/// How much of the drive's recording to make, and the writer's policies for it.
///
/// [Drive::full] is the story's hour; [Drive::scaled] divides the data rates and the byte policies alike and keeps
/// the pieces: each holds the same minutes of the run at every scale.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Drive {
    /// Length of the run, minutes from the board's boot.
    pub minutes: u32,
    /// Samples of `phase_a` per second; it divides 1 000 000, so a sample period is a whole number of µs.
    pub phase_hz: u32,
    /// CAN frames on `can0` per second.
    pub can_hz: u32,
    /// Log lines per hour.
    pub log_per_hour: u32,
    /// Temperature readings per hour.
    pub temp_per_hour: u32,
    /// Milliseconds of the run each block covers: a records block, a chunk of `can0` and one of `phase_a`. It divides
    /// a minute.
    pub block_ms: u32,
    /// Minutes of the run in a piece: the chain cuts to a new piece once a piece holds the chunks of this many minutes
    /// ([ww_tape::CutPolicy::chunks]), so the pieces fall at the same minutes at every scale.
    pub piece_minutes: u32,
    /// The writer places a checkpoint every this many bytes ([ww_tape::IndexPolicy::bytes]).
    pub checkpoint_bytes: Bytes<u64>,
    /// The definitions and the mode lie at most this far behind each use ([ww_tape::StatePolicy::near]).
    pub near_bytes: Bytes<u32>,
    /// The writer copies a state item first written in a piece this far on
    /// ([ww_tape::NearPolicy::copy_spacing]).
    pub copy_spacing: Bytes<u64>,
    /// `phase_a` carries summaries.
    pub summaries: bool,
    /// The number of the chain of [OWNER] the run records into: another number gives other piece ids and session
    /// tags, as another day's run on the same bench does.
    pub chain: u64,
    /// How the writer places blocks: [ww_tape::Layout::UNALIGNED] for a file, [ww_tape::Layout::on_sd_card] for a
    /// raw card.
    pub layout: ww_tape::Layout,
}

A recorder that writes a PieceChain itself and must know in which piece a chunk lands asks PieceChain::cut_due and cuts first with PieceChain::cut_now. A TapeMux does so on its writing thread before it places each chunk. A chunk thus lies whole in one piece, and its handle never notices the cut. TapeMux::cut cuts at once. The drive's recorder only starts the mux with these options, and hands it the acts through its handles:

let mux = TapeMux::create(
    tapes.clone(),
    OWNER,
    drive.chain,
    &[],
    options,
    mux_options(),
)?;
What the example uses here: Act, Recorder
/// 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>),
}

/// A chain written through a mux, one handle for each kind of act.
pub(crate) struct Recorder<T: PieceStore = MemPieces> {
    mux: TapeMux<T>,
    drive: Drive,
    /// The numbers the mux gave the drive's clocks and tracks.
    pub(crate) numbers: DriveNumbers,
    mode: StateHandle<T>,
    records: RecordsHandle<T>,
    can0: ChunkSender<T>,
    /// Made at the first chunk of `phase_a` it is given, which says where the track goes on from.
    phase_a: Option<GridHandle<T, i16>>,
    watch: ProgressWatch,
    /// The piece and its bytes after the last act.
    seen: (u64, u64),
    /// Whether each act waits until it is placed, to say where it lies: only a crash and its resume need that.
    placed: bool,
}

Nothing waits for a cut

Durability comes from the sync policy and the checkpoints, which work inside a piece. A cut only bounds how large one file grows. A slow input of one log line a minute goes into a records block as it comes. The writer syncs it within the sync interval, and a reader of the unclosed piece reads it at once.

What a cut writes

A cut ends the current piece and starts the next one. TapeWriter::cut_with does it in five steps:

  1. It places every deferred block still waiting.
  2. It writes the final index, the close and the tail.
  3. It closes the sink; a file takes its final name.
  4. It starts the next piece in a new sink, which the store makes under the next key.
  5. It puts the definitions of every track that the new head carries, from its caller's Definitions.
a cut: the end of piece 0 and the start of piece 1 piece 0, its last 14.3 KiB final index close close padding, 3865 bytes tail ends on 60.0 KiB (15 × 4 KiB) piece 1, its first 1.7 KiB head puts frames head and 2 blocks of puts piece 1's head names piece 0 by its content hash; its close names piece 1's id head, final index, close, tail puts data padding drawn from the drive's chain at 1/1000 of its data; each row at its own scale
A cut. Piece 0 ends with its final index, its close padded to the 4 KiB end, and its tail. Piece 1 starts with its head and two blocks of puts that carry the definitions, before its first data. Drawn by ww_tape_figures from the drive's chain at 1/1000 of its data; each row has its own scale.

At full rate, piece 0 of the drive ends with a final index of 443 kB. The close takes 2556 bytes, 1680 of them padding, and the tail 164 bytes. Piece 1 starts with a head of 636 bytes, then 2 blocks of puts of 624 bytes in all.

The head lists every track the chain has used so far, a state track included. The puts after it carry their definitions, and the mode's newest item. The definitions a new piece carries says which definitions a piece carries and what they cost.

The four pieces of the hour end on 4 KiB:

Piece Bytes Close padding
0 29396992 1680
1 29614080 1820
2 29605888 1687
3 26890240 3259

A TapeWriter without a chain cuts the same way. TapeWriter::cut_on takes a sink the caller made, and writer::cut the path of the next file. Only a piece of a chain can be cut: such a piece starts with a piece head, which TapeWriter::begin_piece writes. A piece takes data of a bounded number of tracks, and a head carries a bounded number of rows (Tape pieces).

Deleting old pieces

Retention by file deletes the oldest piece. Every piece left reads alone, and the chain reads as head cut: its start was deleted, not damaged.

std::fs::remove_file(dir.join(ww_tape_fs::chain::piece_name(0)))?; // retention: the oldest piece goes
let mut summaries = Vec::new();
for seq in 1..pieces.len() as u64 {
    let bytes = std::fs::read(dir.join(ww_tape_fs::chain::piece_name(seq)))?;
    let reader = TapeReader::open(&bytes[..])?; // each piece reads alone
    summaries.extend(reader.pieces().iter().filter_map(|p| p.summary()));
}
let report = check_chain(&summaries);
assert!(report.head_cut); // the start was deleted, not damaged
assert!(report.links.iter().all(|l| *l == ChainLink::Linked));

The drive's chain without piece 0 shows it. check_chain finds 3 pieces from piece 1, and both links between them hold. The report says head cut, and so not whole. Piece 1 defines every track at its start, the carried ones.

A resume (PieceChain::resume_on, or chain::resume for files) starts at the lowest piece there, as a reader does. Retention and a writer that goes on after a restart thus work together.

A chain in memory keeps a bounded window the same way. MemPieces::remove takes a closed piece out of the store. A reader that already holds the piece reads on unchanged. The piece still being written is not removed (MemError::Unclosed).

A chain in one memory tape keeps its window with MemPieces::drop_front. The call frees the oldest pieces whole, in blocks of memory of up to 64 MiB. Offsets don't move: the tape now starts at its first kept piece (ByteSource::start). A reader opened on it finds the pieces from there, as a head cut. The piece being written stays, and a read of a dropped piece fails with MemError::Dropped.

Pieces removed on purpose

An application may delete pieces from the middle of a chain on purpose, such as a stretch a user cut out. Without a note, the hole reads as pieces lost. The note is a list of the removed pieces in a close: each row gives one removed piece's piece number, id and content hash (RemovedPiece).

The writer appends the note to the chain's last piece, after its close:

  1. Resume the closed last piece (TapeWriter::resume_on, or writer::resume for a file). An append would start a new piece, which cannot name removed pieces.
  2. Name the removed pieces with TapeWriter::record_removed.
  3. Close it. The new close names the pieces, and every later close of the piece names them again.

check_chain then links over the hole as ChainLink::Removed, and checks both ends of the hole by the rows. A row that disagrees with either end reads as broken. A chain whose first pieces were named this way reads as removed, not as head cut. The chain report gives the rules the writer enforces on the rows.

A resume walks over such a hole the same way. Any other hole stops it with ResumeError::Gap, which names the missing piece numbers. The writer never goes on after pieces that may have been lost.

Removing pieces while the chain is written

PieceChain::remove removes closed pieces of a chain that is being written, in one call. Order matters, since a crash can come between any two steps:

  1. Name each removed piece that comes after a piece that stays in the piece being written. The rows a removed piece held for a hole removed before are named again.
  2. Close that piece and sync it, then write on after the close (TapeWriter::close_and_go_on).
  3. Take the pieces out of the store, oldest first (PieceStore::remove): a file is deleted and its directory synced.
// pieces 1 and 2 named in piece 4, which is closed and synced, then taken out of the store
c.remove(&[1, 2]).unwrap();
assert_eq!(mem.keys().unwrap(), [0, 3, 4]);

A crash before the third step leaves pieces at hand that the rows name. A row for a piece still there plays no part in a link. A crash part way through it leaves a hole the rows cover. Either way the chain reads whole and resumes:

// a crash, then a resume over the hole: pieces 0 and 3 closed, piece 4 written on
let (mut c, _) =
    PieceChain::resume_on(mem.clone(), OWNER, 0, options(PieceTapes::Each)).unwrap();
assert_eq!((c.seq(), c.closed().len()), (4, 2));

The pieces before every piece that stays get no row: they go as retention does, and the chain reads as head cut. Rows for them would only pile up, while a head cut already says the start was deleted. In a chain in one memory tape only those pieces go, as the tape's front (MemPieces::drop_front). A piece from the middle of a tape is refused, as is the piece being written.

Writing a chain into one file

A chain of many files suits retention, since old pieces go file by file. One file per recording suits an application that keeps a recording as one document, such as a project file. ChainOptions::tapes makes the choice:

The bytes are the same as those of a chain of many files placed back to back. A reader walks such a file from its end. The last tail gives the last piece's start, and the tail just before that start gives the piece before.

let options = ChainOptions {
    tapes: PieceTapes::One,
    ..ChainOptions::default()
};
let mut chain = ww_tape_fs::chain::create(path, owner, 0, &[], options.clone())?;
chain.write_chunk(defs, head, columns)?;
let first = chain.close()?;
// opened again: written on after the close
let (mut chain, _) = ww_tape_fs::chain::resume(path, owner, 0, options)?;
chain.write_chunk(defs, head, columns)?;
let second = chain.close()?;

The first session leaves one closed piece in the file. The second finds it by the tails, writes on after its close and closes it again. The file still holds one piece, closed twice, and gains a piece only where the chain cuts. An unclosed last piece, cut off by a crash, resumes as When the power fails describes.

The 4 KiB end and cloning

A closed piece is a multiple of 4 KiB long: the writer pads the close with zeros up to the boundary. The boundary makes cloning free on file systems that share data between files. The Linux file systems Btrfs and XFS can clone a range of one file into another. The new file then points at the same disk blocks.

00000000.wwt piece 0 00000001.wwt piece 1 00000002.wwt piece 2 the close pads each piece so that its tail ends on 4 KiB cloned: cp --reflink, FICLONERANGE all.wwt piece 0 piece 1 piece 2 4 KiB 4 KiB 4 KiB The new file points at the same disk blocks: nothing is copied, and the pieces lie back to back.
Three piece files cloned back to back into one file. Each piece ends on 4 KiB, so the next starts on a boundary, and the new file shares the disk blocks of the three.

The kernel clones only ranges that start on a block boundary in both files, 4 KiB on common setups. cp --reflink, the FICLONERANGE call and copy_file_range clone, and std::io::copy uses copy_file_range between files on Linux. Every closed piece ends on a boundary, so pieces clone back to back with nothing between them. In an aligned file, the payloads keep their alignment too.

Clones and subsets of a file

A clone of a file has the same bytes as the original: every block, index entry and content hash. TapeReader::verify checks it against the hash its close states. A subset keeps only some tracks, so it is a new file:

Part Clone Subset
chunk and summary bodies: columns, item numbers, ticks same same
block headers: session tag, sequence number, CRC same the subset's own
definitions and state records same the kept tracks' only, put by the subset's writer
index, close, tail, content hash same new
piece ids same new

The items of a subset keep their item numbers and ticks, so a reference to an item stays valid. To write one, an application holds the kept tracks' definitions, puts their state and writes the chosen blocks through its own writer. It renumbers each block into the subset's session with ww_tape::set_id.