INSIDE ZED Upstream ↗ Repository ↗
ENGINE ROOM / 07 · ENGINEERING AUDIT

Invariants
under pressure.

What does Zed's text engine actually check? What do its convergence tests exercise? And where do the current tests leave room for adversarial cases?

The engineering question

A collaborative text engine has to preserve several kinds of correctness at once: ordered fragment identity, consistency between indexes and text storage, causal replay, undo visibility, stable positions, and eventual agreement between replicas.

Zed does not ask one function to prove all of that. The inspected code has a structural Buffer::check_invariants, local reference-model tests, deterministic multi-replica tests, and a randomized in-memory network. Those layers provide useful evidence - but they are not interchangeable.

EXECUTIVE FINDING

check_invariants is a structural consistency checker, not a convergence proof. The randomized collaboration test adds meaningful schedule variation, duplicate delivery, and undo/redo. The remaining gap is systematic conflict coverage: same-range edits, delete-versus-insert, overlapping deletions with independent undo, and explicit causal-gap tests.

1. Dissecting check_invariants

At the pinned revision, Buffer::check_invariants is a short, explicit set of assertions in crates/text/src/text.rs · lines 1742–1787 ↗. Read literally, it checks four contracts.

CheckWhat is assertedFailure class caught
Fragment orderEvery fragment's Locator is strictly greater than the preceding fragment ID.Duplicate or out-of-order fragment positions in the fragment tree.
Forward index mappingFor each fragment, lookup by (timestamp, insertion_offset) in the insertion tree must find an entry whose fragment_id matches.A fragment without its corresponding insertion-index record, or a mismatched locator.
Reverse index mappingWalking insertion-index entries and seeking the fragment tree must find the same locator and insertion offset.An insertion-index entry pointing to a missing or mismatched fragment.
Rope summary lengthsThe fragment summary's visible/deleted byte counts must equal visible_text.len() and deleted_text.len().Length-accounting divergence between fragment summaries and the two ropes.
Line-ending normalizationThe visible text must not contain a CRLF pair.CRLF surviving in the normalized internal text representation.

Important distinction - the two index walks together check correspondence in both directions, not merely that each visible fragment can be found. The check is stronger than a simple length assertion, but it remains structural.

What this checker does not assert

  • It does not compare the actual bytes reconstructed from fragments with the bytes inside the visible/deleted ropes. The summary comparison checks lengths, not content equality.
  • It does not independently recompute every fragment's visible flag from insertion, deletion, and undo history.
  • It does not validate the contents or coverage of insertion_slices, anchor round-trips, or the semantic correctness of historical snapshots.
  • It does not inspect whether deferred operations are eventually drained, whether a causal dependency is missing, or whether distinct replicas have converged.
  • It does not prove that a deletion or undo affected the intended logical characters. Those properties need behavioral tests with an expected document.

This is not a criticism of the function's size. A fast invariant checker should target cheap internal consistency. The engineering mistake would be treating a passing call as evidence for properties it never examines.

2. The local reference-model tests

test_random_edits provides a separate oracle for ordinary local editing. It starts from a small random string, generates edits, applies the same changes to a reference String, and compares the result with the buffer. It also checks range summaries, subscriptions/patch replay, historical rope snapshots, and anchor-based range updates before calling check_invariants.

Source: test_random_edits · lines 171–307 ↗.

Other focused tests exercise anchor movement through insertion/deletion and bias behavior at boundaries (anchor tests ↗), undo/redo grouping (history tests ↗), and large insertions split at UTF-8 character boundaries (multibyte and split tests ↗).

ANALYSIS - these tests triangulate different properties: a reference string checks visible content; patch replay checks incremental updates; snapshot checks exercise history; anchor assertions check stable positions. None alone substitutes for the others.

3. What the collaboration tests actually simulate

Deterministic three-replica example

test_concurrent_edits creates three replicas from abcdef. Each replaces a different character, then receives the other two operations in different orders. All three must finish as a12c34e56.

Source: test_concurrent_edits ↗.

This is a useful sanity check for merging independent edits. It is not a conflict test: its three replaced ranges do not overlap.

Randomized collaboration test

test_random_concurrent_edits is the more interesting test. It is annotated for 100 test iterations. Unless overridden by environment variables, each run creates five peers and schedules ten mutation events. A mutation is either a local random edit or an undo/redo action; peers also receive pending network messages in partial batches.

Its in-memory Network deliberately makes delivery messy:

  • Each broadcast message is copied between one and three times into every other peer's inbox.
  • Each copy is inserted at a random position in that inbox, so later messages can appear before earlier ones.
  • A receive drains a randomly sized prefix of the inbox, not necessarily the whole queue.

Sources: test network simulator ↗ and test_random_concurrent_edits ↗.

