zgui
Architecture

Reactive internals

How zgui-reactive wraps reactive_graph — signal storage, subscriptions, marking and the flush, waking from other threads, owners, task cancellation, conditional branches, and Selector.

zgui-reactive holds zgui's signals, memos, effects and owners, and the executor that runs effects. A signal write only marks the observers that depend on it. The marked effects run later, in the f.flush step of the frame, after input, timers and animations and before the restyle. Effects that run there change the document, and the later stages of the same frame style, lay out and paint the result.

The sections below follow a value through the system: where it is stored, how a read subscribes, what a write marks, what the flush runs, and how owners free it all again. The user-facing model is in Signals.

Engine and facade

zgui does not implement its own reactive engine. It pins one and wraps it.

LayerCrateRole
enginereactive_graph =0.2.14, feature effectsthe graph, the arena, owners
enginereactive_stores =0.4.3per-field reactivity for structs
facadezgui-reactivethe framework's whole reactive API
viewzgui-viewre-exports a subset in its prelude
umbrellazguipub use zgui_reactive as reactive;

zgui-reactive is the only crate allowed to name reactive_graph, reactive_stores, any_spawner or send_wrapper (stated in its Cargo.toml). The versions are pinned in the workspace manifest.

Two engine features are off:

  • nightly. Signals are read with count.get(), never count(). Enabling it would remove the conversions that let a component property accept a closure; a canary test in crates/zgui-reactive/src/canary.rs fails first if that happens.
  • sandboxed-arenas. With it off, there is one arena for the whole process, not one per thread.

Signal storage

RwSignal<T, S>

A Copy slotmap key (plus a Location in debug builds).

ArenaItem<ArcRwSignal<T>, S>
SlotMap<NodeId, Box<dyn Any + Send + Sync>>

One process-wide map.

ArcRwSignal<T>
  • value: Arc<RwLock<T>>
  • inner: Arc<RwLock<SubscriberSet>>
What an RwSignal handle resolves to
// reactive_graph/src/owner/arena.rs
pub type ArenaMap = SlotMap<NodeId, Box<dyn Any + Send + Sync>>;
static MAP: OnceLock<RwLock<ArenaMap>> = OnceLock::new();

A slotmap key includes a generation counter, so a key whose slot was freed and reused no longer resolves. A handle to a disposed value fails its lookup instead of reading another value. Reads take a read lock on the map; creation and disposal take a write lock.

Because handles are keys, not pointers, they are Copy and can be moved into any number of closures without cloning.

HandlesStorageFreed when
RwSignal, ReadSignal, WriteSignal, Memo, Signal, Trigger, StoredValue, Callback, Store, Fieldarenatheir owner is disposed
ArcRwSignal, ArcReadSignal, ArcWriteSignal, ArcMemo, ArcSignal, ArcTrigger, ArcFieldreference countedthe last clone is dropped

Arc handles bypass the arena, which saves up to four lock acquisitions per read (see Costs). They also live independently of any owner. zgui uses this for window state: the size, scale, focus, occlusion, maximized and fullscreen signals behind a WindowHandle are ArcRwSignals, so they stay valid as long as the handle does, even after the component that opened the window unmounts.

SyncStorage and LocalStorage

Arena slots are Box<dyn Any + Send + Sync>. The Storage type parameter is how a value that is not Send/Sync gets in:

SyncStorage (default)LocalStorage
Stored asTSendWrapper<T>
Bound on TSend + Sync + 'static'static
Readable fromany threadthe creating thread only
Constructorsnew, signal, derivenew_local, signal_local, derive_local

The thread check happens on each read, in LocalStorage::try_with: SendWrapper panics if it is dereferenced on a different thread than it was created on. provide_local_context uses the same mechanism and wraps its value in a private newtype so it cannot collide with provide_context of the same type. Trigger and ArcTrigger store no value and are not generic over storage.

Graph edges

The graph uses type-erased handles, not NodeId:

