INSIDE ZED Upstream ↗ Repository ↗
FIELD GUIDE / 05 · RUNTIME

One thread owns the state. The compiler knows.

Zed's UI runtime keeps an Rc/RefCell object graph alive across asynchronous work. That is only sound because the executor holding it is !Send, the priority queue is a weighted draw that renormalises over non-empty queues, and cross-replica ordering is a Lamport timestamp over a four-slot inline version vector. Each claim below is traced to a line of the pinned checkout, and the concurrency and fairness rules are covered by executed tests.

Scope and revision. Every file reference, line number and code excerpt on this page comes from Zed at commit 2664a0aa1eae5dabf8f8273c03f88d53061ca7dc. The tests named here are in this repository and run against that checkout's own crates (scheduler, clock) via tools/setup-zed.sh. Nothing on this page describes a reimplementation.

The runtime is three crates, not one

The parts that decide when work runs are split out of gpui into crates/scheduler. That separation is what makes the scheduling rules testable without a window: the executor, the priority enum and a deterministic test scheduler all live in a crate with no rendering dependency.

gpui/src/queue.rs        weighted pop over three priority queues
crates/scheduler/
  scheduler.rs           Priority, Priority::weight(), Scheduler trait
  executor.rs            LocalExecutor (!Send), SendLocalExecutor, BackgroundExecutor
  test_scheduler.rs      TestScheduler: seeded, deterministic, single-threaded
  tests.rs               31 #[test] functions - the only tests in the crate
crates/clock/            ordering across replicas
  clock.rs               285 lines, Lamport, Global, ReplicaId
  system_clock.rs         49 lines

Measured at the pin: crates/scheduler is 3215 lines with 31 tests, all in tests.rs. crates/clock is 334 lines with zero tests. That asymmetry is the reason this page ships its own tests for the clock rather than pointing at existing ones.

The !Send executor is the load-bearing idea

A GUI framework that mutates shared state from event handlers, async tasks and background workers has to answer one question: who is allowed to touch the object graph? Zed's answer is a type-level one. LocalExecutor carries a marker field whose only purpose is to make the type immovable across threads:

crates/scheduler/src/executor.rs

/// A `!Send` executor pinned to a single session. Tasks spawned on it run in
/// order on whichever thread drains the dispatch destination supplied at
/// construction time - typically the main thread for the default session, or
/// a dedicated OS thread for sessions created by `spawn_dedicated_thread`.
#[derive(Clone)]
pub struct LocalExecutor {
    session_id: SessionId,
    scheduler: Arc<dyn Scheduler>,
    dispatch: Arc<dyn Fn(Runnable<RunnableMeta>) + Send + Sync>,
    not_send: PhantomData<Rc<()>>,
}

PhantomData<Rc<()>> contributes nothing at runtime. It exists solely so that Rc's lack of Send propagates to LocalExecutor. The consequence is that the type that runs UI futures cannot be moved to another thread, so the Rc<RefCell<..>> graph it touches cannot be mutated concurrently. There is no lock, no atomic swap and no runtime check: the borrow checker rejects the program.

This was tested, and the first attempt was wrong. The first version of harness/tests/ui_runtime.rs asserted LocalExecutor: Send. The compiler refused it. The negative property is therefore recorded as a compile error rather than a runtime assertion, because no stable API can assert !Send inside a test body. What is assertable is the bridge, and that is what the test pins.

Crossing a thread boundary is an explicit opt-in through to_send(), which produces a SendLocalExecutor that accepts only Send futures and posts them back to the same dispatch destination:

/// Creates a thread-safe handle that submits `Send` futures to this
/// executor's dispatch destination.
pub fn to_send(&self) -> SendLocalExecutor {
    SendLocalExecutor {
        _scheduler: self.scheduler.clone(),
        dispatch: self.dispatch.clone(),
    }
}

So the rule is not "the UI is single-threaded" as a convention. It is: single-threaded state is protected by a type that is physically unable to leave its thread, and background work reaches it only through a handle that refuses non-Send payloads. harness/tests/ui_runtime.rs pins SendLocalExecutor, BackgroundExecutor and SessionId as Send + Sync, and LocalExecutor as Clone (how it is shared within a thread), so the boundary is asserted from the side that compiles.

Fairness is a weighted draw, not a strict heap

A strict priority queue starves low-priority work. Zed instead keeps three queues and picks among them by probability, using hard-coded weights:

crates/scheduler/src/scheduler.rs

impl Priority {
    /// Returns the relative probability weight for this priority level.
    /// Used by schedulers to determine task selection probability.
    pub const fn weight(self) -> u32 {
        match self {
            Priority::High => 60,
            Priority::Medium => 30,
            Priority::Low => 10,
            // realtime priorities are not considered for probability scheduling
            Priority::RealtimeAudio => 0,
        }
    }
}

