Skip to content

Tracing and journal

Ranvier pairs two complementary diagnostic mechanisms:

  • Tracing (Trace) 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) records external inputs (Signal writes, AsyncSource outcomes, and Mvu 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:

<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.* query calls with #if RANVIER_TRACE in multi-configuration projects. Traced flushes also guard against runaway loops, raising InvalidOperationException 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 () -> ...) labels the first node or owner created inside its thunk and compiles in every build (inlining to f () when untraced).

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

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 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")(Live, Disposed, Checkpointed, Missing, Foreign), Trace.lookupNode, or Trace.resolve.

Why did it run

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

lines.Value <- [ 8m ]
Trace.why graph banner |> Trace.render graph |> printfn "%s"
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 reports why an observer stayed quiet:

lines.Value <- [ 3m; 5m ] // subtotal stays 8m
Trace.whyNot graph banner |> Trace.render graph |> printfn "%s"
// -> checked clean #63 over /total
Trace.whyNot outputMeaning
checked clean #n over ...Pull-check walk confirmed upstream dependencies did not move.
not reached: propagation stopped at #nAn upstream write or memo cutoff stopped propagation before marking this node.
queued #nScheduled, awaiting the end of an open batched block or inbox flush.
unobserved since mark #nLazy memo marked stale with no active reader pulling it.
skipped as the running reader #nNode wrote to one of its own dependencies while already running.
disposed #n / no reason recordedNode was disposed, or already ran since its last mark.

What did each run do

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

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 names the pending upstream source a suspended reader stopped at, and for an AsyncMemo lists its flights newest-first (in flight, settled, failed, cancelled, or dropped as superseded / disposed / suspended / trailing / retried):

waiting /total
  suspended on /shipping

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

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

Where did it come from

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

/total Memo at Cart.fsx:12 #8

What the graph looks like

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

/
  /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
Example code
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)
]
Hover a node for its state; click it for why it last ran.

Memo tables, signal ports, bridges, and bounded export

In addition to core node, flight, timing (Timed*), and stream (Stream*) events (Streams and threading), the log records O(1)O(1) events for bounded caches and cross-graph channels:

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

  • SignalPort posts: PortPosted logs inline owner-thread posts (plus any queued off-thread posts superseded).

  • Inbox drains: PortDrained logs the winning value and count of off-thread posts coalesced into one inbox drain.

  • bridge (BridgeLink, BridgePosted, BridgeSuppressed): 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)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:

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, Trace.runs, Trace.whyWith, Trace.whyNot, Trace.waitingOn, and Trace.lookup serialize deterministically via TraceJson.* and Trace.dumpTextWith graph codecs. Parse dumps offline via TraceContract.parseDumpWith / TraceModel.parseDump.

C# callers use Tracing.*Document in C#. Custom TraceCodecentries encode domain types losslessly (Null, Exact, Encoded, Lossy). See trace benchmarks, Native AOT notes, and the core API reference.

Deterministic journal and replay

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

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 updates, or Journal.derived are derived and not recorded.

  • External inputs: inputs arriving from outside computations record Origin = External.

  • Produced inputs: async continuations started by Mvu commands, .NET effect continuations, or Journal.work + Journal.produce (required under Fable where AsyncLocal is absent; name startup tasks with Journal.name) record Origin = Produced (started, index, call).

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

  • Codecs: share codecs across .NET and Fable with Ranvier.Wire (Wire transport).

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

use fresh = new Graph (GraphOptions.Default.WithJournal (MemoryJournal "replay"))
buildCart fresh |> ignore
Journal.replay ReplayMode.Diagnostic fresh journal.Entries
  • ReplayMode.Diagnostic: applies every recorded External and Produced entry in exact Flush batch order. It replays failures as JournalReplayedFailure and drops duplicate live outputs of matched Producedcalls. Check Journal.replaying graph <> Some ReplayMode.Diagnostic to skip external I/O altogether.

    Replaying into a traced build reproduces the exact Trace.snapshot and effect Trace.why chains (see the shop replay recipe).

  • ReplayMode.Reenact: applies External entries and skips Produced 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 verifies that the target's startup async works (Journal.setupWorksOf graph) match any recorded Setup entry, raising JournalReplayException on setup mismatches, missing keys, or codec version/decode errors.

  • Snapshots: combine Journal.replay with stored state snapshots via Ranvier.Persistence journal restore.

Edit this page