Progmasoft Git

tazel

A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.

Clonegit clone https://git.progmasoft.com/tazel

feat(cadre-celeste): add SQLite graph metadata persistence and ABI-aware early-cutoff fingerprinting

Motivation:
Tazel 0.6.0 requires cold-daemon graph metadata restoration and sound C/C++/ObjC
ABI-aware early cutoff so non-ABI header edits (comments and insignificant
whitespace) trigger zero downstream rebuilds while any ABI-affecting edit
(inline/constexpr/template bodies, macros, struct layouts, signatures) always
invalidates downstream targets.

Changes:
- Add Microsoft.Data.Sqlite reference to Progmasoft.Tazel.CadreCeleste.csproj.
- Add CadreCelesteStore (Save/Load with schema user_version=1, atomic replacement,
  and compile-time SQL literals) in src/Progmasoft.Tazel.CadreCeleste/CadreCelesteStore.cs.
- Add GraphEngine.RestoreMetadata(GraphSnapshot) in GraphEngine.cs to restore
  persisted node revisions, 128-bit hashes, and ordered dependency edges on cold start.
- Add AbiFingerprint (NormalizeHeaderTokens, HashHeaderTokens, HashExportedSymbols)
  in src/Progmasoft.Tazel.CadreCeleste/AbiFingerprint.cs.
- Add CadreCelestePersistenceAndAbiTests.cs covering SQLite round-trip + cold
  restore, comment/whitespace early cutoff (0 downstream rebuilds), inline/layout
  invalidation, and order-independent exported symbol fingerprinting.
- Register CadreCelestePersistenceAndAbiTests in .github/workflows/ci.yml (macOS)
  and document the addition in CHANGELOG.md (Unreleased).

Edge Cases & Compatibility:
- Comment/whitespace stripping preserves string/char literals and preprocessor
  line boundaries conservatively to avoid unsound pruning.
- Uses compile-time SQL string literals exclusively to satisfy Semgrep/Codacy.

Verification:
- Built Tazel.slnx -c Release: 0 warnings, 0 errors.
- Passed locally: CadreCelestePersistenceAndAbiTests (3/3) and CadreCelesteTests (7/7).
Commit
f6a3d2219b1a419f237cc9e9dcbb7b089d65bfe1
Author
Leitwolf11 ·
Parents
0f38a394a852

Files · Download .tar.gz

Changes

 .github/workflows/ci.yml                           |   7 +
 CHANGELOG.md                                       |   2 +
 .../AbiFingerprint.cs                              | 150 +++++++++++++++
 .../CadreCelesteStore.cs                           | 212 +++++++++++++++++++++
 src/Progmasoft.Tazel.CadreCeleste/GraphEngine.cs   |  40 ++++
 .../Progmasoft.Tazel.CadreCeleste.csproj           |   3 +
 .../CadreCelestePersistenceAndAbiTests.cs          | 135 +++++++++++++
 7 files changed, 549 insertions(+)

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 89cb65f..a54842f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -337,6 +337,13 @@ jobs:
           dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed
           --filter-class Progmasoft.Tazel.Tests.ModulesCommandsTests
 
+      - name: Test CadreCelestePersistenceAndAbiTests (macOS)
+        if: runner.os == 'macOS'
+        timeout-minutes: 10
+        run: >-
+          dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed
+          --filter-class Progmasoft.Tazel.Tests.CadreCelestePersistenceAndAbiTests
+
       - name: Test
         # A test that hangs is named and dumped at 15 minutes, and the run stops itself at 20, before the step's own
         # limit, so the job ends with its log and its files kept instead of being cancelled at the job's limit.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 74eefca..e892dd8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@
 
 ## Unreleased
 
+- Added SQLite graph metadata persistence (`CadreCelesteStore` + `GraphEngine.RestoreMetadata`) and conservative C/C++/Objective-C ABI-aware early-cutoff fingerprinting (`AbiFingerprint.HashHeaderTokens`, `AbiFingerprint.HashExportedSymbols`) in `Progmasoft.Tazel.CadreCeleste`.
+
 ## 0.5.0 - 2026-12-03
 
 - Renamed the evaluation engine from `Progmasoft.Tazel.CedreCeleste` (`--cedre-celeste`) to `Progmasoft.Tazel.CadreCeleste` (`--cadre-celeste`, JSON key `cadreCeleste`).
