Skip to content

Equality, buffers and timing

GraphOptions.Equality sets the graph-wide default for equality cutoff (GraphOptions.Default.WithEquality policy or a custom IEqualityPolicy). Individual nodes or Phase-1 inputs can override it with a typed IEqualityComparer<'T>:

  • JsIdentityPolicy (default): JavaScript === semantics — primitives and strings by value, reference types by reference, nan <> nan.

  • StructuralPolicy: EqualityComparer<'T>.Default — cuts off equal records, tuples, lists, Some x, and nan on .NET.

Writing the same object instance back is cut off on both targets. For separately constructed equal values, .NET and Fable compare as follows:

TypeDefault on .NETDefault under FableStructuralPolicy, both targets
int, float, string, NoneCut offCut offCut off
nanPropagatesPropagatesCut off on .NET, propagates under Fable
DateTime, DateTimeOffset, decimal, KeyValuePair, struct records/tuplesCut offPropagatesCut off
Some 1PropagatesCut offCut off
Records, tuples, lists, Some of a recordPropagatesPropagatesCut off
Class without custom equality, 'T[] arraysPropagatesPropagatesPropagates

Per-node comparers

Override equality on a single source, Phase-1 input key, or Phase-2 output without changing the rest of the graph:

open System
open Ranvier
open Ranvier.CE

let ci = StringComparer.OrdinalIgnoreCase

let configure (rawHost: Signal<string>) (fetchTag: string -> System.Threading.CancellationToken -> System.Threading.Tasks.Task<string>) =
    let name =
        signal {
            comparer ci
            return "Ada"
        }

    let badge =
        memo {
            comparer ci
            let! host = rawHost |> withComparer ci
            return host.Trim ()
        }

    let remoteTag =
        asyncMemo {
            comparer ci
            let! host = rawHost |> withComparer ci
            let! ct = asyncMemo.cancellationToken
            return! fetchTag host ct
        }

    name, badge, remoteTag
PrimitiveCE syntax / factoryCutoff behaviour
Signalsignal { comparer cmp; ... } (createSignalWithComparer)Rejects equal writes in place, keeping the existing instance.1
Phase-1 input keysrc |> withComparer keyCmp (createEffectOnWithComparer)Per-source or per-and! arm on split memo, effect, bridge, asyncMemo, and stream: equal keys skip Phase 2 and preserve owned scopes, flights, and streams.
Memomemo { comparer outCmp; ... } (create*Memo*WithComparer)Caches the newly computed value and suppresses downstream observer marks when equal.2
Async memoasyncMemo { comparer cmp; ... } (create*Async*WithComparer)Suppresses downstream wakes on equal settled Ready -> Ready refreshes (Settled-value cutoff).
Boundary, bridge & memoTablecomparer cmp header (keyComparer kcmp on memoTable)Typed output/key equality (AsyncSource has no cutoff; StreamMemo uses GraphOptions.Equality).

Null comparers raise ArgumentNullException at construction. A throwing signal comparer aborts the write and surfaces to the writer; a throwing computed-node comparer fails that node.3 From C#, see C#.

Buffers updated in place

On .NET, JsIdentityPolicy and StructuralPolicy both compare arrays by reference. If you mutate a float32[] in place and write the same reference back, equality cutoff suppresses the write.

Allocating a new array above 85,000 B hits the Large Object Heap. Benchmarks measured 3.9x slower performance at 512 KB and 199 Gen2 GCs per 1,000 ticks at 4 MB.

For large buffers (about 85 KB or more) or sparse element edits (about 37–40 ns versus copying megabytes), publish in place with a version counter or an always-unequal comparer:

open System.Collections.Generic
open Ranvier
open Ranvier.CE

let everyWrite<'T> =
    { new IEqualityComparer<'T[]> with
        member _.Equals(_, _) = false
        member _.GetHashCode _ = 0 }

let setupBuffer (integrate: float32[] -> unit) (upload: float32[] -> unit) =
    let positions =
        signal {
            comparer everyWrite
            return Array.zeroCreate<float32> 1_048_576
        }

    effect {
        let! buf = positions
        upload buf
    }

    // Per simulation tick (or increment a separate `version: Signal<int>` beside a plain array):
    integrate positions.Peek
    positions.Value <- positions.Peek
  • Downstream memos: a memo returning that same float32[] reference cuts off under default equality; add comparer everyWrite if it passes the array on, or return a scalar summary (such as Array.sum).

  • Batching: multiple writes inside batched { ... } wake effects and bindings once per flush.

  • Thread safety: Ranvier's thread guard covers positions.Value <- ..., not concurrent element mutations across threads.

Debounce and throttle

Timed nodes capture upstream changes eagerly on every mark and delay publication according to four rules (all four publish their first ready value immediately; zero duration propagates inline without allocating a timer):