WHAT THE TEST ASSERTS AFTER THE NETWORK QUIETS
for every replica:
    visible_text == replica_0.visible_text
    check_invariants()

The test checks invariants during the schedule for the currently selected buffer, then compares final visible text across replicas and checks the other replicas again at convergence.

The receiver's causal gate is also important. apply_ops queues operations whose captured version has not yet been observed. flush_deferred_ops retries them after new operations arrive, while deferred_replicas prevents a later operation from the same replica from jumping ahead of an earlier deferred one. An operation already observed by the local version is not applied again.

Sources: apply_ops / apply_op ↗ and deferred queue and causal readiness ↗.

A minimal dependency-gap test can make the deferral contract explicit: create two sequential operations on one sender, deliver the second first, and then deliver its prerequisite.

#[test]
fn test_deferred_operation_applies_after_its_dependency() {
    let buffer_id = BufferId::new(1).unwrap();
    let mut sender = Buffer::new(ReplicaId::new(1), buffer_id, "ab");
    let mut receiver = Buffer::new(ReplicaId::new(2), buffer_id, "ab");

    let first = sender.edit([(1..1, "X")]);
    let second = sender.edit([(2..2, "Y")]);

    receiver.apply_ops([second]);
    assert!(receiver.has_deferred_ops());

    receiver.apply_ops([first]);
    assert!(!receiver.has_deferred_ops());
    assert_eq!(receiver.text(), "aXYb");
    receiver.check_invariants();
}

This exercises the actual dependency gap and the retry path rather than relying on the random simulator to happen to produce it. This proposal is also not yet run.

What the simulator does not model

This is a strong unit-level delivery simulator, not a distributed-systems deployment test. It has in-memory inboxes and eventual delivery. It does not simulate process restarts, durable log recovery, server persistence, authentication/session changes, real transport framing, or permanent message loss. Its random schedules provide sampling, not exhaustive enumeration of every legal schedule.

4. The semantic core: what a remote edit is allowed to delete

The key distinction in the fragment model is between text that exists now and text the sending operation had observed when it was created.

EditOperation carries a Lamport timestamp, a causal version, full-offset ranges, and replacement strings. A remote edit walks fragments in the sender's versioned coordinate space. When it intersects a fragment, it adds its deletion timestamp only if the operation's version had observed that fragment and the fragment was visible in that version. A fragment inserted concurrently - and therefore absent from that version - is not treated as old text that the remote operation can erase.

Sources: EditOperation and UndoOperation ↗, remote intersection and deletion handling ↗, and fragment visibility predicates and summaries ↗.

ANALYSIS - the causal version is not decorative metadata. It decides which fragments count as part of the sender's observed document. This is the foundation for reasoning about delete-versus-insert and overlapping replacement races.

Undo follows the same operation-aware model. A fragment is visible only when its insertion is not currently undone and all deletion operations affecting it have been undone. The undo map evaluates undo counts against the version being queried, rather than simply restoring a previous whole-document string. See UndoMap ↗.

5. Adversarial test matrix

The next step is not to invent a grand claim about collaboration. It is to turn the risky interactions into tiny deterministic tests, with two or three replicas, controlled timestamps, explicit delivery orders, and exact expected text.

ScenarioMinimal setupProperty to assertStatus
Same-cursor insertionFrom ab, A inserts X at 1 and B inserts Y at 1 before sync.Both delivery directions produce the same deterministic order.SOURCE-DERIVED Proposed test in the collaboration lab.
Delete versus inner insertFrom abcdef, A deletes 2..5; B inserts X at 3..3, both before sync.The delete must not erase an insertion that its causal version never observed; replicas must agree on placement.NOT TESTED
Same-range replacementA and B replace the same original range with different strings from the same base version.Concurrent inserted fragments survive; both delivery orders converge to one well-defined result.NOT TESTED
Overlapping deletes + one undoA deletes 1..4; B deletes 2..5; sync, then undo only A's edit.Only characters covered exclusively by A's deletion return. Shared deleted characters remain hidden until B's deletion is also undone.MODEL-DERIVED
Causal gapA creates op1, then op2 based on op1. Deliver op2 to B before op1.op2 is deferred; when op1 arrives, op1 applies and the deferred op2 is flushed. No permanent deferred work remains.NOT TESTED EXPLICITLY
Duplicate deliveryDeliver the same operation multiple times, both in one batch and across separate receives.Visible text changes once; already-observed timestamps do not mutate the buffer again.PARTLY STRESSED Duplicates occur in the random simulator.
Undo/redo raceOne replica undoes an edit while another makes a concurrent edit touching the same logical range; reorder both operation streams.Undo affects only its targeted edit IDs; replicas converge after all causal prerequisites arrive.NOT ISOLATED
Unicode boundary conflictInsert/delete around multi-byte UTF-8 characters concurrently, including an emoji and combining marks.No invalid byte boundary, split fragment, lost code point, or divergent anchor resolution.PARTLY COVERED Local split and anchor tests exist; collaborative conflict is not isolated.

