Skip to content

Streams, threading and multi-graph dispatch

A Graph is a single-writer consistency domain. Owner-thread reads and writes pay zero synchronization overhead, while off-thread producers, streams, and peer worker graphs cross the boundary through explicit coalescing ports or ordered FIFO dispatch. See The graph.

Choosing a cross-thread or cross-graph primitive

PrimitiveEntry pointCost & allocationOrdering & semantics
Direct writesig.Value <- vO(1)O(1) guard + synchronous flush (0 B)Same-thread immediate read-your-own-writes; throws InvalidOperationException off-thread under Guarded.
Coalescing portsig.Post v / SignalPort<'T> (sig.CreatePort ())O(1)O(1) post; 0 B steady-state, at most 1 inbox slotThread-safe latest-value delivery; coalesces bursts before drain; silent no-op after target graph disposal.
1-source bridgebindSignalTo / bindMemoToO(1)O(1) / 0 B off-thread coalescingForwards one source signal or settled memo into another graph's Signal / SignalPort without Activate ().
Projected bridgebridge target { ... }O(1)O(1) / 0 B steady-stateCross-graph CE with Phase-1 input + Phase-2 output cutoff and optional debounce / throttle* (see Effects, bindings and bridges).
Ordered commanddispatch graph { ... } / graph.DispatchO(1)O(1) enqueue; 1 closure per off-thread itemFIFO ordered commands and multi-signal batched { ... } transactions; runs every item in arrival order.
Request / replydispatch graph { return ... } / graph.DispatchAsyncO(1)O(1) inline on owner; Task<'T> off-threadRuns inside graph's domain and returns Task<'T> (optional cancellation ct; faults on disposal).
Stream foldstream { ... } / StreamSourceLock-guarded fold; 0 B coalesced drain wakeupFolds IAsyncEnumerable<'T>, channels, observables, or push sinks; publishes latest state once per inbox drain.
Circuit affinityThreadAffinity.SerialisedAtomic enter/leave gate per entry (~2.2x vs Guarded)Single logical circuit hopping thread-pool threads on one SynchronizationContext (such as Blazor Server).
Parallel demand DAGRanvier.DagMulti-core Fork / Join + 128-bit hash firewallPull-only content-addressed parallel derivation; publish final snapshots into Ranvier.Graph via SignalPort or dispatch.

Streams