// reactive_graph/src/graph/source.rs, subscriber.rs
pub struct AnySource(pub(crate) usize, pub(crate) Weak<dyn Source + Send + Sync>, /* Location */);
pub struct AnySubscriber(pub usize, pub Weak<dyn Subscriber + Send + Sync>);

The usize is the address of the inner state and is used for Hash and Eq. Both directions are weak references, so a node that goes away leaves dead edges, not dangling ones, and nothing has to walk the graph to remove them.

Tracking reads

A tracking context is a run of a closure the reactive system started: an effect, a memo, or a reactive hole in a view. During that run, a thread-local holds the current observer:

// reactive_graph/src/graph/subscriber.rs
thread_local! {
    static OBSERVER: RefCell<Option<ObserverState>> = const { RefCell::new(None) };
}

AnySubscriber::with_observer sets it for the duration of a call and restores the previous value on drop, including during unwinding, so nesting works.

A tracked read adds two edges:

// reactive_graph/src/traits.rs
impl<T: Source + ToAnySource + DefinedAt> Track for T {
    fn track(&self) {
        if self.is_disposed() { return; }
        if let Some(subscriber) = Observer::get() {
            subscriber.add_source(self.to_any_source());   // forward edge
            self.add_subscriber(subscriber);               // back edge
        }
        // else, debug builds only: "outside a reactive tracking context" diagnostic
    }
}
EdgeDirectionUsed by
back edgesource → subscribera write, to mark observers
forward edgesubscriber → sourcethe flush, to check whether a marked observer must run; the next run, to unsubscribe

get() is track() plus an untracked read; get_untracked() is the read alone. With and Read reduce to the same two paths.

A read with no current observer prints a diagnostic to stderr in debug builds only. Wrapping code in enter_non_reactive_zone suppresses that message and nothing else: a read inside the zone still subscribes if an observer is current. To avoid subscribing, use an _untracked method.

Both edge sets (SourceSet, SubscriberSet) are insertion-ordered IndexSets. SubscriberSet::unsubscribe uses shift_remove so that order is preserved: nested effects are created in order, and an inner effect may assume the outer one has already run in this pass.

Re-running an effect

An effect's task loop is the whole update protocol:

// reactive_graph/src/effect/render_effect.rs
while rx.next().await.is_some() {
    if !owner.paused() && subscriber.with_observer(|| subscriber.update_if_necessary()) {
        subscriber.clear_sources(&subscriber);
        let old_value = mem::take(&mut *value.write().or_poisoned());
        let new_value = owner.with_cleanup(|| subscriber.with_observer(|| fun(old_value)));
        *value.write().or_poisoned() = Some(new_value);
    }
}
  • clear_sources drops every old dependency, and the run re-subscribes through track. Dependencies are rebuilt, not diffed: a closure that read three signals last time and one this time ends with one.
  • owner.with_cleanup disposes the effect's owner before running. Cleanups registered in an effect therefore run before its next run, and signals created inside the effect are freed then.

Marking on write

A write runs nothing. It updates node states and sets one bit in each affected effect's notification channel.

// reactive_graph/src/graph/node.rs
pub enum ReactiveNodeState { Clean, Check, Dirty }
StateMeaning
CleanUp to date.
CheckA source may have changed.
DirtyA source definitely changed.

Propagation:

  1. The write. Dropping the write guard calls mark_dirty on every direct subscriber of the signal.
  2. One Dirty edge. A memo marked dirty sets itself to Dirty and calls mark_check on its own subscribers.
  3. Check for the rest. mark_check sets Check (unless already Dirty) and continues. So Dirty travels one edge and Check covers the rest of the observer graph.
  4. The effect. Each chain ends at an effect. mark_dirty sets its dirty flag and notifies its channel; mark_check only notifies.

The ready set

There is no list of dirty nodes. Each effect has a single-slot channel:

// reactive_graph/src/channel.rs
struct Inner { waker: AtomicWaker, set: AtomicBool }

impl Sender {
    pub fn notify(&mut self) { self.0.set.store(true, Relaxed); self.0.waker.wake(); }
}

