Skip to content
Basic

Writing from many threads

A recorder rarely has one source. A protocol analyser reads several links, and a test bench samples a current while a board sends log lines. Each source has a thread or a task of its own, and none of them should wait for the disk. How do they write one tape together? They hand their data to a mux, which owns the writer on a thread of its own.

A writing thread and its handles

A TapeMux owns a PieceChain and its definitions on the writing thread, a thread that does nothing but write. Producers never touch the writer. Each holds a handle, which takes its data, makes finished units of it and sends them into one queue. The writing thread takes the units from the queue in the order they came and places them.

producer threads, each with its handle the mode StateHandle::put log lines, temperatures RecordsHandle::send CAN frames EventsHandle::push_all phase current GridHandle::push a typed handle encodes its chunk, hashes the payload and computes the summary leaves on this thread the queue bounded by bytes full: wait, fail or drop, by each handle's pressure in order the writing thread TapeMux holds the definitions places each unit puts definitions and state builds the summary levels cuts, syncs, checkpoints completes a quiet handle's chunk closes the chain the chain's pieces readers: ProgressWatch, ChainFollower
The drive's four sources, each on a thread of its own with its handle. The typed handles do the costly passes on their own threads. One queue, bounded by bytes, carries every unit to the writing thread, which does every chore of the chain.

Each kind of data has its handle:

Handle Takes Sends
StateHandle a state item, on change a put
RecordsHandle a records block built with a BlockWriter the block
EventsHandle items of one events track, one by one or in batches an events chunk it encodes
GridHandle time steps of one series track: its samples, or the cells of its tiles a series chunk per tile, which it encodes
ChunkSender a chunk the caller encoded the chunk
RelayHandle another producer's blocks each block, as a relay passes it

The writing thread does every chore the writer needs. It puts definitions and state where blocks need them, cuts by the chain's policy and syncs by the sync policy. It places checkpoints and closes the chain. Handles never pass definitions: the mux holds them, and TapeMux::define_track gives a track its number.

A shared lock around the writer would serialize the producers instead. A slow sync to the disk would then block every producer that waits for the lock. With a writing thread, a sync blocks only that thread. A producer waits only when the queue is full, and the thread wakes by itself when a sync or a checkpoint falls due.

A small mux

A mux this small still shows the shape. Two sensors push pings on their own events track, each in one call to EventsHandle::push_all. A third pushes levels on a series track with GridHandle::push. Each thread holds its own handle into one chain in memory, joins, and the mux closes:

/// Two sensors push pings on their own events track, and a third pushes levels on a series track.
///
/// Each thread holds its own handle into one chain in memory; [read_back] after the close shows every item arrived.
///
/// # Errors
///
/// A mux or handle call that failed.
pub fn threads() -> Result<Counts, Error> {
    let tapes = MemPieces::new();
    let mux = TapeMux::create(
        tapes.clone(),
        OWNER,
        0,
        &[],
        ChainOptions::default(),
        MuxOptions::default(),
    )?;
    let clock = mux.define_clock(clock())?;
    let pings_a = mux.define_track(pings_track(clock, "pings_a"))?;
    let pings_b = mux.define_track(pings_track(clock, "pings_b"))?;
    let levels = mux.define_track(levels_track(clock))?;

    thread::scope(|s| -> Result<(), Error> {
        let a = s.spawn(|| -> Result<(), Error> {
            let mut h = mux.events(pings_a, EventsOptions::default())?;
            let events: Vec<Event<'_>> = (0..PINGS)
                .map(|i| Event {
                    start: i64::from(i),
                    end: i64::from(i),
                    ..Event::default()
                })
                .collect();
            h.push_all(&events)?;
            h.finish()?;
            Ok(())
        });
        let b = s.spawn(|| -> Result<(), Error> {
            let mut h = mux.events(pings_b, EventsOptions::default())?;
            let events: Vec<Event<'_>> = (0..PINGS)
                .map(|i| Event {
                    start: i64::from(i),
                    end: i64::from(i),
                    ..Event::default()
                })
                .collect();
            h.push_all(&events)?;
            h.finish()?;
            Ok(())
        });
        let c = s.spawn(|| -> Result<(), Error> {
            let mut h = mux.grid::<i16>(levels, GridOptions::default())?;
            h.push(&vec![0i16; LEVELS])?;
            h.finish()?;
            Ok(())
        });
        joined(a)?;
        joined(b)?;
        joined(c)
    })?;

    let pieces = pieces_of(&tapes, &mux.close()?)?;
    read_back(&pieces, pings_a, pings_b, levels)
}

