This page describes what a ycpp document is made of in memory. It covers IDs, items, content, the struct store, and how items link into lists and map keys. It is the base for Integration and Deletes and GC.
The model is Yjs's model. The names map almost one to one: Item, GC, Skip, StructStore.
What differs is the memory layout, which follows Yrs: items sit in an arena and point at each
other by 32-bit slot.
Every piece of content gets an ID when it is written (include/ycpp/id.hpp):
struct ID {
std::uint64_t client = 0; // the peer that wrote it
std::uint32_t clock = 0; // that peer's counter
};clientnames the peer. EachDochas one:Doc(client_id).clockcounts every unit of content that client ever wrote, starting at 0.
A unit is one array element, or one UTF-16 code unit of text. So typing "hello" in one go takes clocks 0 to 4. The next write starts at 5. Deleting does not take clocks: a delete only names the clocks it removes.
IDs never change and are never reused. That is what lets peers talk about the same character.
The clock is 32 bits on the wire. A local write checks first that it still fits
(Doc::clock_room in src/integrate.cpp). A peer could fill our clock space by sending structs
under our client id, so every write asks. When the space is full, the write fails. MapRef::set, for example, returns
Error::clock_exhausted.
The store holds Structs (include/ycpp/item.hpp):
using Struct = std::variant<std::monostate, Item, Gc, Skip>;Itemis real content, alive or deleted.Gcstands for content that was garbage-collected. It keeps only its ID and length. It holds clocks so the client's list has no hole.Skipstands for clocks an update does not carry. It appears only in updates, and in merged updates. A document never stores one:Doc::take_structdrops it.std::monostateis an empty arena slot, freed by a merge.
A struct covers the clocks id.clock to id.clock + length - 1.
struct Item {
ID id;
std::optional<ID> origin;
std::optional<ID> right_origin;
Parent parent;
std::optional<std::string_view> parent_sub;
Content content;
Slot left = no_slot;
Slot right = no_slot;
bool deleted : 1 = false;
bool keep : 1 = false;
};| Field | Meaning |
|---|---|
id |
The ID of the item's first unit. |
origin |
The ID of the unit that was on the left when the item was written. Empty at the start of a list. Never changes. |
right_origin |
The ID of the unit that was on the right when the item was written. Empty at the end of a list. Never changes. |
parent |
Which type holds the item. See below. |
parent_sub |
The map key, for an item that is a map value. Empty for a list item. |
content |
What the item holds. See Content. |
left, right |
The item's neighbours now, as arena slots. They change as other items arrive. |
deleted |
Set when the item is deleted. The item stays in the list as a tombstone. |
keep |
Set by an undo manager on items it may restore. Cleanup then neither merges nor collects them. |
The length of an item is the length of its content (content_length in src/content.cpp).
The two pairs of links have different jobs:
originandright_originrecord intent: "I was typed between these two". They are IDs, so they mean the same thing on every peer. Integration uses them to find the item's place.leftandrightrecord the current order. They are slots, local to this document. Reading a list walksrightfrom the container's first item.
Neighbours are slots, not pointers, because the arena moves when it grows. A slot is 4 bytes where
an ID takes 16. A split appends one slot instead of moving every struct after it.
struct ParentKey { std::string_view key; }; // a root type, by name
struct ParentItem { ID id; }; // a nested type, by the item that holds it
using Parent = std::variant<std::monostate, ParentKey, ParentItem>;A root type, like doc.map("m"), is named by its key. A nested type, like a map inside an array,
lives in an item whose content is a ContentType. Its children name that item's ID as parent.
Yjs leaves the parent off the wire when the item has an origin or a right origin: the neighbour
already says where it is. Such an item arrives with std::monostate. Doc::integrate then copies
parent and parent_sub from the neighbour.
Keys are std::string_views into the document's KeyPool (include/ycpp/index.hpp). Each key
string is stored once per document. A key repeated on many items would otherwise be the largest
field of an Item. An item read from the wire points into the update's own pool, so
Doc::adopt_keys re-points it at the document's pool before the item is stored.
Content is a variant of nine kinds (include/ycpp/content.hpp). The numbers are the Yjs
content refs, written on the wire.
| Kind | Ref | Holds | Length | Counted in list length | Merges with a neighbour |
|---|---|---|---|---|---|
ContentDeleted |
1 | only a length | len |
no | yes |
ContentJson |
2 | JSON values (old Yjs) | one per value | yes | yes |
ContentBinary |
3 | a byte buffer | 1 | yes | no |
ContentString |
4 | UTF-8 text, plus its UTF-16 length | UTF-16 units | yes | yes |
ContentEmbed |
5 | one embed in a text | 1 | yes | no |
ContentFormat |
6 | a formatting mark (key, value) | 1 | no | no |
ContentType |
7 | a nested shared type | 1 | yes | no |
ContentAny |
8 | Any values |
one per value | yes | yes |
ContentDoc |
9 | a subdocument | 1 | yes | no |
A few notes:
- Text is stored as UTF-8, but measured in UTF-16 units, because Yjs counts that way on the wire.
Each
ContentStringcaches its UTF-16 length. ContentAnykeeps a single value inline, and a run of values in a vector. A map value is always a single value, so it costs no allocation.ContentFormatandContentDocare rare but large. They areBoxed, so they do not set the size of the whole variant.content_prefixandcontent_suffixcut content in two for a split. They are declared incontent.hppand defined insrc/integrate.cpp. A string is cut by UTF-16 unit. A cut that falls between the two halves of a surrogate pair puts U+FFFD on both sides, as Yjs'sContentString.splicedoes.
StructStore (include/ycpp/store.hpp, src/store.cpp) holds every struct the document knows.
The arena. Each struct lives in a slot. Slots are allocated in chunks of 64 structs. A chunk
never moves, so an Item* stays valid while the store grows. A slot freed by a merge goes on
free_slots and is reused.
One list per client. clients holds one ClientStructs per client: the client id, and its
slots sorted by clock. The list covers clocks 0 to the client's state with no hole. Deleted items
and Gc structs keep their clocks. So:
state_of(client)is the end of the client's last struct. That is the next clock the document expects from it. The state vector is this number for every client.- Clients are kept in the order they first arrived, not sorted. A hostile update could list
clients in descending order, and keeping them sorted would make loading quadratic. A hash table,
client_table_, finds a client's list. The encoder sorts clients itself.
Finding a struct by ID. StructStore::locate(id) returns the slot of the struct covering
id.clock:
- Find the client's list in the hash table.
- Binary search on start clocks: the last struct starting at or before
id.clock. - Check the clock falls inside that struct.
This is Yjs's findIndexSS. The free function struct_index_at is the same search, returning an
index. locate also remembers the last struct it found. Most lookups come from a walk that just
found the struct before, so the hint often skips the search.
item_at(id) and item_containing(id) wrap locate and return the Item*. Doc::item_at gives
read-only access from outside:
#include <cassert>
#include "ycpp/doc.hpp"
#include "ycpp/item.hpp"
#include "ycpp/map.hpp"
ycpp::Doc doc(1);
auto written = doc.map("m").set("k", ycpp::Any{1});
assert(written.has_value());
const ycpp::Item* item = doc.item_at(ycpp::ID{1, 0});
assert(item != nullptr);
assert(item->parent_sub == "k"); // a map value
assert(!item->origin.has_value()); // the key had no value before
assert(!item->deleted);Inserting. StructStore::insert appends to the client's list when the clock is past the end,
which is the usual case. A split inserts in the middle, after a binary search. Decoding uses
begin_block and append, since the wire delivers each client's structs in clock order.
Items hold runs: "hello" typed in one go is one item. When something needs to point inside a run, the run is cut. This happens when:
- a new item's origin or right origin falls inside an item;
- a delete range starts or ends inside an item;
- a local insert or delete lands at an index inside an item.
Doc::split_at(id) (src/integrate.cpp:342) cuts the item covering id so that a new item
starts exactly at id:
- The right half is a copy of the item, with:
- id
id; - origin: the left half's last clock;
- the same right origin, parent and key;
- the content's suffix.
- id
- The right half goes into a new slot, right after the left half in the client's list.
- The left half keeps its slot and its id. Its content becomes the prefix.
- The links are rewired: left half, right half, old right neighbour.
- If the item was a map value the key index pointed at, the index now points at the right half.
- An undo manager's redo link moves to the right half, shifted by the offset.
- The split is noted in the transaction (
note_touched). Cleanup will try to merge the halves back. See Deletes and GC.
Doc::clean_end(id) is the twin: it makes an item end at id, by splitting at id.clock + 1.
Integration calls clean_end on an origin and split_at on a right origin. Yjs calls them
getItemCleanEnd and getItemCleanStart.
Yjs keeps a type's state in the type object (AbstractType). ycpp keeps it in a Doc::Container
(include/ycpp/doc.hpp):
| Field | Yjs | Meaning |
|---|---|---|
parent, name |
A nested type's item ID, or a root type's name. | |
start |
_start |
Slot of the first item of the list, deleted or not. |
keys |
_map |
For a map: each key to the ID of its current item. |
key_count |
_map.size (live) |
How many keys hold a live value. |
length |
_length |
Visible length: the sum of live, countable item lengths. |
markers |
_searchMarker |
Remembered positions for indexed access. |
has_formatting |
_hasFormatting |
Whether a format item ever landed here. |
type_ref |
Map, array, text, or an xml kind. |
Containers are found by a hash on the parent ID or the root name (container_table_). They are
allocated one by one, so a container's address stays valid while the table grows.
A list is the chain of items from start along right. It includes tombstones. Readers skip
items that are deleted or not countable.
A map does not overwrite a value. Each set writes a new item for the key:
- its
parent_subis the key; - its origin is the last clock of the item the key held until now;
- it has no right origin.
So the items written for one key form their own little list, linked by left and right.
Integration puts a new item at the right end of that chain, then deletes the item on its left
(src/integrate.cpp, after the insert). Only the rightmost item is alive.
Two peers may set the same key at the same time. Both items have the same origin. The conflict scan orders them by client id, as for any list (see Integration). The higher client id ends up rightmost, so it wins. Every peer picks the same one.
The container's key index (KeyIndex, Yjs's parent._map) points at the rightmost item. To find
the chain's head, Doc::key_head walks left from there. Integration starts its scan from the
head, as Yjs does.
Two pieces of undo bookkeeping live outside Item, or in a single bit of it:
Item::keepis Yjs'sitem.keep. An undo manager sets it on items it may restore.Doc::redone_is Yjs'sitem.redone: which item replaced an undone one. Only undone items have one, so it is a sorted table beside the store instead of a field every item pays for.