The slot is one bit, cleared when the task polls. Writing a signal a thousand times between two flushes causes one re-run, so no batching API is needed.

Waking puts the task into the UI thread's futures LocalPool (crates/zgui-reactive/src/executor/pool.rs). Its internal FuturesUnordered keeps a queue of woken tasks; that queue is the ready set.

Deciding whether an effect runs

A woken effect first calls update_if_necessary(). If it is dirty, it runs. Otherwise it asks each source the same question. A memo answers by recomputing (when Dirty, or when a source says it changed while the memo is Check) and returns whether its new value differs from the old one.

So a memo that recomputes to an equal value stops propagation, and an effect that was only Check does not run. Memo::new requires T: PartialEq; Memo::new_with_compare takes a custom comparison.

Marking is eager and cheap; the decision to run is made lazily, when the task is polled.

The flush

// crates/zgui-reactive/src/executor/frame.rs
pub fn flush() -> FlushOutcome;

pub struct FlushOutcome {
    pub needs_another_frame: bool,
    pub budget_exhausted: bool,
}

Steps:

  1. assert_ui_thread("flush") (debug builds).
  2. Claim the flush. A thread-local running flag guards re-entry. A flush called from inside an effect returns FlushOutcome::default() and does nothing; flushes do not nest.
  3. Increment the flush generation (used by the iteration budget) and clear the outcome flags.
  4. Drain posted closures (those sent with Ui::post from other threads), so their writes are settled in this frame. A closure that posts another schedules it for the next flush.
  5. Poll the pool inside the configured PollContext (the Tokio integration enters its runtime here). The pool also polls tasks woken during the poll. A wake that lands after the pool stalls is caught by polling again, up to three rounds (MAX_ROUNDS = 3). If wakes are still arriving after the last round, needs_another_frame is set.
  6. Re-wake deferred tasks (see the budget below) and set needs_another_frame if there were any.

A drop guard clears running if a task panics. The panic propagates to the caller, and the next flush continues with the remaining tasks.

The iteration budget

Two effects that write each other's sources would keep each other ready forever inside one flush. The budget caps that:

// crates/zgui-reactive/src/executor/budget.rs
pub(crate) const BUDGET: u32 = if cfg!(debug_assertions) { 32 } else { 8 };

The cap is per task, per flush. WakeThrough::poll (executor/through.rs) checks TaskBudget::admit(generation) before polling. A new generation resets the count.

AdmissionWhenEffect
Runwithin the cappoll the task
Deferfirst poll over the cap in this flushlog once at error level, set the task aside, return Pending
AlreadyDeferredlater polls over the capreturn Pending silently

The log names the spawn location for tasks spawned through zgui-reactive's spawn or spawn_local. Debug builds allow more polls so that a long dependency chain can be diagnosed rather than cut short. Correct code is polled once or twice per flush and never reaches the cap.

Where the runtime flushes

Applications never call install or flush directly. App::into_handler installs the executor (crates/zgui-runtime/src/app.rs), and the runtime flushes:

  • once per frame (window/frame.rs);
  • between queued input events (window/input.rs), so the second event sees the first one's effects;
  • after delivering geometry observations (window/observe.rs);
  • inside the scroll animation (window/scroll/mod.rs);
  • once more when the runtime is dropped, after closing every window.

The frame explains why each of these sites needs its own flush. needs_another_frame is folded into the frame's redraw request. budget_exhausted is not read by the runtime; it is the programmatic form of the logged error.

Waking from another thread

The pool's own waker only queues a task. The UI thread, however, sleeps in the platform event loop, so a task made ready by another thread also has to wake that loop. Every spawned task is therefore polled with a composite waker:

// crates/zgui-reactive/src/executor/through.rs
impl ArcWake for Composite {
    fn wake_by_ref(arc_self: &Arc<Self>) {
        arc_self.pool.wake_by_ref();
        if !frame::note_wake() {
            arc_self.target.ping();
        }
    }
}