Reading the chain back after the close shows every item of every thread arrived.

Every blocking call has an async twin, named with _async. The same three sources, as tasks on tokio instead of threads, push and close the same way:

/// [producers::threads], the same calls as `_async`, on tokio tasks: two push pings, a third pushes levels, each
/// its own task. `smol::spawn` schedules the same futures the same way.
async fn tasks() -> Result<Counts, Error> {
    let tapes = MemPieces::new();
    let mux = TapeMux::create(
        tapes.clone(),
        OWNER,
        0,
        &[],
        ChainOptions::default(),
        MuxOptions::default(),
    )?;
    let clock = mux.define_clock_async(producers::clock()).await?;
    let pings_a = mux
        .define_track_async(producers::pings_track(clock, "pings_a"))
        .await?;
    let pings_b = mux
        .define_track_async(producers::pings_track(clock, "pings_b"))
        .await?;
    let levels = mux
        .define_track_async(producers::levels_track(clock))
        .await?;

    let mut a = mux.events_async(pings_a, EventsOptions::default()).await?;
    let mut b = mux.events_async(pings_b, EventsOptions::default()).await?;
    let mut c = mux
        .grid_async::<i16>(levels, GridOptions::default())
        .await?;

    let t_a = tokio::spawn(async move {
        let events: Vec<Event<'_>> = (0..PINGS)
            .map(|i| Event {
                start: i64::from(i),
                end: i64::from(i),
                ..Event::default()
            })
            .collect();
        a.push_all_async(&events).await?;
        a.finish_async().await
    });
    let t_b = tokio::spawn(async move {
        let events: Vec<Event<'_>> = (0..PINGS)
            .map(|i| Event {
                start: i64::from(i),
                end: i64::from(i),
                ..Event::default()
            })
            .collect();
        b.push_all_async(&events).await?;
        b.finish_async().await
    });
    let t_c = tokio::spawn(async move {
        c.push_async(&vec![0i16; LEVELS]).await?;
        c.finish_async().await
    });

    t_a.await
        .map_err(|_join| Error::Settings("a task panicked"))??;
    t_b.await
        .map_err(|_join| Error::Settings("a task panicked"))??;
    t_c.await
        .map_err(|_join| Error::Settings("a task panicked"))??;

    let pieces = producers::pieces_of(&tapes, &mux.close_async().await?)?;
    producers::read_back(&pieces, pings_a, pings_b, levels)
}

smol::spawn schedules the same futures the same way; neither runtime is a dependency of ww_tape_mux.

The drive with one thread per source

The drive's hour (What a tape holds) shows the pattern with four threads. The program first starts a mux on a chain in memory and defines the clocks and tracks on it:

let mux_tapes = MemPieces::new();
let mux = TapeMux::create(
    mux_tapes.clone(),
    OWNER,
    drive.chain,
    &[],
    options(drive),
    MuxOptions::default(),
)?;
let numbers = define_on_mux(
    &mux,
    drive.phase_hz,
    drive.summaries,
    drive.near_bytes.get(),
)?;
let end_us = i64::from(drive.minutes) * 60_000 * US_PER_MS;
What the example uses here: define_on_mux
let host_clock = mux.define_clock(host)?;
let board_clock = mux.define_clock_with_maps(board, &[(host_clock, &segments)])?;
let on_board = |path, name, repeat, kind| track(board_clock, path, name, repeat, kind);
Ok(DriveNumbers {
    board_clock,
    host_clock,
    log: mux.define_track(on_board(log, "log", TrackRepeat::Stream, events.clone()))?,
    mode: mux.define_track(on_board(mode_path, "mode", mode, events.clone()))?,
    can0: mux.define_track(on_board(can0, "can0", TrackRepeat::Stream, events.clone()))?,
    phase_a: mux.define_track(on_board(
        phase_a,
        "phase_a",
        TrackRepeat::Stream,
        TrackKind::Series(phase),
    ))?,
    temp: mux.define_track(on_board(temp, "temp", TrackRepeat::Stream, events))?,
})

One thread puts the mode each time it changes. The state track needs no put at each use. The writer carries the newest item into each new piece and writes copies by its own rule.

