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 (Signalwrites,AsyncSourceoutcomes, andMvumessages) 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 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 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 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)
]
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 events for bounded caches and cross-graph channels:
MemoTable(SlotState): records per-key slot transitions (Empty,Resident,Evicted,StampEvictedwith retained'Stamppayload and oversized flag) under aTraceNodeKind.MemoTablehost.SignalPortposts:PortPostedlogs inline owner-thread posts (plus any queued off-thread posts superseded).Inbox drains:
PortDrainedlogs 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 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
Mvuupdates, orJournal.derivedare derived and not recorded.External inputs: inputs arriving from outside computations record
Origin = External.Produced inputs: async continuations started by
Mvucommands, .NET effect continuations, orJournal.work+Journal.produce(required under Fable whereAsyncLocalis absent; name startup tasks withJournal.name) recordOrigin = Produced (started, index, call).Replay keys: register replayable inputs with
Journal.key(signals),Journal.keySource(AsyncSource—AsyncMemoflights are derived from their inputs),Mvu.journal, orJournal.messages+Journal.recordMessage. Unkeyed external writes recordNonReplayableand 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 recordedExternalandProducedentry in exactFlushbatch order. It replays failures asJournalReplayedFailureand drops duplicate live outputs of matchedProducedcalls. CheckJournal.replaying graph <> Some ReplayMode.Diagnosticto skip external I/O altogether.Replaying into a traced build reproduces the exact
Trace.snapshotand effectTrace.whychains (see the shop replay recipe).ReplayMode.Reenact: appliesExternalentries and skipsProducedentries 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.replayverifies that the target's startup async works (Journal.setupWorksOf graph) match any recordedSetupentry, raisingJournalReplayExceptionon setup mismatches, missing keys, or codec version/decode errors.Snapshots: combine
Journal.replaywith stored state snapshots via Ranvier.Persistence journal restore.