frame::note_wake returns true while a flush is running, and records the wake so the flush polls again. In that case no platform wake is sent: an effect that writes a signal must not request a redraw from inside the frame that is already running. It also returns true on a thread that is being torn down.

Worker thread: background future completes
The UI task's receiver

Marks the task ready and wakes it.

Composite::wake_by_ref
  • pool.wake_by_ref(): queue the task on the UI thread's pool
  • target.ping(): only when no flush is running
RuntimeWaker::wakecrates/zgui-runtime/src/wake.rs
  • If a frame is in progress, record one owed frame
  • Otherwise ask the platform to wake (ReactiveWork { surfaces })
The event loop

Runs a frame; the frame calls flush(), which polls the task.

How background work wakes the event loop

The FrameWaker contract

// crates/zgui-reactive/src/executor/wake.rs
pub trait FrameWaker: Send + Sync + 'static {
    fn wake(&self);
}
pub fn set_frame_waker(waker: Arc<dyn FrameWaker>);

An implementation must be callable from any thread, must not block, must not assume an owner or the UI thread, and must be idempotent: many wakes between two frames should cost one frame.

The composite wakers on a thread share one WakeTarget, created eagerly, so a waker installed after effects already exist still reaches them.

The runtime installs RuntimeWaker, which records which surfaces a wake concerns and coalesces wakes through its FrameGate; the frame describes both. The test a_wake_inside_a_frame_is_owed_rather_than_sent asserts that a thousand wakes during a frame produce no platform requests and one owed frame.

Two separate checks suppress wakes: note_wake in the reactive layer (wakes during a flush) and FrameGate in the runtime (wakes from anywhere during a frame, such as a timer or a mutation).

Until set_frame_waker is called, a task woken from another thread is queued but nothing requests the frame that would poll it. A host that drives the pipeline itself must install a waker. TestWaker counts wakes for tests: count() reads, take() reads and resets.

Owners

An owner is the unit of disposal.

// reactive_graph/src/owner.rs
pub(crate) struct OwnerInner {
    pub parent: Option<Weak<RwLock<OwnerInner>>>,
    nodes: Vec<NodeId>,
    pub contexts: FxHashMap<TypeId, Box<dyn Any + Send + Sync>>,
    pub cleanups: Vec<Box<dyn FnOnce() + Send + Sync>>,
    pub children: Vec<Weak<RwLock<OwnerInner>>>,
    paused: bool,
}

Creating an arena-backed handle inserts it into the arena and registers its NodeId with the current owner. With no current owner, the value is never freed, and nothing reports it. Only four APIs assert that an owner exists: provide_context, provide_local_context, on_cleanup_local and Selector::is_selected. RwSignal::new does not.

Disposal always runs in this order:

  1. Take cleanups, nodes and children out under one write lock.
  2. Dispose every child, recursively.
  3. Run cleanups in registration order.
  4. Remove all the owner's NodeIds from the arena under one write lock.

Contexts are stored in the owner's map keyed by TypeId, and lookups walk toward the root. Because the key is only the type, provide a newtype rather than a bare String or u32.

Debug builds log an error (without panicking) when an owner chain exceeds MAX_OWNER_DEPTH = 4096 or one owner exceeds MAX_OWNER_CHILDREN = 1024 children.

Synchronous disposal with Mounted

// crates/zgui-reactive/src/own/mounted.rs
#[must_use = "an unmounted scope frees nothing; store it and call `unmount` when the node goes away"]
pub struct Mounted { /* private */ }

impl Mounted {
    #[track_caller] pub fn new() -> Self;
    pub fn with<T>(&self, build: impl FnOnce() -> T) -> T;
    pub fn owner(&self) -> &Owner;
    pub fn unmount(mut self);
}

Each mounted node has one owner, and unmount disposes everything before returning. Deferring disposal to the executor would leave a frame in which an unmounted node's timers could still fire, its rows still occupy shared tables, and its observers report geometry for a node that is gone. Reading an arena handle after disposal panics, so that gap would be a crash.

  • Drop also disposes, so a scope dropped during a panic is still freed.
  • Cleanups run with no current owner. They can also run when the last owner handle is dropped, from anywhere, so a cleanup must capture everything it needs when registered.

