← all notes

A tarball we never build.

A Cell export downloads as one .tar.zst. It tells you its exact size before the first byte, and you can resume it if the connection drops. The file itself doesn't exist anywhere. This is how that works.

An explant is a full copy of a Cell, for when you want to keep one yourself or take it somewhere else. It has the Cell's source and config, every c3 database it uses, and every object in its g7 buckets. The layout is a BagIt bag. BagIt is a plain directory format that libraries and archives use for long-term copies (it's RFC 8493): your files go under data/, and a manifest next to them lists a SHA-256 for each one, so you can check years later that nothing changed.

ribo explant export downloads the bag file by file. Plenty of people don't want a tool, though. They want one file they can fetch with curl or a browser and put on a backup disk. So there's also a single URL that returns the whole bag as one .tar.zst:

curl -C - -o orders-api.tar.zst -H "Authorization: Bearer $TISSUE_TOKEN" \
  https://api.tissue.systems/v1/cells/orders-api/explant/$ID/download
zstd -d < orders-api.tar.zst | tar -x

The response tells curl exactly how many bytes are coming, before it sends any of them. If the connection dies at 3.1 GB, running the same command again picks up at 3.1 GB. And the .tar.zst isn't stored anywhere. Not on the edge, not in object storage, not in a temp directory. The edge puts it together as it streams it out, from pieces that were saved when the export was built plus a few bytes it makes up per request.

Getting all three of those at once took some care, and most of it comes down to one number.

An HTTP response can say how long it is in a Content-Length header, or it can skip that and send the body in chunks, with the client finding out where it ends when it gets there. For a web page it hardly matters. For a 6 GB export it matters in a few ways.

The obvious one is progress. With a length, a browser shows "2.1 of 6.0 GB, 4 minutes left". Without one it shows "2.1 GB of unknown" and you have no idea whether to wait or go get lunch. You also can't check up front whether the file fits on the disk you're saving it to.

The bigger one is resuming. When you run curl -C - on a half-finished file, curl looks at how many bytes are already on disk, say N, and sends Range: bytes=N-, which means "everything from byte N to the end". A server that supports this answers 206 Partial Content with a header like Content-Range: bytes 3100000000-5999999999/6000000000. That header carries the total size, so the server has to know it. And underneath that there's a stricter requirement: byte N of the second response has to be exactly the byte that would have been at position N in the first one. If the server assembled the file a little differently the second time, curl would glue the first half of one file onto the second half of another. Nothing would complain until you tried to decompress it, possibly hours later.

The last one is honesty. A client trusts Content-Length. If we promise more bytes than we send, the download hangs until it times out. If we promise fewer, the client stops early and you get a truncated archive that looks finished. The number has to be right, to the byte, every time.

tar is an old and very simple archive format. A tar file is a flat list: a 512-byte header with a file's name, size and date, then the file's bytes, then zeros to pad up to the next multiple of 512, then the next header, and so on. Two blocks of 512 zero bytes mark the end. tar doesn't compress anything. You pipe it through a compressor, which is where .tar.gz and .tar.zst come from. zstd is the compressor here: it's fast in both directions and the zstd tool is easy to get on any system.

The usual recipe is tar -c ... | zstd > out.tar.zst, and it breaks everything above. You only learn the compressed size when the compressor is done. And a compressor works by noticing repeats and writing "copy those bytes from earlier" instead of the bytes, so compressed byte N depends on everything before it. To start sending from the middle you'd have to compress the whole thing again from the start, and hope it comes out identical.