let mode_t = s.spawn(|| -> Result<u64, Error> {
    let state = mux.state(numbers.mode)?;
    let mut mode = Mode::at(0);
    state.put(0, mode.item())?;
    let mut n = 1u64;
    while let Some(next) = mode.next_change_us().filter(|&c| c < end_us) {
        mode = Mode::at(next);
        state.put(next, mode.item())?;
        n += 1;
    }
    Ok(n)
});

Another thread pushes the CAN frames of can0 in batches of 4096 into an EventsHandle. A third pushes a second of phase current at a time into a GridHandle. Each handle ends with finish, which completes its open chunk and sends it:

let can0_t = s.spawn(|| -> Result<u64, Error> {
    let mut can0 = mux.events(numbers.can0, EventsOptions::default())?;
    let period_us = 1_000_000 / u64::from(drive.can_hz);
    let total = first_at(end_us, u64::from(drive.can_hz) * 3_600);
    let mut k = 0u64;
    while k < total {
        let take = CAN0_BATCH.min(total - k);
        let payloads: Vec<(i64, Vec<u8>)> =
            (k..k + take).map(|i| frame(i, period_us)).collect();
        let events: Vec<Event<'_>> = payloads
            .iter()
            .map(|(start, payload)| Event {
                start: *start,
                end: *start,
                payload,
                ..Event::default()
            })
            .collect();
        can0.push_all(&events)?;
        k += take;
    }
    can0.finish()?;
    Ok(total)
});

let phase_t = s.spawn(|| -> Result<u64, Error> {
    let mut phase_a = mux.grid::<i16>(
        numbers.phase_a,
        GridOptions {
            codec: PHASE_CODEC,
            summaries: drive.summaries,
            ..GridOptions::default()
        },
    )?;
    let total = first_at(end_us, u64::from(drive.phase_hz) * 3_600);
    let step = u64::from(drive.phase_hz).max(1);
    let mut n = 0u64;
    while n < total {
        let take = step.min(total - n);
        phase_a.push(&phase_values(drive, n, take))?;
        n += take;
    }
    phase_a.finish()?;
    Ok(total)
});

A fourth thread sends the log lines and temperatures as records blocks through a RecordsHandle. When every thread is done, the program closes the mux, which places what was sent and closes the chain:

let closed = mux.close()?;

Which unit reaches the queue first depends on the threads, so the bytes of the chain differ from run to run. What each track holds does not. A test decodes every track and compares it with the drive's recording through one thread. That recording drives the same handles from one thread in a fixed order, so it writes the same bytes every run.

Typed handles encode on their own thread

An EventsHandle or a GridHandle keeps an open chunk. A push adds items to it, and the handle completes the chunk when it is full: 4096 items or 1 MiB of payload by default. Completing encodes the chunk's columns and hashes its payload with BLAKE3, the costliest pass of a write. It also computes the leaves of the track's summary, such as a series' statistics per group of samples.

A series track with fixed axes keeps a chunk per tile. Its GridHandle takes a time step of the whole grid, or of a box of tiles (TapeMux::grid_box), and splits it into the open chunk of each tile. The tiles' chunks hold the same time steps and are completed together. Several producers may each write a box of their own, and a tile that no box holds is never written. A tile's time step must fit a chunk and a block: a handle refuses a larger one with CallError::StepTooLarge and never splits it.

All of this runs on the producer's thread, so the work spreads over the producers. The writing thread places the chunk with its hash given, and builds the summary levels above the leaves. It keeps one summary tree per track and piece and ends it before each cut.

A producer may go quiet with a chunk half full. The writing thread then completes the chunk itself once its first item has waited the handle's latency, 1 second by default (EventsOptions::latency). A quiet source's items thus reach the tape within that time, behind every unit the handle sent before.

Pushing items one at a time costs a call per item. EventsHandle::push_all takes a batch, which the handle encodes in one pass. The bytes are the same either way.

The other handles take units that are already whole. A ChunkSender takes a chunk that its caller encoded, as the page Event times and their codecs shows. A RecordsHandle takes a records block, and the writing thread numbers it as the writer's next block. A RelayHandle takes another producer's blocks, as Live feeds and relays explains.

The queue and back-pressure