When a window closes, the runtime unmounts its view tree in tree order while the application's scope is still alive, then unmounts the window's own scope. When the application ends, zgui_reactive::shutdown() polls the pool once (so tasks whose effects are gone can finish) and drops the remaining tasks, up to eight rounds, before the thread's destructors run. Otherwise cleanups in leftover tasks would run after the reactive runtime was gone.

Bounded child lists with Scope

An owner keeps a weak reference to every child it ever had; dropping a child does not remove the entry. A long-lived parent with many short-lived children (a scrolling list, a changing route) accumulates one dead entry per child.

Scope (crates/zgui-reactive/src/own/scope.rs) avoids this by creating members inside generations and dropping spent generations whole:

const RETIRE_AFTER: usize = 64;

impl Scope {
    pub fn new() -> Self;
    pub fn mount(&self) -> Mounted;
    pub fn live(&self) -> usize;
    pub fn generation_children(&self) -> usize;
    pub fn generations_created(&self) -> usize;
}

When a member is released, a new generation starts if the newest one holds more dead members than the scope holds live ones (minimum 64). Generations that are neither the newest nor occupied are then dropped.

  • Generations are siblings under the scope's owner, so dropping one never disposes another.
  • Live members are never moved, so a virtualised list that always has rows on screen still retires generations.
  • A generation's owner is dropped only after its last member is gone.

A test mounts and unmounts 10,000 members and asserts generation_children() <= 65.

For implements the same policy directly over Owner in crates/zgui-view/src/flow/each/generation.rs, with no minimum, bounding dead references at 2 × live + generations.

Tasks and cancellation

Tasks spawned with spawn or spawn_local are cancelled when the scope that spawned them is disposed. Cancellation drops the future (and what it captured) during the unmount itself, not at the next flush.

Each owner that should own tasks holds one TaskSet (crates/zgui-reactive/src/task/set.rs), provided as a local context with a single cleanup that cancels everything in it. Tasks leave the set when they finish. One cleanup per spawn would grow without bound: a listener runs in the owner where its on: binding was written, so a button that spawns on every click would add a cleanup to a long-lived component owner on every click.

Task sets are installed at the boundaries that should own tasks:

BoundaryWhere
each componentScoped::build in crates/zgui-view/src/view/scope.rs
each windowcrates/zgui-runtime/src/window/mod.rs
the applicationcrates/zgui-runtime/src/app.rs

Installing a set per component keeps a spawn from landing in a short-lived effect scope, where every later task of the component would be cancelled when that effect re-ran.

When a component is rebuilt, its owner is cleaned first, which cancels the previous run's tasks and removes the task set with the other cleanups. The rebuild then provides a fresh set, so tasks spawned by the new run are cancelled at the next rebuild or at unmount, like the first run's.

The handle spawn returns is for cancelling early; dropping it does not cancel the task (unlike TimeoutHandle and IntervalHandle). Use spawn_detached for work that must outlive its scope.

Conditional branches

Show is built on a gated hole, Branch (crates/zgui-view/src/flow/branch.rs). It watches a small selector value (for Show, the boolean condition) and replaces its content only when that value changes. A condition that reads a list and checks whether it is empty swaps branches when the list becomes empty, and does nothing on ordinary inserts.

Each branch is built in its own child owner, which is disposed when the branch is replaced. It is not built in the effect's owner, because that owner is cleaned every time the selector re-runs: a branch built there would lose what it created (a prop default, a stored value) on every unrelated write the selector reads, while its nodes stayed on screen.

When the component around a Show is rebuilt, the component's owner is cleaned first, which takes the branch's state with it. The new effect starts from the previous selection, so no nodes move, but the current branch is rebuilt in place in a fresh branch owner so its reactive state exists again.

Selector

