Files
synchronicity/docs/blob-streaming.md
Greg Shuflin b3c3e440eb
Build Debug APK / build (push) Successful in 18m34s
An ALPN's version number lives in its constant and nowhere else
Every P2P protocol's ALPN carries a version suffix, and it moves whenever the
wire shape does — this project has no backwards-compatibility constraint, so
bumps are routine. A number copied into prose is wrong from the next bump
onward and nothing fails when it rots, so seven of the eleven versioned
references in docs/ were already stale, and so were twelve of the nineteen in
doc comments.

Everything outside the constants now reads `/syn/doc-sync/…` and names the
constant for the live value. Where a bump is itself the point — a change to
what a message *means*, which is what the convention exists for — the docs
still say a bump happened, just not which number it landed on.

Three things this turned up that were not merely stale:

- `p2p/revocation_delivery.rs`'s module header called the protocol
  `/syn/revocation`. There is no such ALPN; the constant eight lines below it
  is `/syn/membership`. NODE_REVOCATION.md had copied the wrong name twice.
- `document-sync.md` carried a per-version changelog that stopped at 6 and
  skipped 4. Rewritten as what the bumps added, keeping every cross-reference
  and dropping the numbering that rots.
- ADR 0014's title named `/syn/node-admin/1` in the heading and in the index
  row, two bumps ago. The ADR number and filename are unchanged, so links
  still resolve.

AGENTS.md gets the rule, since this is the second time it has been cleaned up
and nothing was stopping it coming back.
2026-08-31 00:32:17 -07:00

19 KiB
Raw Permalink Blame History

Blob Streaming Protocol

Pull-driven, byte-range-capable protocol over iroh for consuming blob-backed artifact content without permanent local storage. A node that has a document's blob-backed artifact value (PrimaryContent, Thumbnail, or Attachment — see the Storage::BlobStore classification in docs/data-model.md) but not the blob bytes can stream that content from a peer that holds it, without waiting for a full local copy.

The protocol is deliberately blob-level, not type-specific: it operates on (stored_hash, plaintext_hash, vault_id), the same identifiers regardless of which document type or artifact kind the blob is attached to. What varies by type is how the client consumes the stream, not what the wire protocol says — see "Per-type consumption strategies" under Integration Points below. Audio/podcast playback is the first concrete consumer and the one the worked examples below use, but PDF random-access reads and comic-page prefetching are the same protocol wearing a different client-side adapter, not a different protocol.

Distinction from Blob Sync

/syn/blob-sync/… (see docs/document-sync.md) transfers blobs for permanent local storage: the receiver buffers the full ciphertext, verifies the BLAKE3 hash, and writes it to the blob store. The sync protocol is designed for batch transfers and gives the receiver a durable local copy.

Streaming is different in every dimension:

blob-sync blob-stream
Local copy after transfer yes (permanent) no (ephemeral cache only)
Wire payload ciphertext ciphertext (sealed chunks — see "Server never decrypts" below)
What the receiver does with it writes verbatim to the blob store decrypts each chunk, discards the ciphertext
Seeks / partial ranges no yes
Purpose offline availability immediate consumption
Chunk size 4 MiB 64 KiB

Transport

ALPN: /syn/blob-stream/… (p2p::blob_stream::BLOB_STREAM_ALPN)

The same iroh Endpoint used by all other protocols. QUIC provides:

  • Authenticated connections — the remote node's identity is verified from Connection::remote_id(); no additional signature is needed in the protocol.
  • Transport encryption — QUIC's TLS layer encrypts the stream end-to-end between two authenticated ensemble members, on top of the AEAD-sealed chunks the wire already carries.
  • Flow control — if the player consumes audio slower than the network delivers it, QUIC's receive-window back-pressure naturally throttles the sender without any application-level acking.
  • Stream-level reliability — ordered, lossless delivery within a stream means chunks can be decrypted in sequence without an explicit index (see below).

Each streaming session uses one bidirectional QUIC stream (open_bi), consistent with the other protocols. The requester sends one request message; the responder uses the send side to stream the response.

The server never decrypts; the client always does (ADR 0028)

Blobs are stored as a sequence of independently-sealed chunks (vault::encrypt_blob — BLOB_CHUNK_PLAINTEXT_SIZE plaintext bytes each, ChaCha20-Poly1305, a per-chunk nonce derived from the chunk index, associated data binding plaintext_hash || chunk_index). The streaming server (node A) never resolves a vault key at all: it looks up the blob's plaintext size from the ciphertext file's length (BlobStore::plaintext_size_of, no decrypt needed), seeks straight to the chunk range covering the requested bytes (BlobStore::read_ciphertext_chunk_range), and sends those sealed chunks over the wire unmodified.