The queue between the handles and the writing thread is bounded by bytes, not by units. A put is small and a chunk of samples may be large, so a count of units would bound nothing. A unit takes its bytes from the budget when it is sent and gives them back when it is placed. The budget is MuxOptions::queue_bytes, 64 MiB by default.

When the budget is spent, a handle meets back-pressure: it cannot send until the writing thread catches up. Each handle chooses what to do then with its Pressure:

Pressure A full queue Suits
Wait, the default blocks the call until there is room; nothing is lost a recorder that keeps every item
Fail returns MuxError::Full with the unit a producer that decides itself, such as one that buffers elsewhere
Drop drops the unit and counts it a live monitor that must never block

Handles that wait are served in the order they started to wait, so a fast producer cannot starve the others. A unit larger than the whole budget goes alone once the queue is empty.

A dropped chunk leaves a gap in its track's item numbers. The next chunk starts past the dropped items, so a reader sees that items were lost and how many. MuxStats counts the drops of each track. The test below lets one handle drop and another fail while the sink stalls:

let drop = mux
    .chunks(TrackNum::new(1))
    .unwrap()
    .pressure(Pressure::Drop);
let fail = mux
    .chunks(TrackNum::new(2))
    .unwrap()
    .pressure(Pressure::Fail);
let mut dropped = 0;
for k in 0..40 {
    if send_chunk(&drop, 0, k).unwrap() == Sent::Dropped {
        dropped += 1;
    }
}
assert!(dropped > 20, "{dropped} dropped");
match send_chunk(&fail, 1, 0) {
    Err(MuxError::Full(Unit::Chunk { head, .. })) => assert_eq!(head.first_item.get(), 0),
    other => panic!("{other:?}"),
}

The order units land in

One handle's units land in the order it sent them: its chunks, its puts and its blocks. Units of different handles land in the order they reached the queue, which need not be the order of their times. A chunk of samples may land after a records block whose times are later.

The format does not need time order across tracks. Each track is indexed on its own, a state is looked up by its tick, and a reader merges tracks by time. One order is fixed: a definition lands before any data that names it, since a handle is made only once the mux holds its track.

Cuts and closes under live handles

The writing thread cuts between units, never inside one. A chunk therefore lies whole in one piece, and a handle never notices a cut. The chain cuts by its CutPolicy before it places a chunk, and TapeMux::cut cuts once every unit sent before is placed. Item numbers go on across the cut, as Pieces and chains shows.

TapeMux::close refuses everything sent after it: every handle's next call returns MuxError::Closed. The units sent before are placed, the summary trees are ended, and the chain is closed. The close does not wait for the handles to be dropped, so one forgotten handle cannot hold it up.

A mux dropped without a close places what was sent, syncs, and leaves the last piece unclosed, as a crash would. TapeMux::resume goes on with the chain and rebuilds the summary tree of the piece from the chunks it kept. When the power fails explains the resume.

Errors reach every handle

A producer learns of an error where it can act on it. Three kinds of error surface in three places:

Kind Example Where it surfaces
refused at the call an item too long, a chunk of another track the call returns MuxError::Call, and nothing was sent
refused by the writer a block on a track the definitions don't hold the handle's next call, flush or sync returns MuxError::Refused
the mux failed a write or a sync that failed every call of every handle, and the close, return MuxError::Failed

A failed write stops the chain, since the writer never retries. The test below lets the sink fail after one block:

rigged.rig.fail.store(true, Ordering::SeqCst);
// taken by the queue; the writing thread's write of it fails
assert_eq!(send_chunk(&chunks, 0, 1).unwrap(), Sent::Queued);
assert!(matches!(mux.flush(), Err(MuxError::Failed(_))));
let failed = |r: Result<Sent, MuxError<MemError<u64>>>| matches!(r, Err(MuxError::Failed(_)));
assert!(failed(send_chunk(&chunks, 0, 2)));
assert!(failed(log.send(records(crate::id(2), 2))));
assert!(failed(state.put(3, b"x")));
assert!(failed(relay.send(records(crate::id(3), 3))));
assert!(matches!(chunks.flush(), Err(MuxError::Failed(_))));
assert!(matches!(state.sync(), Err(MuxError::Failed(_))));
assert!(matches!(mux.cut(), Err(MuxError::Failed(_))));
assert!(mux.stats().failed);
assert!(matches!(mux.close(), Err(MuxError::Failed(_))));

