tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add Progmasoft.Tazel.CedreCeleste incremental evaluation engine
- Commit
788df0a5301eda81a3dc0cab118621c8d4c2ab08- Author
- Leitwolf11 ·
- Parents
246a7d2dbd8b
Changes
CHANGELOG.md | 4 + Tazel.slnx | 1 + src/Progmasoft.Tazel.CedreCeleste/GraphEngine.cs | 432 +++++++++++++++++++++ src/Progmasoft.Tazel.CedreCeleste/GraphSnapshot.cs | 104 +++++ src/Progmasoft.Tazel.CedreCeleste/NodeKey.cs | 112 ++++++ .../Progmasoft.Tazel.CedreCeleste.csproj | 14 + src/Progmasoft.Tazel/Progmasoft.Tazel.csproj | 1 + tests/Progmasoft.Tazel.Tests/CedreCelesteTests.cs | 261 +++++++++++++ 8 files changed, 929 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e85697..195ab07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- Added `Progmasoft.Tazel.CedreCeleste`, Tazel's internal demand-driven, revision-based incremental evaluation engine + with interned keys, ordered dynamic dependencies, 128-bit content-hash change pruning, async evaluation without + restarts, cycle detection, error-as-value caching, and graph introspection snapshots. + - Added `tazel dotnet daemon start|restart|terminate|kill` (replacing `start-daemon|restart-daemon|stop-daemon`) with a persistent .NET daemon over a user-private Unix domain socket (`TAZEL_DAEMON`, `TAZEL_DAEMON_IDLE_MINUTES`, `TAZEL_DAEMON_MAX_HEAP`, `TAZEL_DAEMON_DIR`) and live status reporting in `tazel log daemon`. diff --git a/Tazel.slnx b/Tazel.slnx index 29b2006..7d95105 100644 --- a/Tazel.slnx +++ b/Tazel.slnx @@ -1,5 +1,6 @@ <Solution> <Folder Name="/src/"> + <Project Path="src/Progmasoft.Tazel.CedreCeleste/Progmasoft.Tazel.CedreCeleste.csproj" /> <Project Path="src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> <Project Path="src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> <Project Path="src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj" /> diff --git a/src/Progmasoft.Tazel.CedreCeleste/GraphEngine.cs b/src/Progmasoft.Tazel.CedreCeleste/GraphEngine.cs new file mode 100644 index 0000000..dbd1e1d --- /dev/null +++ b/src/Progmasoft.Tazel.CedreCeleste/GraphEngine.cs @@ -0,0 +1,432 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.CedreCeleste; + +/// <summary>Evaluation context passed to node evaluators for dynamic dependency reads.</summary> +public interface IEvaluationContext +{ + /// <summary>Evaluates and records <paramref name="key"/> as an ordered dependency of the current node.</summary> + ValueTask<TValue> GetAsync<TValue>(NodeKey key, CancellationToken cancel = default); + + /// <summary>Evaluates and records <paramref name="key"/> as an ordered dependency, returning the untyped value.</summary> + ValueTask<object?> GetAsync(NodeKey key, CancellationToken cancel = default); +} + +/// <summary> +/// Demand-driven, revision-based incremental evaluation engine with ordered dynamic dependencies, +/// content-hash change pruning, async evaluation without restarts, and no eager reverse-edge fanout. +/// </summary> +public sealed class GraphEngine +{ + /// <summary>Async evaluator function registered for a node kind.</summary> + public delegate ValueTask<object?> NodeEvaluator(NodeKey key, IEvaluationContext context, CancellationToken cancel); + + /// <summary>Lazy resolver function for unknown inputs of a node kind.</summary> + public delegate ValueTask<(object? Value, ContentHash Hash)> InputResolver(NodeKey key, CancellationToken cancel); + + private readonly KeyInterner _interner = new(); + private readonly ConcurrentDictionary<string, NodeEvaluator> _evaluators = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary<string, InputResolver> _inputResolvers = new(StringComparer.Ordinal); + private readonly Lock _stateGate = new(); + private readonly Dictionary<int, NodeRecord> _nodes = []; + private readonly ConcurrentDictionary<(int Id, long Revision), Task<NodeRecord>> _inFlight = []; + + private long _revision = 1; + private long _greenHits; + private long _redEvaluations; + private long _prunedEvaluations; + + /// <summary>When false (<c>--notrack-inc-state</c>), dependency lists are not retained and every evaluation runs fresh.</summary> + public bool TrackIncrementalState { get; set; } = true; + + /// <summary>Current global revision counter.</summary> + public long Revision => Volatile.Read(ref _revision); + + /// <summary>Registers an async evaluator for all nodes of <paramref name="kind"/>.</summary> + public void Register(string kind, NodeEvaluator evaluator) + { + ArgumentException.ThrowIfNullOrWhiteSpace(kind); + ArgumentNullException.ThrowIfNull(evaluator); + _evaluators[kind] = evaluator; + } + + /// <summary>Registers a lazy resolver for unknown inputs of <paramref name="kind"/>.</summary> + public void RegisterInputResolver(string kind, InputResolver resolver) + { + ArgumentException.ThrowIfNullOrWhiteSpace(kind); + ArgumentNullException.ThrowIfNull(resolver); + _inputResolvers[kind] = resolver; + } + + /// <summary> + /// Sets an input node's value. Advances the global revision only if the content hash changed, + /// so saving an unchanged file invalidates nothing. + /// </summary> + public bool SetInput(NodeKey key, object? value, ContentHash? hash = null) + { + var id = _interner.Intern(key); + var contentHash = hash ?? ContentHash.FromValue(value); + lock (_stateGate) + { + if (_nodes.TryGetValue(id, out var existing) && existing.IsInput && !existing.Unknown && existing.Hash == contentHash) + { + existing.Value = value; + existing.ValuePresent = true; + return false; + } + + var nextRev = ++_revision; + _nodes[id] = new NodeRecord + { + Id = id, + IsInput = true, + Unknown = false, + Value = value, + ValuePresent = true, + Hash = contentHash, + ChangedAt = nextRev, + VerifiedAt = nextRev, + Dependencies = [], + }; + return true; + } + } + + /// <summary>Marks one input node as unknown so it is lazily checked when next read.</summary> + public void MarkInputUnknown(NodeKey key) + { + if (!_interner.TryGetId(key, out var id)) + { + return; + } + + lock (_stateGate) + { + if (_nodes.TryGetValue(id, out var node) && node.IsInput) + { + node.Unknown = true; + _revision++; + } + } + } + + /// <summary>Marks every input node as unknown (e.g. after a restart or watcher overflow).</summary> + public void MarkAllInputsUnknown() + { + lock (_stateGate) + { + var touched = false; + foreach (var node in _nodes.Values) + { + if (node.IsInput) + { + node.Unknown = true; + touched = true; + } + } + + if (touched) + { + _revision++; + } + } + } + + /// <summary>Drops cached non-input values while retaining their hashes and dependencies for pruning.</summary> + public void DiscardAnalysisCache() + { + lock (_stateGate) + { + foreach (var node in _nodes.Values) + { + if (!node.IsInput) + { + node.Value = null; + node.ValuePresent = false; + } + } + } + } + + /// <summary>Evaluates <paramref name="key"/> at the current revision.</summary> + public async ValueTask<TValue> GetAsync<TValue>(NodeKey key, CancellationToken cancel = default) + { + var value = await GetAsync(key, cancel).ConfigureAwait(false); + return value is null ? default! : (TValue)value; + } + + /// <summary>Evaluates <paramref name="key"/> at the current revision, returning the untyped value.</summary> + public async ValueTask<object?> GetAsync(NodeKey key, CancellationToken cancel = default) + { + var record = await EvaluateInternalAsync(key, Revision, ImmutableList<int>.Empty, cancel).ConfigureAwait(false); + if (record.Error is not null) + { + throw record.Error; + } + + return record.Value; + } + + /// <summary>Captures a point-in-time introspection snapshot for <c>tazel dump</c>.</summary> + public GraphSnapshot Snapshot() + { + lock (_stateGate) + { + var entries = new List<GraphNodeSnapshot>(_nodes.Count); + foreach (var node in _nodes.Values) + { + var key = _interner.GetKey(node.Id); + var deps = node.Dependencies.Select(depId => _interner.GetKey(depId)).ToArray(); + entries.Add(new GraphNodeSnapshot( + key, + node.IsInput, + node.ChangedAt, + node.VerifiedAt, + node.Hash, + node.ValuePresent, + node.Error?.Message, + deps)); + } + + return new GraphSnapshot( + _revision, + Volatile.Read(ref _greenHits), + Volatile.Read(ref _redEvaluations), + Volatile.Read(ref _prunedEvaluations), + entries); + } + } + + private async Task<NodeRecord> EvaluateInternalAsync( + NodeKey key, long targetRevision, ImmutableList<int> stack, CancellationToken cancel) + { + var id = _interner.Intern(key); + var cycleIndex = stack.IndexOf(id); + if (cycleIndex >= 0) + { + var chain = stack.Skip(cycleIndex).Append(id).Select(nodeId => _interner.GetKey(nodeId)).ToList(); + throw new CycleException(chain); + } + + if (TryGetVerified(id, targetRevision, out var cached)) + { + return cached; + } + + var flightKey = (id, targetRevision); + var task = _inFlight.GetOrAdd(flightKey, _ => ComputeNodeAsync(id, key, targetRevision, stack.Add(id), cancel)); + try + { + return await task.ConfigureAwait(false); + } + finally + { + _inFlight.TryRemove(flightKey, out _); + } + } + + private bool TryGetVerified(int id, long targetRevision, out NodeRecord record) + { + lock (_stateGate) + { + if (_nodes.TryGetValue(id, out var existing) && + existing.VerifiedAt == targetRevision && + !existing.Unknown && + (existing.ValuePresent || existing.Error is not null)) + { + record = existing; + return true; + } + } + + record = null!; + return false; + } + + private async Task<NodeRecord> ComputeNodeAsync( + int id, NodeKey key, long targetRevision, ImmutableList<int> stack, CancellationToken cancel) + { + NodeRecord? previous; + lock (_stateGate) + { + _nodes.TryGetValue(id, out previous); + } + + if (previous is { IsInput: true }) + { + return await VerifyInputAsync(id, key, previous, targetRevision, cancel).ConfigureAwait(false); + } + + if (TrackIncrementalState && previous is not null && (previous.ValuePresent || previous.Error is not null)) + { + if (await AreDependenciesGreenAsync(previous, targetRevision, stack, cancel).ConfigureAwait(false)) + { + Interlocked.Increment(ref _greenHits); + lock (_stateGate) + { + previous.VerifiedAt = targetRevision; + } + + return previous; + } + } + + return await RunEvaluatorAsync(id, key, previous, targetRevision, stack, cancel).ConfigureAwait(false); + } + + private async Task<NodeRecord> VerifyInputAsync( + int id, NodeKey key, NodeRecord input, long targetRevision, CancellationToken cancel) + { + if (input.Unknown) + { + if (!_inputResolvers.TryGetValue(key.Kind, out var resolver)) + { + throw new InvalidOperationException($"no input resolver registered for unknown input '{key}'"); + } + + var (newValue, newHash) = await resolver(key, cancel).ConfigureAwait(false); + lock (_stateGate) + { + var changed = newHash != input.Hash; + input.Value = newValue; + input.ValuePresent = true; + input.Hash = newHash; + input.Unknown = false; + input.VerifiedAt = targetRevision; + if (changed) + { + input.ChangedAt = targetRevision; + } + + return input; + } + } + + lock (_stateGate) + { + input.VerifiedAt = targetRevision; + return input; + } + } + + private async Task<bool> AreDependenciesGreenAsync( + NodeRecord node, long targetRevision, ImmutableList<int> stack, CancellationToken cancel) + { + foreach (var depId in node.Dependencies) + { + var depKey = _interner.GetKey(depId); + var depRecord = await EvaluateInternalAsync(depKey, targetRevision, stack, cancel).ConfigureAwait(false); + if (depRecord.ChangedAt > node.VerifiedAt) + { + return false; + } + } + + return true; + } + + private async Task<NodeRecord> RunEvaluatorAsync( + int id, NodeKey key, NodeRecord? previous, long targetRevision, ImmutableList<int> stack, CancellationToken cancel) + { + if (!_evaluators.TryGetValue(key.Kind, out var evaluator)) + { + throw new InvalidOperationException($"no evaluator or input registered for node '{key}'"); + } + + Interlocked.Increment(ref _redEvaluations); + var recordedDeps = new List<int>(); + var context = new RecordingContext(this, targetRevision, stack, recordedDeps); + + object? value = null; + Exception? error = null; + ContentHash hash; + try + { + value = await evaluator(key, context, cancel).ConfigureAwait(false); + hash = ContentHash.FromValue(value); + } + catch (CycleException) + { + throw; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + error = ex; + hash = ContentHash.FromString($"ERROR:{ex.GetType().FullName}:{ex.Message}"); + } + + lock (_stateGate) + { + var pruned = previous is not null && previous.Hash == hash && (previous.Error is null) == (error is null); + if (pruned) + { + Interlocked.Increment(ref _prunedEvaluations); + } + + var updated = new NodeRecord + { + Id = id, + IsInput = false, + Unknown = false, + Value = value, + ValuePresent = error is null, + Error = error, + Hash = hash, + ChangedAt = pruned ? previous!.ChangedAt : targetRevision, + VerifiedAt = targetRevision, + Dependencies = TrackIncrementalState ? recordedDeps.ToArray() : [], + }; + _nodes[id] = updated; + return updated; + } + } + + private sealed class RecordingContext( + GraphEngine engine, long targetRevision, ImmutableList<int> stack, List<int> recordedDeps) : IEvaluationContext + { + public async ValueTask<TValue> GetAsync<TValue>(NodeKey key, CancellationToken cancel = default) + { + var value = await GetAsync(key, cancel).ConfigureAwait(false); + return value is null ? default! : (TValue)value; + } + + public async ValueTask<object?> GetAsync(NodeKey key, CancellationToken cancel = default) + { + var record = await engine.EvaluateInternalAsync(key, targetRevision, stack, cancel).ConfigureAwait(false); + recordedDeps.Add(record.Id); + if (record.Error is not null) + { + throw record.Error; + } + + return record.Value; + } + } + + private sealed class NodeRecord + { + public required int Id { get; init; } + public required bool IsInput { get; init; } + public bool Unknown { get; set; } + public object? Value { get; set; } + public bool ValuePresent { get; set; } + public Exception? Error { get; set; } + public ContentHash Hash { get; set; } + public long ChangedAt { get; set; } + public long VerifiedAt { get; set; } + public required int[] Dependencies { get; set; } + } +} diff --git a/src/Progmasoft.Tazel.CedreCeleste/GraphSnapshot.cs b/src/Progmasoft.Tazel.CedreCeleste/GraphSnapshot.cs new file mode 100644 index 0000000..ae48c62 --- /dev/null +++ b/src/Progmasoft.Tazel.CedreCeleste/GraphSnapshot.cs @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Progmasoft.Tazel.CedreCeleste; + +/// <summary>Snapshot of a single node in the Cedre Celeste graph.</summary> +public sealed record GraphNodeSnapshot( + NodeKey Key, + bool IsInput, + long ChangedAt, + long VerifiedAt, + ContentHash Hash, + bool HasValue, + string? ErrorMessage, + IReadOnlyList<NodeKey> Dependencies); + +/// <summary>Point-in-time introspection snapshot of a <see cref="GraphEngine"/>.</summary> +public sealed record GraphSnapshot( + long Revision, + long GreenHits, + long RedEvaluations, + long PrunedEvaluations, + IReadOnlyList<GraphNodeSnapshot> Nodes) +{ + /// <summary>Formats the snapshot according to a <c>tazel dump --cedre-celeste=<view></c> mode.</summary> + public string Format(string view) => view.ToLowerInvariant() switch + { + "summary" => FormatSummary(), + "count" => FormatCounts(), + "deps" => FormatDeps(), + "rdeps" => FormatReverseDeps(), + "value" => FormatValues(), + _ => FormatSummary(), + }; + + private string FormatSummary() => + $"revision: {Revision}\nnodes: {Nodes.Count}\ngreen: {GreenHits}\nred: {RedEvaluations}\npruned: {PrunedEvaluations}"; + + private string FormatCounts() + { + var sb = new StringBuilder(); + foreach (var group in Nodes.GroupBy(n => n.Key.Kind, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal)) + { + sb.AppendLine($"{group.Key}: {group.Count()}"); + } + + return sb.ToString().TrimEnd(); + } + + private string FormatDeps() + { + var sb = new StringBuilder(); + foreach (var node in Nodes.OrderBy(n => n.Key.ToString(), StringComparer.Ordinal)) + { + sb.AppendLine($"{node.Key} -> [{string.Join(", ", node.Dependencies)}]"); + } + + return sb.ToString().TrimEnd(); + } + + private string FormatReverseDeps() + { + var reverse = new Dictionary<NodeKey, List<NodeKey>>(); + foreach (var node in Nodes) + { + reverse.TryAdd(node.Key, []); + foreach (var dep in node.Dependencies) + { + if (!reverse.TryGetValue(dep, out var list)) + { + list = []; + reverse[dep] = list; + } + + list.Add(node.Key); + } + } + + var sb = new StringBuilder(); + foreach (var (key, callers) in reverse.OrderBy(pair => pair.Key.ToString(), StringComparer.Ordinal)) + { + sb.AppendLine($"{key} <- [{string.Join(", ", callers.OrderBy(c => c.ToString(), StringComparer.Ordinal))}]"); + } + + return sb.ToString().TrimEnd(); + } + + private string FormatValues() + { + var sb = new StringBuilder(); + foreach (var node in Nodes.OrderBy(n => n.Key.ToString(), StringComparer.Ordinal)) + { + var state = node.ErrorMessage is not null ? $"error({node.ErrorMessage})" : node.HasValue ? $"hash={node.Hash}" : $"evicted(hash={node.Hash})"; + sb.AppendLine($"{node.Key}: changed@{node.ChangedAt} verified@{node.VerifiedAt} {state}"); + } + + return sb.ToString().TrimEnd(); + } +} diff --git a/src/Progmasoft.Tazel.CedreCeleste/NodeKey.cs b/src/Progmasoft.Tazel.CedreCeleste/NodeKey.cs new file mode 100644 index 0000000..8ae04f3 --- /dev/null +++ b/src/Progmasoft.Tazel.CedreCeleste/NodeKey.cs @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Threading; + +namespace Progmasoft.Tazel.CedreCeleste; + +/// <summary>Typed, immutable identity of a node in the Cedre Celeste evaluation graph.</summary> +public readonly record struct NodeKey(string Kind, string Name) +{ + /// <inheritdoc/> + public override string ToString() => $"{Kind}:{Name}"; +} + +/// <summary>128-bit content digest used to detect value changes and prune downstream re-evaluation.</summary> +public readonly record struct ContentHash(ulong High, ulong Low) +{ + /// <summary>Computes a deterministic 128-bit content hash from UTF-8 text.</summary> + public static ContentHash FromString(string? text) + { + var bytes = text is null ? [] : Encoding.UTF8.GetBytes(text); + return FromBytes(bytes); + } + + /// <summary>Computes a deterministic 128-bit content hash from raw bytes.</summary> + public static ContentHash FromBytes(ReadOnlySpan<byte> bytes) + { + Span<byte> digest = stackalloc byte[32]; + SHA256.HashData(bytes, digest); + var high = BitConverter.ToUInt64(digest[..8]); + var low = BitConverter.ToUInt64(digest[8..16]); + return new ContentHash(high, low); + } + + /// <summary>Computes a content hash for an arbitrary evaluated value.</summary> + public static ContentHash FromValue(object? value) => value switch + { + null => new ContentHash(0, 0), + ContentHash existing => existing, + byte[] bytes => FromBytes(bytes), + string text => FromString(text), + IFormattable formattable => FromString($"{value.GetType().FullName}:{formattable.ToString(null, CultureInfo.InvariantCulture)}"), + _ => FromString($"{value.GetType().FullName}:{value}"), + }; + + /// <inheritdoc/> + public override string ToString() => $"{High:x16}{Low:x16}"; +} + +/// <summary>Exception thrown when a node directly or indirectly depends on itself.</summary> +public sealed class CycleException(IReadOnlyList<NodeKey> chain) + : Exception($"dependency cycle detected: {string.Join(" -> ", chain)}") +{ + /// <summary>Ordered cycle chain starting and ending at the repeated node.</summary> + public IReadOnlyList<NodeKey> Chain { get; } = chain; +} + +/// <summary>Interns <see cref="NodeKey"/> instances into dense 32-bit integer identifiers.</summary> +internal sealed class KeyInterner +{ + private readonly Lock _gate = new(); + private readonly Dictionary<NodeKey, int> _toId = []; + private readonly List<NodeKey> _toKey = []; + + public int Count + { + get + { + lock (_gate) + { + return _toKey.Count; + } + } + } + + public int Intern(NodeKey key) + { + lock (_gate) + { + if (_toId.TryGetValue(key, out var existing)) + { + return existing; + } + + var id = _toKey.Count; + _toKey.Add(key); + _toId[key] = id; + return id; + } + } + + public bool TryGetId(NodeKey key, out int id) + { + lock (_gate) + { + return _toId.TryGetValue(key, out id); + } + } + + public NodeKey GetKey(int id) + { + lock (_gate) + { + return _toKey[id]; + } + } +} diff --git a/src/Progmasoft.Tazel.CedreCeleste/Progmasoft.Tazel.CedreCeleste.csproj b/src/Progmasoft.Tazel.CedreCeleste/Progmasoft.Tazel.CedreCeleste.csproj new file mode 100644 index 0000000..3e633a4 --- /dev/null +++ b/src/Progmasoft.Tazel.CedreCeleste/Progmasoft.Tazel.CedreCeleste.csproj @@ -0,0 +1,14 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- Cedre Celeste: Tazel's internal demand-driven incremental evaluation engine. --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <RootNamespace>Progmasoft.Tazel.CedreCeleste</RootNamespace> + <IsPackable>false</IsPackable> + </PropertyGroup> + <ItemGroup> + <InternalsVisibleTo Include="Progmasoft.Tazel" /> + <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> + <InternalsVisibleTo Include="Progmasoft.Tazel.Benchmarks" /> + </ItemGroup> +</Project> diff --git a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj index 8a9fa27..317889c 100644 --- a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj +++ b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj @@ -10,6 +10,7 @@ <TieredPGO>true</TieredPGO> </PropertyGroup> <ItemGroup> + <ProjectReference Include="../Progmasoft.Tazel.CedreCeleste/Progmasoft.Tazel.CedreCeleste.csproj" /> <ProjectReference Include="../Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> <ProjectReference Include="../Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj" /> </ItemGroup> diff --git a/tests/Progmasoft.Tazel.Tests/CedreCelesteTests.cs b/tests/Progmasoft.Tazel.Tests/CedreCelesteTests.cs new file mode 100644 index 0000000..5477aa1 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/CedreCelesteTests.cs @@ -0,0 +1,261 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using CsCheck; +using Progmasoft.Tazel.CedreCeleste; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class CedreCelesteTests +{ + [Fact] + public async Task UnchangedInputDoesNotAdvanceRevisionOrRerunNodes() + { + var token = TestContext.Current.CancellationToken; + var engine = new GraphEngine(); + var runs = 0; + engine.Register("upper", async (key, ctx, ct) => + { + runs++; + var text = await ctx.GetAsync<string>(new NodeKey("input", key.Name), ct); + return text.ToUpperInvariant(); + }); + + var inputKey = new NodeKey("input", "a"); + var upperKey = new NodeKey("upper", "a"); + Assert.True(engine.SetInput(inputKey, "hello")); + Assert.Equal("HELLO", await engine.GetAsync<string>(upperKey, token)); + Assert.Equal(1, runs); + + // Saving the same content again must not bump revision or re-run evaluators. + var revBefore = engine.Revision; + Assert.False(engine.SetInput(inputKey, "hello")); + Assert.Equal(revBefore, engine.Revision); + Assert.Equal("HELLO", await engine.GetAsync<string>(upperKey, token)); + Assert.Equal(1, runs); + } + + [Fact] + public async Task ChangePruningStopsDownstreamReevaluationOnSameHash() + { + var token = TestContext.Current.CancellationToken; + var engine = new GraphEngine(); + var stripRuns = 0; + var compileRuns = 0; + + engine.Register("strip", async (key, ctx, ct) => + { + stripRuns++; + var raw = await ctx.GetAsync<string>(new NodeKey("file", key.Name), ct); + return raw.Split("//")[0].Trim(); + }); + + engine.Register("compile", async (key, ctx, ct) => + { + compileRuns++; + var code = await ctx.GetAsync<string>(new NodeKey("strip", key.Name), ct); + return $"obj:{code}"; + }); + + var file = new NodeKey("file", "main.c"); + var target = new NodeKey("compile", "main.c"); + engine.SetInput(file, "int main() {} // v1"); + Assert.Equal("obj:int main() {}", await engine.GetAsync<string>(target, token)); + Assert.Equal(1, stripRuns); + Assert.Equal(1, compileRuns); + + // Comment-only edit: strip re-runs, produces identical output -> compile stays green. + engine.SetInput(file, "int main() {} // v2 comment"); + Assert.Equal("obj:int main() {}", await engine.GetAsync<string>(target, token)); + Assert.Equal(2, stripRuns); + Assert.Equal(1, compileRuns); + + var snap = engine.Snapshot(); + Assert.Equal(1, snap.PrunedEvaluations); + Assert.Contains("pruned: 1", snap.Format("summary"), StringComparison.Ordinal); + Assert.Contains("compile: 1", snap.Format("count"), StringComparison.Ordinal); + Assert.Contains("strip:main.c -> [file:main.c]", snap.Format("deps"), StringComparison.Ordinal); + Assert.Contains("file:main.c <- [strip:main.c]", snap.Format("rdeps"), StringComparison.Ordinal); + Assert.Contains("compile:main.c:", snap.Format("value"), StringComparison.Ordinal); + } + + [Fact] + public async Task DynamicDependenciesShortCircuitIrrelevantLaterReads() + { + var token = TestContext.Current.CancellationToken; + var engine = new GraphEngine(); + var branchBRuns = 0; + + engine.Register("branch", async (key, ctx, ct) => + { + if (key.Name == "B") + { + branchBRuns++; + } + + return await ctx.GetAsync<string>(new NodeKey("in", key.Name), ct); + }); + + engine.Register("choose", async (_, ctx, ct) => + { + var pick = await ctx.GetAsync<string>(new NodeKey("in", "pick"), ct); + return await ctx.GetAsync<string>(new NodeKey("branch", pick), ct); + }); + + engine.SetInput(new NodeKey("in", "pick"), "B"); + engine.SetInput(new NodeKey("in", "A"), "alpha"); + engine.SetInput(new NodeKey("in", "B"), "beta"); + Assert.Equal("beta", await engine.GetAsync<string>(new NodeKey("choose", "root"), token)); + Assert.Equal(1, branchBRuns); + + // Switch pick to A and mutate B: ordered dependency check sees pick changed first, + // so branch:B must NOT be re-evaluated. + engine.SetInput(new NodeKey("in", "pick"), "A"); + engine.SetInput(new NodeKey("in", "B"), "beta-2"); + Assert.Equal("alpha", await engine.GetAsync<string>(new NodeKey("choose", "root"), token)); + Assert.Equal(1, branchBRuns); + } + + [Fact] + public async Task DetectsCyclesWithOrderedChain() + { + var token = TestContext.Current.CancellationToken; + var engine = new GraphEngine(); + engine.Register("loop", async (key, ctx, ct) => + { + var next = key.Name == "a" ? "b" : "a"; + return await ctx.GetAsync<string>(new NodeKey("loop", next), ct); + }); + + var error = await Assert.ThrowsAsync<CycleException>(async () => + await engine.GetAsync<string>(new NodeKey("loop", "a"), token)); + Assert.Equal(3, error.Chain.Count); + Assert.Equal(new NodeKey("loop", "a"), error.Chain[0]); + Assert.Equal(new NodeKey("loop", "b"), error.Chain[1]); + Assert.Equal(new NodeKey("loop", "a"), error.Chain[2]); + } + + [Fact] + public async Task CachesErrorsAsValuesAndInvalidatesWhenFixed() + { + var token = TestContext.Current.CancellationToken; + var engine = new GraphEngine(); + var runs = 0; + engine.Register("parse", async (key, ctx, ct) => + { + runs++; + var raw = await ctx.GetAsync<string>(new NodeKey("src", key.Name), ct); + return int.Parse(raw, System.Globalization.CultureInfo.InvariantCulture); + }); + + var src = new NodeKey("src", "num"); + var parse = new NodeKey("parse", "num"); + engine.SetInput(src, "not-a-number"); + await Assert.ThrowsAsync<FormatException>(async () => await engine.GetAsync<int>(parse, token)); + await Assert.ThrowsAsync<FormatException>(async () => await engine.GetAsync<int>(parse, token)); + Assert.Equal(1, runs); + + engine.SetInput(src, "42"); + Assert.Equal(42, await engine.GetAsync<int>(parse, token)); + Assert.Equal(2, runs); + } + + [Fact] + public async Task DiscardAnalysisCacheAndMarkAllInputsUnknownWorkLazily() + { + var token = TestContext.Current.CancellationToken; + var engine = new GraphEngine(); + var disk = new Dictionary<string, string>(StringComparer.Ordinal) { ["x"] = "hello" }; + var resolverCalls = 0; + var computeCalls = 0; + + engine.RegisterInputResolver("file", (key, _) => + { + resolverCalls++; + var val = disk[key.Name]; + return ValueTask.FromResult<(object?, ContentHash)>((val, ContentHash.FromString(val))); + }); + engine.Register("len", async (key, ctx, ct) => + { + computeCalls++; + var val = await ctx.GetAsync<string>(new NodeKey("file", key.Name), ct); + return val.Length; + }); + + var file = new NodeKey("file", "x"); + var len = new NodeKey("len", "x"); + engine.SetInput(file, "hello"); + Assert.Equal(5, await engine.GetAsync<int>(len, token)); + Assert.Equal(1, computeCalls); + + // Simulate restart / watcher overflow with unchanged content on disk: + engine.MarkAllInputsUnknown(); + Assert.Equal(5, await engine.GetAsync<int>(len, token)); + Assert.Equal(1, resolverCalls); + Assert.Equal(1, computeCalls); + + // Discard analysis cache: value is evicted, hash stays, re-evaluation recomputes cleanly. + engine.DiscardAnalysisCache(); + Assert.Contains("evicted(", engine.Snapshot().Format("value"), StringComparison.Ordinal); + Assert.Equal(5, await engine.GetAsync<int>(len, token)); + Assert.Equal(2, computeCalls); + } + + [Fact] + public void PropertyIncrementalEqualsFromScratchAcrossRandomDagMutations() + { + var token = TestContext.Current.CancellationToken; + var gen = Gen.Select( + Gen.Int[0, 5].Array[3], + Gen.Select(Gen.Int[0, 2], Gen.Int[0, 5]).Array[1, 8]); + + gen.Sample((initial, mutations) => + { + var inc = BuildDagEngine(); + for (var i = 0; i < 3; i++) + { + inc.SetInput(new NodeKey("in", i.ToString(System.Globalization.CultureInfo.InvariantCulture)), initial[i]); + } + + var current = (int[])initial.Clone(); + var root = new NodeKey("derived", "2"); + Assert.Equal(EvalScratch(current), inc.GetAsync<int>(root, token).AsTask().GetAwaiter().GetResult()); + + foreach (var (index, newValue) in mutations) + { + current[index] = newValue; + inc.SetInput(new NodeKey("in", index.ToString(System.Globalization.CultureInfo.InvariantCulture)), newValue); + Assert.Equal(EvalScratch(current), inc.GetAsync<int>(root, token).AsTask().GetAwaiter().GetResult()); + } + }, iter: 100); + } + + private static GraphEngine BuildDagEngine() + { + var engine = new GraphEngine(); + engine.Register("derived", async (key, ctx, ct) => + { + var a = await ctx.GetAsync<int>(new NodeKey("in", "0"), ct); + var b = await ctx.GetAsync<int>(new NodeKey("in", "1"), ct); + var c = await ctx.GetAsync<int>(new NodeKey("in", "2"), ct); + return key.Name switch + { + "0" => (a + b) % 3, + "1" => (await ctx.GetAsync<int>(new NodeKey("derived", "0"), ct) * 7) + c, + _ => await ctx.GetAsync<int>(new NodeKey("derived", "1"), ct) + (a % 2), + }; + }); + return engine; + } + + private static int EvalScratch(int[] inputs) + { + var d0 = (inputs[0] + inputs[1]) % 3; + var d1 = (d0 * 7) + inputs[2]; + return d1 + (inputs[0] % 2); + } +}