Integration is how a new item finds its place in a list. It is the heart of the CRDT. Two peers that integrate the same items, in any order, must end with the same list.
ycpp does it exactly as Yjs does. Yjs's algorithm is a variant of YATA. The code is
Doc::integrate in src/integrate.cpp (line 440), a port of Item.integrate in Yjs's
src/structs/Item.js. If you know that function, you know this one.
Read Data model first: this page uses items, origins, slots and containers.
Client 1 and client 2 both have "AB". At the same moment, client 1 types "x" between A and B, and client 2 types "y" in the same place. Each peer then receives the other's item.
Both new items say "I go between A and B". Something must decide whether the result is "AxyB" or "AyxB". Both peers must decide the same way, without talking to each other.
When an item is written, it records its two neighbours by ID:
origin: the unit on its left at that moment;right_origin: the unit on its right at that moment.
These never change. Other items may later land between an item and its origins. So an item's
current neighbours (left, right) can differ from its origins. The origins say where the item
was meant to go. Integration turns that intent into a place.
Given an item that is ready (its origins and parent are in the store), Doc::integrate:
- Resolves its origins.
left = clean_end(origin), so an item ends exactly at the origin.right = split_at(right_origin), so an item starts exactly at the right origin. Both may split an item (see Data model). - Turns it into garbage if its anchor is gone. This is Yjs's
Item.getMissing. The item becomes aGcstruct (Doc::integrate_gc) when:- its origin or right origin points at a
Gcstruct; - its parent item was collected, or no longer holds a type;
- it has no parent and no neighbour to take one from.
- its origin or right origin points at a
- Fills in a missing parent. An item that came without a parent copies
parentandparent_subfrom its origin or right origin. - Finds its container, by parent ID or root name. For a list, it records the change for observers. A remote item also clears the list's search markers.
- Checks whether it sits where its origins say. If
left.rightis alreadyright, nothing came between the origins. That is the usual case, and always the case for a local write. Then the item goes right there. - Otherwise, runs the conflict scan described below. It may move
leftto the right. - Links the item in after
left: it sets the neighbours' links, or the container'sstart. - For a map value, makes it the key's current item. Then it deletes the item on its left, the value it replaces.
- Updates the container's length, if the item is a visible list item.
- Deletes it at once if it arrived as
ContentDeleted, if its parent is deleted, or if it is a map value that did not end up last in its key's chain.
The scan walks the items between left and right. These are the items some other peer placed
between our origins, concurrently with us. The scan decides which of them we go after.
Here is the loop, from src/integrate.cpp (null checks trimmed):
Slot cursor = cursor_left != nullptr ? cursor_left->right : head;
IdSet before_origin(memory_);
IdSet conflicting(memory_);
while (cursor != no_slot && cursor != right_slot) {
const Item* other = store_.item_at_slot(cursor);
before_origin.add(other->id);
conflicting.add(other->id);
if (item.origin == other->origin) {
if (other->id.client < item.id.client) {
left = cursor;
conflicting.clear();
} else if (item.right_origin == other->right_origin) {
break;
}
} else if (other->origin.has_value() &&
holds_covering(store_, before_origin, *other->origin)) {
if (!holds_covering(store_, conflicting, *other->origin)) {
left = cursor;
conflicting.clear();
}
} else {
break;
}
cursor = other->right;
}head is the container's first item, or the head of the key's chain for a map value.
Two sets track what the scan has seen:
before_origin(Yjs'sitemsBeforeOrigin): every item scanned so far.conflicting(Yjs'sconflictingItems): the items scanned sinceleftlast moved.
For each item o in the range, in order:
- Same origin as ours.
owas inserted at the same place as us.- If
o's client id is lower,ogoes first. Movelefttoo. - If it is higher, and
oalso has our right origin, we go beforeo. Stop. - If it is higher but its right origin differs, keep scanning. A later item may still decide.
- If
- Its origin is an item we already passed.
ohangs off an item in the range.- If that item is not in
conflicting, it sits at or before our currentleft. Thenobelongs with it, soogoes first too. Movelefttoo. - If that item is in
conflicting, it sits after our currentleft, where our place is not decided yet. Keepleft, and keep scanning.
- If that item is not in
- Anything else.
o's origin is outside the range, to the left of it. Everything from here on was placed relative to items before ours. Stop.
When the loop ends, the item goes right after left.
Three clients insert at the start of an empty list, concurrently:
- client 1 types "a", then "x" after it;
- client 2 types "b";
- client 3 types "c".
A peer holds a x c and now receives b. Its origin and right origin are both empty. So the
scan starts at the list's head:
a: same origin (none). Client 1 is lower than 2, soleftmoves toa.x: its origin isa, which the scan already passed, and which is not inconflicting. Soxgoes beforeb, andleftmoves tox.c: same origin (none). Client 3 is higher, and the right origins match. Stop.
b goes after x: the list reads a x b c. Step 2 is the important one. x was typed right
after a, and the scan keeps them together. Without that rule, b could land between them, and
two runs typed concurrently would interleave.
Yjs asks itemsBeforeOrigin.has(getItem(store, o.origin)). getItem returns the struct that
contains the origin clock. After merges, that struct may start earlier than the origin.
ycpp's sets hold item IDs (start IDs). So it asks the same question with holds_covering: locate
the struct covering the origin clock, then test its start ID. The test
"yata case two matches origins that live inside merged structs" in tests/test_doc.cpp pins this.
A full proof is in the YATA paper and the Yjs sources. The intuition:
- The scan only reads things every peer agrees on: IDs, origins, right origins. It never reads arrival order or local state.
- Origins never change. So the set of items "between my origins" is the same on every peer that has them all.
- Ties between items with the same origin are broken by client id. That is a total order, the same everywhere.
- An item always stays after its origin and before its right origin. The second rule keeps an item glued to whatever it was typed after.
So for any set of items, there is one order that satisfies all the rules. Each peer reaches it, whatever order the items arrived in.
The differential tests check this against real Yjs. They replay random multi-peer sessions, delivered in random orders, and compare the final bytes. See Testing.
You can see it with two documents:
#include <cassert>
#include <vector>
#include "ycpp/doc.hpp"
#include "ycpp/text.hpp"
ycpp::Doc one(1);
ycpp::Doc two(2);
bool ok = one.text("t").insert(0, "AB").has_value();
ok = ok && two.apply_update(one.encode_state_as_update()).has_value();
// Both type at index 1, between A and B, before hearing from each other.
ok = ok && one.text("t").insert(1, "x").has_value();
ok = ok && two.text("t").insert(1, "y").has_value();
const std::vector<ycpp::byte> from_one = one.encode_state_as_update();
const std::vector<ycpp::byte> from_two = two.encode_state_as_update();
ok = ok && one.apply_update(from_two).has_value();
ok = ok && two.apply_update(from_one).has_value();
assert(ok);
// The lower client id goes first, on both peers.
assert(one.text("t").to_string() == "AxyB");
assert(two.text("t").to_string() == "AxyB");An update can arrive before the updates it builds on. Then a struct cannot be integrated yet. There are two reasons:
- Its own client has a gap. We have client 1 up to clock 5, and the struct starts at 8.
- An origin, right origin or parent is missing. It points at a clock we do not have yet.
Doc::missing_id (line 319) finds the second case. It is Yjs's getMissing. It only checks
references to other clients: a reference to the item's own client is earlier in the same
client's list, which the first check covers.
Doc::take_struct (src/doc.cpp) returns Take::pending for such a struct. Then, in
apply_streamed:
- The struct's keys are re-pointed at the document's pool, since the update's pool dies with the update.
- The structs left over from this update are merged into
pending_structs_. They are kept sorted by client and clock. Duplicates are dropped and overlaps trimmed, as Yjs'smergeUpdateswould. This decides which struct boundaries a re-sent state keeps. - For each, the ID it waits for goes into
pending_missing_. Only the lowest clock per client is kept.
After each update, Doc::apply_pending runs:
pending_ready()checks whether any waited-for clock has now arrived. If none has, the parked structs are left alone. A stream of unrelated updates must not rescan a large pending set.- If one has,
resolve_pending_structs()walks the parked structs once. When a struct still cannot land, the walk jumps to the parked struct that holds the clock it waits for, using a stack. A chain of dependencies then resolves in one walk, not one pass per link. - Structs that still cannot land stay parked, and
pending_missing_is rebuilt. - Parked delete ranges are retried after every update, gate or not (
apply_pending_deletes). A range is applied up to the client's current state. The rest stays parked.
All of this happens inside the one remote transaction of the apply_update call. So the structs
that come out of pending fire their events together with the update that freed them.
A document still sends what it holds in pending. Doc::encode_state_as_update writes the parked
structs after each client's stored structs, and adds the parked delete ranges to the delete set.
Yjs does the same, so a relay that has not caught up still forwards everything.
Integration splits items often. A remote item with an origin inside a run splits that run. A local insert in the middle of a word does too. Once the transaction is over, items that could be one again are merged back. That is part of cleanup: see Deletes and GC.
The algorithm is the same. The plumbing differs:
- Slots instead of pointers.
left,rightandstartare slots. Afterstore_.insert(...), every neighbour is looked up again by slot. An insert may grow the arena. - Containers instead of type objects. Yjs's
this.parentis a type object. ycpp looks up aContainerby parent ID or root name. - Garbage in place of a missing anchor. Yjs's
getMissingandintegrateboth turn such an item into aGC. ycpp folds those checks into the start ofintegrate. - Hash sets for the scan.
before_originandconflictingareIdSets (include/ycpp/index.hpp). Thousands of concurrent items at one spot stay fast. - A walk bound. Loops that follow links stop after
store_.slot_count()steps. A corrupt update cannot make them loop forever.