Ranvier.Dag
0.2.0
dotnet add package Ranvier.Dag --version 0.2.0
NuGet\Install-Package Ranvier.Dag -Version 0.2.0
<PackageReference Include="Ranvier.Dag" Version="0.2.0" />
<PackageVersion Include="Ranvier.Dag" Version="0.2.0" />
<PackageReference Include="Ranvier.Dag" />
paket add Ranvier.Dag --version 0.2.0
#r "nuget: Ranvier.Dag, 0.2.0"
#:package Ranvier.Dag@0.2.0
#addin nuget:?package=Ranvier.Dag&version=0.2.0
#tool nuget:?package=Ranvier.Dag&version=0.2.0
Ranvier.Dag
Bounded incremental Merkle computation graphs for .NET and NativeAOT, backed by Ranvier's MemoTable.
Ranvier.Dag models an incremental build, analyzer, or compiler pipeline as pure, parameterized rules (Rule<'A, 'B>) evaluated against immutable input snapshots (Snapshot). Every rule argument, snapshot input, and early-cutoff firewall result is hashed through an explicit, reflection-free IHasher<'T> into a 128-bit xxHash128 Hash digest. Dependency edges record only 16-byte digests, allowing bulky intermediate syntax trees and semantic tables to be evicted or garbage-collected without invalidating downstream cache entries.
Quickstart
open Ranvier.Dag
// 1. Bind external inputs to their content hashers at definition time.
let sourceText = Input.define "Program.fs" Hasher.string
let optimizeFlag = Input.defineWithDurability InputDurability.High "optimize" Hasher.bool
// 2. Define incremental rules with explicit argument (and firewall result) hashers.
// - WhileReferenced retains lexed tokens only while a budgeted root traces to them.
// - Rule.firewall cuts off downstream recomputation when the public surface digest matches.
let lexTokens =
Rule.derived "lex-tokens" Retention.WhileReferenced Hasher.unit (fun () ->
dag {
let! text = inputValue sourceText.Key
return text.Split(' ', System.StringSplitOptions.RemoveEmptyEntries)
})
let publicSurface =
Rule.firewall
"public-surface"
(Retention.Count 64)
Hasher.unit
(Hasher.array Hasher.string)
(fun () ->
dag {
let! tokens = demandValue lexTokens ()
return tokens |> Array.filter (fun t -> not (t.StartsWith("_")))
})
let emitBanner =
Rule.derived "emit-banner" (Retention.Count 16) Hasher.unit (fun () ->
dag {
let! surface = demandValue publicSurface ()
and! opt = inputValue optimizeFlag.Key
let mode = if opt then "release" else "debug"
return sprintf "[%s] exports=%s" mode (String.concat "," surface)
})
// 3. Capture immutable snapshots and demand or validate outputs across sessions.
use engine = new Engine({ EngineOptions.Default with Workers = 4 })
let s1 =
Snapshot.Empty
.Set(sourceText, "alpha _internal1 beta")
.Set(optimizeFlag, true)
let out1 = engine.NewSession(s1).DemandValueSync(emitBanner, ())
// "[release] exports=alpha,beta"
// Private-body edit: lexTokens and publicSurface rerun, publicSurface produces the
// same surface digest, and emitBanner skips recomputation via early cutoff.
let s2 = s1.Set(sourceText, "alpha _internal2 beta")
let out2 = engine.NewSession(s2).DemandValueSync(emitBanner, ())
// Non-computing validation checks whether a cached result is still valid for s2
// without starting any rule bodies (returns Some NodeRef<'B> or None).
let cached = engine.NewSession(s2).ValidateSync(emitBanner, ())
Core Concepts
1. Explicit 128-Bit Hashing (Hash, IHasher<'T>, Hasher, StructuralPrimitives)
Ranvier.Dag compiles with --reflectionfree and <IsAotCompatible>true</IsAotCompatible>. Rather than walking object graphs via runtime reflection, callers supply immutable IHasher<'T> instances wherever a value's identity participates in caching:
Hash: 128-bit value struct (Hi: uint64,Lo: uint64) backed bySystem.IO.Hashing.XxHash128with per-process random seeding (Hash.deriveBytes,Hash.deriveUtf8,Hash.deriveUInt64,Hash.deriveSpan,Hash.combine).IHasher/IHasher<'T>:IHasheris an empty marker interface for heterogeneous storage;IHasher<'T>exposesHash: 'T -> Hash.- Scalar & enum combinators:
Hasher.unit,Hasher.bool,Hasher.byte,Hasher.sbyte,Hasher.int16,Hasher.uint16,Hasher.int,Hasher.uint32,Hasher.int64,Hasher.uint64,Hasher.nativeint,Hasher.unativeintHasher.char,Hasher.rune,Hasher.string,Hasher.bytes,Hasher.guid,Hasher.dateTimeOffset,Hasher.timeSpanHasher.float32andHasher.float: preserve exact IEEE-754 bit patterns (NaNpayloads,-0.0vs+0.0)Hasher.decimal: preserves trailing scale (1.0mvs1.00m)Hasher.intWithMeasure<[<Measure>] 'u>,Hasher.int64WithMeasure<[<Measure>] 'u>,Hasher.floatWithMeasure<[<Measure>] 'u>,Hasher.float32WithMeasure<[<Measure>] 'u>,Hasher.decimalWithMeasure<[<Measure>] 'u>Hasher.enumInt32<'E>,Hasher.enumByte<'E>,Hasher.enumInt64<'E>,Hasher.hash
- Wrapper & sum combinators:
Hasher.option inner: matchesNonebefore invokinginner, soNone,Some null, andSome ""all produce distinct digests despite F#'snullrepresentation ofNoneHasher.voption,Hasher.nullable,Hasher.result,Hasher.choice2,Hasher.choice3Hasher.contramap projection innerandHasher.rec' factory(ties recursive type knots once at construction time)
- Tuple & collection combinators:
- Reference tuples
Hasher.tuple2..Hasher.tuple6and struct tuplesHasher.structTuple2..Hasher.structTuple4 - Ordered sequences
Hasher.array,Hasher.immutableArray(IsDefaultguarded distinctly from empty),Hasher.list,Hasher.seq - Canonical sets and maps
Hasher.setandHasher.map(order-independent over sorted F#Set/Maptraversal)
- Reference tuples
- Graph reference combinators:
Hasher.input<'T>andHasher.snapshotInput<'T>: hash the input key's identityHasher.nodeRef<'T>: hashes the demanded node key combined with its observed result digest (DepIdentity.edgeHash), so references to distinct nodes whose results happen to share a digest still hash apart
- Zero-allocation codegen primitives (
StructuralPrimitives):StructuralPrimitives.recordSpan typeTag (ReadOnlySpan<Hash>)StructuralPrimitives.unionCase0,unionCase1,unionCase2,unionCase3,unionCaseSpanStructuralPrimitives.hashSpan seqTag elemHasher (ReadOnlySpan<'T>)(ideal for custom slice/block containers exposing.AsSpan())
2. Inputs, Durability Tiers, and Snapshot
External state enters the graph exclusively through immutable Snapshot values:
| Type | Role |
|---|---|
Input<'T> |
Typed input key identified by (name, typeof-free runtime type token, durability) |
SnapshotInput<'T> |
Binds an Input<'T> to its content IHasher<'T> (Input.define / Input.defineWithDurability) so all write sites share one canonical hashing policy |
InputDurability |
Low for frequently edited inputs (active source files); High for stable configuration (SDK manifests, target framework flags, reference assemblies) |
Snapshot |
Persistent immutable map of (InputKey -> (Hash, value)) plus per-tier revision chains |
SnapshotBuilder |
Mutable batch builder producing a single Snapshot root via .ToSnapshot() |
- Bound writes:
snapshot.Set(boundInput, value)hashesvaluewithboundInput.Hasher. - Pre-hashed capture writes:
snapshot.Set(inputKey, precomputedHash, value)records an already-computed content digest directly (for example from a file watcher or content-addressed blob store). - Constant-time tier validation: Every cached trace records the union of
InputDurabilitytiers across its transitive input dependencies. When a newSnapshotonly editsLow-durability inputs, any subgraph depending solely onHigh-durability inputs validates in $O(1)$ without walking a single dependency edge.
3. Rules, Early Cutoff, and Computed<'T>
| Constructor | Result Digest Policy | Use Case |
|---|---|---|
Rule.derived name retention argHasher body |
Derived from (ruleTag, argHash, sortedDepEdgeDigests) |
Intermediate representations and bulky outputs that lack cheap structural comparison |
Rule.derivedWeighted name maxWeight argHasher weight body |
Same as derived, bounded by cumulative int64 weight |
Variable-size outputs (e.g. emitted assembly byte buffers or large syntax trees) |
Rule.derivedRec name retention argHasher body |
Self-referential derived rule (self -> 'A -> Computed<'B>) |
Recursive queries over module/call hierarchies |
Rule.firewall name retention argHasher resultHasher body |
Computed by resultHasher.Hash result |
Early-cutoff boundary: absorbs upstream edits whenever the projected summary digest is unchanged |
Rule.firewallWeighted name maxWeight argHasher resultHasher weight body |
Weighted firewall |
Size-bounded early-cutoff boundaries |
Rule bodies return Computed<'T>, authored with either dag { ... } or computed { ... } computation expressions:
let! x = demandValue rule arg(orlet! ref = demand rule argto inspectref.Valueandref.Hash)let! v = inputValue key(orlet! ref = input key;tryInput/tryInputValuefor optional inputs)- Applicative parallel fan-out via
let! a = ... and! b = ...orComputed.traverseParallel/Computed.traverseArrayParallel - Cooperative external
Task<'T>integration viaComputed.ofTask (fun ct -> ...)orlet! x = someTaskinsidedag { }
4. Bounded Retention on Ranvier.MemoTable
Each Rule<'A, 'B> declares its own isolated Retention policy backed by Ranvier.MemoTable:
Retention.Count maxNodes: Retains at mostmaxNodesdistinct arguments in per-rule LRU order; churn in one rule never evicts another rule's entries.Retention.Weight maxWeight: Retains entries whose cumulative weight (summed across up toMaxEntriesPerNoderemembered traces per node) fits withinmaxWeight. Nodes heavier thanmaxWeightstill return their result to the caller without being retained.Retention.WhileReferenced: Retains intermediate nodes only while at least one retained budgeted node (CountorWeight) or pinned in-flight rule body traces to them, buffered by a bounded LRU nursery (EngineOptions.MaxUnreferenced) and swept by work-paced mark-and-sweep garbage collection (engine.Collect()).- Multi-entry undo traces (
EngineOptions.MaxEntriesPerNode, default2): Each retained node remembers up to $K$ recent(deps, result)traces, making undo/redo and A/B branch toggling instant $O(1)$ or trace-hit operations with zero recomputation.
5. Multi-Core Single-Flight Execution, Cycles, Validation, and Determinism
- Cooperative heap-stack fibers: Deep dependency chains (tens of thousands of nodes) execute and validate on heap-allocated fiber frames (
StepsPerSlice), never overflowing the CLR thread stack. - Multi-core worker pool (
EngineOptions.Workers): Parallel branches (Fork) schedule acrossWorkersthreads withPriority.ForegroundpreemptingPriority.Backgroundbetween slices. - Session single-flight deduplication: Concurrent demands for the same
NodeKeywithin aSessioncoalesce onto oneInFlightClaim. Cross-fiber wait-graph deadlocks are detected deterministically and raiseCycleDetectedwith the exact cycle path. - Non-computing validation (
session.Validate/session.ValidateSync): Checks whether a resident valid value exists for(rule, arg)under the session'sSnapshotwithout executing any rule bodies. If a concurrent demand is already computing(rule, arg)on the same session,Validateshares that in-flight claim; if validation misses while a concurrentDemandis waiting, the claim seamlessly promotes to compute for the demanding caller while returningNonetoValidate. - Determinism checking (
engine.DeterminismCheck): Set toDeterminismCheck.RaiseorDeterminismCheck.Report callbackin tests or CI to re-execute validated cache hits and verify that both the resultHashand exact dependency set match the remembered trace.
Packages and Targets
| Package | Description |
|---|---|
Ranvier.Dag |
Production build (net10.0 and net8.0, FSharp.Core >= 8.0.300, Ranvier >= 0.2.5) |
Ranvier.Dag.Traced |
Identical assembly and API surface compiled against Ranvier.Traced with per-graph reactive trace events enabled |
Both net10.0 and net8.0 builds compile with fsc --reflectionfree, <IsAotCompatible>true</IsAotCompatible>, and XML documentation enforcement (FS3390).
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- FSharp.Core (>= 8.0.300)
- Ranvier (>= 0.2.7)
- System.IO.Hashing (>= 8.0.0)
-
net8.0
- FSharp.Core (>= 8.0.300)
- Ranvier (>= 0.2.7)
- System.IO.Hashing (>= 8.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Ranvier.Dag:
| Package | Downloads |
|---|---|
|
Ranvier.Build
Typed incremental build orchestration, content-addressed artifact caching, isolated subprocess execution, and reactive terminal telemetry on Ranvier, Ranvier.Dag, Ranvier.Persistence, and Ranvier.Terminal. |
GitHub repositories
This package is not used by any popular GitHub repositories.
Pre-1.0 release. The API may change before 1.0.