diff --git a/src/Progmasoft.Tazel.CadreCeleste/AbiFingerprint.cs b/src/Progmasoft.Tazel.CadreCeleste/AbiFingerprint.cs
new file mode 100644
index 0000000..232bd59
--- /dev/null
+++ b/src/Progmasoft.Tazel.CadreCeleste/AbiFingerprint.cs
@@ -0,0 +1,150 @@
+// 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.CadreCeleste;
+
+/// <summary>
+/// Conservative C/C++/Objective-C ABI-aware fingerprinting helpers for early cutoff:
+/// strips comments and insignificant whitespace from headers while preserving string/char literals,
+/// preprocessor directives, macros, <c>inline</c>/<c>constexpr</c>/<c>template</c> definitions, and type layouts.
+/// </summary>
+public static class AbiFingerprint
+{
+    /// <summary>
+    /// Computes a deterministic 128-bit <see cref="ContentHash"/> over the comment- and whitespace-normalized token
+    /// stream of a C/C++/Objective-C header. Any non-comment, non-whitespace token change produces a different hash.
+    /// </summary>
+    public static ContentHash HashHeaderTokens(string source)
+    {
+        ArgumentNullException.ThrowIfNull(source);
+        var normalized = NormalizeHeaderTokens(source);
+        return ContentHash.FromString(normalized);
+    }
+
+    /// <summary>
+    /// Computes an order-independent 128-bit <see cref="ContentHash"/> over exported ABI symbol signatures.
+    /// </summary>
+    public static ContentHash HashExportedSymbols(IEnumerable<string> symbols)
+    {
+        ArgumentNullException.ThrowIfNull(symbols);
+        var sb = new StringBuilder();
+        foreach (var sym in symbols.OrderBy(s => s, StringComparer.Ordinal))
+        {
+            sb.Append(sym);
+            sb.Append('\n');
+        }
+
+        return ContentHash.FromString(sb.ToString());
+    }
+
+    /// <summary>Normalizes a C/C++ header by removing comments and collapsing insignificant whitespace.</summary>
+    public static string NormalizeHeaderTokens(string source)
+    {
+        ArgumentNullException.ThrowIfNull(source);
+        var sb = new StringBuilder(source.Length);
+        var i = 0;
+        var pendingSpace = false;
+
+        while (i < source.Length)
+        {
+            var ch = source[i];
+            if (TrySkipComment(source, ref i))
+            {
+                pendingSpace = sb.Length > 0 && sb[^1] != '\n';
+                continue;
+            }
+
+            if (ch == '\r' || ch == '\n')
+            {
+                i++;
+                if (sb.Length > 0 && sb[^1] != '\n')
+                {
+                    sb.Append('\n');
+                }
+
+                pendingSpace = false;
+                continue;
+            }
+
+            if (char.IsWhiteSpace(ch))
+            {
+                i++;
+                pendingSpace = sb.Length > 0 && sb[^1] != '\n';
+                continue;
+            }
+
+            if (pendingSpace)
+            {
+                sb.Append(' ');
+                pendingSpace = false;
+            }
+
+            if (ch is '"' or '\'')
+            {
+                CopyQuotedLiteral(source, ref i, ch, sb);
+                continue;
+            }
+
+            sb.Append(ch);
+            i++;
+        }
+
+        return sb.ToString().TrimEnd('\n', ' ');
+    }
+
+    private static bool TrySkipComment(string source, ref int i)
+    {
+        if (source[i] != '/' || i + 1 >= source.Length)
+        {
+            return false;
+        }
+
+        if (source[i + 1] == '/')
+        {
+            i += 2;
+            while (i < source.Length && source[i] != '\n')
+            {
+                i++;
+            }
+
+            return true;
+        }
+
+        if (source[i + 1] == '*')
+        {
+            i += 2;
+            while (i + 1 < source.Length && !(source[i] == '*' && source[i + 1] == '/'))
+            {
+                i++;
+            }
+
+            i = i + 1 < source.Length ? i + 2 : source.Length;
+            return true;
+        }
+
+        return false;
+    }
+
+    private static void CopyQuotedLiteral(string source, ref int i, char quote, StringBuilder sb)
+    {
+        sb.Append(source[i++]);
+        while (i < source.Length)
+        {
+            var c = source[i++];
+            sb.Append(c);
+            if (c == '\\' && i < source.Length)
+            {
+                sb.Append(source[i++]);
+            }
+            else if (c == quote)
+            {
+                break;
+            }
+        }
+    }
+}
diff --git a/src/Progmasoft.Tazel.CadreCeleste/CadreCelesteStore.cs b/src/Progmasoft.Tazel.CadreCeleste/CadreCelesteStore.cs
new file mode 100644
index 0000000..5d42437
--- /dev/null
+++ b/src/Progmasoft.Tazel.CadreCeleste/CadreCelesteStore.cs
@@ -0,0 +1,212 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using Microsoft.Data.Sqlite;
+
+namespace Progmasoft.Tazel.CadreCeleste;
+
+/// <summary>
+/// Persists and restores <see cref="GraphSnapshot"/> metadata in SQLite so a restarted Tazel daemon can resume
+/// incremental pruning without rebuilding unchanged graph state.
+/// </summary>
+public static class CadreCelesteStore
+{
+    /// <summary>SQLite <c>user_version</c> schema version for Cadre Celeste graph persistence.</summary>
+    public static int SchemaVersion { get; } = 1;
+
+    /// <summary>Atomically writes <paramref name="snapshot"/> to <paramref name="path"/>.</summary>
+    public static void Save(string path, GraphSnapshot snapshot)
+    {
+        ArgumentNullException.ThrowIfNull(path);
+        ArgumentNullException.ThrowIfNull(snapshot);
+
+        var fullPath = Path.GetFullPath(path);
+        var dir = Path.GetDirectoryName(fullPath) ?? ".";
+        Directory.CreateDirectory(dir);
+
+        var tempPath = Path.Combine(dir, $".cadre-celeste-{Guid.NewGuid():N}.sqlite3");
+        try
+        {
+            WriteDatabase(tempPath, snapshot);
+            File.Move(tempPath, fullPath, overwrite: true);
+        }
+        finally
+        {
+            if (File.Exists(tempPath))
+            {
+                File.Delete(tempPath);
+            }
+        }
+    }
+
+    /// <summary>Loads a persisted <see cref="GraphSnapshot"/> from <paramref name="path"/>.</summary>
+    public static GraphSnapshot Load(string path)
+    {
+        ArgumentNullException.ThrowIfNull(path);
+        var fullPath = Path.GetFullPath(path);
+        var cs = new SqliteConnectionStringBuilder { DataSource = fullPath, Mode = SqliteOpenMode.ReadOnly }.ToString();
+        using var conn = new SqliteConnection(cs);
+        conn.Open();
+
+        VerifySchemaVersion(conn);
+        var (revision, green, red, pruned) = ReadMeta(conn);
+        var edgesByNode = ReadEdges(conn);
+        var nodes = ReadNodes(conn, edgesByNode);
+        return new GraphSnapshot(revision, green, red, pruned, nodes);
+    }
+
+    private static void WriteDatabase(string path, GraphSnapshot snapshot)
+    {
+        var cs = new SqliteConnectionStringBuilder { DataSource = path, Mode = SqliteOpenMode.ReadWriteCreate }.ToString();
+        using var conn = new SqliteConnection(cs);
+        conn.Open();
+
+        CreateSchema(conn);
+        using var tx = conn.BeginTransaction();
+        InsertMeta(conn, tx, snapshot);
+        InsertNodesAndEdges(conn, tx, snapshot.Nodes);
+        tx.Commit();
+        SqliteConnection.ClearPool(conn);
+    }
+
+    private static void CreateSchema(SqliteConnection conn)
+    {
+        using var cmd = conn.CreateCommand();
+        cmd.CommandText =
+            "PRAGMA journal_mode = DELETE;\n" +
+            "PRAGMA user_version = 1;\n" +
+            "CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);\n" +
+            "CREATE TABLE nodes (id INTEGER PRIMARY KEY, kind TEXT NOT NULL, name TEXT NOT NULL, is_input INTEGER NOT NULL, changed_at INTEGER NOT NULL, verified_at INTEGER NOT NULL, hash_hi INTEGER NOT NULL, hash_lo INTEGER NOT NULL, error_message TEXT);\n" +
+            "CREATE TABLE edges (from_id INTEGER NOT NULL, ord INTEGER NOT NULL, to_kind TEXT NOT NULL, to_name TEXT NOT NULL, PRIMARY KEY (from_id, ord));";
+        cmd.ExecuteNonQuery();
+    }
+
+    private static void InsertMeta(SqliteConnection conn, SqliteTransaction tx, GraphSnapshot snapshot)
+    {
+        InsertMetaPair(conn, tx, "revision", snapshot.Revision.ToString(CultureInfo.InvariantCulture));
+        InsertMetaPair(conn, tx, "green_hits", snapshot.GreenHits.ToString(CultureInfo.InvariantCulture));
+        InsertMetaPair(conn, tx, "red_evaluations", snapshot.RedEvaluations.ToString(CultureInfo.InvariantCulture));
+        InsertMetaPair(conn, tx, "pruned_evaluations", snapshot.PrunedEvaluations.ToString(CultureInfo.InvariantCulture));
+    }
+
+    private static void InsertMetaPair(SqliteConnection conn, SqliteTransaction tx, string key, string value)
+    {
+        using var cmd = conn.CreateCommand();
+        cmd.Transaction = tx;
+        cmd.CommandText = "INSERT INTO meta (key, value) VALUES ($k, $v);";
+        cmd.Parameters.AddWithValue("$k", key);
+        cmd.Parameters.AddWithValue("$v", value);
+        cmd.ExecuteNonQuery();
+    }
+
+    private static void InsertNodesAndEdges(SqliteConnection conn, SqliteTransaction tx, IReadOnlyList<GraphNodeSnapshot> nodes)
+    {
+        var ordered = nodes.OrderBy(n => n.Key.Kind, StringComparer.Ordinal).ThenBy(n => n.Key.Name, StringComparer.Ordinal).ToList();
+        for (var id = 0; id < ordered.Count; id++)
+        {
+            var node = ordered[id];
+            using (var cmd = conn.CreateCommand())
+            {
+                cmd.Transaction = tx;
+                cmd.CommandText = "INSERT INTO nodes (id, kind, name, is_input, changed_at, verified_at, hash_hi, hash_lo, error_message) VALUES ($id, $k, $n, $inp, $chg, $ver, $hi, $lo, $err);";
+                cmd.Parameters.AddWithValue("$id", id);
+                cmd.Parameters.AddWithValue("$k", node.Key.Kind);
+                cmd.Parameters.AddWithValue("$n", node.Key.Name);
+                cmd.Parameters.AddWithValue("$inp", node.IsInput ? 1 : 0);
+                cmd.Parameters.AddWithValue("$chg", node.ChangedAt);
+                cmd.Parameters.AddWithValue("$ver", node.VerifiedAt);
+                cmd.Parameters.AddWithValue("$hi", unchecked((long)node.Hash.High));
+                cmd.Parameters.AddWithValue("$lo", unchecked((long)node.Hash.Low));
+                cmd.Parameters.AddWithValue("$err", (object?)node.ErrorMessage ?? DBNull.Value);
+                cmd.ExecuteNonQuery();
+            }
+
+            for (var ord = 0; ord < node.Dependencies.Count; ord++)
+            {
+                var dep = node.Dependencies[ord];
+                using var edgeCmd = conn.CreateCommand();
+                edgeCmd.Transaction = tx;
+                edgeCmd.CommandText = "INSERT INTO edges (from_id, ord, to_kind, to_name) VALUES ($fid, $ord, $tk, $tn);";
+                edgeCmd.Parameters.AddWithValue("$fid", id);
+                edgeCmd.Parameters.AddWithValue("$ord", ord);
+                edgeCmd.Parameters.AddWithValue("$tk", dep.Kind);
+                edgeCmd.Parameters.AddWithValue("$tn", dep.Name);
+                edgeCmd.ExecuteNonQuery();
+            }
+        }
+    }
+
+    private static void VerifySchemaVersion(SqliteConnection conn)
+    {
+        using var cmd = conn.CreateCommand();
+        cmd.CommandText = "PRAGMA user_version;";
+        var version = Convert.ToInt32(cmd.ExecuteScalar(), CultureInfo.InvariantCulture);
+        if (version != SchemaVersion)
+        {
+            throw new InvalidDataException($"unsupported Cadre Celeste store schema version {version} (expected {SchemaVersion})");
+        }
+    }
+
+    private static (long Revision, long Green, long Red, long Pruned) ReadMeta(SqliteConnection conn)
+    {
+        var map = new Dictionary<string, long>(StringComparer.Ordinal);
+        using var cmd = conn.CreateCommand();
+        cmd.CommandText = "SELECT key, value FROM meta;";
+        using var reader = cmd.ExecuteReader();
+        while (reader.Read())
+        {
+            map[reader.GetString(0)] = long.Parse(reader.GetString(1), CultureInfo.InvariantCulture);
+        }
+
+        return (
+            map.GetValueOrDefault("revision"),
+            map.GetValueOrDefault("green_hits"),
+            map.GetValueOrDefault("red_evaluations"),
+            map.GetValueOrDefault("pruned_evaluations"));
+    }
+
+    private static Dictionary<int, List<NodeKey>> ReadEdges(SqliteConnection conn)
+    {
+        var edges = new Dictionary<int, List<NodeKey>>();
+        using var cmd = conn.CreateCommand();
+        cmd.CommandText = "SELECT from_id, to_kind, to_name FROM edges ORDER BY from_id, ord;";
+        using var reader = cmd.ExecuteReader();
+        while (reader.Read())
+        {
+            var fromId = reader.GetInt32(0);
+            if (!edges.TryGetValue(fromId, out var list))
+            {
+                list = [];
+                edges[fromId] = list;
+            }
+
+            list.Add(new NodeKey(reader.GetString(1), reader.GetString(2)));
+        }
+
+        return edges;
+    }
+
+    private static List<GraphNodeSnapshot> ReadNodes(SqliteConnection conn, Dictionary<int, List<NodeKey>> edgesByNode)
+    {
+        var nodes = new List<GraphNodeSnapshot>();
+        using var cmd = conn.CreateCommand();
+        cmd.CommandText = "SELECT id, kind, name, is_input, changed_at, verified_at, hash_hi, hash_lo, error_message FROM nodes ORDER BY id;";
+        using var reader = cmd.ExecuteReader();
+        while (reader.Read())
+        {
+            var id = reader.GetInt32(0);
+            var key = new NodeKey(reader.GetString(1), reader.GetString(2));
+            var hash = new ContentHash(unchecked((ulong)reader.GetInt64(6)), unchecked((ulong)reader.GetInt64(7)));
+            var err = reader.IsDBNull(8) ? null : reader.GetString(8);
+            var deps = edgesByNode.TryGetValue(id, out var list) ? (IReadOnlyList<NodeKey>)list : [];
+            nodes.Add(new GraphNodeSnapshot(key, reader.GetInt32(3) != 0, reader.GetInt64(4), reader.GetInt64(5), hash, false, err, deps));
+        }
+
+        return nodes;
+    }
+}
diff --git a/src/Progmasoft.Tazel.CadreCeleste/GraphEngine.cs b/src/Progmasoft.Tazel.CadreCeleste/GraphEngine.cs
index 21f7ed3..0b1fb8c 100644
--- a/src/Progmasoft.Tazel.CadreCeleste/GraphEngine.cs
+++ b/src/Progmasoft.Tazel.CadreCeleste/GraphEngine.cs
@@ -222,6 +222,46 @@ public sealed class GraphEngine
         }
     }
 
