Skip to content

Latest commit

 

History

History
260 lines (198 loc) · 12.2 KB

integration.md

File metadata and controls

260 lines (198 loc) · 12.2 KB

Integration

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.

The problem

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.

Origins

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.

How Doc::integrate works

Given an item that is ready (its origins and parent are in the store), Doc::integrate:

  1. 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).
  2. Turns it into garbage if its anchor is gone. This is Yjs's Item.getMissing. The item becomes a Gc struct (Doc::integrate_gc) when:
    • its origin or right origin points at a Gc struct;
    • its parent item was collected, or no longer holds a type;
    • it has no parent and no neighbour to take one from.
  3. Fills in a missing parent. An item that came without a parent copies parent and parent_sub from its origin or right origin.
  4. 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.
  5. Checks whether it sits where its origins say. If left.right is already right, nothing came between the origins. That is the usual case, and always the case for a local write. Then the item goes right there.
  6. Otherwise, runs the conflict scan described below. It may move left to the right.
  7. Links the item in after left: it sets the neighbours' links, or the container's start.
  8. For a map value, makes it the key's current item. Then it deletes the item on its left, the value it replaces.
  9. Updates the container's length, if the item is a visible list item.
  10. 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 conflict scan

Two concurrent inserts at the same place, as each peer integrates them

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's itemsBeforeOrigin): every item scanned so far.
  • conflicting (Yjs's conflictingItems): the items scanned since left last moved.

For each item o in the range, in order:

  1. Same origin as ours. o was inserted at the same place as us.
    • If o's client id is lower, o goes first. Move left to o.
    • If it is higher, and o also has our right origin, we go before o. Stop.
    • If it is higher but its right origin differs, keep scanning. A later item may still decide.
  2. Its origin is an item we already passed. o hangs off an item in the range.
    • If that item is not in conflicting, it sits at or before our current left. Then o belongs with it, so o goes first too. Move left to o.
    • If that item is in conflicting, it sits after our current left, where our place is not decided yet. Keep left, and keep scanning.
  3. 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.

A three-way example

The conflict scan step by step, with three clients

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:

  1. a: same origin (none). Client 1 is lower than 2, so left moves to a.
  2. x: its origin is a, which the scan already passed, and which is not in conflicting. So x goes before b, and left moves to x.
  3. 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.

A detail: "covering", not "starting at"

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.

Why it converges

A full proof is in the YATA paper and the Yjs sources. The intuition:

  1. The scan only reads things every peer agrees on: IDs, origins, right origins. It never reads arrival order or local state.
  2. Origins never change. So the set of items "between my origins" is the same on every peer that has them all.
  3. Ties between items with the same origin are broken by client id. That is a total order, the same everywhere.
  4. 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");

Missing dependencies: pending structs

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.

An update whose origin is missing waits in pending until its dependency arrives

Doc::take_struct (src/doc.cpp) returns Take::pending for such a struct. Then, in apply_streamed:

  1. The struct's keys are re-pointed at the document's pool, since the update's pool dies with the update.
  2. 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's mergeUpdates would. This decides which struct boundaries a re-sent state keeps.
  3. 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:

  1. 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.
  2. 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.
  3. Structs that still cannot land stay parked, and pending_missing_ is rebuilt.
  4. 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.

After a transaction: merging

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.

How ycpp differs from Yjs here

The algorithm is the same. The plumbing differs:

  • Slots instead of pointers. left, right and start are slots. After store_.insert(...), every neighbour is looked up again by slot. An insert may grow the arena.
  • Containers instead of type objects. Yjs's this.parent is a type object. ycpp looks up a Container by parent ID or root name.
  • Garbage in place of a missing anchor. Yjs's getMissing and integrate both turn such an item into a GC. ycpp folds those checks into the start of integrate.
  • Hash sets for the scan. before_origin and conflicting are IdSets (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.