A hand-written BSON encoder grows a string inside a subdocument in an existing buffer, and readers now reject or truncate the document: what did it forget, and what do length prefixes cost a writer?
answer
- count the enclosing frames
- nothing in the layout leaves slack
- the first four bytes come first
- readers fail differently per stale length
basics
~20 sGrowing a nested BSON value changes the string's int32, every enclosing document's int32 and the offset of all later bytes. A writer must also patch or precompute each length, since BSON has no padding to grow into.
solid answer
~40 sGrowing a nested string by one byte changes every length around it: the string's `int32`, the subdocument's and the root's, each by one, and every later byte shifts. The encoder likely patched the string and missed a frame. Readers then differ: a walking one rejects the mismatch, while one that jumps a stale subdocument length lands on that subdocument's own trailing `0x00`, takes it for the parent's end and can lose later fields. Prefixes also cost a writer up front, since the length comes first and is unknown until the body exists. So it reserves four bytes per open document and patches on close, or encodes children first and copies them, or sizes in a prior pass. A same-width overwrite is the one edit needing none of that.
code
plaintext · 3 linesbefore: 16 00 00 00 03 78 00 0E 00 00 00 02 61 00 02 00 00 00 62 00 00 00
after: 17 00 00 00 03 78 00 0F 00 00 00 02 61 00 03 00 00 00 62 63 00 00 00
^^ ^^ ^^ ^^go deeper
Know that a document's first four bytes hold its size, so changing how long a nested value is changes the sizes of everything wrapped around it.
Explain why a writer cannot emit the length until the body exists, and describe reserving four bytes and filling them in when the document closes. Count which lengths change in a small example.
Diagnose by stale frame: a stale subdocument length can silently drop later fields for a skipping reader while a walking reader rejects it. Validate with a walking reader, and prefer rebuilding to patching in place.
Treat a hand-written encoder as a liability: the savings are rarely worth the frame bugs. If one must exist, require the corpus decode-error and round-trip vectors as its test suite.
## What the encoder forgot A BSON **length prefix** is a byte count stored ahead of the bytes it covers, and BSON has no padding or slack between elements. So changing a value's width affects three things: - the value's own `int32`, when it has one; - the `int32` of **every enclosing document or array**, all the way to the root; - the position of **every later byte**, which must move. An encoder that patches the string and stops there leaves stale frames behind. ## A worked growth Take `{"x": {"a": "b"}, "y": 1}` with `1` as an `int32`, and change `"b"` to `"bc"`. Before the change, the root is 29 bytes, the subdocument 14, and the string's `int32` is 2. After it: ```plaintext offset bytes meaning 0x00 1E 00 00 00 root length: 30 (was 29) 0x04 03 78 00 type: embedded document, name "x" 0x07 0F 00 00 00 subdocument length: 15 (was 14) 0x0B 02 61 00 type: string, name "a" 0x0E 03 00 00 00 string length: 3 (was 2) 0x12 62 63 00 "bc" and its NUL 0x15 00 subdocument terminator 0x16 10 79 00 type: int32, name "y" 0x19 01 00 00 00 value: 1 0x1D 00 root terminator ``` Check the frames: the subdocument starts at `0x07` and declares 15, so it ends at `0x16`, where `y` begins. The root ends at `0x1E`, which is 30. Three lengths changed, and `y` moved one byte along. ## What each stale length does The interesting part of the diagnosis is that different consumers fail differently. Here is one stale length at a time, in the grown document: | Stale value | A reader that jumps the subdocument | A reader that walks every element | |---|---|---| | String `int32` still 2 | Never looks, so it reads `y` correctly | Finds `c` where the string's NUL must be, and rejects | | Subdocument `int32` still 14 | Lands at `0x15`, the subdocument's own `0x00`, and takes it for the root's end; `y` is lost unless it compares position with the root's length | Reaches that `0x00` at `0x15`, so the frame closes at `0x16` rather than `0x15`, and rejects | | Root `int32` still 29 | Frames 29 bytes; the leftover `0x00` is read as the start of whatever follows, as in a `.bson` file of contiguous documents | Runs out of frame inside `y`'s value with no terminator, and rejects | The BSON corpus test vectors treat this class as decode errors, with names that describe the mechanism: a subdocument length too long "eats outer terminator", and one too short "leaks terminator". ## What prefixes cost a writer The length is the first thing in a document and the last thing a writer knows. There are three ordinary ways to resolve that: 1. **Reserve and back-patch.** Skip four bytes, write the body into one buffer, and write the length into the reserved slot when the document closes. Each open nested document holds one such slot. 2. **Encode children first.** Build each child's bytes separately, then prepend the length. This is simple, and it copies bytes once per nesting level. 3. **Size first.** Walk the value tree to compute sizes, then write once. This is two passes over the input. The consequence for streaming: a writer cannot send a document's first byte until it knows the document's size. So it buffers each document or computes its size first. ## What needs no patching An edit that keeps the width needs no length changes: - `int32` 1 to `int32` 2; - `true` to `false`; - a string replaced by another of exactly the same byte length. Changing a type usually changes the width: `int32` to `int64` adds four bytes, and null to a boolean adds one. Those are growth, with all that follows. ## How to diagnose and fix it 1. **Decode with a validating reader**, since a skipping one can pass over the problem. Agreement between skipping readers is no evidence that a document is well-formed. 2. **Check the frames by hand.** For a document starting at offset `s` with length `n`, the byte at `s + n - 1` must be `0x00`, reached at an element boundary. 3. **Stop patching in place.** Rebuild the document with a tested encoder, or have the hand-written one adjust every enclosing frame from a recorded list of offsets. 4. **Test against the corpus.** The `decodeErrors` vectors exist for exactly these mistakes, and a round trip of the `valid` vectors catches off-by-one length writes.
- Why might a BSON document with a corrupted nested string pass one consumer and fail another?A consumer that jumps over the subdocument reads only its int32 and never touches the string, so it sees nothing wrong as long as that length is right. A consumer that walks the elements finds the bad string and rejects the document. Agreement among skipping readers proves little.
- Could a BSON writer avoid back-patching by putting the length at the end of a document?Not within the format. The grammar places the int32 first, and readers depend on that to jump forward and to frame contiguous documents. Moving it would give up the traversal the prefix was added for, and the result would not be BSON.
- Growing a value only requires updating that value's own length.
- Nested lengths are relative to the root, so only the root's changes.
- BSON documents keep padding so that values can grow in place.
- An encoder can start sending a document before it knows the document's size.
- If every skipping reader accepts a document, then it is well-formed.
- Overwriting an int32 with another int32 rewrites every enclosing length.