ModePipe combinator / CE headerAdmission rule
Debouncedebounced delay src / debounce delayPublishes the latest changed capture after delay of quiet; each unequal capture extends the deadline.
Leading throttlethrottledFirst interval src / throttleFirst intervalAdmits the leading change and discards changes during interval (0 timers; timestamp check only).
Trailing throttlethrottledLast interval src / throttleLast intervalOpens a fixed interval window on the first change and publishes the latest capture at expiry.
Leading + trailingthrottled interval src / throttle intervalAdmits the leading change and the latest trailing change; trailing admission starts the next cooldown.

In F#, a CE header gates the entire static Phase-1 key. Use debounce, throttle, throttleFirst, or throttleLast on memo, effect, bridge, asyncMemo, or stream. Add clock customClock to supply a clock.

To gate individual inputs, pipe each one through debounced* or throttled*. The *With options variants accept TimedOptions<'T> with Clock and Comparer:

let search (http: System.Net.Http.HttpClient) (query: Signal<string>) =
    asyncMemo {
        policy FlightPolicy.CancelPrevious
        debounce (System.TimeSpan.FromMilliseconds 250.)
        let! term = query
        let! ct = asyncMemo.cancellationToken
        return! http.GetStringAsync($"/api/search?q={term}", ct)
    }

Explicit-graph factories (debounce*, throttle* in TimedCombinators) and C# Reactive.Debounce / Throttle* build the same Timed<'T> node.

Pending captures cancel held candidates. Failed captures publish immediately, preserving ErrorOrigin.

TimedClock.system uses Stopwatch on .NET (TimedClock.ofTimeProvideris available on net10.0) and performance.now() under Fable. Without a SynchronizationContext, call graph.Pump () on the owning thread when real timers fire (see Streams, threading and multi-graph dispatch).

Watch admission on the signal map

Both replays inject deterministic MapClock() steps (clock.Advance ms advances simulated time rather than wall-clock time; see Signal maps).

Debounce waits for quiet

Capture 1 at 0 ms and 2 at 50 ms: at 100 ms output stays 0because the second capture extended the quiet deadline to 150 ms.

Example code
let clock = MapClock()
let input = signal { return 0 }
let admitted =
    input
    |> debouncedWith { Clock = clock; Comparer = None } (System.TimeSpan.FromMilliseconds 100.)
effect {
    let! v = admitted
    printfn "admitted %d" v
}

controls [
    button "Capture 1" (fun () -> input.Value <- 1)
    |> expect "initial publication is held" (fun () -> admitted.Peek = 0)
    button "50 ms, capture 2" (fun () -> clock.Advance 50.; input.Value <- 2)
    |> expect "latest capture is held" (fun () -> admitted.Peek = 0)
    button "Advance time to 100 ms" (fun () -> clock.Advance 50.)
    |> expect "extended deadline has not expired" (fun () -> admitted.Peek = 0)
    button "Advance time to 150 ms" (fun () -> clock.Advance 50.)
    |> expect "latest capture publishes" (fun () -> admitted.Peek = 2)
]
Hover a node for its state; click it for why it last ran.

Compare the three throttle modes

first admits 1 immediately and drops 2 during its cooldown.

last holds until 100 ms and publishes 2.

both publishes 1 at 0 ms and 2 at 100 ms, starting a fresh cooldown from that trailing admission.

Example code
let clock = MapClock()
let input = signal { return 0 }
let options = { Clock = clock; Comparer = None }
let interval = System.TimeSpan.FromMilliseconds 100.
let first = input |> throttledFirstWith options interval
let last = input |> throttledLastWith options interval
let both = input |> throttledWith options interval
effect {
    let! a = first
    and! b = last
    and! c = both
    printfn "%d / %d / %d" a b c
}

controls [
    button "Capture 1" (fun () -> input.Value <- 1)
    |> expect "leading modes publish immediately" (fun () -> (first.Peek, last.Peek, both.Peek) = (1, 0, 1))
    button "50 ms, capture 2" (fun () -> clock.Advance 50.; input.Value <- 2)
    |> expect "trailing modes hold the candidate" (fun () -> (first.Peek, last.Peek, both.Peek) = (1, 0, 1))
    button "Advance time to 100 ms" (fun () -> clock.Advance 50.)
    |> expect "trailing modes publish the latest capture" (fun () -> (first.Peek, last.Peek, both.Peek) = (1, 2, 2))
    button "Capture 3 at 100 ms" (fun () -> input.Value <- 3)
    |> expect "combined mode starts a new cooldown" (fun () -> (first.Peek, last.Peek, both.Peek) = (3, 2, 2))
    button "Advance time to 200 ms" (fun () -> clock.Advance 100.)
    |> expect "next trailing admissions publish" (fun () -> (first.Peek, last.Peek, both.Peek) = (3, 3, 3))
]
Hover a node for its state; click it for why it last ran.

Edit this page