# Tracing and journal

> Provenance queries over the per-graph trace log and deterministic input journaling and replay.

Ranvier pairs two complementary diagnostic mechanisms:

- **Tracing (`Trace`{fsharp})** records fine-grained graph execution in development builds to
  answer *why* a node ran, *why* it stayed quiet, what async flight it is waiting on, and where it
  was created. Untraced Release builds compile the log out completely — method-for-method
  identical IL.

- **Input journaling (`Journal`{fsharp})** records external inputs (`Signal`{fsharp} writes,
  `AsyncSource`{fsharp} outcomes, and `Mvu`{fsharp} messages) in *any* build (`0 B` / one null
  check per input when disabled) so production sessions can be replayed deterministically in a
  traced build.

## Enabling traced builds

Debug source builds enable tracing by default; Release builds compile it out unless
`-p:RanvierTrace=true` is passed.

From NuGet, define `$(RanvierSuffix)` once so `.Traced` is appended dynamically across every
`Ranvier*` package (`Ranvier`, `Ranvier.CSharp`, `Ranvier.Elmish`, `Ranvier.Query`,
`Ranvier.Wire`, `Ranvier.Dom`, `Fable.Ranvier.Dom`) without duplicating `<PackageReference>`
items:

```xml
<PropertyGroup>
    <RanvierTrace Condition="'$(RanvierTrace)' == '' and '$(Configuration)' == 'Debug'">true</RanvierTrace>
    <RanvierSuffix Condition="'$(RanvierTrace)' == 'true'">.Traced</RanvierSuffix>
    <DefineConstants Condition="'$(RanvierTrace)' == 'true'">$(DefineConstants);RANVIER_TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
    <PackageReference Include="Ranvier$(RanvierSuffix)" Version="0.2.7" />
</ItemGroup>
```

Guard `Trace.*`{fsharp} query calls with `#if RANVIER_TRACE`{fsharp} in multi-configuration
projects. Traced flushes also guard against runaway loops, raising
`InvalidOperationException`{fsharp} once a node self-requeues `1,000` times or is dequeued
`100,000` times in one flush.

### Labels and node identity

`Trace.named "name" (fun () -> ...)`{fsharp} labels the first node or owner created inside its
thunk and compiles in every build (inlining to `f ()`{fsharp} when untraced).

`Trace.label (graph, node, $"row[{i}]")`{fsharp} assigns computed labels and carries
`[<Conditional("RANVIER_TRACE")>]`{fsharp} so interpolated strings are elided in untraced callers:

```fsharp
open Ranvier
open Ranvier.CE

let lines = Trace.named "lines" (fun () -> signal { return [ 4m; 6m ] })
let discount = Trace.named "discount" (fun () -> signal { return 0m })
let subtotal = Trace.named "subtotal" (fun () -> memo { let! xs = lines in return List.sum xs })
let total = Trace.named "total" (fun () -> memo {
    let! sub = subtotal
    and! disc = discount
    return sub - disc
})
let banner = Trace.named "banner" (fun () -> effect {
    node
    let! t = total
    printfn "total %M" t
})
```

Each node has a runtime integer id (`1..N`{fsharp} per graph), a **located path** (`/Cart.fsx:11`
when any segment lacks a label), or a stable **named path** (`/subtotal`, with `#n` disambiguating
duplicate sibling labels and `@k` numbering incarnations recreated under an owning scope).

Resolve paths or handles with `Trace.lookup graph (TraceAddress.ByPath "/subtotal")`{fsharp}
(`Live`{fsharp}, `Disposed`{fsharp}, `Checkpointed`{fsharp}, `Missing`{fsharp},
`Foreign`{fsharp}), `Trace.lookupNode`{fsharp}, or `Trace.resolve`{fsharp}.

## Why did it run

`Trace.why graph node`{fsharp} walks backwards from `node`{fsharp}'s latest run to the root cause
(use `Trace.whyAt graph node run`{fsharp} for an earlier run or
`Trace.whyDepth graph depth node`{fsharp} to cap depth):

