The sample
We need some data small enough to read byte by byte. Here is a team and its people, written in Dagr's schema language, which is plain Python:
Node("Team", fields=[
"name" >> t.utf8 >> required,
"founded" >> t.u16,
"lead" >> t.ref("Person"),
"members" >> t.ref("Person").array,
])
Node("Person", fields=[
"name" >> t.utf8 >> required,
"age" >> t.u8,
"score" >> t.u32,
])
A field is optional unless it says required. A Node also takes two switches, packed=True and frozen=True. Neither, one, the other, or both: those are the four layouts. The fields stay the same, the code you write against them stays nearly the same, and the bytes change completely.
Two switches, four layouts
It is easier to think of two questions than of four layouts, because each switch answers one question and leaves the other alone.
packeddecides where a node's children are. Off, a child is somewhere else in the buffer and the parent holds a pointer to it. On, the child is written inside the parent.frozendecides how a reader tells the fields apart. Off, the bytes say which field is which, so the list of fields may grow. On, the reader goes by position alone, so the list of fields may never change.
Put the two side by side and you get a square. Everything else about a layout follows from where it stands in it.
| not frozen the bytes say which field is which | frozen fields go by position alone | |
|---|---|---|
| not packed children by pointer |
regularA table per node says where each field is. | frozenPresence bits, then slots in schema order. |
| packed children inside |
packedA tag in front of each value. | frozen + packedPresence bits, then values in schema order. |
The row tells you about sharing and access. In the top row a node can be pointed at twice, or point back at its own ancestor, and a reader can go straight to a field. In the bottom row a node is one unbroken run of bytes, nothing is shared, and a reader walks through the fields in order. The column tells you about change and overhead. In the left column the schema can grow and the bytes carry tables or tags to make that possible. In the right column they carry almost nothing extra, and the schema is fixed for good.
See it
The panel has the same square. Pick a set of data, then a layout. Every cell is one byte of the result, coloured by what it is for. Point at a byte, or tab to it, to read what it means. Where a byte points at another place in the buffer, that place gets a dashed outline.
The bytes come from Dagr's reference writer, and the explanations from dagr explain, a tool that walks a buffer and accounts for every byte. Nothing in the panel is drawn by hand. Three kinds of byte are your data: numbers, text, and nothing else. The other colours are what the format adds so that a reader can find its way.
Regular: a table of contents for every node
Select regular. A regular node starts with a reference to a vtable, a small table with one entry per field that says where in the node that field is, or that it is absent. The fields follow, each in a slot of fixed width. Text and lists do not fit in a slot, so the slot holds a pointer to them, a V62 as in chapter 2.
- Any field is one hop away. To read
membersthe reader looks up entry 3 in the vtable and goes there. It never looks at the fields in between. - The schema can grow. A new field is a new entry at the end of the vtable. An old reader does not look that far; a new reader of old data finds the entry missing and treats the field as absent.
- Nodes are reached by pointer, so they can be shared. With the first set of data, Ada is the lead and also a member. She is in the buffer once, and two pointers lead to her. A pointer can also lead back to a node that contains it, which is what makes cycles possible.
- Vtables are shared too. Choose "most fields left out": the two people have the same fields present, so they use one vtable. In a list of ten thousand similar nodes the table is paid for once.
- It is usually the largest of the four. The tables and pointers are bytes that are not your data, and numbers sit in fixed-width slots.
This is the layout to start with when you do not know yet what your data will need. If you know FlatBuffers, it will look familiar; chapter 7 compares the two.
Frozen: positions agreed in advance
Select frozen. The vtable is gone. In its place is one presence byte with a bit for each optional field, and then the slots of the fields that are present, in schema order. Reader and writer both know the schema, so both can work out where everything is.
- It is as direct to read as regular, with less in the buffer. Pointers and sharing work the same way: Ada is still stored once.
- The schema can never change. This is the price, and it is absolute. Positions are computed from the list of fields, so adding, removing or reordering one makes old data unreadable. Frozen has no compatibility at all.
Use it for types that are finished by nature: a point is x, y, z, a colour is four numbers. Do not use it for anything a product manager can have an opinion about.
Packed: labels, and nothing fixed
Select packed. Now there are no tables and no pointers. A node is its length, then for each field that is present a short tag saying which field comes next, then the value. A child node is not pointed at. It is written right there, inside its parent.
- Numbers shrink. Find Ada's score. In the regular layout it was four bytes, because the schema says
u32. Here it is two, a LEB128. A packed number is written whichever way is shorter, and one bit of the tag tells the reader which way that was. - The schema can grow, as with regular. A reader that meets a tag it does not know keeps everything from there to the end of the node as one piece, and can write it back unchanged. Chapter 6 says why it cannot do better.
- Reading a field means walking to it. There is no table to consult. To find
membersthe reader passes over every field before it. For small nodes read from start to end that costs nothing extra; for picking one field out of a large node it does. - Nothing is shared, and nothing can cycle. Look at the first set of data again: Ada is in the buffer twice, once as the lead and once as a member, because there is no pointer to say "the same one". With that data packed is barely smaller than regular. A node that must be shared, or must point back at an ancestor, cannot sit below a packed one. It can still be packed itself and be shared by regular nodes above it, as the section on mixing shows.
- One length covers a whole subtree. A packed node with everything under it is a single run of bytes with no pointers out of it, so it can be skipped, copied or hashed as one piece.
This is the layout for messages and records: data shaped like a tree, written once, read through. It is the closest of the four to Protocol Buffers, and chapter 6 puts them side by side.
Frozen and packed: only the data
Select frozen + packed. The tags are gone as well. What is left is the length, a presence byte, a second byte with a bit per number saying how each was written, and then the values in schema order.
- It has the least overhead when most fields are present. Choose "large numbers, longer list" and compare the bars.
- It is not always the smallest. Choose "most fields left out": plain packed wins, because it pays nothing at all for an absent field, while this layout always pays its two bytes of bits.
- It has both prices. The schema can never change, as with frozen. Nothing is shared and fields are read in order, as with packed.
Back to the square
Go through the panel once more by rows and then by columns. Down a column, the tables and pointers disappear and the numbers shrink. Along a row, the labels disappear. With "a shared person", the top row stores Ada once and the bottom row twice, whichever column you are in.
We have left speed out of this chapter on purpose. How fast each layout reads and writes depends on the language, the data and how you read it, and the measurements change as the generators improve. They are kept, with the code that produces them, in the repository's benchmarks, and chapter 18 says what they show.
Mixing them
The layout is chosen for each type, so one graph can use several. Select mixed in the panel: Team is regular and Person is frozen and packed.
Node("Team", fields=[...]) # may grow, read by field
Node("Person", fields=[...], frozen=True, packed=True) # small, fixed, many of them
The team keeps its vtable, so it can gain fields and any of them is one hop away. Each person is a compact run of bytes. And because the team reaches its people by pointer, Ada is shared again.
There is one rule to know. Packed spreads downwards. A packed node contains its children, so everything below a packed node is written packed whatever its own type says. A regular node may hold packed ones, as here. The other way round, the inner node quietly loses its table. So the question to ask of a type is not only "what does it need?" but "what will it sit inside?".
What this chapter did not show.
- These buffers are tiny. In 40 bytes a single length or tag is a visible share. The proportions shift in real data, usually in favour of the layouts with tables, whose fixed costs are shared.
- Size is not speed. A smaller buffer can be slower to read, and the other way round.
- The sample has no cycle. Building and writing a graph that loops is its own subject, in chapter 4.
Try it
- With the first set of data, order the five bars by size before you look. Then explain why frozen beats packed there.
- In the regular layout, point at the pointer for
leadand at the first entry ofmembers. Where do they lead? - Find the number 1815 in every layout. In which is it four bytes, and in which two?
- Count the bytes that are not numbers or text in the packed layout of "most fields left out". What is each one for, and could a format do without it?
What comes next
Chapter 6 takes the packed layout and sets it beside Protocol Buffers, which made this style of encoding common. Chapter 7 does the same for regular, FlatBuffers and Cap'n Proto.
