# Lifetimes

> Hierarchical Owner scopes, child roots, LIFO cleanups, and deterministic disposal.

Every derived or side-effecting node (`Memo`{fsharp}, `MemoTable`{fsharp}, `Effect`{fsharp},
`Boundary`{fsharp}, `AsyncMemo`{fsharp}, `StreamMemo`{fsharp}, `Timed`{fsharp},
`Projection`{fsharp}, `Lookup`{fsharp}) attaches at construction to `Graph.CurrentOwner`{fsharp}.
Disposing a `Graph`{fsharp} tears down `graph.Root`{fsharp} and every child scope under it in
$O(\text{nodes})$ time.

Root input cells — `Signal<'T>`{fsharp}, `ReadOnlySignal<'T>`{fsharp}, `SignalPort<'T>`{fsharp},
and `AsyncSource<'T>`{fsharp} — hold no `Owner`{fsharp} and are collected by the GC once
unreferenced.

## Activating a graph

Scope helpers (`root`{fsharp}, `scope { ... }`{fsharp}, `cleanup`{fsharp}, `getOwner ()`{fsharp})
resolve `Graph.Current`{fsharp}, whereas source-bound derivations (`memo`{fsharp},
`effect`{fsharp}, `boundary`{fsharp}, `asyncMemo`{fsharp}, `stream`{fsharp}) infer `source.Graph`{fsharp}
directly from their Phase-1 `let!`{fsharp} / `and!`{fsharp} inputs and attach to
`source.Graph.CurrentOwner`{fsharp}.

See **[The graph](graph.md)** for full details on:

- [Configuring `GraphOptions`](graph.md#configuring-a-graph) (`Equality`{fsharp},
  `ThreadAffinity`{fsharp}, `FlightPolicy`{fsharp}, `Dispatcher`{fsharp}, `Journal`{fsharp}).