```fsharp
lines.Value <- [ 8m ]
Trace.why graph banner |> Trace.render graph |> printfn "%s"
```

```text
why /banner run 2
  #49 RunStart /banner (Cart.fsx:13)
  #46 Mark /banner <- /total (Cart.fsx:13)
  #45 Moved /total (Cart.fsx:12) = 8
  #40 Moved /subtotal (Cart.fsx:11) = 8
  #31 Write /lines (Cart.fsx:9) = [8M]
  root: user write #31
```

Read bottom-up: `#31 Write /lines` marked `/subtotal`, whose value moved to `8`, moving `/total`
and triggering `/banner`. Chains terminate at `user write`, `created`, reader pull, `settle`,
`before the checkpoint`, or `unrecorded`.

## Why did it not run

When a write leaves downstream outputs equal, `Trace.whyNot`{fsharp} reports why an observer
stayed quiet:

```fsharp
lines.Value <- [ 3m; 5m ] // subtotal stays 8m
Trace.whyNot graph banner |> Trace.render graph |> printfn "%s"
// -> checked clean #63 over /total
```

| `Trace.whyNot`{fsharp} output | Meaning |
| --- | --- |
| `checked clean #n over ...` | Pull-check walk confirmed upstream dependencies did not move. |
| `not reached: propagation stopped at #n` | An upstream write or memo cutoff stopped propagation before marking this node. |
| `queued #n` | Scheduled, awaiting the end of an open `batched`{fsharp} block or inbox flush. |
| `unobserved since mark #n` | Lazy memo marked stale with no active reader pulling it. |
| `skipped as the running reader #n` | Node wrote to one of its own dependencies while already running. |
| `disposed #n` / `no reason recorded` | Node was disposed, or already ran since its last mark. |

## What did each run do

`Trace.history graph node`{fsharp} summarizes every retained run in chronological order — its
`RunStart`{fsharp} event, completion status (`ok`, `pending`, `error`, `abandoned`), whether the
output `moved`, flush number, value preview, and root cause:

```text
history /total
  run 1 #15 pending moved flush 1 root: created #8
  run 2 #71 ok moved flush 2 = 11 root: user write #38
```

## What is it waiting on

`Trace.waitingOn graph node`{fsharp} names the pending upstream source a suspended reader stopped
at, and for an `AsyncMemo`{fsharp} lists its flights newest-first (`in flight`, `settled`,
`failed`, `cancelled`, or `dropped` as `superseded` / `disposed` / `suspended` / `trailing` /
`retried`):

```text
waiting /total
  suspended on /shipping

waiting /shipping
  flight 2 #57 run 2 settled #64
  flight 1 #26 run 1 dropped #63 superseded
```

For `debounce`{fsharp} / `throttle*`{fsharp} gates, inspect live window state alongside
`whyNot`{fsharp} via `Trace.timing graph node`{fsharp} (`CapturedStatus`{fsharp},
`PublishedStatus`{fsharp}, `WindowOpen`{fsharp}, `RemainingMilliseconds`{fsharp},
`WinningCapture`{fsharp}).

## Where did it come from

`Trace.origin graph node`{fsharp} returns a `TraceOrigin`{fsharp} naming the node's kind,
innermost user stack frame (`file:line`, skipping `Ranvier*` and BCL frames), enclosing
`Owners`{fsharp} chain, and creating `Run`{fsharp} (`0`{fsharp} for startup nodes vs `> 0`{fsharp}
for dynamically recreated child nodes):

```text
/total Memo at Cart.fsx:12 #8
```

## What the graph looks like

`Trace.snapshot graph`{fsharp} (and historical `Trace.snapshotAt graph seq`{fsharp}) folds the
owner hierarchy with each node's status, run count, and active source edges:

```text
/
  /lines Signal fresh runs 0
  /discount Signal fresh runs 0
  /subtotal Memo ok runs 3 <- /lines
  /total Memo ok runs 2 <- /subtotal, /discount
  /banner Effect ok runs 2 <- /total
```

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