Why the delete/insert case matters

Use base text abcdef. A deletes cde (2..5) while B inserts X between c and d (3..3), with both operations created from the original version. The expected visible result after full synchronization is abXf: the insertion is concurrent text, not part of the characters A observed and deleted.

That expectation follows from the observed-version check in remote deletion handling, but it should still be converted into an upstream test with both delivery orders and invariant checks. The test should also capture the anchor position around the insertion point before either operation.

The following is a concrete test proposal for crates/text/src/tests.rs. It checks both peer perspectives and two different delivery orders on fresh replicas. It has been derived from the inspected APIs and semantics; it has not been compiled or run.

#[test]
fn test_concurrent_delete_preserves_unobserved_insert() {
    let buffer_id = BufferId::new(1).unwrap();
    let mut a = Buffer::new(ReplicaId::new(1), buffer_id, "abcdef");
    let mut b = Buffer::new(ReplicaId::new(2), buffer_id, "abcdef");

    let delete = a.edit([(2..5, "")]);
    let insert = b.edit([(3..3, "X")]);

    // Each author receives the other author's concurrent operation.
    a.apply_ops([insert.clone()]);
    b.apply_ops([delete.clone()]);

    // Two fresh replicas receive the same operations in opposite orders.
    let mut c = Buffer::new(ReplicaId::new(3), buffer_id, "abcdef");
    c.apply_ops([delete.clone(), insert.clone()]);
    let mut d = Buffer::new(ReplicaId::new(4), buffer_id, "abcdef");
    d.apply_ops([insert, delete]);

    for buffer in [&a, &b, &c, &d] {
        assert_eq!(buffer.text(), "abXf");
        buffer.check_invariants();
    }
}

Why overlapping deletes plus undo matters

From abcdef, A deletes bcd and B deletes cde, both based on the same starting state. After both operations converge, the visible text should be af. Undoing only A's deletion should restore b, but not cde, because B's deletion still applies to those characters: the intermediate result should be abf. Undoing B as well should restore abcdef.

This is a direct, human-readable test of the rule that every deletion affecting a fragment must be undone before that fragment becomes visible again. It exercises the interaction between Fragment::is_visible, the undo map, and remote operation propagation - not just the local undo stack.

6. An existing adversarial regression

Zed already contains a useful example of the kind of edge case this investigation should seek. test_edit_partially_intersecting_a_deleted_fragment starts with abcdefgh, deletes cde, then applies a synthetic remote edit whose full-offset range covers b and only part of the deleted fragment (cd, not e).

The test comment records the historical failure: the rope builder could try to consume the full deleted fragment when only part of it was intersected, causing a panic with cannot summarize past end of rope. The regression asserts the resulting text afgh and then undoes the synthetic edit to get abfgh back.

Source: partial deleted-fragment regression ↗.

Engineering lesson - adversarial tests should target representation boundaries, not only user-visible edit stories. Here the bug was a partial intersection between a versioned full-offset range, a deleted fragment, and the rope builder's accounting.

  1. Add the delete-versus-inner-insert test. It probes the causal rule that should protect concurrent text from a delete that never observed it.
  2. Add the overlapping-delete/independent-undo test. It probes whether visibility is derived correctly from multiple deletion IDs and undo counts.
  3. Add a causal-gap test. Deliver a dependent operation first, assert has_deferred_ops(), deliver its prerequisite, then assert the queue drains and the final document is correct.
  4. Add same-range replacement and undo-race tests. Record both delivery permutations and compare all replicas, not only one receiver.
  5. Promote the matrix into a deterministic schedule fuzzer. For a small number of replicas and operations, enumerate permutations that preserve each replica's causal order, inject duplicates, and compare final text plus semantic invariants.

The current randomized test is valuable, but small exhaustive schedules are often better at explaining exactly why a conflict rule works. Random tests can then broaden the search after the expected semantics are explicit.

8. Where the evidence stands

VERIFIED

Fragment/index correspondence, ordering, rope-length accounting, LF normalization, local reference-model behavior, and convergence under the schedules exercised by existing tests.

SUPPORTED ANALYSIS

Version-aware remote replay protects fragments unknown to the sender; undo visibility is accumulated across deletion operations. The code paths provide a concrete model for predicting conflict behavior.

NOT ESTABLISHED

Universal convergence, exhaustive conflict semantics, formal CRDT guarantees, resilience to permanent message loss or process recovery, and performance under adversarial workloads.