stream (pre-CE: createStream, createStreamFold, createStreamOn, createStreamFoldOn; C#: Reactive.Stream* and StreamSources) subscribes to a StreamSource<'T> on its first read and restarts whenever its Phase-1 reactive key settles on an unequal value:

open System.Threading
open System.Threading.Channels
open Ranvier
open Ranvier.CE

let roomCount (room: Signal<string>) (openRoom: string -> CancellationToken -> ChannelReader<string>) =
    stream {
        fold 0 (fun total _ -> total + 1)
        let! channel = room
        let! ct = stream.cancellationToken
        return StreamSource.ofChannel (openRoom channel ct)
    }
  • Latest item: without fold, StreamMemo<'T> stays Pending until the first item and fails with InvalidOperationException if the stream completes empty.

  • Folding: with fold seed folder, each item updates folder state item(folder must be pure), and an empty completion publishes seed.

  • Phase-1 key stability: an equal key, or a transient Pending / Failed key read, keeps the active stream subscription open and accumulating. An unequal settled key cancels stream.cancellationToken and starts fresh from seed on demand.

Stream adapters

Choose a StreamSource adapter for the producer:

  • StreamSource.create (fun sink ct -> task { ... sink.Next x } :> Task) — custom push producer.

  • StreamSource.ofAsyncEnumerable accepts a .NET IAsyncEnumerable<'T>.

  • StreamSource.ofChannel accepts a ChannelReader<'T> on net10.0.

  • StreamSource.ofObservable accepts an IObservable<'T>.

  • StreamSource.ofAsyncIterable accepts a JavaScript async iterable under Fable.

Working with a stream memo

  • Combinators: StreamMemo.map, map2, zip, bind, and bindFold compose downstream nodes.

  • Disposal: disposing a pending StreamMemo cancels its token and settles readers with ObjectDisposedException.

See Benchmarks → Streams.

Threads

Under .NET's default ThreadAffinity.Guarded, the thread that constructs new Graph () owns it (guarded_enter_iff_owner, ~22 ns thread-ID check, 0 B). Any direct sig.Value <- v, batch, node creation, or stale pull from another thread raises InvalidOperationException before mutating graph state.

Under Fable, JavaScript is single-threaded: IsOnGraphThread is true and Dispatch runs inline.

Off-thread producers choose between coalescing and FIFO ordering:

  • Signal posts: SignalPort.Post and sig.Post keep only the latest pending value. Overwriting it in place costs 0 B in steady state and uses at most one inbox slot.1

  • Stream items: StreamSink.Next folds items under a lock on the delivering thread. It posts a drain wake only when none is outstanding.

  • dispatch graph { ... } / graph.Dispatch preserves every step in order: each off-thread call enqueues an item in the FIFO inbox. graph.Pump () drains them in arrival order, recording any item exception in graph.Root.Errors without halting remaining items.2

Watch coalescing vs FIFO dispatch on the signal map

OffThread () simulates a background producer posting to host before draining.

Port burst (1, 2, 3) coalesces three rapid port.Post calls into 1 drain and 1 total run (runs = 2 including setup).

FIFO dispatch (+1 × 3) runs all 3 queued increments in order (runs = 5):

Example code
let host = Graph.Current
let worker = OffThread ()
let ticks = signal { return 0 }
let port = ticks.CreatePort ()
let mutable runs = 0
let total =
    memo {
        let! n = ticks
        runs <- runs + 1
        return n * 10
    }
effect {
    let! v = total
    printfn "total = %d" v
}

controls [
    button "Port burst (1, 2, 3)" (fun () ->
        worker.Run (fun () ->
            port.Post 1
            port.Post 2
            port.Post 3))
    |> describe "SignalPort coalesces 3 off-thread posts into 1 drain and 1 memo run."
    |> expect "coalesced to 30 in 1 new run" (fun () -> total.Peek = 30 && runs = 2)
    button "FIFO dispatch (+1 × 3)" (fun () ->
        worker.Run (fun () ->
            dispatch host { ticks.Value <- ticks.Peek + 1 }
            dispatch host { ticks.Value <- ticks.Peek + 1 }
            dispatch host { ticks.Value <- ticks.Peek + 1 }))
    |> describe "dispatch queues 3 ordered commands; each runs in FIFO order."
    |> expect "all 3 increments ran" (fun () -> total.Peek = 60 && runs = 5)
]
Hover a node for its state; click it for why it last ran.

Dispatcher selection

GraphOptions.Dispatcher controls how off-thread wakes reach the graph's owning thread:

GraphOptions.DispatcherBehavior
None (default) with SynchronizationContext.Current presentCaptures a SynchronizationContextDispatcher (WPF, WinForms, Avalonia, MAUI, Blazor Server UI/circuit contexts drain automatically).
None (default) with no SynchronizationContextFalls back to ManualDispatcher (console apps, background workers, unit tests).
Some (ManualDispatcher ())Queues work until the owning thread calls graph.Pump () (graph.PendingWork reports waiting items).
Some (ImmediateDispatcher ())Calls Pump () inline on the posting thread — unsafe with off-thread settles under Guarded (raises Pump ran on thread ...); use only with externally serialized Unchecked graphs.

Awaiting work from outside the graph

When an external request handler or tool host needs to mutate or query a graph from another thread and await the result, use dispatch graph { ... return ... } (or graph.DispatchAsync(work, ct)):

open System.Threading
open System.Threading.Tasks
open Ranvier
open Ranvier.CE

let incrementAsync (g: Graph) (count: Signal<int>) (ct: CancellationToken) : Task<int> =
    dispatch g {
        cancellation ct
        count.Value <- count.Value + 1
        return count.Value
    }

On the owning thread, DispatchAsync executes inline and returns a completed Task<'T>.

Off-thread, cancelling ct before the drain claims the item cancels the returned task and skips the work. Disposing g faults queued items with ObjectDisposedException(see Contracts).

Never block synchronously (.Result / .Wait()) on DispatchAsync from the sole thread responsible for pumping g.

Multi-graph and parallel topologies

Keeping sig.Value <- v single-threaded preserves 0 B owner writes, synchronous read-your-own-writes (sig.Value <- x immediately visible to memo.Value), and glitch-free batched { ... } transactions. Scale across CPU cores by matching the topology to the workload:

  1. Per-worker graphs. Construct an independent Guarded graph with new Graph () on each worker thread (0 B uncontended local reactivity).

    Publish latest-value state to the UI or coordinator through SignalPort<'T> or bridge uiSignal { ... }. For atomic updates to several signals, use dispatch uiGraph { batched { ... } }.

  2. Parallel demand-driven queries. Use Ranvier.Dag when workers share content-addressed incremental rules evaluated on demand with Fork / Joinand 128-bit hash firewall cutoff.

    Post the resulting snapshot into Ranvier.Graph through SignalPort or dispatch.

  3. Single logical circuit across pool threads (ThreadAffinity.Serialised): use Serialised only when a host framework (such as a Blazor Server circuit) already serializes turns across thread-pool threads via a SynchronizationContext.

Edit this page