# Async sources, flights and boundaries

> Push external outcomes, run cancellable async flights with settled-value cutoff, and recover pending or failed reads at boundaries.

Asynchronous values travel through Ranvier as three-state `Reading<'T>`{fsharp} outcomes
(`Ready value`{fsharp}, `Pending`{fsharp}, or `Failed exn`{fsharp}) rather than manual loading
booleans.

A `Pending`{fsharp} or `Failed`{fsharp} read propagates automatically through dependent memos and
effects (preserving `ErrorOrigin`{fsharp}) until a [`boundary`](#error-and-suspense-boundaries)
converts it into a concrete display value.

To choose a primitive, see the
[primitive decision matrix](editable-and-forms.md#choosing-a-single-value-or-async-primitive).

| Read / inspection | Behavior on `Ready v`{fsharp} | Behavior on `Pending`{fsharp} | Behavior on `Failed ex`{fsharp} |
| --- | --- | --- | --- |
| `node.Value`{fsharp} / `let! x = node`{fsharp} | Tracked; returns `v`{fsharp} | Links edge and suspends (`NotReadyException`{fsharp}) | Links edge and rethrows `ex`{fsharp} |
| `node.TryValue`{fsharp} / `let! r = tryRead node`{fsharp} | Tracked; `Ready v`{fsharp} | Links edge; returns `Pending`{fsharp} without suspending | Links edge; returns `Failed ex`{fsharp} without throwing |
| `node.Peek`{fsharp} | Untracked; returns `v`{fsharp} | Untracked; last settled value (or default) without starting a flight | Untracked; last settled value (or default) |
| `node.Status`{fsharp} (`[<Flags>]`{fsharp}) | `Status.None`{fsharp} (or `Status.Stale`{fsharp}) | Includes `Status.Pending`{fsharp} (`Uninitialized`{fsharp} before first settle) | Includes `Status.Error`{fsharp} (test flags with `HasFlag`{fsharp}) |

## Async sources

`createAsyncSource<'T> ()`{fsharp} creates an externally settled source cell starting in
`Pending ||| Uninitialized`{fsharp}. Call `src.Settle value`{fsharp} or `src.Fail exn`{fsharp} to
push outcomes from callbacks, native bridges, or deterministic tests (see
[Testing async state](testing.md)):

```fsharp
open Ranvier
open Ranvier.CE

let wireSession (g: Graph) =
    g {
        let user = createAsyncSource<string> ()
        let greeting =
            memo {
                let! name = user
                return $"Hello, {name}"
            }

        let before = greeting.TryValue // Pending
        user.Settle "Ada"
        return before, greeting.TryValue // (Pending, Ready "Hello, Ada")
    }
```

- **Recovery:** both `Settle`{fsharp} and `Fail`{fsharp} can be called repeatedly. A subsequent
  `Settle`{fsharp} clears `Status.Error`{fsharp}.

- **Threading:** off-thread calls marshal through `Graph.Dispatch`{fsharp}. With
  `ManualDispatcher`{fsharp}, pump on the owning thread. See
  [Streams, threading and multi-graph dispatch](streams-and-threading.md#dispatcher-selection).

- **No source-level equality cutoff:** unlike `Signal<'T>`{fsharp}, `src.Settle v`{fsharp}
  **always** marks direct observers dirty, even when `v`{fsharp} equals the previously settled
  value.

- **Memo cutoff:** downstream `memo`{fsharp} nodes run once, cut off equal results, and let
  observers resolve checks cleanly.

- **Flight reuse:** `asyncMemo`{fsharp} Phase-1 keys and `AsyncSource.bind`{fsharp} ignore equal
  settled keys without restarting active flights.

`AsyncSource.map`{fsharp}, `map2`{fsharp}, and `zip`{fsharp} provide combinator shortcuts.

## Async memos

`asyncMemo`{fsharp} (pre-CE: `createAsync*`{fsharp}, `createAsyncOn*`{fsharp},
`AsyncMemo.bind*`{fsharp}) launches a demand-driven `Task<'T>`{fsharp} or `ValueTask<'T>`{fsharp}
**flight** on its first read and whenever its Phase-1 reactive inputs change:

```fsharp
open System
open System.Net.Http
open Ranvier
open Ranvier.CE

let fetchProfile (http: HttpClient) (userId: Signal<int>) =
    asyncMemo {
        policy FlightPolicy.CancelPrevious
        debounce (TimeSpan.FromMilliseconds 150.)
        let! id = userId
        let! ct = asyncMemo.cancellationToken
        return! http.GetStringAsync($"/api/users/{id}", ct)
    }
```

### Phase-1 reactive tracking and `RAN012`

:::warning Bind all reactive inputs before awaiting (`RAN012`)
Dependency tracking is active **only** in Phase 1, before asynchronous execution begins. Reading
`someSignal.Value`{fsharp} after an `await` inside a `task { ... }`{fsharp} continuation executes
outside the node's tracking frame, so the read creates no dependency edge. Under
[Fable](fable.md), every promise resumption runs untracked on a later microtask.

- In `asyncMemo { ... }`{fsharp}, bind every reactive input with `let!`{fsharp} / `and!`{fsharp}
  at the top; placing a reactive `let!`{fsharp} after a `Task`{fsharp} or `ValueTask`{fsharp} bind
  is a **compile-time type error**.

- In raw `createAsync (fun prev ct -> ...)`{fsharp} lambdas, capture every `.Value`{fsharp} into a
  local variable **before** entering `task { ... }`{fsharp}; the `RAN012` analyzer flags reactive
  reads after `let!`{fsharp} / `do!`{fsharp} task awaits.
:::

### Headers, tokens, and flight policies

- **`policy fp`{fsharp}:** overrides `GraphOptions.FlightPolicy`{fsharp} for this node.

- **`let! ct = asyncMemo.cancellationToken`{fsharp}:** supplies the flight's
  `CancellationToken`{fsharp}. On .NET (`net10.0`), settled non-overlapping flights call
  `CancellationTokenSource.TryReset()`{fsharp} to reuse token sources without reallocating.

- **`let! prev = asyncMemo.previous`{fsharp}:** supplies `Previous<'T>`{fsharp}, whose
  `prev.Settled : Task<'T voption>`{fsharp} resolves to the last published value. Initially the
  value is `ValueNone`{fsharp}. Under `Queue`{fsharp}, the task waits for the preceding flight's
  application in start order.

- **`owning`{fsharp}:** gives the synchronous prefix (before the first suspending await) a child
  `Owner`{fsharp} scope (see [Lifetimes](lifetimes.md)), disposed when a new key starts or the
  node is disposed.

- **Disposal while pending:** `Disposed`{fsharp} settles readers once with
  `ObjectDisposedException`{fsharp}.

| `FlightPolicy`{fsharp} | Starts immediately | Cancels old `ct`{fsharp} | Discards superseded result | Applies every flight |
| --- | --- | --- | --- | --- |
| `CancelPrevious`{fsharp} (default) | Yes | Yes | Yes | No |
| `KeepLatest`{fsharp} | Yes | No | Yes | No |
| `Queue`{fsharp} | Yes | No | No | Yes, in start order |
| `FinishCurrent`{fsharp} | Trailing run after current settles | No | Current finishes, then 1 trailing flight | No (stays `Pending`{fsharp} until trailing settles) |
| `Drop`{fsharp} | No (ignores changes in flight) | No | Current flight stands | No |
| `DropWhilePending`{fsharp} | Retries once only if flight fails after a dropped change | No | Keeps success; replaces stale failure | No |

An equal settled Phase-1 key precedes **every** flight policy: it neither cancels under
`CancelPrevious`{fsharp} nor enqueues under `Queue`{fsharp}.

## Settled-value cutoff

By default, `AsyncMemo<'T>`{fsharp} compares settled outputs with `GraphOptions.Equality`{fsharp};
supply `comparer cmp`{fsharp} in `asyncMemo`{fsharp} (or `createAsyncWithComparer`{fsharp},
`createOwningAsyncWithComparer`{fsharp}, `createAsyncOnWithComparer`{fsharp},
`createOwningAsyncOnWithComparer`{fsharp}) to override it per node:

```fsharp
let normalizedTag (rawQuery: Signal<string>) (lookup: string -> System.Threading.Tasks.Task<string>) =
    asyncMemo {
        policy FlightPolicy.KeepLatest
        comparer System.StringComparer.OrdinalIgnoreCase
        let! q = rawQuery
        return! lookup q
    }
```

On a direct `Ready prev -> Ready next`{fsharp} refresh, observers see no intervening
`Pending`{fsharp} or `Failed`{fsharp} publication. `AsyncMemo<'T>`{fsharp} compares `prev`{fsharp}
and `next`{fsharp} and **suppresses downstream observer wakes** when the values compare equal.

A direct refresh can happen on .NET when the task completes synchronously during launch, for
example with `Task.FromResult`{fsharp} on a warm cache hit. It can also happen when an unannounced
refresh settles from a `Ready`{fsharp} state.

If observers already observed `Pending`{fsharp} or `Failed`{fsharp} before `Ready next`{fsharp}
arrived, the state transition `Pending -> Ready`{fsharp} or `Failed -> Ready`{fsharp} always
propagates, because readiness itself changed even when `next`{fsharp} matches an earlier value.

A comparer that throws fails the `AsyncMemo<'T>`{fsharp} with that exception.

## Error and suspense boundaries

`boundary`{fsharp} catches `Pending`{fsharp} reads (`pending`{fsharp}), thrown exceptions
(`failed`{fsharp}), or both, returning a `Boundary<'T>`{fsharp} (pre-CE:
`createSuspense*`{fsharp}, `createErrorBoundary*`{fsharp}, `createBoundary*`{fsharp}):

| Header configuration | Pre-CE factory | `Pending`{fsharp} body | `Failed`{fsharp} body |
| --- | --- | --- | --- |
| `pending fallback`{fsharp} | `createSuspense`{fsharp} | Publishes `fallback last`{fsharp} (`IsWaiting = true`{fsharp}) | Propagates `Failed`{fsharp} |
| `failed recover`{fsharp} | `createErrorBoundary`{fsharp} | Propagates `Pending`{fsharp} | Publishes `recover ex last`{fsharp} (`Caught = ex`{fsharp}) |
| `pending`{fsharp} + `failed`{fsharp} | `createBoundary`{fsharp} | Publishes `fallback last`{fsharp} (`IsWaiting = true`{fsharp}) | Publishes `recover ex last`{fsharp} (`Caught = ex`{fsharp}) |

### Retain the last settled value

Both `fallback : 'T voption -> 'T`{fsharp} and `recover : exn -> 'T voption -> 'T`{fsharp} receive
`last`{fsharp} (`ValueNone`{fsharp} before the first settled value, `ValueSome prev`{fsharp}
thereafter).

Passing `ValueOption.defaultValue "Loading…"`{fsharp} shows `"Loading…"`{fsharp} initially and
**retains the previous settled output** during later refreshes while `view.IsWaiting`{fsharp}
reports `true`{fsharp}.

- **Tracked metadata:** `view.IsWaiting`{fsharp}, `view.Caught`{fsharp} (`exn`{fsharp} or
  `null`{fsharp}), and `view.CaughtFrom`{fsharp} (`INode`{fsharp} or `null`{fsharp}) are tracked
  reads.

- **Output cutoff:** add `comparer cmp`{fsharp} to customize output cutoff on settled, fallback,
  and recovered values.

:::warning Create async nodes outside the boundary
`boundary`{fsharp} owns the nodes created inside its Phase-2 body and disposes/replaces them on
every re-run. Creating and reading an `asyncMemo`{fsharp} *inside* `boundary`{fsharp} restarts its
flight on every settle and loops on the fallback forever.

Construct `asyncMemo`{fsharp} in the enclosing scope and bind it in `boundary`{fsharp} (see
[Troubleshooting](troubleshooting.md)).
:::

### Watch retention and recovery on the signal map

`view`{fsharp} starts at `"Loading…"`{fsharp} while the initial quote is in flight. **Settle 12**
publishes `"Quote: 12"`{fsharp}; **Refresh (qty <- 2)** keeps `"Quote: 12"`{fsharp} on screen
(`IsWaiting = true`{fsharp}) while the new flight is pending; **Fail quote** switches to
`"Offline: timeout"`{fsharp}:

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

```fsharp
let desk = Desk<int>()
let qty = signal { return 1 }
let quote =
    asyncMemo {
        let! n = qty
        return! desk.Quote n
    }
let view =
    boundary {
        pending (ValueOption.defaultValue "Loading…")
        failed (fun ex _ -> "Offline: " + ex.Message)
        let! q = quote
        return $"Quote: {q}"
    }
effect {
    let! text = view
    printfn "%s" text
}

controls [
    button "Settle 12" (fun () -> desk.Settle 12)
    |> describe "The first quote settles: view displays Quote: 12."
    |> expect "settled at Quote: 12" (fun () -> view.Peek = "Quote: 12" && not view.IsWaiting)
    button "Refresh (qty <- 2)" (fun () -> qty.Value <- 2)
    |> describe "A new flight starts: pending retains Quote: 12 while IsWaiting is true."
    |> expect "retains Quote: 12 while waiting" (fun () -> view.Peek = "Quote: 12" && view.IsWaiting)
    button "Fail quote" (fun () -> desk.Fail "timeout")
    |> describe "The flight faults: failed recovers with Offline: timeout."
    |> expect "recovers from failure" (fun () -> view.Peek = "Offline: timeout" && not view.IsWaiting)
]
```

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

</div>


For suspension and flight policy benchmarks, see
[Benchmarks → Suspension](../benchmarks/suspension.md).