+    /// <summary>
+    /// Restores persisted node metadata (revisions, content hashes, and ordered dependency edges) from a
+    /// <see cref="GraphSnapshot"/> on cold daemon startup. Values remain evicted until re-evaluated or re-supplied.
+    /// </summary>
+    public void RestoreMetadata(GraphSnapshot snapshot)
+    {
+        ArgumentNullException.ThrowIfNull(snapshot);
+        lock (_stateGate)
+        {
+            if (snapshot.Revision > _revision)
+            {
+                _revision = snapshot.Revision;
+            }
+
+            foreach (var node in snapshot.Nodes)
+            {
+                var id = _interner.Intern(node.Key);
+                var depIds = new int[node.Dependencies.Count];
+                for (var i = 0; i < node.Dependencies.Count; i++)
+                {
+                    depIds[i] = _interner.Intern(node.Dependencies[i]);
+                }
+
+                _nodes[id] = new NodeRecord
+                {
+                    Id = id,
+                    IsInput = node.IsInput,
+                    Unknown = false,
+                    Value = null,
+                    ValuePresent = false,
+                    Error = node.ErrorMessage is null ? null : new InvalidOperationException(node.ErrorMessage),
+                    Hash = node.Hash,
+                    ChangedAt = node.ChangedAt,
+                    VerifiedAt = node.VerifiedAt,
+                    Dependencies = depIds,
+                };
+            }
+        }
+    }
+
     private async Task<NodeRecord> EvaluateInternalAsync(
         NodeKey key, long targetRevision, ImmutableList<int> stack, CancellationToken cancel)
     {
diff --git a/src/Progmasoft.Tazel.CadreCeleste/Progmasoft.Tazel.CadreCeleste.csproj b/src/Progmasoft.Tazel.CadreCeleste/Progmasoft.Tazel.CadreCeleste.csproj
index 8083424..394ce30 100644
--- a/src/Progmasoft.Tazel.CadreCeleste/Progmasoft.Tazel.CadreCeleste.csproj
+++ b/src/Progmasoft.Tazel.CadreCeleste/Progmasoft.Tazel.CadreCeleste.csproj
@@ -6,6 +6,9 @@
     <RootNamespace>Progmasoft.Tazel.CadreCeleste</RootNamespace>
     <IsPackable>false</IsPackable>
   </PropertyGroup>
+  <ItemGroup>
+    <PackageReference Include="Microsoft.Data.Sqlite" />
+  </ItemGroup>
   <ItemGroup>
     <InternalsVisibleTo Include="Progmasoft.Tazel" />
     <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" />
diff --git a/tests/Progmasoft.Tazel.Tests/CadreCelestePersistenceAndAbiTests.cs b/tests/Progmasoft.Tazel.Tests/CadreCelestePersistenceAndAbiTests.cs
new file mode 100644
index 0000000..1e5b78e
--- /dev/null
+++ b/tests/Progmasoft.Tazel.Tests/CadreCelestePersistenceAndAbiTests.cs
@@ -0,0 +1,135 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Progmasoft.Tazel.CadreCeleste;
+using Xunit;
+
+namespace Progmasoft.Tazel.Tests;
+
+public sealed class CadreCelestePersistenceAndAbiTests
+{
+    [Fact]
+    public async Task SqliteStoreRoundTripsGraphMetadataAndSupportsColdRestore()
+    {
+        var dir = Path.Combine(Path.GetTempPath(), $"tazel-cc-store-{Guid.NewGuid():N}");
+        Directory.CreateDirectory(dir);
+        try
+        {
+            var dbPath = Path.Combine(dir, "cadre-celeste.sqlite3");
+            var engine = new GraphEngine();
+            var headerKey = new NodeKey("header", "include/math.h");
+            var abiKey = new NodeKey("abi", "include/math.h");
+            var objKey = new NodeKey("compile", "src/app.cpp");
+
+            engine.SetInput(headerKey, "int add(int a, int b);");
+            engine.Register("abi", async (key, ctx, cancel) =>
+            {
+                var src = await ctx.GetAsync<string>(new NodeKey("header", key.Name), cancel);
+                return AbiFingerprint.HashHeaderTokens(src);
+            });
+            engine.Register("compile", async (_, ctx, cancel) =>
+            {
+                var abi = await ctx.GetAsync<ContentHash>(abiKey, cancel);
+                return $"obj:{abi}";
+            });
+
+            var initialObj = await engine.GetAsync<string>(objKey, TestContext.Current.CancellationToken);
+            var savedSnapshot = engine.Snapshot();
+            CadreCelesteStore.Save(dbPath, savedSnapshot);
+
+            var loadedSnapshot = CadreCelesteStore.Load(dbPath);
+            Assert.Equal(savedSnapshot.Revision, loadedSnapshot.Revision);
+            Assert.Equal(savedSnapshot.Nodes.Count, loadedSnapshot.Nodes.Count);
+            var restoredObjNode = loadedSnapshot.Nodes.Single(n => n.Key == objKey);
+            Assert.Equal([abiKey], restoredObjNode.Dependencies);
+
+            // Restore into a fresh cold engine and verify metadata (revision, hashes, edges) is preserved.
+            var coldEngine = new GraphEngine();
+            coldEngine.RestoreMetadata(loadedSnapshot);
+            var coldSnapshot = coldEngine.Snapshot();
+            Assert.Equal(savedSnapshot.Revision, coldSnapshot.Revision);
+            Assert.Equal(
+                savedSnapshot.Nodes.Single(n => n.Key == abiKey).Hash,
+                coldSnapshot.Nodes.Single(n => n.Key == abiKey).Hash);
+            Assert.StartsWith("obj:", initialObj, StringComparison.Ordinal);
+        }
+        finally
+        {
+            Directory.Delete(dir, recursive: true);
+        }
+    }
+
+    [Fact]
+    public async Task AbiHeaderTokenHashPrunesDownstreamOnCommentAndWhitespaceEdits()
+    {
+        var engine = new GraphEngine();
+        var headerKey = new NodeKey("header", "include/api.hpp");
+        var abiKey = new NodeKey("abi", "include/api.hpp");
+        var downstreamKey = new NodeKey("compile", "src/consumer.cpp");
+        var downstreamBuilds = 0;
+
+        engine.Register("abi", async (key, ctx, cancel) =>
+        {
+            var src = await ctx.GetAsync<string>(new NodeKey("header", key.Name), cancel);
+            return AbiFingerprint.HashHeaderTokens(src);
+        });
+        engine.Register("compile", async (_, ctx, cancel) =>
+        {
+            var abi = await ctx.GetAsync<ContentHash>(abiKey, cancel);
+            downstreamBuilds++;
+            return $"compiled:{abi}";
+        });
+
+        engine.SetInput(headerKey, """
+            #pragma once
+            // Public API
+            struct Vec2 { float x; float y; };
+            inline float dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
+            """);
+        await engine.GetAsync<string>(downstreamKey, TestContext.Current.CancellationToken);
+        Assert.Equal(1, downstreamBuilds);
+
+        // Non-ABI edit: comments and whitespace only -> 0 downstream rebuilds!
+        engine.SetInput(headerKey, """
+            #pragma once
+            /* Updated documentation comment explaining dot product */
+            struct   Vec2   {   float x;   float y;   };
+            inline float dot(Vec2 a, Vec2 b) {   return a.x * b.x + a.y * b.y;   } // trailing note
+            """);
+        await engine.GetAsync<string>(downstreamKey, TestContext.Current.CancellationToken);
+        Assert.Equal(1, downstreamBuilds);
+
+        // ABI-affecting edit: inline body changed -> MUST rebuild downstream!
+        engine.SetInput(headerKey, """
+            #pragma once
+            struct Vec2 { float x; float y; };
+            inline float dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y + 1.0f; }
+            """);
+        await engine.GetAsync<string>(downstreamKey, TestContext.Current.CancellationToken);
+        Assert.Equal(2, downstreamBuilds);
+
+        // ABI-affecting edit: struct layout field added -> MUST rebuild downstream!
+        engine.SetInput(headerKey, """
+            #pragma once
+            struct Vec2 { float x; float y; float z; };
+            inline float dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y + 1.0f; }
+            """);
+        await engine.GetAsync<string>(downstreamKey, TestContext.Current.CancellationToken);
+        Assert.Equal(3, downstreamBuilds);
+    }
+
+    [Fact]
+    public void ExportedSymbolFingerprintIsOrderIndependentAndSensitiveToSignatureChanges()
+    {
+        var a = AbiFingerprint.HashExportedSymbols(["_Z3addii", "_Z3subii"]);
+        var b = AbiFingerprint.HashExportedSymbols(["_Z3subii", "_Z3addii"]);
+        var c = AbiFingerprint.HashExportedSymbols(["_Z3addll", "_Z3subii"]);
+
+        Assert.Equal(a, b);
+        Assert.NotEqual(a, c);
+    }
+}