Two directions
When a schema changes there are, for a while, two versions of everything. Two questions follow, and they have names that are easy to mix up.
- Backward compatible: a new program can read old data. The files on disk, the rows in the database and the messages still in a queue were all written before the change. If the new program cannot read them, they are lost.
- Forward compatible: an old program can read new data. A phone that has not been updated talks to a server that has. Ten copies of a service are replaced one after another, and for an hour the old ones receive what the new ones send.
A change can be fine in one direction and fatal in the other. Most systems need both, because nobody can update every program and every stored byte in the same instant.
What a field is, to the bytes
The earlier chapters already contain the answer to most of this. A field's name is never in the data. What stands for it is its position in the schema: its entry in the vtable of a regular node (chapter 5), or the number in its tag in a packed node (chapter 6). Three rules follow from that alone.
- New fields go at the end. An old reader does not look that far, or keeps what it does not know without reading it.
- A position is never given to another field. Old data still has the old meaning at that position.
- A name can change freely, as far as the bytes are concerned. The programs that use the name are another matter.
Below is a small schema, a shop's product, and thirteen things one might do to it. For each, the panel shows what both versions write, what each makes of the other's bytes, and what Dagr's own check says about the change.
Version 1
Version 2
What each version writes
What each makes of the other's bytes
What dagr check says
Going through the list gives three groups.
- Safe: adding an optional field, adding a required field that has a default, deprecating a field. Renaming is safe for the bytes and breaks the programs that used the old name, which is why the check reports it on a separate line.
- Loud: inserting in the middle, a new required field without a default, making an optional field required. A reader fails with an error. That is unpleasant, and someone notices on the first day. Inserting in the middle is loud here only because the fields that changed places have different types. Between two fields of the same type it would be silent.
- Silent: changing a default, or a field's type. Look at "change a default": both readers return a product, no error anywhere, and the unit is wrong. These are the changes that corrupt data for months before anyone asks why the numbers look odd, and they are the best reason to let a tool check.
Removing a field is a case of its own. Choose it: both readings are fine, and the check refuses it all the same. The harm would come later, when someone adds a new field and it lands on the freed position, with old data still carrying the old meaning there. The answer is to deprecate the field and leave its position occupied for good.
Required fields, without the regret
Whether a field should be optional or required is an old argument, and both sides are right about something.
- An optional field is easy to change. A reader already expects that it may be missing, so it can be added late and dropped again.
- A required field is pleasant to use. Code that reads it gets a value, and never has to ask what to do if there is none.
Protocol Buffers had required fields and took them out again, because a required field could never be removed: every old reader refused data without it. Dagr keeps both kinds. Fields are optional unless the schema says otherwise, and a missing required field is an error the program can handle, not a crash. What lets a required field change after all is a default.
What a default does
"unit" >> t.utf8 >> required >> string_val("piece")
- When data is read and the field is not there, the reader returns the default. That is why "add a required field with a default" is safe in the panel: data written before the field existed reads as if it had always carried the default.
- When data is written and the value equals the default, the writer leaves the field out, since the reader will put it back. Choose "change a default" in the panel: version 1 writes a product whose unit is "piece", and there are no bytes for it.
- When a value is built in a program, a field with a default does not have to be given.
Two consequences are worth saying out loud, because both are in the panel.
- A default can never change. Data that left the field out means "the default as it was then". Change the default and all of that data changes its meaning, silently.
- Giving a default to an existing required field is not harmless either. New writers start leaving the field out, and old readers, which know no default, find a required field missing. Choose "give an existing required field a default" and read the forward direction.
Only for required fields
An optional field can have a default too, but it is used only when a value is built. When data is read, a missing optional field stays missing. Otherwise a reader could not tell "nobody set this" from "somebody set it to the default", and for an optional field that difference is the whole point. Protocol Buffers version 3 merged the two, and later had to add a way to tell them apart again.
Retiring a field
A deprecated field keeps its position, and programs can still read it, since old data has to be migrated somehow. New code can no longer set it.
For an optional field that is all. For a required field there is a catch: old readers insist on finding it. Choose "deprecate a required field" in the panel. The field is given a default at the same moment, and from then on the writer always stores that default, whatever the usual rule about leaving defaults out. Old readers get the value they demand. New code has one field less to think about.
A default for a whole record
Formats that have defaults at all usually have them for numbers and switches. In Dagr every kind of field can have one: text, a list, an enum case, a union. That leaves the hard case, a field that refers to another node. A node is not a value one can write into a schema line.
For that a node type can declare named, ready-made instances of itself. Dagr calls them prefabs.
Node("Color", fields=[
"r" >> t.u8 >> required,
"g" >> t.u8 >> required,
"b" >> t.u8 >> required,
"a" >> t.u8 >> required,
], frozen=True) >> {
"black": {"r": int_val(0), "g": int_val(0), "b": int_val(0), "a": int_val(255)},
"white": {"r": int_val(255), "g": int_val(255), "b": int_val(255), "a": int_val(255)},
}
Node("Paint", fields=[
"label" >> t.utf8 >> required,
"color" >> t.ref("Color") >> required >> ref_val("black"),
"opacity" >> t.f32 >> required >> float_val(1.0),
], packed=True)
A paint's colour defaults to the prefab named black. So a required colour could be added to a schema that had none, and can later be deprecated, like any other field.
What a reader gets
- The opacity is left out when it is 1.0. It is a plain value, and a reader that puts 1.0 back has lost nothing.
- The colour is stored even when it is black. This is deliberate. In general a node can be shared: two fields can point at the same colour, and a program can rely on that (chapter 4). If the writer left out every colour that happens to equal black, the reader would hand back separate copies and the sharing would be gone. So a default node is used only when there truly was nothing in the data.
- Tick "written before colour and opacity existed". Seven bytes, with neither field in them, read as a black paint at full opacity.
Prefabs turned out to be useful for one more thing. An enum case can carry a value, which chapter 8 showed with numbers. The value can also be a prefab, so that a case stored in two bits is handed to the program as a whole record.
Where change is not on offer
- A frozen node cannot gain or lose a field. It has no vtable and no tags. Its fields are found by counting bytes from its start (chapter 5), and one more field moves everything after it. Set the layout to frozen in the first panel: every kind of addition is refused. Frozen is for things that are finished, like a colour or a point in space.
- The layout of a node cannot change either. Regular, packed and frozen are different bytes.
- A SharedBuffer has no tolerance in either direction (chapter 15). Both programs look at the same memory at the same moment, and every field has one fixed place.
- Enums and unions grow up to the capacity they declared, and an old reader sees a case it does not know as "unknown" (chapter 8). A sink takes new kinds of record at the end of its list (chapter 12).
The receipt
All of these rules can be learned. The trouble is that they have to be remembered on an ordinary afternoon, by someone who only wants to tidy a schema, and that the worst mistakes produce no error. A rule that matters this much should be checked by a machine.
To check a change, a tool needs to know what the schema was before. Asking people to keep old schema files around, and to name the right one, does not work for long. So Dagr writes it down itself. Every time code is generated, dagr build also writes a small file next to it, the generation receipt, and you commit that file with your code.
That is the receipt of version 1 above, with empty entries left out. It has three parts.
- The schema, in full. Every type, every field in order, its type, whether it is required, its default, the layout, the prefabs: everything that decides the bytes, and nothing else. Comments and the order of unrelated declarations are not in it. A hash over this part says at a glance whether anything that matters has changed.
- Where it came from. The version of the tool, the command, the time. The name of the machine is left out unless you ask for it, because the file ends up in a repository that others read.
- What was generated. For which languages, and a hash of every generated file.
What it is used for
dagr checkcompares the schema as it is now with the receipt. Its output is what the first panel shows. It rebuilds the old schema from the receipt alone: no old file has to be found, and no old code is run. Put into the tests that run on every change, it stops a breaking change before it is merged.dagr buildruns the same check before it writes anything. If the change breaks compatibility, it stops and leaves both the generated code and the receipt as they were. Breaking on purpose is possible, with a flag that says so.dagr verifyhashes the generated files again. Generated code that somebody edited by hand is found, before the next build quietly overwrites the edit.- The receipt is enough to generate the code again, byte for byte, without the schema file.
Two kinds of breaking
The check asks two separate questions, and the first panel shows both answers.
- Do the bytes still mean the same? Here a field is its position. This is checked in both directions, new reading old and old reading new, and a failure is reported as a wire break.
- Does code that uses the generated library still compile? Here a field is its name. Findings are graded the way version numbers are: major for what breaks callers, minor for what was added.
Choose "rename a field": the bytes are identical and the check still asks for a major version, because product.name no longer exists. Choose "insert a field in the middle": every name is still there, and the bytes are ruined. Neither question can stand in for the other.
The change you did not make: the library
So far the schema was the thing that changed. In most formats a second thing changes underneath you, and you did not ask it to: the library.
The usual arrangement has two parts. A compiler turns the schema into code, and that code calls a runtime library, which your project pulls in as a dependency like any other. The two have to match. Generated code from one version of the compiler can refuse to build, or to run, against another version of the runtime. And the runtime is shared: if two libraries you depend on each need a different version of it, you have a conflict that is not about your data at all. An update that somebody else made can stop code that was working yesterday.
Dagr's generated code has no dependencies. What dagr build writes into your project is all of it: the code for your types and the small runtime it calls, as source files in your language, using nothing beyond the language's standard library.
- Nothing is pulled in. The generated Rust crate has an empty list of dependencies, the Go module requires nothing, the Java needs only the JDK, the C and C++ are headers. There is no package to resolve, so no other package can disagree about its version.
- Nothing updates on its own. The code changes when you run the generator again, and at no other time. The receipt records which version of the generator wrote it, and the same schema with the same version gives the same files.
- The tool is needed only when building.
dagritself is a Python program. It is not part of what you ship.
The price is the other side of the same coin. A correction to the runtime does not reach you through an update of a package. It reaches you when you generate again, and the copy in your repository is yours to keep current. One target is an exception: the library Dagr can generate for Python's data tools (chapter 18) is built on Apache Arrow and depends on it.
Next to the others
- JSON writes every name into the data, so a name is what a field is. A reader takes the names it knows and by custom ignores the rest. This is very forgiving, and nothing checks it: a renamed or retyped field is discovered when a program fails, or when it does not fail and should have. JSON Schema can describe what is expected, if a project chooses to write and enforce one.
- Protocol Buffers gives every field a number, written in the schema, and readers step over numbers they do not know and keep those bytes. Removed numbers can be marked reserved so that nobody reuses them. Version 3 has no required fields and no defaults of your choosing: a missing number is zero and a missing text is empty. Checking for breaking changes is left to separate tools, of which buf is the best known.
- FlatBuffers works like Dagr's regular layout: new fields at the end of a table, old ones marked deprecated and never removed. It has defaults, mainly for numbers, and leaves them out of the data, so a default can never change there either. Its structs, like frozen nodes, can never change. Its compiler can compare a schema against an older one, if you supply the older file.
- Cap'n Proto numbers its fields too, and new ones take the next number. It has no required fields, on principle.
- Avro takes the most different road. Data has no tags or numbers at all, just values in the order of the schema that wrote it. To read it, a program needs that exact schema as well as its own, and the two are matched by field name: fields the reader does not know are dropped, fields the writer did not have are filled from the reader's defaults, and a rename is handled with a list of former names. It is the most flexible scheme of all, and it only works if the writer's schema travels with the data or sits in a registry both sides can reach. Such registries usually refuse a new schema that is not compatible with the last, which is the same idea as the receipt, kept on a server.
| a field is | required fields | your own defaults | who checks a change | |
|---|---|---|---|---|
| JSON | its name | by convention | in code | nobody |
| Protocol Buffers 3 | a number you write | none | none | a separate tool |
| FlatBuffers | its position | some, cannot be retired | mainly numbers | the compiler, given the old file |
| Cap'n Proto | a number you write | none | yes | nobody |
| Avro | its name | all, unless a union with null | yes, used when reading | a schema registry |
| Dagr | its position | yes, with a way out | every type, nodes included | every build, against the receipt |
What none of this catches
- A change of meaning. If the price was in cents and is now in euros, the schema has not changed and every check passes. No format can know what a number means.
- What you did not commit. The check compares against the receipt in the repository. A schema that reached other people without its receipt being committed is unknown to it.
- Sometimes it refuses what would have worked. Removing a field nobody ever wrote does no harm, and is refused. The rules are about what a change can do, not about what your data happens to contain.
- Position as identity has a price. A field cannot be moved to a more sensible place in the list, and a schema that has lived for years carries its deprecated fields with it. Formats with written numbers let you reorder the lines, and Avro lets you reorder and rename.
What these panels are.
- Nothing in them is computed by this page. A script ran Dagr for every change and layout and stored the results: the bytes from its reference writer, the readings from its reference reader, and the verdicts from the code behind
dagr check, printed as that command prints them. The script also confirms that the two agree: where the check passes, both readings are correct. - Each change is shown with a value chosen to make it visible. Many breaking changes work for most values and fail for some.
- The receipt is a real one, for a library with no target language, so its list of generated files is empty.
Try it
- Choose "add a required field without a default". Which direction fails, and what one addition to the schema line would repair it?
- Choose "make a required field optional". The new program reads old data without trouble. Who is hurt, and when?
- Choose "change a field's type" and compare packed with regular. Why does the packed reader get as far as it does?
- Find the two changes where no error appears anywhere and a value is wrong.
- Choose "rename a field". Are the two rows of bytes the same? What does the check ask for, and for whose sake?
- In the second panel, choose black and 1.0, then tick the box. The reader's answer does not change. Which bytes disappeared, and which of them would the writer never have left out on its own?
- You want to replace
price, a whole number of cents, with a record of amount and currency. Using only changes from the safe group, describe the steps.
What comes next
The format is now complete, and one subject has been left out of every comparison of sizes so far. Most data that travels is compressed on the way. Chapter 17 is about what a compressor does, what it costs, and whether Dagr needs one.