A send returns once the queue holds the unit, not once the unit is placed. A producer that needs to know more asks its handle. Its flush returns once every unit of the handle is placed, and its sync once they are durable on the store.

Threads and tasks

Every call that may wait has an async twin, named with _async: EventsHandle::push_async, ChunkSender::send_async, TapeMux::close_async and the rest. A task awaits room in the queue as a thread blocks for it, and both wait in one line. The writing thread wakes them, so the crate needs no async runtime and depends on none. The writing thread itself stays an operating system thread, since its writes and syncs block.

The futures are cancel-safe. A send dropped while it waits leaves the line and sends nothing. A typed handle's push dropped while it waits keeps the chunk it completed. The handle sends that chunk first on its next call, so no item is lost. The test below ends an events handle and the mux from a task:

for i in i..ITEMS {
    h.push_async(i as i64 * 10, i as i64 * 10, 0, &i.to_le_bytes())
        .await
        .unwrap();
}
h.finish_async().await.unwrap();
mux.close_async().await.unwrap();

A typed handle's drop sends its open chunk and blocks while it does. Async code therefore ends a handle with finish_async.

Readers while the mux writes

A reader in the writer's own process waits on a ProgressWatch from TapeMux::watch. The writing thread wakes it each time it places more. The watch tells the piece, its bytes written and synced, and the newest chunk of each track.

A reader in another process follows the chain's files with a follower. A ChainFollower hands out each block once it checks, and a TrackFollower gives one track's items as their chunks land. Reading a growing piece explains both.

Several chains, one writer each

One mux writes one chain, and a process may run several. The radio capture of Series writes its samples and its decoded bursts into two chains, each from a mux of its own. Neither writing thread waits for the other's writes, and a TimeMerge gives a reader the items of both in time order.

Each chain has one writer. A file sink locks the file it writes, so a second writer of the same chain is refused. The lock holds against another process and against the same one.

Data from other processes therefore travels to the writing process over a channel of the program's own, such as a socket or shared memory. A completed chunk or a block is plain bytes. The writing process hands each unit to a RelayHandle or a ChunkSender.

How fast the mux writes

The bench handles writes the same data through a mux and through one thread writing a chain directly. It splits the data across 1, 4 and 16 tracks, each track a producer thread on the mux. The events are instants with a 16-byte payload and their summaries:

Writer Tracks ms M events/s MB/s written vs direct Waits
direct 1 128 62.3 262 1.00 0
mux 1 145 55.0 231 0.88 0
mux, one by one 1 553 14.5 61 0.23 0
direct 4 118 67.7 285 1.00 0
mux 4 47 170.4 717 2.52 0
mux, one by one 4 137 58.5 246 0.86 0
direct 16 115 69.7 294 1.00 0
mux 16 25 323.9 1365 4.65 0
mux, one by one 16 59 135.9 573 1.95 0

just bench-handles on gpd-omarchy, load average 9.21 before, 8.71 after.

With one track, the mux reaches 88 % of the direct writer's rate: the queue and the second thread cost a little. A producer that pushes events one by one reaches only 23 %, which is why a batch is worth making. With 16 tracks, the producers encode in parallel, and the mux writes 4.6 times as many events a second as the direct writer.

The second table writes a radio capture, 20 million IQ samples a second, packed to 12 bits with summaries:

Writer Tracks ms MS/s MB/s written vs direct Waits
direct 1 1248 256.4 783 1.00 0
mux 1 1169 273.7 836 1.07 0
direct 4 1190 269.0 822 1.00 0
mux 4 401 797.6 2437 2.97 0
direct 16 1231 260.0 795 1.00 0
mux 16 303 1055.3 3224 4.06 1400

just bench-handles on gpd-omarchy, load average 8.71 before, 8.25 after.

With 16 tracks, the mux writes 4.1 times as many samples as the direct writer, 3.2 GB/s. There the writing thread becomes the limit: 1 400 sends waited for room in the queue. A source faster than one writing thread gets a chain of its own, and the chains are merged when they are read.

The bench ran on gpd-omarchy, a machine with 24 logical CPUs (AMD Ryzen AI 9 HX 370 w/ Radeon 890M, x86_64). It was a release build at opt-level 3 of commit d7abba98a, built with 24 jobs. The load average ran from 8.25 to 9.21 across the tables.

just bench-handles --help lists the bench's settings, and Sizes and speeds says how to run the benches on your own machine.