Ranvier.Dag 0.2.0

dotnet add package Ranvier.Dag --version 0.2.0
                    
NuGet\Install-Package Ranvier.Dag -Version 0.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Ranvier.Dag" Version="0.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Ranvier.Dag" Version="0.2.0" />
                    
Directory.Packages.props
<PackageReference Include="Ranvier.Dag" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Ranvier.Dag --version 0.2.0
                    
#r "nuget: Ranvier.Dag, 0.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Ranvier.Dag@0.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Ranvier.Dag&version=0.2.0
                    
Install as a Cake Addin
#tool nuget:?package=Ranvier.Dag&version=0.2.0
                    
Install as a Cake Tool

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 by System.IO.Hashing.XxHash128 with per-process random seeding (Hash.deriveBytes, Hash.deriveUtf8, Hash.deriveUInt64, Hash.deriveSpan, Hash.combine).
  • IHasher / IHasher<'T>: IHasher is an empty marker interface for heterogeneous storage; IHasher<'T> exposes Hash: '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.unativeint
    • Hasher.char, Hasher.rune, Hasher.string, Hasher.bytes, Hasher.guid, Hasher.dateTimeOffset, Hasher.timeSpan
    • Hasher.float32 and Hasher.float: preserve exact IEEE-754 bit patterns (NaN payloads, -0.0 vs +0.0)
    • Hasher.decimal: preserves trailing scale (1.0m vs 1.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: matches None before invoking inner, so None, Some null, and Some "" all produce distinct digests despite F#'s null representation of None
    • Hasher.voption, Hasher.nullable, Hasher.result, Hasher.choice2, Hasher.choice3
    • Hasher.contramap projection inner and Hasher.rec' factory (ties recursive type knots once at construction time)
  • Tuple & collection combinators:
    • Reference tuples Hasher.tuple2 .. Hasher.tuple6 and struct tuples Hasher.structTuple2 .. Hasher.structTuple4
    • Ordered sequences Hasher.array, Hasher.immutableArray (IsDefault guarded distinctly from empty), Hasher.list, Hasher.seq
    • Canonical sets and maps Hasher.set and Hasher.map (order-independent over sorted F# Set / Map traversal)
  • Graph reference combinators:
    • Hasher.input<'T> and Hasher.snapshotInput<'T>: hash the input key's identity
    • Hasher.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, unionCaseSpan
    • StructuralPrimitives.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) hashes value with boundInput.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 InputDurability tiers across its transitive input dependencies. When a new Snapshot only edits Low-durability inputs, any subgraph depending solely on High-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 (or let! ref = demand rule arg to inspect ref.Value and ref.Hash)
  • let! v = inputValue key (or let! ref = input key; tryInput / tryInputValue for optional inputs)
  • Applicative parallel fan-out via let! a = ... and! b = ... or Computed.traverseParallel / Computed.traverseArrayParallel
  • Cooperative external Task<'T> integration via Computed.ofTask (fun ct -> ...) or let! x = someTask inside dag { }

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 most maxNodes distinct 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 to MaxEntriesPerNode remembered traces per node) fits within maxWeight. Nodes heavier than maxWeight still return their result to the caller without being retained.
  • Retention.WhileReferenced: Retains intermediate nodes only while at least one retained budgeted node (Count or Weight) 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, default 2): 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 across Workers threads with Priority.Foreground preempting Priority.Background between slices.
  • Session single-flight deduplication: Concurrent demands for the same NodeKey within a Session coalesce onto one InFlightClaim. Cross-fiber wait-graph deadlocks are detected deterministically and raise CycleDetected with the exact cycle path.
  • Non-computing validation (session.Validate / session.ValidateSync): Checks whether a resident valid value exists for (rule, arg) under the session's Snapshot without executing any rule bodies. If a concurrent demand is already computing (rule, arg) on the same session, Validate shares that in-flight claim; if validation misses while a concurrent Demand is waiting, the claim seamlessly promotes to compute for the demanding caller while returning None to Validate.
  • Determinism checking (engine.DeterminismCheck): Set to DeterminismCheck.Raise or DeterminismCheck.Report callback in tests or CI to re-execute validated cache hits and verify that both the result Hash and 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.

Version Downloads Last Updated
0.2.0 765 11/30/2026
0.1.0 93 11/29/2026

Pre-1.0 release. The API may change before 1.0.