That leaves two easy options. One is to build the .tar.zst once and store it, which doubles the storage for every export (the bag's files are stored too) and adds one more large thing to clean up when the export expires after seven days. The other is to compress on every request, which puts the CPU cost on the edge serving the download, the same machine that serves Cells, and pays it again for every download and every resume. The length still isn't known up front.

We wanted neither. What we wanted was one file that plain zstd and tar can read, an exact length before the first byte, no extra stored copy, and no compression work at download time.

A zstd file is made of frames. A frame is a self-contained unit: a short header, then blocks of data, and a decoder can turn it back into the original bytes without looking at anything outside it. The format (RFC 8878) allows any number of frames one after another, and a decoder just outputs each frame's content in order. So for any two inputs:

cat a.zst b.zst | zstd -d   # same bytes as: cat a b

That means the tarball doesn't have to be one compressed stream. We can cut the tar stream into pieces, make each piece its own frame, and line the frames up. The result is a valid .tar.zst, and a decoder can't tell it apart from one made the usual way. tar gives us the cut points for free: every header, every file's content, every bit of padding and the trailer at the end is its own piece.

header      521 B     made per request
cell.js     stored    compressed at build time
padding     ≤ 520 B   made per request
header      521 B     made per request
orders.db   part 0    32 MiB in, compressed at build time
orders.db   part 1    32 MiB in, compressed at build time
orders.db   part 2    the rest
padding     ≤ 520 B   made per request
trailer     1033 B    made per request

The download is those pieces in that order, with nothing in between. Once each piece is its own frame, the two kinds can be handled differently. File content is almost all of the bytes, so it gets compressed, once, when the export is built. Headers, padding and the trailer are tiny, so they get made fresh on each request in a way whose size we can work out with arithmetic.

When an export is built, each file is cut into parts of 32 MiB. Each part is compressed into one complete zstd frame and saved as its own object in g7. Why 32 MiB: g7 caps a single upload at 100 MiB, and compressed output can come out slightly bigger than its input when the data doesn't compress, so 32 MiB leaves plenty of room. Smaller parts also mean a resume can start in the right part instead of reading a huge object from the beginning.

We compress at level 3, which is zstd's default. Level 19 takes roughly ten times the CPU for a few percent smaller output on mixed data like this, and the build runs on an edge that's also serving traffic.

Some data isn't worth compressing at all. A JPEG or a zip file is already compressed, and running zstd over it saves nothing and makes whoever extracts it do the decompression work anyway. So a part is stored as-is (still wrapped in a zstd frame, more on that below) if its content type is an image, video, audio, an archive or a web font. SVG is the exception, since it's text and compresses like text. Content types lie, though: a .bin might really be a JPEG. So everything else gets a quick test first. We compress the first 128 KiB, and if that saves less than 5%, the part is stored as-is.

For every part, the build writes its original size, its stored size and its hash into a file called layout.json. That file is what the download works from.

The small pieces are generated on every request, and we don't compress them. They're too small for it to help, but the real reason is that compressed output has whatever size the compressor decides on. We'd have to run the compressor just to learn the length, and the whole point is to know the length without doing that.

zstd has a way to put bytes in a frame without compressing them: a raw block, which just says "the next n bytes are literal". We build these frames by hand. Here's the whole format:

28 B5 2F FD        magic number: "this is a zstd frame"
00                 frame header: no checksum, no content size given
38                 window size: 128 KiB (explained below)
3 bytes            block header: block size n, type Raw, last-block flag
...n bytes...      the content, unchanged

A raw block can hold at most 128 KiB, so longer content takes several blocks, each with its own 3-byte header. That makes the size of a raw frame a function of the content length and nothing else:

pub fn raw_frame_len(n: u64) -> u64 {
    if n == 0 { return 0; }
    FRAME_PREFIX_LEN + n.div_ceil(MAX_RAW_BLOCK) * 3 + n
}

Plugging in real numbers: a tar header frame is always 6 + 3 + 512 = 521 bytes. A file's padding is 512 - size % 512 zero bytes (none if the size is already a multiple of 512), so its frame length follows from the file size we saved in layout.json. The trailer is 1024 zeros in a 1033-byte frame. Files stored as-is at build time use the same raw frames, which is why "stored as-is" still produces valid zstd.

That 38 byte took us one wrong turn. When zstd compresses, it refers back to bytes it has already seen, and the window is how far back it's allowed to look. A decoder has to set aside that much memory before it starts, so every frame declares its window size up front, and decoders refuse frames that ask for more than they're willing to give.

zstd also lets a frame skip the window byte and set a flag instead, which means "the window is the size of this whole frame". It's one byte shorter, and for a 512-byte tar header it's harmless. For a raw frame around a 32 MiB part, it asks the decoder for 32 MiB of window, and with larger content it gets worse. Past the decoder's limit, the zstd tool stops and tells you to pass --long or --memory, which reads exactly like a corrupt archive.

Raw blocks don't refer back to anything, so the window only has to be big enough to hold one block. 128 KiB is the smallest window that allows a full-size block, so every raw frame declares exactly that. With it, every frame decodes on a default decoder however big the file is.

Every generated piece has a size from a formula and every stored piece has a size written down in layout.json. So Content-Length is a sum:

pub fn content_length(&self) -> u64 {
    let per_member: u64 = self.members.iter().map(|m| {
        zframe::raw_frame_len(tar::BLOCK) as u64
            + m.stored_bytes()
            + zframe::raw_frame_len(tar::padding_len(m.bytes)) as u64
    }).sum();
    per_member + zframe::raw_frame_len(tar::TRAILER_LEN) as u64
}

Answering it doesn't open a single object. The same layout also gives the download its list of pieces in order: each one is either a few bytes made on the spot (a header, padding, the trailer) or the key of a stored object along with its size.

This only works if the tar header we generate at download time is exactly the header the length calculation assumed, byte for byte, every time. A tar library would fill in things like the current user and file permissions from wherever it runs, so we write the headers ourselves in the POSIX ustar format, using only the file's path, size and modification time from layout.json. Permissions are always 0644 and the owner is always uid 0, tissue. Nothing in the header depends on which edge serves it or when.

ustar has one limit that bites in practice. A file name gets 100 bytes, plus a 155-byte prefix field for the leading directories, so about 255 bytes in total, split at a /. Paths in an export look like data/g7/<bucket>/<key>, and the key is whatever the customer chose, so some don't fit. Those objects are left out of the export, and the export says so. We don't shorten the name, because a shortened name would extract as a different file, maybe one that overwrites another. And we check at build time, not at download time. If we only found out when building the header for a download, the export would already be marked ready, and every download of it would fail partway through.

When curl comes back with Range: bytes=N-, every piece's length is known, so finding byte N is a walk down the list. Every piece that ends before N is skipped, and a skipped stored piece is never fetched from g7. The piece that contains N starts partway in: the edge slices the generated bytes, or asks g7 for the stored object starting at the right offset. Every piece after that goes out in full.

The answer is a 206 with a Content-Range header. If N is past the end, it's a 416 Range Not Satisfiable, which is how curl learns the file is already complete.

Resuming is safe because an export never changes once it's ready. The export ID in the URL names one fixed set of stored parts and one layout.json, so byte N on Tuesday is byte N on Thursday.

We only honour the open-ended bytes=N- form, because that's what download tools send to resume. Other forms exist: bytes=100-199 for a specific slice, bytes=-500 for the last 500 bytes, or several ranges at once. Those get the whole file with a 200. HTTP lets a server ignore any Range it doesn't want to serve, every client handles it, and it beats serving the wrong bytes under a 206.

Since nothing gets compressed at download time, all the edge does per request is copy bytes from g7 to the socket. It holds a few kilobytes at a time, however big the export is.

Everything above rests on one promise: the length we announce and the bytes we send agree. The test suite builds an export with a JavaScript file, a SQLite database, a PNG (which gets stored as-is), an empty file and a file big enough to span several parts. It serves the parts from a stand-in for g7 that handles Range the way the real one does. A stand-in that ignored Range would let the tests pass while production served garbage. Then it checks:

assert_eq!(whole.len() as u64, layout.content_length(),
           "Content-Length would have lied");

It also resumes at a list of awkward offsets: 0, 1, 7, inside a generated header, one byte before the boundary between two pieces, right on it, one byte after, the middle of a stored part, and the very last byte. Each time, what comes back has to be exactly the tail of the full download. Finally it decodes the whole thing with the zstd library and checks that the first tar header names {root}/data/source/cell.js.

The format isn't free. Every file in the export carries about a kilobyte of uncompressed overhead: the 521-byte header frame, plus a padding frame of up to 520 bytes. A bucket with a hundred thousand tiny objects pays that a hundred thousand times. Compression is per part, so small files can't benefit from each other, and two similar files compress no better together than apart. For most exports, a plain tar | zstd would give you a smaller file.

We took that trade because of where the costs land. Building an export compresses each byte once. Serving it costs only bandwidth, no matter how many times it's downloaded or resumed. And what you save is still an ordinary .tar.zst that zstd -d, tar --zstd -xf and bsdtar -xf all read. After you extract it, running sha256sum -c manifest-sha256.txt in the bag's root directory checks every file against the hash recorded when it was exported.