```fsharp
let lines = signal { return [ 4; 6 ] }
let discount = signal { return 0 }
let subtotal = memo { let! xs = lines in return List.sum xs }
let total = memo {
    let! sub = subtotal
    and! disc = discount
    return sub - disc
}
effect {
    let! t = total
    printfn $"total {t}"
}

controls [
    button "Add a line" (fun () -> lines.Value <- lines.Value @ [ 5 ])
    button "Discount 2" (fun () -> discount.Value <- 2)
]
```

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

</div>


### Memo tables, signal ports, bridges, and bounded export

In addition to core node, flight, timing (`Timed*`{fsharp}), and stream (`Stream*`{fsharp}) events
([Streams and threading](streams-and-threading.md#streams)), the log records $O(1)$ events for
bounded caches and cross-graph channels:

- **`MemoTable`{fsharp} (`SlotState`{fsharp}):** records per-key slot transitions
  (`Empty`{fsharp}, `Resident`{fsharp}, `Evicted`{fsharp}, `StampEvicted`{fsharp} with retained
  `'Stamp`{fsharp} payload and oversized flag) under a `TraceNodeKind.MemoTable`{fsharp} host.

- **`SignalPort`{fsharp} posts:** `PortPosted`{fsharp} logs inline owner-thread posts (plus any
  queued off-thread posts superseded).

- **Inbox drains:** `PortDrained`{fsharp} logs the winning value and count of off-thread posts
  coalesced into one inbox drain.

- **`bridge`{fsharp} (`BridgeLink`{fsharp}, `BridgePosted`{fsharp}, `BridgeSuppressed`{fsharp}):**
  tracks target signal links (same-graph or cross-graph via target graph uid), posted values, and
  source-side equality cutoffs.

Each event appends to the per-graph log in $O(1)$ amortized time; untraced builds allocate `0 B`.

Because an uncheckpointed log retains events and object payload references in memory, bound
long-running traced sessions with incremental cursors, checkpoints, or ring-bounded
`Trace.export`{fsharp}:

```fsharp
let fresh = Trace.eventsSince graph cursor
Trace.checkpoint graph lastSeq "session-1" // folds & prunes disposed nodes via TraceModel.prune

use sink = TraceSinks.jsonl "session.jsonl"
use export =
    Trace.export graph sink {
        Capacity = 1024
        Full = TraceExportFull.Drop
        Checkpoint = TraceExportCheckpoint.Enqueued // bounds retained log to < Capacity events
        Codecs = TraceCodecs.ofList []
    }
```

For tools, tests, and agents, prefer schema 3 JSON contracts over rendered text:
`Trace.state`{fsharp}, `Trace.runs`{fsharp}, `Trace.whyWith`{fsharp}, `Trace.whyNot`{fsharp},
`Trace.waitingOn`{fsharp}, and `Trace.lookup`{fsharp} serialize deterministically via
`TraceJson.*`{fsharp} and `Trace.dumpTextWith graph codecs`{fsharp}. Parse dumps offline via
`TraceContract.parseDumpWith`{fsharp} / `TraceModel.parseDump`{fsharp}.

C# callers use `Tracing.*Document`{fsharp} in [C#](csharp.md#tracing). Custom `TraceCodec`{fsharp}
entries encode domain types losslessly (`Null`{fsharp}, `Exact`{fsharp}, `Encoded`{fsharp},
`Lossy`{fsharp}). See [trace benchmarks](../benchmarks/tracing.md),
[Native AOT notes](getting-started.md#native-aot-and-trimming), and the
[core API reference](/reference/ranvier/index.md).

## Deterministic journal and replay

Attach an `IInputJournal`{fsharp} (`MemoryJournal "cart"`{fsharp} or a custom sink) via
`GraphOptions.Default.WithJournal journal`{fsharp} to record external inputs as schema 3
`JournalEntry`{fsharp} records (`Write`{fsharp}, `Settle`{fsharp}, `Fail`{fsharp},
`Message`{fsharp}, `Flush`{fsharp}, and `Setup`{fsharp}):

```fsharp
let intCodec: JournalCodec<int> = {
    Name = "int"; Version = 1
    Encode = string
    Decode = fun s -> match System.Int32.TryParse s with true, v -> Ok v | _ -> Error $"bad int: {s}"
}

let journal = MemoryJournal "cart"
use graph = new Graph (GraphOptions.Default.WithJournal journal)

let buildCart (g: Graph) =
    g {
        let qty = signal { return 1 } |> Journal.key "qty" intCodec
        let quote = createAsyncSource<int> () |> Journal.keySource "quote" intCodec
        let total = memo { let! q = qty and! p = quote in return q * p }
        effect { let! t = total in printfn "total = %d" t }
        return qty, quote
    }

let qty, quote = buildCart graph
qty.Value <- 3
quote.Settle 10
```

- **Derived inputs:** writes/settles inside memos, effects, synchronous `Mvu`{fsharp} updates, or
  `Journal.derived`{fsharp} are *derived* and not recorded.

- **External inputs:** inputs arriving from outside computations record
  `Origin = External`{fsharp}.

- **Produced inputs:** async continuations started by `Mvu`{fsharp} commands, .NET effect
  continuations, or `Journal.work`{fsharp} + `Journal.produce`{fsharp} (required under
  [Fable](fable.md) where `AsyncLocal`{fsharp} is absent; name startup tasks with
  `Journal.name`{fsharp}) record `Origin = Produced (started, index, call)`{fsharp}.

- **Replay keys:** register replayable inputs with `Journal.key`{fsharp} (signals),
  `Journal.keySource`{fsharp} (`AsyncSource`{fsharp} — `AsyncMemo`{fsharp} flights are derived
  from their inputs), `Mvu.journal`{fsharp}, or `Journal.messages`{fsharp} +
  `Journal.recordMessage`{fsharp}. Unkeyed external writes record `NonReplayable`{fsharp} and halt
  replay if reached.

- **Codecs:** share codecs across .NET and Fable with `Ranvier.Wire`
  ([Wire transport](integrations.md#wire-transport)).

Replay recorded entries into a freshly constructed matching target graph on its owning thread:

```fsharp
use fresh = new Graph (GraphOptions.Default.WithJournal (MemoryJournal "replay"))
buildCart fresh |> ignore
Journal.replay ReplayMode.Diagnostic fresh journal.Entries
```

- **`ReplayMode.Diagnostic`{fsharp}:** applies every recorded `External`{fsharp} and
  `Produced`{fsharp} entry in exact `Flush`{fsharp} batch order. It replays failures as
  `JournalReplayedFailure`{fsharp} and drops duplicate live outputs of matched `Produced`{fsharp}
  calls. Check `Journal.replaying graph <> Some ReplayMode.Diagnostic`{fsharp} to skip external
  I/O altogether.

  Replaying into a traced build reproduces the exact `Trace.snapshot`{fsharp} and effect
  `Trace.why`{fsharp} chains (see the
  [shop replay recipe](https://ranvier-org.github.io/Ranvier.Persistence/guide/shop-replay/)).

- **`ReplayMode.Reenact`{fsharp}:** applies `External`{fsharp} entries and skips
  `Produced`{fsharp} entries so the application's own async commands/effects re-execute against
  new code or services while preserving exact external input timing.

- **Target matching:** before applying entries, `Journal.replay`{fsharp} verifies that the
  target's startup async works (`Journal.setupWorksOf graph`{fsharp}) match any recorded
  `Setup`{fsharp} entry, raising `JournalReplayException`{fsharp} on setup mismatches, missing
  keys, or codec version/decode errors.

- **Snapshots:** combine `Journal.replay`{fsharp} with stored state snapshots via
  [Ranvier.Persistence journal restore](https://ranvier-org.github.io/Ranvier.Persistence/guide/journal-restore/).