Node B (the requester) decrypts each StreamChunk on arrival, re-deriving content_key = KDF(vault_key, plaintext_hash) exactly as local BlobStore::load does, and trims the first/last chunk to the exact requested range (a chunk can only be authenticated as a whole, so a request starting or ending mid-chunk still receives — and must decrypt — the whole covering chunk). A chunk that fails authentication is a hard error, not silently-wrong bytes: it means corruption, tampering, or a chunk-index mismatch, none of which "try the next chunk anyway" would be safe to paper over.

Why this instead of the server decrypting: it makes "the client always decrypts" a system-wide invariant rather than one with an exception, which matters once vaults other than the shared default exist (passphrase or shared-key vaults some nodes hold and others don't) — and it means a node without this blob's vault key can already serve it, which is the prerequisite for a future keyless relay or cross-ensemble/guest-access scenario, without having built one yet. See ADR 0028 for the full reasoning, including why the one seemingly-server-side case (format-aware seeking, below) turns out not to need this either.

Byte-Range Seeking

The protocol is range-capable: the requester specifies a start_byte offset, and the server begins streaming from that point in the plaintext. Two uses:

  1. Scrubbing during playback — the user seeks to a new position; the client translates the target time to an approximate byte offset and opens a new streaming session from there.

  2. Resuming after a dropped connection — the client tracks how many bytes it has written to its streaming cache; on reconnect it requests from that offset rather than re-downloading from the beginning.

  3. Bounded random-access reads — a PDF renderer (or any other random-access consumer) requests exactly the byte range needed to satisfy one read call via start_byte + length (see Wire Messages below), rather than opening a stream it intends to read partway through and abandon. This is the same request shape as 1 and 2, just with an explicit end instead of an implicit "run to EOF."

Time-to-byte translation: The protocol uses byte offsets, not time offsets. Node B is responsible for computing the target byte from playback time. For constant-bitrate (CBR) formats like MP3 the approximation is:

byte_offset ≈ (seek_time_secs / total_duration_secs) × total_plaintext_bytes

Both values are available on node B without the audio file: total_duration_secs from the document's duration_secs property, and total_plaintext_bytes from BlobRef.size_bytes.

For variable-bitrate (VBR) formats or container formats with embedded seek tables (Ogg/Vorbis, FLAC, MP4/AAC), the CBR approximation may be inaccurate. The audio decoder (currently Symphonia) will sync to the nearest valid frame boundary from the requested offset; the result is good enough for interactive scrubbing. A second seek request can refine if needed.

The response header echoes the actual_start_byte the server used (the server may clamp to the blob end or, in a future version, snap to a frame boundary).

Future work — time-hint seeking: A hint_time_secs field in the request could let the server perform format-aware seeking — parsing the audio container to locate the nearest keyframe or sync point and returning the precise time it started from. This is useful for VBR formats and video streams. It requires format-parsing logic on the server side and is deferred. Per ADR 0028, this would be a small metadata-only query (a byte-offset answer, not blob content) — it doesn't reopen "the server decrypts": a node without the vault key still can't answer it, same as it can't parse the container at all, but a node that can answer it never needs to relay decrypted bytes to do so.

Wire Messages

All messages use MessagePack via rmp-serde, length-prefixed with a 4-byte big-endian u32 — identical framing to doc-sync and blob-sync.

/// Sent by the requester to start (or resume) a stream.
StreamRequest {
    /// BLAKE3(ciphertext) — identifies the blob file on disk.
    stored_hash:    [u8; 32],
    /// BLAKE3(plaintext) — used to re-derive the per-blob content key.
    plaintext_hash: [u8; 32],
    /// The vault that owns this blob.
    vault_id:       [u8; 16],
    /// Byte offset in the plaintext at which streaming should begin.
    /// 0 to start from the beginning.
    start_byte:     u64,
    /// Number of bytes to stream before sending a final chunk and closing
    /// the stream. `None` streams to end-of-file — the right default for
    /// sequential playback (audio/video/podcast). `Some(n)` bounds the
    /// response to `n` bytes — a `pread`-style range read, the shape a PDF
    /// renderer or any other random-access consumer needs to pull one
    /// range without holding the connection open past it. The server clamps
    /// `start_byte + length` to the blob's actual size.
    length:         Option<u64>,
}

/// First message sent by the responder.
StreamHeader {
    /// True if the blob was found locally. Never false due to a missing
    /// vault key — the server doesn't need one (see "The server never
    /// decrypts" above).
    found:             bool,
    /// Full plaintext size of the blob. Always the total size regardless of
    /// start_byte — lets the client display a meaningful progress bar.
    /// Computed from the ciphertext file's length, not by decrypting.
    total_size_bytes:  u64,
    /// The actual plaintext offset streaming begins at.
    /// Equal to start_byte unless the server clamped it to the blob's end.
    actual_start_byte: u64,
    /// Human-readable reason if found=false.
    error:             Option<String>,
}

/// One sealed AEAD chunk — BLOB_CHUNK_PLAINTEXT_SIZE plaintext bytes sealed
/// with a 16-byte Poly1305 tag (`vault::encrypt_blob`), except possibly the
/// blob's last chunk. The requester decrypts each one on receipt.
StreamChunk {
    /// Sealed chunk bytes, or empty to mean "the requested range is empty"
    /// — the only case `data` isn't a real sealed chunk (a real one is
    /// never empty: even zero plaintext bytes seals to a 16-byte tag).
    data:     Vec<u8>,
    /// True on the last chunk of the response — either the blob's actual
    /// end, or `length` bytes in for a bounded request.
    is_final: bool,
}

Chunk size: 64 KiB, matching vault::BLOB_CHUNK_PLAINTEXT_SIZE exactly — one StreamChunk is one sealed AEAD chunk, no re-framing between the encryption format and the wire. At a typical audio bitrate of 192 kbps, one chunk is approximately 2.7 seconds of audio — small enough to minimise time-to-first-audio on high-latency links. A request range that doesn't fall on a chunk boundary still receives whichever whole chunks cover it; the requester trims the excess after decrypting (trim_chunk_bounds).

Session Flow

Node B (requester)                          Node A (responder)
     |                                           |
     |-- StreamRequest ──────────────────────>   |  (hash + vault + start_byte)
     |                                           |  [stat ciphertext file, seek to chunk range]
     |   <───────────────────── StreamHeader ---|  (found, total_size, actual_start_byte)
     |   <─────────────────── StreamChunk(1) ---|  (sealed chunk)
     |   <─────────────────── StreamChunk(2) ---|  (sealed chunk)
     |        ...                                |
     |   <─────────────────── StreamChunk(K) ---|  (sealed chunk, is_final=true)
     |                                           |
    [decrypt each chunk, write plaintext to streaming cache, feed to player]

The responder streams chunks without waiting for explicit acks. QUIC flow control prevents the responder from outrunning the receiver's buffer.

If node B wants to abandon the stream early (e.g. the user navigates away or issues a seek past the downloaded range), it simply closes the connection; node A observes the connection close and stops sending.

Streaming Cache

Audio decoders require a seekable source (Read + Seek). Rather than buffering the full file in heap memory, node B writes received chunks to a streaming cache file as they arrive. The cache file grows as chunks land; the audio decoder reads from it concurrently via a custom MediaSource wrapper that blocks on reads when the read position catches up to the write position.

Cache location

A dedicated stream-cache/ subdirectory within the node's data directory (the same directory that holds the blob store and SQLite database). Rationale:

  • OS temp directories have platform-specific security guarantees and may be on a different filesystem than the data directory.
  • Keeping streaming cache under the data directory makes cleanup and TTL enforcement straightforward.
  • The directory is clearly owned by synchronicity and can be wiped on startup if it contains unexpected files.

Cache files are named <stored_hash_hex>.stream (the stored hash uniquely identifies the content).

Robustness on connection drop

The partial cache file is not deleted when a connection drops. If the user is still on the same track when connectivity returns, the streaming client checks the current file size and issues a new StreamRequest with start_byte set to the number of bytes already written. The server resumes from that point. This gives the same resumability as the blob-sync cursor mechanism, adapted for live streaming.

Cleanup policy

  • On track change: mark the previous cache file for deletion.
  • On node shutdown: delete all files in stream-cache/ that are not actively referenced by a running playback session.
  • On startup: delete any stream-cache/ files older than a configurable TTL (default: 24 hours) to catch files orphaned by unclean shutdowns.
  • On explicit user action ("keep a local copy"): the node copies the cache file into the permanent blob store via BlobStore::store_ciphertext (after re-encrypting the plaintext under the vault key), then creates the BlobRef.

Future work — secure deletion

Unlinking a file does not guarantee the decrypted content is unrecoverable from disk. A future version should overwrite the cache file with zeros before unlinking (or use a platform secure-erase API where available). This is especially important for non-default vault content. Tracked as a known limitation; no mitigation in the first implementation.

Producer-Consumer Playback Integration

Playback begins once the cache file contains at least start_threshold bytes (default: 2 MiB, configurable). The arrangement:

  1. A downloader task opens the streaming session and writes StreamChunk.data bytes to the cache file sequentially.
  2. Once written_bytes >= start_threshold, the downloader signals the audio layer.
  3. The audio layer opens the cache file via a custom StreamingMediaSource that implements Read + Seek:
    • read(): reads from the file at the current position. If the read position has reached written_bytes, blocks (parks the async task or sleeps briefly) until more bytes land or is_final is received.
    • seek(SeekFrom::Start(n)):
      • If n <= written_bytes: seek within the already-downloaded portion — no network action needed.
      • If n > written_bytes: this is a forward-seek past the buffer. The StreamingMediaSource closes the current downloader task, opens a new StreamRequest with start_byte = n, waits for the new StreamHeader, truncates the cache file to n bytes (or creates a new one starting at offset n with appropriate bookkeeping), and returns from seek() once the new stream is ready.

The seek(SeekFrom::Start(n)) path for values beyond written_bytes is also the mechanism for user-initiated scrubbing: when the user scrubs to time T, the music layer computes the target byte offset and calls seek() on the StreamingMediaSource. The source handles reconnection transparently.

Note that this design does not assume rodio specifically — any audio library that consumes a Read + Seek source can use StreamingMediaSource. The abstraction boundary is the MediaSource trait, not any rodio API.

Integration Points

Shared transport (build once, ahead of any single consumer):

  • p2p/blob_stream.rs — BlobStreamHandler (server side, never resolves a vault key — ADR 0028) and a client-side open_blob_stream(endpoint, target_node_id, blob_store, blob_ref, start_byte, length) (blob_store resolves the key used to decrypt each chunk) returning a BlobStreamSession that per-type adapters wrap — not a StreamingMediaSource itself, since PDF and comics don't want that shape.
  • BlobStreamHandler registered with the Router in p2p/mod.rs.
  • stream-cache/ directory created alongside the blob store on node startup.

Per-type consumption strategies (this is where the types actually diverge — build each as that type's streaming work lands, not all at once):

  • Audio/podcast — StreamingMediaSource in a new agents/streaming.rs (or adjacent to the music agent): implements Read + Seek + Send over a growing cache file with reconnection logic, requesting length: None (stream to EOF) for sequential playback. Music agent gains a stream_track_from_peer path alongside the existing local select_track_and_decode path, passing a StreamingMediaSource to Symphonia instead of a Cursor<Vec<u8>>. This is the first concrete consumer; docs/sync-management.md phase 6 already shipped a coarser whole-blob-fetch fallback (fetch_track_to_stream_cache) ahead of this real protocol landing.
  • PDF — a Read + Seek adapter issuing bounded (start_byte + length) range requests per page instead of buffering the whole file, handing mupdf's stream callbacks something backed by the network rather than a local file. Needs a page → byte-range index (from the PDF's xref table) to know what range to request, which doesn't exist yet.
  • Comics — not really "streaming" in the range-read sense at all: each page is a separate Image document with its own whole PrimaryContent blob. This wants a small prioritized-fetch queue (request the page the reader is on and the next few, in order) built from ordinary start_byte: 0, length: None requests — reusing this protocol's transport, not a new one, but with scheduling logic in place of a Read + Seek adapter.

Future Work

  • Format-aware seeking — server parses the audio/video container to snap seeks to keyframe boundaries and returns the exact playback time started from. (Chunked AEAD landed — ADR 0028 — so this is now the only deferred item from the original "Server-Side Decryption" section; see the note under "Byte-Range Seeking" on why it doesn't reopen server-side decryption.)
  • Video streaming — same protocol; additions are subtitle/chapter-track negotiation and tighter buffering requirements.
  • Adaptive quality — for very slow connections, negotiate a lower-bitrate transcode variant of the blob (requires server-side transcoding or pre-stored variants).
  • Secure cache deletion — overwrite cache files with zeros before unlinking.
  • Local HTTP gateway — expose StreamingMediaSource via a loopback HTTP server with Range request support so external media players (e.g. a browser or mpv) can consume streamed content through a standard interface.