Three details matter, and all three are easy to get wrong when describing this design:

  • 60/30/10 is 6:3:1, and it sums to 100. The numbers read as percentages, which is why the ratio is discoverable without running the code. Medium is #[default], so unannotated work is not the least favoured.
  • RealtimeAudio has weight 0 and is excluded from the draw entirely, because realtime work is dispatched on its own thread. It is in the enum for classification, not for selection.
  • The weights are only relative to the queues that are non-empty. The selector multiplies each weight by whether that queue has work, then renormalises:
crates/gpui/src/queue.rs, spin_try_pop()

let high   = P::High.weight()   * !queues.high_priority.is_empty()   as u32;
let medium = P::Medium.weight() * !queues.medium_priority.is_empty() as u32;
let low    = P::Low.weight()    * !queues.low_priority.is_empty()    as u32;
let mut mass = high + medium + low;

if !queues.high_priority.is_empty() {
    let flip = self.rand.random_ratio(P::High.weight(), mass);
    if flip { return Ok(queues.high_priority.pop_front()); }
    mass -= P::High.weight();
}

This is a sequential draw, not a single weighted choice: high is tried first with probability 60/mass, and if it loses, its weight leaves the mass before medium is tried. With all three queues occupied the shares are exactly 60/30/10. The renormalisation is what makes an idle queue harmless: if only the low queue has work, the mass is 10 rather than 100, so low is selected with probability 10/10 and runs immediately instead of waiting on a 10% chance against two empty queues.

The draw, measured

harness/src/bin/priority-draw.rs reads Priority::weight() out of the real crate and replays the same walk over a fixed-seed xorshift64*, so the numbers below are reproducible on any machine without depending on rand's version. One million draws over the three weighted priorities:

PriorityWeightMeasured shareNominal
High6060.063%60%
Medium3029.921%30%
Low1010.015%10%

Maximum absolute deviation from nominal: 0.079 percentage points over 1 000 000 draws (high 600 635, medium 299 210, low 100 155). RealtimeAudio was then placed in the candidate list next to High and Low for 200 000 draws and was selected zero times: a zero-width band can never contain a target drawn from [0, mass).

The honest framing of this measurement: it validates the arithmetic contract of the weights, not the behaviour of a running editor. It shows that the published weights produce the documented shares when consumed by the real selection loop. It says nothing about frame times, and this page draws no conclusion about them.

Determinism is a first-class feature of the runtime

Scheduling bugs are order-dependent, and order-dependent bugs are hard to reproduce. Zed's answer is to ship a scheduler that can be driven by a seed. TestSchedulerConfig is public and exposes the knobs that make a run reproducible:

crates/scheduler/src/test_scheduler.rs

pub struct TestSchedulerConfig {
    pub seed: u64,
    pub randomize_order: bool,
    pub allow_parking: bool,
    pub capture_pending_traces: bool,
    pub timeout_ticks: RangeInclusive<usize>,
}

impl TestSchedulerConfig {
    pub fn with_seed(seed: u64) -> Self { ... }
}

randomize_order defaults to true, which means the weighted selection path is on the hot path during tests as well, not only in production. That is a deliberate trade: tests explore orderings rather than replaying one fixed interleaving. harness/tests/ui_runtime.rs asserts the seed is actually carried (with_seed(42).seed == 42, and two different seeds do not collapse), that randomize_order is the default, and that a freshly built TestScheduler starts with an empty queue and returns from run() with it still empty.

Ordering across replicas, with no tests upstream

crates/clock is the smallest crate on this page and the one with the most surprising audit result: 334 lines, zero #[test] functions. The ordering rules that every collaborative edit depends on are exercised only indirectly, through the text crate's operation tests. This repository therefore tests them directly, in harness/tests/concurrency.rs.

The timestamp: value first, replica id breaks ties

crates/clock/src/clock.rs

impl Ord for Lamport {
    fn cmp(&self, other: &Self) -> Ordering {
        // Use the replica id to break ties between concurrent events.
        self.value
            .cmp(&other.value)
            .then_with(|| self.replica_id.cmp(&other.replica_id))
    }
}

Causal order is carried by value; the replica id is only consulted when two events are concurrent. That distinction is tested both ways: a later value from a lower replica still sorts after an earlier value from a higher one (Lamport{value:5, replica:1} > Lamport{value:4, replica:9}), and equal values from different replicas get a deterministic total order rather than comparing equal.

The packing is lossless

pub fn as_u64(self) -> u64 {
    ((self.value as u64) << 32) | (self.replica_id.0 as u64)
}

