Skip to content

Memo tables

A Memo<'T> retains its last computed value even after disposal.1 When deriving heavy payloads — syntax trees, rendered buffers, query plans, or layout frames — across a large or open key space 'K, retaining every value forever grows memory without bound.

MemoTable<'K, 'V> memoizes a pure derivation 'K -> 'V under an O(1)O(1) intrusive LRU budget while keeping reactive dependency edges and downstream observer wiring live across payload eviction2:

open Ranvier
open Ranvier.CE

type ParsedDoc = { Hash: uint64; Ast: string array }

let parseTable (revision: Signal<int>) (loadSource: string -> int -> ParsedDoc) =
    memoTable {
        maxEntries 64
        stamp (fun (doc: ParsedDoc) -> doc.Hash)
        let! path = memoTable.key
        and! rev = revision
        return loadSource path rev
    }

The example binds the table key alongside the reactive revision input. See The graph — Graph inference for how reactive inputs determine a graph.

Choose the read surface that matches whether a missing key should allocate a slot or throw on Pending / Failed:

Method / pipeCE descriptorMissing keyUnready key
table.Get key / MemoTable.get key table ('V)MemoTable.at key tableCreates & evaluates slotRaises on Pending / Failed
table.TryGet key / MemoTable.tryGet key table ('V voption)MemoTable.tryAt key tableValueNone untracked (0 slots created)Raises on Pending / Failed when live
table.TryRead key / MemoTable.tryRead key table (Reading<'V>)tryRead (MemoTable.at key table)Creates & evaluates slotReturns Pending or Failed ex

Two cutoff tiers: stamps vs value comparers

When an entry's payload is evicted to stay within MaxWeight, its lightweight reactive slot remains wired into the graph. How an evicted slot answers a subsequent upstream write depends on its cutoff tier:

Tier / CE headerRetained on evictionDownstream cutoff after eviction
stamp stampOf (MemoTable.CreateByStamp*, optional stampComparer cmp)Lightweight 'Stamp (8–32 B, e.g. content hash or length)Exact: recomputes 'Stamp and suppresses downstream observer runs whenever the stamp compares equal.3
Default or comparer cmp (MemoTable.Create*)0 payload bytesResident-exact, evicted-conservative: cuts off equal outputs while resident; evicted slots conservatively wake downstream readers on upstream change.

Step through the timeline below: loading "b" and "c" into a 2-entry table evicts "a" into its dashed stamp-retained state (⌗7 for "a:alpha"). Writing "bravo" (same length 7) verifies "a"'s stamp and cuts off the downstream effect without re-running it:

Example code
let suffix = signal { return "alpha" }
let cache =
    memoTable {
        maxEntries 2
        stamp (fun (s: string) -> s.Length)
        let! k = memoTable.key
        let! s = suffix
        return $"{k}:{s}"
    }
let mutable effectRuns = 0
effect {
    let! v = MemoTable.at "a" cache
    effectRuns <- effectRuns + 1
    printfn "%s" v
}

controls [
    button "Load b & c (evict a)" (fun () ->
        cache.Get "b" |> ignore
        cache.Get "c" |> ignore)
    |> expect "a's payload is evicted while b and c stay resident" (fun () ->
        cache.PeekResident "a" = ValueNone && cache.ResidentCount = 2 && effectRuns = 1)
    button "Same-length write (bravo)" (fun () ->
        suffix.Value <- "bravo")
    |> expect "Equal stamp (7) suppresses downstream effect re-run across eviction" (fun () ->
        effectRuns = 1)
]
Hover a node for its state; click it for why it last ran.

Entry budgets, weighted budgets and oversized values

Bound resident memory by entry count (maxEntries n, weight 1L each) or byte/cost weight (maxWeight budget weigh), and optionally cap unobserved skeleton slots with maxDormant n:

let frameCache (scale: Signal<float>) (render: int -> float -> byte array) =
    memoTable {
        maxWeight (16L * 1024L * 1024L) (fun (bytes: byte array) -> int64 bytes.LongLength)
        maxDormant 256
        let! frameId = memoTable.key
        and! zoom = scale
        return render frameId zoom
    }
  • Clean refill: reading an evicted clean slot reconstructs 'V without perturbing observer announcements or reactive run counts.4

  • Stack pinning: active keys stay pinned across nested Get / TryRead calls so inner lookups cannot evict an active caller's slot.5

  • Oversized values: when weigh v > MaxWeight or maxEntries 0 applies, the table returns the value directly and keeps warm entries resident. A stamped slot retains its 'Stamp. Negative weights clamp to 0L.6

  • Dormant slots: unobserved slots (ObserverCount = 0) beyond maxDormantdetach their upstream edges passively.7

  • Explicit eviction: call table.Evict key or table.Trim ().

  • Passive disposal: call table.Dispose () or dispose the enclosing owner.8

MemoTable bodies run in ScopeMode.Pure,9 while calling table.Get from inside another pure memo is always safe because lazy slots attach to the table's internal scope.10

Cycle detection and recovery

Keys that depend on other keys dynamically (such as spreadsheet formulas or module imports) raise CycleDetectedException on re-entry by default, or recover cleanly via onCycleuntracked without poisoning outer keys.11

Bind recursive lookups in Phase 1 with for + let! v = MemoTable.at dep tableso every dynamic cell edge is tracked (avoiding RAN016 untracked Phase-2 reads):

let evalCell (formulas: Map<string, Signal<string list>>) =
    let rec table: MemoTable<string, int> =
        memoTable {
            maxEntries 128
            onCycle (fun _ -> 0)
            let! cellId = memoTable.key
            match Map.tryFind cellId formulas with
            | None -> return 0
            | Some depsSig ->
                let! deps = depsSig
                let mutable sum = 0
                for dep in deps do
                    let! v = MemoTable.at dep table
                    sum <- sum + v
                return sum
        }
    table

Complexity

OperationTimeSpace / Allocation
Get / TryGet / TryRead (clean resident hit)O(1)O(1)0 B (intrusive LRU touch + edge track)
Miss, stale refresh, or clean refillO(compute+deps+evicted)O(\text{compute} + \text{deps} + \text{evicted}) (O(deps)O(\text{deps}) amortized)Bounded by MaxWeight + MaxDormantNodes
Evicted stamp check on upstream writeO(compute+deps)O(\text{compute} + \text{deps})0 downstream observer runs when 'Stamp is equal
Evict key / Trim () / passive Dispose ()O(1)O(1) evict; O(slots)O(\text{slots}) trim or passive teardownReleases all cached 'V and 'Stamp payloads

See Benchmarks → Memos for memotable-hit, memotable-evict-cutoff, and memotable-churn instruction counts.

Multi-core incremental demand graphs (Ranvier.Dag)

MemoTable<'K, 'V> runs inside a single-owner Ranvier.Graph, tracking live Signal<'T> and Memo<'T> reads with Pending/Failedpropagation on both .NET and Fable.

For a multi-core, pull-only demand pipeline (compiler frontends, static analyzers, or build graphs) that evaluates rules in parallel via Fork/Join with 128-bit content-hash firewalls, use Ranvier.Dag for the pipeline. Publish results to a UI-thread Ranvier.Graph via Graph.Dispatch (see Streams and threading).

Edit this page