This is the evidence boundary. It neither dismisses the implementation nor claims more than the inspected tests show.

9. Executed evidence: two independent runs

Two separate executions back the claims on this page. They are not interchangeable, and neither is an estimate.

Run 1 - patch applied to a clean upstream checkout (CI)

The five deterministic cases were packaged as a patch. A GitHub Actions job checks out the pinned revision, validates the patch with git apply --check, applies it, then runs the full crate suite. No upstream file is committed by this project.

RUN 1: GREEN - the job log reports running 43 tests and test result: ok. 43 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.95s. All five adversarial tests appear individually as ok. Both figures are quoted from the log, not recomputed.

WHY GREPPING THE LOG GIVES 35, NOT 43 - this trips up anyone auditing the artefact, so it is documented rather than hidden. The log interleaves test output with INFO lines emitted during a test, and eight of them land between the test name and its verdict:

test tests::test_line_len ... 2026-11-25T04:16:14+00:00 INFO [text::patch::tests] editing 0..3: "MOE"

The trailing ok is pushed onto the next output line, so a grep for ^test .* \.\.\. ok$ finds 35 of 43. Counting the distinct test NAME ... prefixes finds all 43 - the eight missing ones are exactly the tests that log while running. The authoritative figure is the harness's own summary line (43 passed; 0 failed), and the 8 names are recoverable, which is how this was verified rather than assumed.

Run 2 - standalone harness, no patch, sixth case included

The repository also carries harness/, a small crate whose dependencies are path links into a pinned Zed checkout. It needs no patch and no upstream modification: it links the real text, rope, clock, and sum_tree crates and calls them directly. Building with the test-support feature exposes Buffer::check_invariants(), so each scenario asserts Zed's own structural consistency, not just string equality.

./tools/setup-zed.sh          # sparse, filtered checkout of the pin
cd harness && cargo test --release

RUN 2: 6 PASSED, 0 FAILED - measured locally on the pin 2664a0aa1eae5dabf8f8273c03f88d53061ca7dc with Rust 1.100.0, the toolchain that commit itself declares. Every case below executed and returned ok. The same six tests were then re-run from a fresh clone of this published repository, with the vendor tree rebuilt by tools/setup-zed.sh, and passed again - so the result does not depend on the state of a working copy.

Adversarial testRun 1 (patch, CI)Run 2 (harness, local)
test_adversarial_same_cursor_insertions_convergePASSPASS
test_adversarial_concurrent_delete_preserves_unobserved_insertPASSPASS
test_adversarial_overlapping_deletes_undo_independentlyPASSPASS
test_adversarial_deferred_operation_applies_after_dependencyPASSPASS
test_adversarial_duplicate_delivery_is_idempotentPASSPASS
test_adversarial_three_same_cursor_insertions_all_orders_convergenot in patchPASS

The sixth case, now executed

The permutation case was previously withdrawn: its first draft never compiled (E0282, type annotations needed), so it was never reported as a result. It is rewritten in harness/tests/permutations.rs and now runs.

Three replicas each insert one character at the same offset of "ab". All six delivery orders are tried on a fresh observer buffer. Every order must drain its deferred operations, satisfy check_invariants(), produce byte-identical text, and preserve each inserted character exactly once.

RESULT: all six orders converge to the single string "aCBAb". Convergence here is total, not statistical: the ordering is fixed by Lamport::cmp, which breaks ties on replica_id (self.value.cmp(&other.value).then_with(|| self.replica_id.cmp(&other.replica_id)) in crates/clock/src/clock.rs). Concurrent inserts at one offset therefore sort by replica id, deterministically, on every peer.

This is worth stating precisely, because it is easy to overclaim. The test proves convergence for this conflict shape under exhaustive delivery order. It does not prove convergence for arbitrary interleavings of deletes, undo, and redo at scale; that remains the schedule-fuzzer target below.

10. Reproduction commands and source revision

All source links on this page are pinned to upstream commit 2664a0aa1eae5dabf8f8273c03f88d53061ca7dc (the revision inspected for this study). The focused test commands for the upstream suite, in a local checkout of that revision, are:

cargo test -p text test_random_edits
cargo test -p text test_concurrent_edits
cargo test -p text test_random_concurrent_edits
cargo test -p text test_edit_partially_intersecting_a_deleted_fragment

The upstream suite was run in full by Run 1 above (cargo test -p text, 43 passed). The individual commands here select a single test each and are listed for targeted re-runs.

NEXT RESEARCH TARGET - promote the permutation test into a deterministic schedule fuzzer: enumerate orders that preserve each replica's causal sequence, inject duplicates, and compare final text plus semantic invariants across replicas. The current exhaustive six-order case covers one conflict shape only.