# Streams, threading and multi-graph dispatch

> Fold push and async streams, cross thread boundaries safely, and connect worker graphs.

A `Graph`{fsharp} 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](graph.md#requirements-and-invariants).

## Choosing a cross-thread or cross-graph primitive

| Primitive | Entry point | Cost & allocation | Ordering & semantics |
| --- | --- | --- | --- |
| Direct write | `sig.Value <- v`{fsharp} | $O(1)$ guard + synchronous flush (`0 B`) | Same-thread immediate read-your-own-writes; throws `InvalidOperationException`{fsharp} off-thread under `Guarded`{fsharp}. |
| Coalescing port | `sig.Post v`{fsharp} / `SignalPort<'T>`{fsharp} (`sig.CreatePort ()`{fsharp}) | $O(1)$ 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`{fsharp} / `bindMemoTo`{fsharp} | $O(1)$ / `0 B` off-thread coalescing | Forwards one source signal or settled memo into another graph's `Signal`{fsharp} / `SignalPort`{fsharp} without `Activate ()`{fsharp}. |
| Projected bridge | `bridge target { ... }`{fsharp} | $O(1)$ / `0 B` steady-state | Cross-graph CE with Phase-1 input + Phase-2 output cutoff and optional `debounce`{fsharp} / `throttle*`{fsharp} (see [Effects, bindings and bridges](effects-and-bindings.md#cross-graph-bridges)). |
| Ordered command | `dispatch graph { ... }`{fsharp} / `graph.Dispatch`{fsharp} | $O(1)$ enqueue; `1` closure per off-thread item | **FIFO ordered** commands and multi-signal `batched { ... }`{fsharp} transactions; runs every item in arrival order. |
| Request / reply | `dispatch graph { return ... }`{fsharp} / `graph.DispatchAsync`{fsharp} | $O(1)$ inline on owner; `Task<'T>`{fsharp} off-thread | Runs inside `graph`{fsharp}'s domain and returns `Task<'T>`{fsharp} (optional `cancellation ct`{fsharp}; faults on disposal). |
| Stream fold | `stream { ... }`{fsharp} / `StreamSource`{fsharp} | Lock-guarded fold; `0 B` coalesced drain wakeup | Folds `IAsyncEnumerable<'T>`{fsharp}, channels, observables, or push sinks; publishes latest state once per inbox drain. |
| Circuit affinity | `ThreadAffinity.Serialised`{fsharp} | Atomic enter/leave gate per entry (~`2.2x` vs `Guarded`{fsharp}) | Single logical circuit hopping thread-pool threads on one `SynchronizationContext`{fsharp} (such as [Blazor Server](blazor-server.md)). |
| Parallel demand DAG | [`Ranvier.Dag`](https://github.com/ranvier-org/Ranvier.Dag) | Multi-core `Fork`{fsharp} / `Join`{fsharp} + 128-bit hash firewall | Pull-only content-addressed parallel derivation; publish final snapshots into `Ranvier.Graph`{fsharp} via `SignalPort`{fsharp} or `dispatch`{fsharp}. |

## Streams

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

```fsharp
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`{fsharp}, `StreamMemo<'T>`{fsharp} stays `Pending`{fsharp} until
  the first item and fails with `InvalidOperationException`{fsharp} if the stream completes empty.

- **Folding:** with `fold seed folder`{fsharp}, each item updates `folder state item`{fsharp}
  (`folder`{fsharp} must be pure), and an empty completion publishes `seed`{fsharp}.

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

### Stream adapters

Choose a `StreamSource`{fsharp} adapter for the producer:

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

- `StreamSource.ofAsyncEnumerable`{fsharp} accepts a .NET `IAsyncEnumerable<'T>`{fsharp}.

- `StreamSource.ofChannel`{fsharp} accepts a `ChannelReader<'T>`{fsharp} on `net10.0`.

- `StreamSource.ofObservable`{fsharp} accepts an `IObservable<'T>`{fsharp}.

- `StreamSource.ofAsyncIterable`{fsharp} accepts a JavaScript async iterable under
  [Fable](fable.md).

### Working with a stream memo

- **Combinators:** `StreamMemo.map`{fsharp}, `map2`{fsharp}, `zip`{fsharp}, `bind`{fsharp}, and
  `bindFold`{fsharp} compose downstream nodes.

- **Disposal:** disposing a pending `StreamMemo`{fsharp} cancels its token and settles readers
  with `ObjectDisposedException`{fsharp}.

See [Benchmarks → Streams](../benchmarks/streams.md).

## Threads

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

Under [Fable](fable.md), JavaScript is single-threaded: `IsOnGraphThread`{fsharp} is
`true`{fsharp} and `Dispatch`{fsharp} runs inline.

Off-thread producers choose between **coalescing** and **FIFO ordering**:

- **Signal posts:** `SignalPort.Post`{fsharp} and `sig.Post`{fsharp} keep only the latest pending
  value. Overwriting it in place costs `0 B` in steady state and uses at most one inbox
  slot.[^port-coalesce]

- **Stream items:** `StreamSink.Next`{fsharp} folds items under a lock on the delivering thread.
  It posts a drain wake only when none is outstanding.

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

### Watch coalescing vs FIFO dispatch on the signal map

`OffThread ()`{fsharp} simulates a background producer posting to `host`{fsharp} before draining.

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

**FIFO dispatch (+1 × 3)** runs all **3** queued increments in order (`runs = 5`{fsharp}):

<div class="rv-map-card">

```fsharp
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)
]
```

<div class="rv-map-host" id="rvm-pab5d7d58cc-c1" data-ranvier-map-page="pab5d7d58cc" data-ranvier-map-cell="c1"></div>

</div>


## Dispatcher selection

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

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

:::warning Console and worker hosts must pump `ManualDispatcher`
Without a `SynchronizationContext`{fsharp}, off-thread `Task.Run`{fsharp} / `HttpClient`{fsharp}
completions wait in the inbox and `AsyncMemo`{fsharp} stays `Pending`{fsharp} until the owning
thread calls `graph.Pump ()`{fsharp}.
:::

## 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 ... }`{fsharp} (or
`graph.DispatchAsync(work, ct)`{fsharp}):

```fsharp
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`{fsharp} executes inline and returns a completed
`Task<'T>`{fsharp}.

Off-thread, cancelling `ct`{fsharp} before the drain claims the item cancels the returned task and
skips the work. Disposing `g`{fsharp} faults queued items with `ObjectDisposedException`{fsharp}
(see [Contracts](../concepts/contracts.md)).

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

## Multi-graph and parallel topologies

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

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

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

2. **Parallel demand-driven queries.** Use
   [`Ranvier.Dag`](https://github.com/ranvier-org/Ranvier.Dag) when workers share
   content-addressed incremental rules evaluated on demand with `Fork`{fsharp} / `Join`{fsharp}
   and 128-bit hash firewall cutoff.

   Post the resulting snapshot into `Ranvier.Graph`{fsharp} through `SignalPort`{fsharp} or
   `dispatch`{fsharp}.

3. **Single logical circuit across pool threads (`ThreadAffinity.Serialised`{fsharp}):** use
   `Serialised`{fsharp} only when a host framework (such as a [Blazor Server](blazor-server.md)
   circuit) already serializes turns across thread-pool threads via a
   `SynchronizationContext`{fsharp}.

[^port-coalesce]: [`signal_port_inv_and_coalesce`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Concurrency.html#signal_port_inv_and_coalesce).
[^inbox-fifo]: [`inbox_drain_fifo_fault_isolated`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Concurrency.html#inbox_drain_fifo_fault_isolated).
