# Memo tables

> Bounded per-key reactive memoization with O(1) weighted LRU eviction, stamp cutoff, and passive disposal.

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

`MemoTable<'K, 'V>`{fsharp} memoizes a pure derivation `'K -> 'V`{fsharp} under an $O(1)$
intrusive LRU budget while keeping reactive dependency edges and downstream observer wiring live
across payload eviction[^memotable-inv]:

```fsharp
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`{fsharp} input. See
[The graph — Graph inference](graph.md#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`{fsharp} / `Failed`{fsharp}:

| Method / pipe | CE descriptor | Missing key | Unready key |
| --- | --- | --- | --- |
| `table.Get key`{fsharp} / `MemoTable.get key table`{fsharp} (`'V`{fsharp}) | `MemoTable.at key table`{fsharp} | Creates & evaluates slot | Raises on `Pending`{fsharp} / `Failed`{fsharp} |
| `table.TryGet key`{fsharp} / `MemoTable.tryGet key table`{fsharp} (`'V voption`{fsharp}) | `MemoTable.tryAt key table`{fsharp} | `ValueNone`{fsharp} untracked (`0` slots created) | Raises on `Pending`{fsharp} / `Failed`{fsharp} when live |
| `table.TryRead key`{fsharp} / `MemoTable.tryRead key table`{fsharp} (`Reading<'V>`{fsharp}) | `tryRead (MemoTable.at key table)`{fsharp} | Creates & evaluates slot | Returns `Pending`{fsharp} or `Failed ex`{fsharp} |

## Two cutoff tiers: stamps vs value comparers

When an entry's payload is evicted to stay within `MaxWeight`{fsharp}, 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 header | Retained on eviction | Downstream cutoff after eviction |
| --- | --- | --- |
| `stamp stampOf`{fsharp} (`MemoTable.CreateByStamp*`{fsharp}, optional `stampComparer cmp`{fsharp}) | Lightweight `'Stamp`{fsharp} (`8`–`32 B`, e.g. content hash or length) | **Exact**: recomputes `'Stamp`{fsharp} and suppresses downstream observer runs whenever the stamp compares equal.[^evicted-cutoff] |
| Default or `comparer cmp`{fsharp} (`MemoTable.Create*`{fsharp}) | `0` payload bytes | **Resident-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"`{fsharp} and `"c"`{fsharp} into a `2`-entry table
evicts `"a"`{fsharp} into its dashed stamp-retained state (`⌗7` for `"a:alpha"`{fsharp}). Writing
`"bravo"`{fsharp} (same length `7`{fsharp}) verifies `"a"`{fsharp}'s stamp and cuts off the
downstream effect without re-running it:

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

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

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

</div>


## Entry budgets, weighted budgets and oversized values

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

```fsharp
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`{fsharp} without perturbing
  observer announcements or reactive run counts.[^refill-clean]

- **Stack pinning:** active keys stay pinned across nested `Get`{fsharp} / `TryRead`{fsharp} calls
  so inner lookups cannot evict an active caller's slot.[^get-pin]

- **Oversized values:** when `weigh v > MaxWeight`{fsharp} or `maxEntries 0`{fsharp} applies, the
  table returns the value directly and keeps warm entries resident. A stamped slot retains its
  `'Stamp`{fsharp}. Negative weights clamp to `0L`{fsharp}.[^weigh-clamp]

- **Dormant slots:** unobserved slots (`ObserverCount = 0`{fsharp}) beyond `maxDormant`{fsharp}
  detach their upstream edges passively.[^retire-dormant]

- **Explicit eviction:** call `table.Evict key`{fsharp} or `table.Trim ()`{fsharp}.

- **Passive disposal:** call `table.Dispose ()`{fsharp} or dispose the enclosing
  [owner](lifetimes.md).[^passive-dispose]

`MemoTable`{fsharp} bodies run in `ScopeMode.Pure`{fsharp},[^body-pure] while calling
`table.Get`{fsharp} from inside another pure `memo`{fsharp} is always safe because lazy slots
attach to the table's internal scope.[^pure-caller]

## Cycle detection and recovery

Keys that depend on other keys dynamically (such as spreadsheet formulas or module imports) raise
`CycleDetectedException`{fsharp} on re-entry by default, or recover cleanly via `onCycle`{fsharp}
untracked without poisoning outer keys.[^cycle-recover]

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

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

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

See [Benchmarks → Memos](../benchmarks/memos.md) for `memotable-hit`, `memotable-evict-cutoff`,
and `memotable-churn` instruction counts.

## Multi-core incremental demand graphs (Ranvier.Dag)

`MemoTable<'K, 'V>`{fsharp} runs inside a single-owner `Ranvier.Graph`{fsharp}, tracking live
`Signal<'T>`{fsharp} and `Memo<'T>`{fsharp} reads with `Pending`{fsharp}/`Failed`{fsharp}
propagation 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`{fsharp}/`Join`{fsharp} with 128-bit
content-hash firewalls, use [`Ranvier.Dag`](https://github.com/ranvier-org/Ranvier.Dag) for the
pipeline. Publish results to a UI-thread `Ranvier.Graph`{fsharp} via `Graph.Dispatch`{fsharp} (see
[Streams and threading](streams-and-threading.md#multi-graph-and-parallel-topologies)).

[^disposed-memo]: [`disposed_memo_answers`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#disposed_memo_answers).
[^memotable-inv]: [`memotable_inv_preserved`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#memotable_inv_preserved).
[^evicted-cutoff]: [`recompute_evicted_cutoff_sound`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#recompute_evicted_cutoff_sound), [`resolve_check_evicted_cutoff_no_refill`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#resolve_check_evicted_cutoff_no_refill).
[^refill-clean]: [`refill_clean_preserves_graph_and_unannounced`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#refill_clean_preserves_graph_and_unannounced).
[^get-pin]: [`get_pin_survives_nested_eviction`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTableWitnesses.html#get_pin_survives_nested_eviction).
[^weigh-clamp]: [`weigh_throw_and_clamp_contained`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTableWitnesses.html#weigh_throw_and_clamp_contained).
[^retire-dormant]: [`memotable_retire_key_preserves_coherent`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#memotable_retire_key_preserves_coherent).
[^passive-dispose]: [`memotable_dispose_passive_teardown`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#memotable_dispose_passive_teardown).
[^body-pure]: [`memotable_body_pure_enforced`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#memotable_body_pure_enforced).
[^pure-caller]: [`memotable_create_slot_pure_caller_ok`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTable.html#memotable_create_slot_pure_caller_ok).
[^cycle-recover]: [`cycle_throw_and_recover_eviction_invariant`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.MemoTableWitnesses.html#cycle_throw_and_recover_eviction_invariant).