- [Activating `Graph.Current`](graph.md#activating-a-graph) with `graph { ... }`{fsharp},
  `use _ = graph.Activate ()`{fsharp}, `graph.Run`{fsharp}, and automatic hosting inside turns.
- [Graph inference rules](graph.md#graph-inference) and
  [single-graph / threading requirements](graph.md#requirements-and-invariants).

## Roots and owners

Create a disposable child `Owner`{fsharp} scope in $O(1)$ inside an active graph with
`root { ... }`{fsharp} (`createRoot`{fsharp}):

- **Unit body returns `Owner`{fsharp}:** a `unit`{fsharp} body returns the newly created
  `Owner`{fsharp} directly (`use scope = root { ... }`{fsharp}).

- **Custom return value (`root.owner`{fsharp}):** bind `let! o = root.owner`{fsharp} and end with
  `return (o, result)`{fsharp} when setup returns domain handles alongside the scope.

- **Re-entering a captured owner (`scope { ... }`{fsharp}):** any `scope: Owner`{fsharp} is itself
  a `0 B` computation expression builder (`scope { ... }`{fsharp}, wrapping
  `runWithOwner scope`{fsharp}) that attaches new nodes or cleanups to `scope`{fsharp}. Because
  `Owner`{fsharp} stores no back-reference to `Graph`{fsharp}, ensure its graph is active when
  re-entering outside a turn (`graph { scope { ... } }`{fsharp}).

- **Inspecting the current owner:** call `getOwner ()`{fsharp} inside an owning scope, or
  `tryGetOwner ()`{fsharp} (`Owner voption`{fsharp}) when helper code may also run inside a pure
  memo (where `tryGetOwner ()`{fsharp} returns `ValueNone`{fsharp} without throwing).

- **Attaching external disposables:** call `scope.Attach disposable`{fsharp} to dispose any
  `IDisposable`{fsharp} resource automatically with `scope`{fsharp}.

```fsharp
open Ranvier
open Ranvier.CE

let mountPage (graph: Graph) (route: Signal<string>) =
    graph {
        return
            root {
                let! owner = root.owner
                let title = memo { let! r = route in return $"Page: {r}" }
                effect { let! t = title in printfn "%s" t }
                return owner, title
            }
    }
```

### Disposing an owner

Disposing an `Owner`{fsharp} tears down its entire subtree in $O(\text{subtree})$ time, unlinking
every upstream observer edge[^disposed-no-edges] so subsequent signal writes never wake disposed
effects.[^disposed-effect] Disposal is idempotent:[^retire-idempotent]

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

```fsharp
let count = signal { return 0 }
let mutable runs = 0
let scope =
    root {
        effect {
            let! n = count
            runs <- runs + 1
            printfn "count = %d" n
        }
    }

controls [
    button "Write 1" (fun () -> count.Value <- 1)
    |> describe "The root's effect responds while its owner is alive."
    |> expect "Effect runs before disposal" (fun () -> runs = 2)
    button "Dispose root" (fun () -> scope.Dispose ())
    |> describe "Disposal detaches the effect from count."
    |> expect "Disposal does not re-run the effect" (fun () -> runs = 2)
    button "Write 2" (fun () -> count.Value <- 2)
    |> describe "count updates, while the disposed effect stays silent."
    |> expect "Disposed effect never runs again" (fun () -> runs = 2 && count.Peek = 2)
]
```

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

</div>


A disposed `Memo<'T>`{fsharp} detaches its upstream sources and stops recomputing, while answering
reads with its last cached value.[^disposed-memo] When cached payloads themselves must be freed on
eviction or disposal, use a [`MemoTable<'K, 'V>`](memo-tables.md).

## Cleanup

Register teardown logic on the innermost active scope with `cleanup { ... }`{fsharp}
(`onCleanup f`{fsharp}) in $O(1)$.

Inside an `effect`{fsharp}, `boundary`{fsharp}, or `memo { owning; ... }`{fsharp}, each registered
cleanup runs untracked **before the next re-run** and **on scope disposal**, executing at most
once:[^cleanup-once]

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

```fsharp
let user = signal { return "Ada" }
let mutable released = []
let scope =
    root {
        effect {
            let! name = user
            printfn "subscribe %s" name
            cleanup {
                released <- released @ [ name ]
                printfn "unsubscribe %s" name
            }
        }
    }

controls [
    button "Switch to Grace" (fun () -> user.Value <- "Grace")
    |> describe "Ada's cleanup runs before subscribing to Grace."
    |> expect "Previous subscription released" (fun () -> released = [ "Ada" ])
    button "Dispose" (fun () -> scope.Dispose ())
    |> describe "Disposal releases Grace and detaches the effect."
    |> expect "Final subscription released" (fun () -> released = [ "Ada"; "Grace" ])
]
```

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

</div>


### Ordering, purity, and error containment

- **LIFO interleaving:** cleanups and child scopes share one reverse-acquisition
  stack:[^lifo-order] a cleanup registered *after* a child node runs *before* that child is
  disposed.

- **Pure scope guard:** calling `cleanup`{fsharp} inside a pure `memo`{fsharp} raises
  `InvalidOperationException`{fsharp}.[^memo-scope-violation] Add the `owning`{fsharp} header
  (`memo { owning; ... }`{fsharp}) when a derived computation owns resources.

- **Fault isolation:** a throwing cleanup records its exception in `scope.Errors`{fsharp} (or
  `graph.Root.Errors`{fsharp} for computation scopes; inspect new entries via
  `scope.ErrorCount`{fsharp} and `scope.ErrorsFrom idx`{fsharp}) while remaining cleanups still
  run.[^cleanup-fault]

- **Writes during cleanup:** signal writes inside a cleanup are visible to the incoming re-run
  without scheduling a duplicate run.[^cleanup-writes]

See [Benchmarks → Lifetimes](../benchmarks/lifetimes.md) for creation and teardown instruction
counts.

[^disposed-no-edges]: [`disposed_no_edges_new_graph`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#disposed_no_edges_new_graph).
[^disposed-effect]: [`disposed_effect_never_runs`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#disposed_effect_never_runs).
[^retire-idempotent]: [`retire_unlinked_child_idempotent`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#retire_unlinked_child_idempotent).
[^disposed-memo]: [`disposed_memo_answers`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#disposed_memo_answers), [`disposed_memo_no_refresh`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Check.html#disposed_memo_no_refresh).
[^cleanup-once]: [`cleanup_once_new_graph`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#cleanup_once_new_graph), [`heap_ownership_guarantees`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Heap.Ownership.html#heap_ownership_guarantees).
[^lifo-order]: [`dispose_reverse_order`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#dispose_reverse_order), [`teardown_runs_in_reverse`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#teardown_runs_in_reverse), [`owners_in_order`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#owners_in_order).
[^memo-scope-violation]: [`memo_scope_violation_returns`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#memo_scope_violation_returns).
[^cleanup-fault]: [`cleanup_failure_contained`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#cleanup_failure_contained), [`teardown_continues`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#teardown_continues).
[^cleanup-writes]: [`in_cleanup_ignores_marks`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Marking.html#in_cleanup_ignores_marks), [`flush_survives_cleanup`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Scheduler.html#flush_survives_cleanup).