A 32-bit sequence in the high half and a 16-bit replica in the low half. Because it is a pure shift-or of non-overlapping fields, sorting by the packed integer must agree with Ord for causally related pairs. The test checks both: six distinct timestamps pack to six distinct integers, and the packed order matches the causal order.

The version vector is four slots wide by default

pub struct Global {
    // 4 is chosen as it is the biggest count that does not increase the size of the field itself.
    // Coincidentally, it also covers all the important non-collab replica ids.
    values: SmallVec<[u32; 4]>,
}

Everything up to four replicas stays inline; a fifth replica spills to the heap. The four reserved ids are LOCAL = 0, REMOTE_SERVER = 1, AGENT = 2, LOCAL_BRANCH = 3, and FIRST_COLLAB_ID = 8 is the threshold above which a replica counts as a peer:

pub fn is_remote(self) -> bool {
    self == ReplicaId::REMOTE_SERVER || self >= ReplicaId::FIRST_COLLAB_ID
}

The test asserts the predicate agrees with the constants on both sides of the threshold: id 7 is not remote, id 8 is, and the four reserved ids classify as documented.

A zero slot means "unobserved", and that changes what meet does

This is the subtlest part of the crate, and the place where a plausible-sounding description is wrong. join is a per-replica maximum, which is ordinary. meet looks like its dual and on paper is a per-replica minimum, but a zero entry does not mean "sequence 0", it means "this replica was never observed". A literal element-wise minimum would therefore erase knowledge that only one side holds. The implementation special-cases zero:

match (*left, right) {
    // left has not observed the replica
    (0, _) => *left = right,
    // right has not observed the replica
    (_, 0) => (),
    (_, _) => *left = cmp::min(*left, right),
}

The practical consequence, which the test pins: meet with an empty vector keeps the other side's knowledge rather than zeroing it, and meet is symmetric even when one side is empty. Both properties follow from the two 0 arms, and both would break under a naive min. The test also checks the minimum on the ordinary case ([1:6, 2:1] meet [1:2, 2:9] gives [1:2, 2:1]), and idempotence.

A wrong hypothesis, recorded. The first version of the test asserted that meet was asymmetric: that an unobserved left slot is filled from the right while an unobserved right slot leaves the left untouched, so meet(a,b) != meet(b,a). That was a misreading. Running it produced a failure, and a 500-case randomised probe (random version vectors over four replicas, values 0 to 5) found zero commutativity, associativity or idempotence violations. The asymmetry claim was deleted and replaced with what the code actually does. The probe is described here rather than kept, because the property it tests is now covered structurally by the committed test.

What the other tests pin: join is the per-replica maximum and is commutative and associative (verified on concrete vectors, including that joining never loses knowledge); observe always advances strictly past the observed timestamp, including the fast path and the case where the local clock is already ahead; observed, observed_any and observed_all treat an unseen replica as unobserved rather than as zero, which is what gates deferred operations.

Executed evidence

Two test files back the claims above. Both compile against the pinned checkout's own crates, both are in this repository, and both were run on the toolchain Zed pins:

FileCrate under testTestsResult
harness/tests/concurrency.rsclock (334 lines, 0 upstream tests)88 passed
harness/tests/ui_runtime.rsscheduler (3215 lines, 31 upstream tests)55 passed
harness/tests/adversarial.rstext55 passed
harness/tests/permutations.rstext11 passed

Full suite: 33 tests, 33 passed, 0 failed, 0 warnings, on rustc 1.100.0 (0ef1bc386 2026-11-09). The raw output is committed as harness/results/suite-run.txt and the fairness measurement as harness/results/priority-draw.txt, so no figure on this page rests on a recollection. Reproduce with:

./tools/setup-zed.sh
cd harness
cargo test --release
cargo run --release --bin priority-draw

What this design buys and what it costs

Buys. The single-threaded object graph needs no locks, so entity reads are plain memory reads and there is no lock contention on the UI path. !Send makes that sound at compile time rather than by convention. The weighted draw removes starvation without an aging mechanism. A seeded scheduler makes order-dependent bugs reproducible. A four-slot inline version vector keeps the common case allocation-free.

Costs. Every background task that touches UI state must round-trip through the local executor, which is a queue hop per interaction. Priority is advisory: a 6:3:1 draw can still run low-priority work late under sustained load, because nothing in the weights bounds latency, only long-run share. A weight-0 priority must be dispatched elsewhere or it never runs, so the classification and the dispatch are coupled by convention rather than by the type. And the clock crate, which every collaborative edit depends on, has no internal tests: correctness there is currently inferred from the behaviour of its consumers and from tests like the ones on this page.

19 TESTS EXECUTEDPINNED 2664a0aaTOOLCHAIN 1.100.0