Skip to content

Latest commit

 

History

History
343 lines (250 loc) · 15 KB

encoding.md

File metadata and controls

343 lines (250 loc) · 15 KB

Binary encoding

This page is for people who change how ycpp reads or writes bytes. It covers the number and string formats, the Any value encoding, update v1 and v2, the classes that implement them, and the defences against hostile input. JSON parsing and printing is at the end.

The rule behind every choice here is simple: the bytes must be Yjs's bytes. A ycpp peer and a Yjs peer exchange updates, so ycpp reads what lib0 writes and writes what lib0 writes, byte for byte. The differential tests check this against real Yjs (see testing).

Where each part lives:

Part Header Source
Numbers, strings, Any, run-length coders include/ycpp/encoding.hpp src/encoding.cpp, src/any.cpp
Update field coders (v1 and v2) include/ycpp/update_codec.hpp (header only)
Struct and delete-set reader/writer (internal) src/update_shared.hpp
Public update functions include/ycpp/update.hpp src/update.cpp, src/update_v2.cpp
JSON include/ycpp/json.hpp, include/ycpp/any.hpp src/json_parse.cpp, src/any.cpp

Numbers

var-uint

A var-uint is an unsigned number in as few bytes as it needs. Each byte carries 7 bits of the value, lowest bits first. The top bit of a byte is the continuation bit: 1 means another byte follows.

300 encodes as 0xAC 0x02

So 0 to 127 take one byte, 128 to 16383 take two, and so on. Clocks, client ids, lengths and counts are all var-uints.

The writer is Encoder::write_var_uint (src/encoding.cpp:45). The reader is Decoder::read_var_uint (src/encoding.cpp:113). The reader refuses two things:

  1. More than 8 bytes. That is already 56 bits, more than any legal value.
  2. A value above max_wire_uint, which is 2^53 - 1 (include/ycpp/encoding.hpp:62). lib0 runs in JavaScript, where a number above 2^53 is not exact. lib0 refuses such a value, so ycpp refuses it too.

var-int

A var-int is a signed number. The first byte gives one of its value bits to a sign bit (0x40), so it carries 6 value bits. The following bytes carry 7 bits each, like a var-uint.

lib0 can write -0: the sign bit set and a magnitude of zero. It really does this in two places: a float -0 in an Any, and the run-length coders. An int64_t cannot hold -0, so ycpp has write_var_int_parts and read_var_int_parts, which keep the magnitude and the sign apart (include/ycpp/encoding.hpp:28 and :73).

Fixed-width numbers

float32, float64 and big_int64 are written big-endian, as lib0's DataView writes them.

Strings

A string is a var-uint byte length, then the UTF-8 bytes. lib0 writes strings with TextEncoder, so this is plain UTF-8.

On read, every string is validated as UTF-8 (utf8::is_valid, src/utf8.cpp:223). An ill-formed string is Error::malformed. A text struct needs its UTF-16 length too, because Yjs counts text positions in UTF-16 units. Decoder::read_var_string_counted validates and counts in one pass, so a large paste is not scanned twice (src/encoding.cpp:208).

Two other read forms avoid copies:

  • read_var_string_view returns a view into the input. Map keys use it, since the key is copied into the document's key pool anyway.
  • read_var_string_view_unchecked skips validation. Only a caller that already validated the same bytes may use it (see the two-pass read below).

The Any encoding

An Any is a lib0 value: JSON plus undefined, binary and bigint. Maps and arrays hold Any values written by MapRef::set, ArrayRef::push and friends.

Each value starts with a one-byte type tag (src/any.cpp:21):

Tag Value Body
127 undefined none
126 null none
125 integer var-int
124 float32 4 bytes big-endian
123 float64 8 bytes big-endian
122 bigint 8 bytes big-endian
121 false none
120 true none
119 string var-uint length, UTF-8
118 object var-uint count, then key string and value, per entry
117 array var-uint count, then each value
116 binary var-uint length, bytes

Numbers follow JavaScript, because lib0 only has JavaScript numbers (write_number, src/any.cpp:130):

  1. An integer with absolute value up to 2^31 - 1 goes out as tag 125, a var-int.
  2. Otherwise, a number that a float holds exactly goes out as tag 124.
  3. Everything else goes out as tag 123, a double.

So an int64_t above 2^31 is written as a double. Above 2^53 it loses precision, exactly as it would in Yjs. Use a BigInt for a 64-bit integer that must stay exact.

Object keys are written in JavaScript's Object.keys order: array-index keys ("0", "1", ...) first, ascending, then the other keys in insertion order (js_key_indices, src/any.cpp:71). Without this, a map holding {"b":1,"1":2} would encode differently from Yjs.

