# Equality, buffers and timing

> Configure graph and per-node equality cutoffs, publish in-place buffers, and gate updates with debounce and throttle.

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

- **`JsIdentityPolicy`{fsharp} (default):** JavaScript `===` semantics — primitives and strings by
  value, reference types by reference, `nan <> nan`{fsharp}.

- **`StructuralPolicy`{fsharp}:** `EqualityComparer<'T>.Default`{fsharp} — cuts off equal records,
  tuples, lists, `Some x`{fsharp}, and `nan`{fsharp} on .NET.

Writing the same object instance back is cut off on both targets. For separately constructed equal
values, `.NET` and [Fable](fable.md) compare as follows:

| Type | Default on .NET | Default under Fable | `StructuralPolicy`{fsharp}, both targets |
| --- | --- | --- | --- |
| `int`{fsharp}, `float`{fsharp}, `string`{fsharp}, `None`{fsharp} | Cut off | Cut off | Cut off |
| `nan`{fsharp} | Propagates | Propagates | Cut off on .NET, propagates under Fable |
| `DateTime`{fsharp}, `DateTimeOffset`{fsharp}, `decimal`{fsharp}, `KeyValuePair`{fsharp}, struct records/tuples | Cut off | Propagates | Cut off |
| `Some 1`{fsharp} | Propagates | Cut off | Cut off |
| Records, tuples, lists, `Some`{fsharp} of a record | Propagates | Propagates | Cut off |
| Class without custom equality, `'T[]`{fsharp} arrays | Propagates | Propagates | Propagates |

## Per-node comparers

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

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

| Primitive | CE syntax / factory | Cutoff behaviour |
| --- | --- | --- |
| **Signal** | `signal { comparer cmp; ... }`{fsharp} (`createSignalWithComparer`{fsharp}) | Rejects equal writes in place, keeping the existing instance.[^signal-noop] |
| **Phase-1 input key** | `src |> withComparer keyCmp`{fsharp} (`createEffectOnWithComparer`{fsharp}) | Per-source or per-`and!`{fsharp} arm on split `memo`{fsharp}, `effect`{fsharp}, `bridge`{fsharp}, `asyncMemo`{fsharp}, and `stream`{fsharp}: equal keys skip Phase 2 and preserve owned scopes, flights, and streams. |
| **Memo** | `memo { comparer outCmp; ... }`{fsharp} (`create*Memo*WithComparer`{fsharp}) | Caches the newly computed value and suppresses downstream observer marks when equal.[^memo-cutoff] |
| **Async memo** | `asyncMemo { comparer cmp; ... }`{fsharp} (`create*Async*WithComparer`{fsharp}) | Suppresses downstream wakes on equal settled `Ready -> Ready`{fsharp} refreshes ([Settled-value cutoff](async-and-boundaries.md#settled-value-cutoff)). |
| **Boundary, bridge & memoTable** | `comparer cmp`{fsharp} header (`keyComparer kcmp`{fsharp} on `memoTable`{fsharp}) | Typed output/key equality (`AsyncSource`{fsharp} has no cutoff; `StreamMemo`{fsharp} uses `GraphOptions.Equality`{fsharp}). |

Null comparers raise `ArgumentNullException`{fsharp} at construction. A throwing signal comparer
aborts the write and surfaces to the writer; a throwing computed-node comparer fails that
node.[^comparer-throw] From C#, see [C#](csharp.md).

## Buffers updated in place

On .NET, `JsIdentityPolicy`{fsharp} and `StructuralPolicy`{fsharp} both compare arrays by
reference. If you mutate a `float32[]`{fsharp} 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**:

```fsharp
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`{fsharp} returning that same `float32[]`{fsharp} reference cuts
  off under default equality; add `comparer everyWrite`{fsharp} if it passes the array on, or
  return a scalar summary (such as `Array.sum`{fsharp}).

- **Batching:** multiple writes inside `batched { ... }`{fsharp} wake effects and
  [bindings](effects-and-bindings.md#one-source-bindings) once per flush.

- **Thread safety:** Ranvier's thread guard covers `positions.Value <- ...`{fsharp}, 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):

| Mode | Pipe combinator / CE header | Admission rule |
| --- | --- | --- |
| Debounce | `debounced delay src`{fsharp} / `debounce delay`{fsharp} | Publishes the latest changed capture after `delay`{fsharp} of quiet; each unequal capture extends the deadline. |
| Leading throttle | `throttledFirst interval src`{fsharp} / `throttleFirst interval`{fsharp} | Admits the leading change and discards changes during `interval`{fsharp} (`0` timers; timestamp check only). |
| Trailing throttle | `throttledLast interval src`{fsharp} / `throttleLast interval`{fsharp} | Opens a fixed `interval`{fsharp} window on the first change and publishes the latest capture at expiry. |
| Leading + trailing | `throttled interval src`{fsharp} / `throttle interval`{fsharp} | Admits the leading change and the latest trailing change; trailing admission starts the next cooldown. |

:::warning Capture runs eagerly
Timing gates publication, not capture evaluation. Keep expensive projections and IO **downstream**
of the timed gate — either in Phase 2 of a timed CE or in a node reading a `Timed<'T>`{fsharp}.
:::

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

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

```fsharp
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*`{fsharp}, `throttle*`{fsharp} in `TimedCombinators`{fsharp})
and C# `Reactive.Debounce`{fsharp} / `Throttle*`{fsharp} build the same `Timed<'T>`{fsharp} node.

`Pending`{fsharp} captures cancel held candidates. `Failed`{fsharp} captures publish immediately,
preserving `ErrorOrigin`{fsharp}.

`TimedClock.system`{fsharp} uses `Stopwatch`{fsharp} on .NET (`TimedClock.ofTimeProvider`{fsharp}
is available on `net10.0`) and `performance.now()` under Fable. Without a
`SynchronizationContext`{fsharp}, call `graph.Pump ()`{fsharp} on the owning thread when real
timers fire (see
[Streams, threading and multi-graph dispatch](streams-and-threading.md#dispatcher-selection)).

## Watch admission on the signal map

Both replays inject deterministic `MapClock()`{fsharp} steps (`clock.Advance ms`{fsharp} advances
simulated time rather than wall-clock time; see [Signal maps](signal-maps.md)).

### Debounce waits for quiet

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

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

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

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

</div>


### Compare the three throttle modes

`first`{fsharp} admits `1`{fsharp} immediately and drops `2`{fsharp} during its cooldown.

`last`{fsharp} holds until `100 ms` and publishes `2`{fsharp}.

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

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

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

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

</div>


[^signal-noop]: [`signal_update_noop`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Check.html#signal_update_noop).
[^memo-cutoff]: [`cutoff`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Runs.html#cutoff), [`resolve_clean_unmoved`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Check.html#resolve_clean_unmoved).
[^comparer-throw]: [`comparer_throw_contained`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#comparer_throw_contained).
