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
| Primitive | Entry point | Cost & allocation | Ordering & semantics |
|---|---|---|---|
| Direct write | sig.Value <- v | guard + synchronous flush (0 B) | Same-thread immediate read-your-own-writes; throws InvalidOperationException off-thread under Guarded. |
| Coalescing port | sig.Post v / SignalPort<'T> (sig.CreatePort ()) | post; 0 B steady-state, at most 1 inbox slot | Thread-safe latest-value delivery; coalesces bursts before drain; silent no-op after target graph disposal. |
| 1-source bridge | bindSignalTo / bindMemoTo | / 0 B off-thread coalescing | Forwards one source signal or settled memo into another graph's Signal / SignalPort without Activate (). |
| Projected bridge | bridge target { ... } | / 0 B steady-state | Cross-graph CE with Phase-1 input + Phase-2 output cutoff and optional debounce / throttle* (see Effects, bindings and bridges). |
| Ordered command | dispatch graph { ... } / graph.Dispatch | enqueue; 1 closure per off-thread item | FIFO ordered commands and multi-signal batched { ... } transactions; runs every item in arrival order. |
| Request / reply | dispatch graph { return ... } / graph.DispatchAsync | inline on owner; Task<'T> off-thread | Runs inside graph's domain and returns Task<'T> (optional cancellation ct; faults on disposal). |
| Stream fold | stream { ... } / StreamSource | Lock-guarded fold; 0 B coalesced drain wakeup | Folds IAsyncEnumerable<'T>, channels, observables, or push sinks; publishes latest state once per inbox drain. |
| Circuit affinity | ThreadAffinity.Serialised | Atomic 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 DAG | Ranvier.Dag | Multi-core Fork / Join + 128-bit hash firewall | Pull-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>staysPendinguntil the first item and fails withInvalidOperationExceptionif the stream completes empty.Folding: with
fold seed folder, each item updatesfolder state item(foldermust be pure), and an empty completion publishesseed.Phase-1 key stability: an equal key, or a transient
Pending/Failedkey read, keeps the active stream subscription open and accumulating. An unequal settled key cancelsstream.cancellationTokenand starts fresh fromseedon demand.
Stream adapters
Choose a StreamSource adapter for the producer:
StreamSource.create (fun sink ct -> task { ... sink.Next x } :> Task)— custom push producer.StreamSource.ofAsyncEnumerableaccepts a .NETIAsyncEnumerable<'T>.StreamSource.ofChannelaccepts aChannelReader<'T>onnet10.0.StreamSource.ofObservableaccepts anIObservable<'T>.StreamSource.ofAsyncIterableaccepts a JavaScript async iterable under Fable.
Working with a stream memo
Combinators:
StreamMemo.map,map2,zip,bind, andbindFoldcompose downstream nodes.Disposal: disposing a pending
StreamMemocancels its token and settles readers withObjectDisposedException.
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.Postandsig.Postkeep only the latest pending value. Overwriting it in place costs0 Bin steady state and uses at most one inbox slot.1Stream items:
StreamSink.Nextfolds items under a lock on the delivering thread. It posts a drain wake only when none is outstanding.dispatch graph { ... }/graph.Dispatchpreserves 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 ingraph.Root.Errorswithout 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)
]
Dispatcher selection
GraphOptions.Dispatcher controls how off-thread wakes reach the graph's owning thread:
GraphOptions.Dispatcher | Behavior |
|---|---|
None (default) with SynchronizationContext.Current present | Captures a SynchronizationContextDispatcher (WPF, WinForms, Avalonia, MAUI, Blazor Server UI/circuit contexts drain automatically). |
None (default) with no SynchronizationContext | Falls 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:
Per-worker graphs. Construct an independent
Guardedgraph withnew Graph ()on each worker thread (0 Buncontended local reactivity).Publish latest-value state to the UI or coordinator through
SignalPort<'T>orbridge uiSignal { ... }. For atomic updates to several signals, usedispatch uiGraph { batched { ... } }.Parallel demand-driven queries. Use
Ranvier.Dagwhen workers share content-addressed incremental rules evaluated on demand withFork/Joinand 128-bit hash firewall cutoff.Post the resulting snapshot into
Ranvier.GraphthroughSignalPortordispatch.Single logical circuit across pool threads (
ThreadAffinity.Serialised): useSerialisedonly when a host framework (such as a Blazor Server circuit) already serializes turns across thread-pool threads via aSynchronizationContext.