Reading an Any recurses for nested arrays and objects. The depth is capped at max_any_depth, 32 by default (include/ycpp/encoding.hpp:54). A board has a small stack, and a hostile update could nest a value thousands deep. The cap is a build option (-Dmax_any_depth), and the write side refuses a deeper value too (any_writable returns Error::too_deep), so a document never writes what peers would refuse.

Update v1

An update is the unit peers exchange. Doc::encode_state_as_update writes one; Doc::apply_update reads one. It has two parts:

  1. The structs, grouped by client.
  2. The delete set.

Structs grouped by client

The update starts with the number of client blocks. Each block is:

  • the number of structs in the block,
  • the client id,
  • the clock of the first struct,
  • the structs themselves.

The clocks inside a block are consecutive, so only the first one is written. Each struct owns length clocks, and the next struct starts where it ends. Blocks go out with the highest client id first, as Yjs's writeClientsStructs does (write_state_as_update, src/update_shared.hpp:807).

One struct

A struct starts with its info byte.

The info byte: three flag bits and a 5-bit content kind

After the info byte, in this order (read_struct_body, src/update_shared.hpp:350):

  1. If bit 7 is set: the left origin, as a client var-uint and a clock var-uint.
  2. If bit 6 is set: the right origin, the same way.
  3. If neither origin bit is set, the struct names its parent itself:
    • a parent-info var-uint: 1 means a root type name follows, 0 means a parent item ID follows;
    • then, if bit 5 is set, the map key (parent_sub).
  4. The content, whose shape depends on the kind (read_content, src/update_shared.hpp:179).

Why is the parent only written when both origins are absent? An item with an origin sits next to that origin, so it has the same parent. The receiver finds the parent through the neighbour.

Two kinds are not items:

  • GC (kind 0) is a collected range: just a length.
  • Skip (kind 10) is a hole in a client's clocks: just a length. Note that a Skip writes its length with the raw var-uint, while GC uses write_len. The two are the same in v1 but not in v2.

Here is a whole update, decoded by hand:

A 20-byte v1 update decoded byte by byte

The delete set

After the structs comes the delete set: which clock ranges are deleted. It is the number of clients, then per client: the client id, the number of ranges, and each range as a clock and a length. Clients go out from the highest id down, and ranges are sorted and merged (write_delete_set, src/update_shared.hpp:596).

A delete set is how a deletion travels. A deleted item does not change its own struct: the delete set says it is gone. See deletes and GC for what happens to it next.

Update v2

v2 holds the same structs and the same delete set. It only lays the fields out differently: one stream per kind of field, each run-length encoded. On a real document, many fields repeat (the same client, the same info byte, a clock that grows by one), so the streams compress well.

The same update as v1 rows and as v2 columns

A v2 update is (UpdateEncoderV2::finish, include/ycpp/update_codec.hpp:121):

  1. A var-uint feature flag, always 0.
  2. Nine streams, each as a var-uint length and its bytes: keyClock, client, leftClock, rightClock, info, strings, parentInfo, typeRef, len.
  3. The rest, with no length prefix: struct counts, first clocks, Any values, binaries, and the delete set.

The stream coders mirror lib0 (include/ycpp/encoding.hpp:120 to :256):

Coder Used for How it works
RleEncoder info, parentInfo a byte, then how many more times it repeats
UintOptRleEncoder client, typeRef, len, string lengths a value; a negative sign means "a run count follows"
IntDiffOptRleEncoder keyClock, leftClock, rightClock the difference to the previous value, doubled, low bit = "a run count follows"
StringEncoder strings every string glued into one UTF-8 table, plus their UTF-16 lengths

Some details that bite:

  • The run-length encoders never flush their last run. The decoders repeat the last value forever past the end, as lib0's do (RleDecoder::read, src/encoding.cpp:459).
  • UintOptRleEncoder writes a run of zeros as -0: that is why the var-int parts API exists.
  • The string table counts lengths in UTF-16 units. A length that would cut a surrogate pair in half cannot be represented in UTF-8, so it is refused (utf16_bytes, src/encoding.cpp:546).
  • A delete-set clock is written as the difference to the previous range's end, and a length as len - 1 (write_ds_clock, write_ds_len).
  • A JSON value (embeds, format values) is a JSON string in v1 and an Any in v2.
  • Yjs never fills its key cache on write, so every key is written as new. The reader still supports cached keys, as Yjs's does.

convert_update_v1_to_v2 and convert_update_v2_to_v1 re-encode one into the other. merge_updates and merge_updates_v2 merge updates without a document, one struct at a time (src/update_v2.cpp).

