Where trees stop
A record that holds other records is written by writing them inside it, and they hold theirs the same way. JSON does this with braces, Protocol Buffers with a length in front of each inner message. It works as long as everything has exactly one place to be.
Two things in ordinary data do not:
- Sharing. Something is referred to from two places. A tree has to write it twice, and the reader gets two things back with no way to know they were one.
- Cycles. Something refers, directly or through others, back to itself. A tree cannot write that at all. It would never finish.
Here are four people. An arrow means "has as a friend". Start with the tree, then add the arrows that make it something else, and see what each way of writing it down makes of it.
- A shared friend is written twice. With "a shared friend", Dan appears under Bob and again under Cate. Nothing is wrong yet, but if Dan were a large record, or shared a thousand times, the cost would be plain. And whoever reads it back has two Dans.
- A cycle never ends. With "a cycle", Dan has Alex as a friend, who has Bob, who has Dan. The panel gives up after a screenful. A real writer runs until the memory is gone.
- Numbering the people fixes the writing. Choose "with ids": give every person a number, write each once in a flat list, and write numbers where friends were. This is what people do in JSON and in Protocol Buffers, and it works. But the format no longer knows that those numbers are people. Checking that number 4 exists, and turning it back into Dan, is now your program's job, in every program that reads the data.
Pointers in the bytes
The other fix is to let the format itself say "that one, over there". Each node is written once, and where it is referred to, the bytes hold a pointer: the distance from here to there. Readers follow it without knowing or caring that it is a number.
These are the same three graphs, written by Dagr. Its name for this container, one value with everything that hangs from it, is a DataGraph. In the regular layout every node sits behind a pointer. In the packed layout nodes are written inside their parent, which is to say as a tree. Point at a pointer to see where it leads.
- For a tree, pointers are pure cost. With "a tree" the packed form is a little smaller. Nothing is shared, so the pointers bought nothing.
- With sharing, they pay for themselves. With "a shared friend" the regular form has Dan once and two pointers to him, one from Bob's list and one from Cate's. The packed form has him twice and is the larger of the two.
- A cycle needs a pointer that goes backwards. With "a cycle", find the last four bytes of the regular form. That is Dan's friend, a pointer back to byte 1, where Alex is. The packed layout has no pointers, so it cannot write this graph at all.
- That backward pointer is four bytes, and the others are one. The distance would fit in less. But the writer met Dan while it was still in the middle of writing Alex, so it did not yet know how far away Alex would end up. It left a slot wide enough for any distance in the buffer, carried on, and filled the slot in at the end. This is the trick from chapter 2, a number written wider than it needs to be so that it can be decided later.
So the bytes are a solved problem: write each node once, point at it, leave a slot when you must point at something unfinished. The harder half of the story is not in the bytes at all.
The trouble in memory
Before a graph is written it has to exist in your program, and the obvious way to hold one is the way every language teaches: an object for each person, with a list of references to other people.
let alex = Person(name: "Alex")
let bob = Person(name: "Bob")
alex.friends = [bob]
bob.friends = [alex]
Four lines, and two things have already gone wrong.
Asking a simple question
Is this graph equal to that one? The obvious way to compare two people is to compare their names and then their friends, who are people, so compare their names and then their friends. In the first panel, choose "a cycle" and then "equal? the obvious way" to watch it go round. Printing a person does the same. So does computing a hash.
The fix is for the comparison to keep a list of the pairs it is already comparing. If it meets one of them again, it does not go round a second time. Choose "equal? keeping a list". Every function that walks the graph needs this treatment: equality, hashing, printing, and writing it out. Dagr generates all of them for the types in your schema, so you do not write them, but it is worth knowing that they are there and why.
Letting go
The second problem is quieter. Many languages free an object when the last reference to it goes away: Swift, Rust's Rc, C++'s shared_ptr. Alex holds a reference to Bob, and Bob to Alex. When your program is done with both, each is still referred to by the other, so neither is freed. That is a memory leak, and it needs no bug in your code, only a cycle in your data.
Languages with a garbage collector that traces what is still reachable, such as Java, Go, JavaScript and Python, do not have this problem. Others give you weak references, and you must decide which arrow of every cycle is the weak one. Rust goes further and makes a graph of objects that point at each other awkward to write in the first place.
The arena
Dagr's answer is to stop using references between objects. All the people live in one table, owned by one object, the arena. A person in your hands is not the record. It is a small handle: the arena, and a row number in it. A friend is a row number too.
let arena = SocialGraphArena()
var alex = arena.newPerson(name: "Alex")
var bob = arena.newPerson(name: "Bob")
alex.friends = [bob]
bob.friends = [alex] // a cycle, and nothing to leak
print(alex.friends[0].friends[0].name) // "Alex"
The code reads the same as before, because the handle has the properties the object had. Underneath, everything is different:
- A cycle is two numbers. Row 0 mentions row 1, row 1 mentions row 0. Nothing holds anything alive.
- Everything is freed at once. Let go of the arena and every node in it goes, however they were connected.
- It is the same in every language. A table and row numbers can be written in Rust, C, Go, Swift or Java without fighting any of them, so Dagr can generate the same design for each.
- The graph can be changed. Nodes can be added, rewired and deleted before it is written out, or after it was read in.
It is not free, and you should know what it costs:
- Every access goes through the arena. Reading a name is a lookup in a table, not a field of an object.
- A handle means something only with its arena. You cannot hand a person to code that does not have the arena they live in.
- Deleting needs care. A handle to a deleted row must not quietly become a handle to whatever is put there next, so the arena has to recognise a stale handle when it is used. For that reason deleting is something a schema asks for, not something every graph pays for.
- It is a lot of machinery if you only want to write something once.
When you do not need one
The last cost matters, because much data is built once, written, and forgotten, and much data is only read.
- Trees need no arena. If your types are packed, the data is a tree by construction. Dagr then also generates plain values, ordinary structs you fill in and hand to a writer, with no arena behind them.
- Reading needs no arena either. Dagr's readers can work on the bytes as they are: asking a person for their friends follows a pointer, and nothing is built in memory. A cycle is harmless there, since nothing is expanded until you ask for it. A reader that does rebuild the whole graph keeps a table of what it has already rebuilt, for the same reason equality does, and refuses data nested deeper than a fixed limit, because bytes from a stranger may be built to make it run for ever.
- Graphs built once could be lighter, and this is planned. For a graph that is assembled, written and thrown away, plain objects with ordinary references would do, if something broke the cycles at the end. The plan is to generate those objects together with one call that walks the graph and dissolves its cycles so that everything can be freed. It is not built yet. Today a graph with sharing or cycles is built in an arena.
What the panels are. The first is a drawing: the text in it is produced by a few lines of JavaScript that walk the arrows, not by any format. The second shows Dagr's bytes, written by its reference writer and explained by dagr explain.
Try it
- In the first panel, start from "a tree" and add only the arrow from Bob to Alex. How many people are in the smallest cycle you can make?
- With "a shared friend", count the comparisons the obvious way of testing equality makes, and then with a list. Why does the list help even though nothing loops?
- In the second panel, with "a shared friend", find the two pointers to Dan. Are they the same number? Should they be?
- All four people in the regular form use one table of field positions, the table of chapter 3. Find it, and find the four bytes that refer to it.
- A format with ids and a format with pointers both write each person once. Name one thing a reader of the pointer form can do that a reader of the id form cannot do without help from your program.
What comes next
Whether a node sits behind a pointer or inside its parent turned out to decide a great deal: sharing, cycles, size. In Dagr that is one switch on a type, and there is a second switch beside it. Chapter 5 puts the two together.