When every row of a list checks "am I selected?" against a shared selection signal, every row subscribes to it, and changing the selection re-runs every row. A memo per row reduces the work to the comparison, but every memo is still marked and polled.

The engine's Selector keeps one boolean signal per key instead:

// reactive_graph/src/computed/selector.rs
pub struct Selector<T> where T: PartialEq + Eq + Clone + Hash + 'static {
    subs: Arc<RwLock<FxHashMap<T, ArcRwSignal<bool>>>>,   // one signal per watched key
    v: Arc<RwLock<Option<T>>>,                            // last source value
    f: Arc<dyn Fn(&T, &T) -> bool + Send + Sync>,
    effect: Arc<RenderEffect<T>>,                         // the source's only subscriber
}

Each row tracks only the boolean signal for its own key. When the source changes, the selector's effect notifies the new and the previous key. Two rows re-run, not all of them.

The engine never removes entries from subs, so the map grows with every key ever displayed. zgui's Selector (crates/zgui-reactive/src/reexport/selector.rs) adds eviction. is_selected registers the (owner, key) pair once, counts watchers per key, and registers an on_cleanup_local that decrements the count and removes the key from the engine selector when it reaches zero.

APINotes
Selector::new(source)source: impl Fn() -> K + Clone + Send + Sync + 'static
Selector::new_with_fn(source, matches)custom match, e.g. path-prefix or range containment
is_selected(&key) -> boolcall from the row's own scope
watched_keys() -> usizediagnostic; assert on it in tests of long-running lists

Tests: only_the_two_affected_rows_re_run (eight rows, two re-runs after a selection change) and ten_thousand_rows_leave_nothing_behind (watched_keys() == 0 afterwards).

is_selected with no current owner fails assert_owner in debug builds. In release builds the key is never evicted. Selector<K> uses Rc<RefCell<..>> internally and is not Send.

Engine APIs that are not exported

Compile-fail tests in crates/zgui-reactive/tests/ui/ assert these engine APIs are unreachable:

Not exportedProblemUse instead
Effect::new_synccan run off the UI thread, where the document must not be touchedRenderEffect
Effect::new_isomorphicfor server and client rendering, which zgui does not haveRenderEffect
Owner::on_cleanuprequires Send + Sync closures, which view code rarely hason_cleanup_local
unkeyed store indexing (StoreFieldIterator)re-runs later siblings' observers and panics when the collection shrinks under an observer#[store(key: K = ...)] and at_key

Also not re-exported:

  • untrack(...): use the _untracked methods at the read site.
  • batch(...): unnecessary, since writes never run anything synchronously and the one-bit channel coalesces writes.

The engine crates are not re-exported either, except zgui_reactive::store::reactive_stores, which #[derive(Store)] expands to.

Costs

OperationWorkScales with
get() on an arena signal, untracked context2 arena read locks, 1 value read lock, clone of Tconstant
get() on an arena signal, tracked4 arena read locks, 1 value read lock, 2 set insertionsconstant
get() on an Arc signal1 value read lock (+2 set insertions if tracked)constant
get_untracked()1 arena read lock, 1 value read lockconstant
set() / update()2 arena read locks, 1 value write lock, mark each subscriberdirect subscribers
further markingone mark_check per edgeobserver subgraph
flush(), nothing readyone flag check, one poll of an empty queueconstant
flush() with workone poll and one update_if_necessary per ready taskready tasks and their dependencies
one effect re-rundispose its owner, drop old edges, run, add new edgesold + new dependencies + owned values
disposing an ownerchildren, cleanups, one arena write lockeverything registered under it

What follows from the table:

  • Arc handles are the faster read. The arena handles' extra locks are the price of Copy, which is the right trade in view code but not in a hot loop.
  • maybe_update can decline to notify: returning false drops the guard without notifying.
  • Only a memo stops propagation, by recomputing to an equal value.

A still document runs no frames at all, so it runs no flushes (idle.frames is 0 in docs/performance.md). Within a frame the reactive phase is small and never scans the whole graph. See the cost model for whole-frame numbers.

Next

On this page