One reader, two formats

v1 and v2 share all their struct code. The field coders differ, so they are separate classes: UpdateEncoderV1, UpdateEncoderV2, UpdateDecoderV1, UpdateDecoderV2 (include/ycpp/update_codec.hpp). They all offer the same methods: read_info, read_left_id, read_key, write_len, and so on. The struct reader and writer in src/update_shared.hpp are templates over that Codec type.

So a fix to struct reading is made once and covers both formats. A v2-only difference belongs in the codec class, never in the shared reader.

The core classes underneath are plain:

  • Encoder appends to a std::pmr::vector<byte>. Every write method appends; bytes() returns the result.
  • Decoder reads a std::span with a position. Every read returns std::expected, so a short or bad input is an error value, never an exception or a read past the end.

Both take a std::pmr::memory_resource, so an embedded build can decode into an arena.

Defences against hostile input

An update comes from the network, so ycpp treats it as hostile. The goal: a bad update is refused whole, and the document stays as it was. A wrong or malicious update must never crash, hang, or eat all memory.

Validate first, then apply

Doc::apply_update reads the update twice (stream_update_codec, src/update_shared.hpp:755):

  1. The first pass reads everything and hands nothing over. It checks every byte and records each text's UTF-16 length.
  2. Only if the first pass succeeded, the second pass reads again and hands each struct to the document as it is read.

So a corrupt byte near the end cannot leave half an update applied. The second pass reuses the recorded text lengths (TextUnits, src/update_shared.hpp:129), so a megabyte of text is validated once, not twice.

Length checks

  • Decoder::take refuses any count larger than what is left (src/encoding.cpp:104).
  • No buffer is reserved from a count read off the wire. A forged count of 2^31 elements in a 10-byte update would otherwise allocate gigabytes up front. Containers grow as elements actually arrive.
  • Clocks and delete-set values are 32-bit. A wire value above 2^32 - 1 is malformed, never narrowed. A struct whose end clock would pass 2^32 - 1 is malformed too.
  • A struct of length 0 is malformed: it owns no clock, so it would never move the state forward.

Bounded work

The v2 decoders repeat their last value forever. So a few bytes can claim two billion structs. To stop this, the number of structs per update is capped by the update's size (struct_limit_for, src/update_shared.hpp:56):

limit = 64 + 4 * (update size in bytes)

The worst legitimate ratio measured is 0.2 structs per byte, so 4 leaves a wide margin. Subdocuments get the same treatment, one per 32 bytes plus 64 (subdoc_limit_for), since each one costs a whole Doc.

Several places were rewritten so that hostile input stays linear:

  • Decoded delete-set ranges are sorted and merged once, not inserted one by one (DeleteSet::canonicalize, src/delete_set.cpp:127).
  • A client repeated many times in one update is grouped once, not looked up per entry.
  • When an update repeats a client block, only the last one is kept, as Yjs does (keep_last_client_block, src/update_shared.hpp:451).
  • The store keeps client blocks in arrival order with a hash index, so clients in descending order do not cause a shift per block.

Depth cap

Nested Any values and nested JSON are capped at max_any_depth. See the Any encoding above.

The fuzzer

All of this is checked by a libFuzzer target that feeds random bytes to every reader. See testing.

JSON

Yjs uses JSON in three content kinds: ContentJSON (an old array format), ContentEmbed and ContentFormat. In v1 their values travel as JSON text, read with JSON.parse and written with JSON.stringify. ycpp needs both directions, and they must agree with JavaScript exactly.

Parsing: parse_json

parse_json (include/ycpp/json.hpp, src/json_parse.cpp:391) turns JSON text into an Any.

  • It is strict RFC 8259. Anything else is Error::malformed.
  • Nesting is capped at max_any_depth, like the binary decoder.
  • An integer literal that fits an int64_t becomes an integer. Anything else becomes a double, parsed with fast_float.
  • An overflowing literal becomes infinity and an underflowing one becomes 0, as JSON.parse does.
  • A \u escape of a lone surrogate is refused. JSON.parse accepts it, but UTF-8 cannot hold it. This is a deliberate gap, marked simplify: in the source.

Printing: to_json

to_json (src/any.cpp:502) is JSON.stringify for an Any:

  • undefined prints as null.
  • Doubles print with the shortest round-trip form (dragonbox), the way JavaScript prints numbers.
  • NaN and infinities print as null, as in JavaScript.
  • Strings are escaped as lib0's output does (to_json_string).
  • Object keys come out in JavaScript key order, like the binary writer.

Doc::to_json and MapRef::to_json build on it.