/** * Regression tests for critical bugs found and fixed in the implementation. * Each test documents a specific bug and ensures it doesn't reoccur. * * This file serves as: * 1. Documentation of bugs found during development * 2. Protection against regressions * 3. Examples of edge cases that were problematic */ import { describe, expect, it, } from "vitest"; import { createTestDb, } from "../db/test-db-factory.js"; import { ImmutableTree, } from "../immutable-tree.js"; import { MutableTree, } from "../mutable-tree.js"; import { Node, } from "../node.js"; import { NodeKey, } from "../node-key.js"; import { NodeDB, } from "../storage/node-db.js"; import { DEFAULT_OPTIONS, } from "../types/options.js"; const encoder = new TextEncoder(); describe("Regression Tests", () => { describe("Issue #1: getWorkingHash() fails with unsaved nodes", () => { it("should compute working hash after set operations without saving", async () => { // Bug: getWorkingHash() threw "Left/Right child hash must be computed before parent" // Root Cause: computeHash() expects child nodes to have either: // - Pre-computed hash (hash !== null), OR // - A nodeKey (node has been persisted) // Unsaved nodes from set() have both hash=null and nodeKey=null // // Fix: Use computeHashWithDescendants() instead of computeHash() // Commit: ff83fea7 const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); // Set multiple keys without saving (creates unsaved nodes) await mutableTree.set(encoder.encode("key1"), encoder.encode("value1")); await mutableTree.set(encoder.encode("key2"), encoder.encode("value2")); await mutableTree.set(encoder.encode("key3"), encoder.encode("value3")); // This should NOT throw an error const hash1 = mutableTree.getWorkingHash(); expect(hash1).not.toBeNull(); expect(hash1!.length).toBe(32); // Adding more keys should change the hash await mutableTree.set(encoder.encode("key4"), encoder.encode("value4")); const hash2 = mutableTree.getWorkingHash(); expect(Buffer.from(hash1!).equals(Buffer.from(hash2!))).toBe(false); // Multiple calls without changes should return same hash const hash3 = mutableTree.getWorkingHash(); expect(Buffer.from(hash2!).equals(Buffer.from(hash3!))).toBe(true); await ctx.cleanup(); }); it("should compute working hash for complex tree structures", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); // Create a tree that will have multiple levels for (let i = 0; i < 10; i++) { await mutableTree.set(encoder.encode(`key${i.toString().padStart(3, "0")}`), encoder.encode(`value${i}`)); } // Should handle nested branch nodes const hash = mutableTree.getWorkingHash(); expect(hash).not.toBeNull(); expect(hash!.length).toBe(32); await ctx.cleanup(); }); }); describe("Issue #2: saveNewNodes creates self-reference overwriting root data", () => { it("should not overwrite root node data when saving new nodes", async () => { // Bug: saveNewNodes() called saveRoot() at the end, creating a self-reference // When root has nonce=1: // - saveNode stores 45-byte serialized data at key s<1> // - saveRoot writes 13-byte reference at the SAME key // - This overwrites the node data, causing "child not found" errors // // Fix: Remove saveRoot() call from saveNewNodes() // Commit: 773957f1 const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, { ...DEFAULT_OPTIONS, sync: true, }); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); // Set keys to create a branch node await mutableTree.set(encoder.encode("key1"), encoder.encode("value1")); await mutableTree.set(encoder.encode("key2"), encoder.encode("value2")); await mutableTree.set(encoder.encode("key3"), encoder.encode("value3")); const saveResult = await mutableTree.saveVersion(); const savedHash = saveResult.hash; // Verify root was saved correctly by loading it const rootNodeKey = await nodeDB.getRoot(1n); expect(rootNodeKey).not.toBeNull(); // Load the root node - this would fail if data was overwritten const rootNode = await nodeDB.getNode(rootNodeKey!); expect(rootNode).not.toBeNull(); // Create immutable tree from loaded root const loadedTree = new ImmutableTree(rootNode!, nodeDB, 1n); // Verify all data is accessible (would fail if nodes were corrupted) expect(await loadedTree.get(encoder.encode("key1"))).toEqual(encoder.encode("value1")); expect(await loadedTree.get(encoder.encode("key2"))).toEqual(encoder.encode("value2")); expect(await loadedTree.get(encoder.encode("key3"))).toEqual(encoder.encode("value3")); // Verify hash matches expect(loadedTree.hash()).toEqual(savedHash); await ctx.cleanup(); }); it("should properly save and load trees across multiple versions", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, { ...DEFAULT_OPTIONS, sync: true, }); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); const hashes: Uint8Array[] = []; // Save 5 versions for (let i = 1; i <= 5; i++) { await mutableTree.set(encoder.encode(`key${i}`), encoder.encode(`value${i}`)); const result = await mutableTree.saveVersion(); hashes.push(result.hash); } // Load each version and verify for (let i = 1; i <= 5; i++) { const rootNodeKey = await nodeDB.getRoot(BigInt(i)); expect(rootNodeKey).not.toBeNull(); const rootNode = await nodeDB.getNode(rootNodeKey!); expect(rootNode).not.toBeNull(); const tree = new ImmutableTree(rootNode!, nodeDB, BigInt(i)); // Verify cumulative data for (let j = 1; j <= i; j++) { const value = await tree.get(encoder.encode(`key${j}`)); expect(value).toEqual(encoder.encode(`value${j}`)); } // Verify hash expect(tree.hash()).toEqual(hashes[i - 1]); } await ctx.cleanup(); }); }); describe("Issue #3: getRoot incorrectly detects references by length", () => { it("should correctly detect references by prefix byte, not length", async () => { // Bug: getRoot() assumed 32-byte values were legacy hashes // This failed when 32-byte serialized node data was stored // // Fix: Detect references by checking first byte == 0x73 ('s' prefix) // Commit: 773957f1 const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, { ...DEFAULT_OPTIONS, sync: true, }); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); // Create a tree with a single key (will be a leaf node) // When serialized, this might be around 32 bytes await mutableTree.set(encoder.encode("test-key-1"), encoder.encode("test-value-1")); const result = await mutableTree.saveVersion(); expect(result.version).toBe(1n); // Load the version - this tests getRoot() with potentially 32-byte data const rootNodeKey = await nodeDB.getRoot(1n); expect(rootNodeKey).not.toBeNull(); const rootNode = await nodeDB.getNode(rootNodeKey!); expect(rootNode).not.toBeNull(); const loadedTree = new ImmutableTree(rootNode!, nodeDB, 1n); expect(await loadedTree.get(encoder.encode("test-key-1"))).toEqual(encoder.encode("test-value-1")); await ctx.cleanup(); }); it("should handle reference roots (version reuse) correctly", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, { ...DEFAULT_OPTIONS, sync: true, }); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); // Create version 1 await mutableTree.set(encoder.encode("key1"), encoder.encode("value1")); const result1 = await mutableTree.saveVersion(); // Save version 2 without changes (idempotent save returns same version) const result2 = await mutableTree.saveVersion(); expect(result2.version).toBe(1n); // Idempotent - no changes, returns same version expect(result2.hash).toEqual(result1.hash); // Make a change and save version 2 await mutableTree.set(encoder.encode("key2"), encoder.encode("value2")); const result3 = await mutableTree.saveVersion(); expect(result3.version).toBe(2n); // Load version 1 (should have only key1) const rootNodeKey1 = await nodeDB.getRoot(1n); expect(rootNodeKey1).not.toBeNull(); const rootNode1 = await nodeDB.getNode(rootNodeKey1!); const tree1 = new ImmutableTree(rootNode1!, nodeDB, 1n); expect(await tree1.get(encoder.encode("key1"))).toEqual(encoder.encode("value1")); expect(await tree1.get(encoder.encode("key2"))).toBeNull(); // Load version 2 (should have both keys) const rootNodeKey2 = await nodeDB.getRoot(2n); const rootNode2 = await nodeDB.getNode(rootNodeKey2!); const tree2 = new ImmutableTree(rootNode2!, nodeDB, 2n); expect(await tree2.get(encoder.encode("key1"))).toEqual(encoder.encode("value1")); expect(await tree2.get(encoder.encode("key2"))).toEqual(encoder.encode("value2")); await ctx.cleanup(); }); }); describe("Issue #4: CrossKvDB persistence failures", () => { it("should persist and reload data correctly with sync option", async () => { // Bug: Data wasn't being flushed to disk before database close // Root Cause: // - sync option wasn't implemented in NodeDB.commit() // - @cross/kv needs time to flush writes asynchronously // // Fix: Implement sync support and add flush delays // Commit: 212ad5e8 const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, { ...DEFAULT_OPTIONS, sync: true, }); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); // Add data await mutableTree.set(encoder.encode("persist-key"), encoder.encode("persist-value")); const result = await mutableTree.saveVersion(); // Note: With sync:true, data should be flushed expect(result.version).toBe(1n); // Verify data is accessible expect(await mutableTree.get(encoder.encode("persist-key"))).toEqual(encoder.encode("persist-value")); await ctx.cleanup(); }); }); describe("AVL Tree Balance Invariants", () => { it("should maintain balance factor |bf| <= 1 after random operations", async () => { // Ensures AVL balance property is maintained // This catches issues with rotation logic const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); // Helper to check balance recursively const checkBalance = (node: Node): void => { if (!node || node.isLeaf()) return; const balance = node.getBalanceFactor(); expect(Math.abs(balance)).toBeLessThanOrEqual(1); if (node.leftNode) checkBalance(node.leftNode); if (node.rightNode) checkBalance(node.rightNode); }; // Perform random operations const keys = []; for (let i = 0; i < 100; i++) { const key = encoder.encode(`key${i.toString().padStart(5, "0")}`); const value = encoder.encode(`value${i}`); keys.push(key); await mutableTree.set(key, value); // Check balance after every 10 operations if (i % 10 === 9 && mutableTree.getRoot()) { checkBalance(mutableTree.getRoot()!); } } // Final balance check if (mutableTree.getRoot()) { checkBalance(mutableTree.getRoot()!); } await ctx.cleanup(); }); it("should maintain tree height within AVL bounds", async () => { // AVL tree height should be h <= 1.44 * log2(n) // This is a fundamental AVL property const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); const n = 1000; for (let i = 0; i < n; i++) { await mutableTree.set(encoder.encode(`key${i.toString().padStart(5, "0")}`), encoder.encode(`value${i}`)); } const height = mutableTree.getWorkingTree().height(); const maxHeight = Math.ceil(1.44 * Math.log2(n)); expect(height).toBeLessThanOrEqual(maxHeight); await ctx.cleanup(); }); }); describe("Hash Determinism and Consistency", () => { it("should produce identical hashes for identical operation sequences", async () => { // Ensures hash computation is deterministic const operations = [ { key: "apple", value: "red", }, { key: "banana", value: "yellow", }, { key: "cherry", value: "red", }, { key: "date", value: "brown", }, ]; const hashes: Uint8Array[] = []; // Run twice with same operations for (let run = 0; run < 2; run++) { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); for (const op of operations) { await mutableTree.set(encoder.encode(op.key), encoder.encode(op.value)); } const result = await mutableTree.saveVersion(); hashes.push(result.hash); await ctx.cleanup(); } // Both runs should produce identical hash expect(Buffer.from(hashes[0]).equals(Buffer.from(hashes[1]))).toBe(true); }); it("should produce consistent working hash across multiple calls", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); await mutableTree.set(encoder.encode("key"), encoder.encode("value")); // Multiple calls without changes should return same hash const hash1 = mutableTree.getWorkingHash(); const hash2 = mutableTree.getWorkingHash(); const hash3 = mutableTree.getWorkingHash(); expect(Buffer.from(hash1!).equals(Buffer.from(hash2!))).toBe(true); expect(Buffer.from(hash2!).equals(Buffer.from(hash3!))).toBe(true); await ctx.cleanup(); }); }); describe("Node Serialization Correctness", () => { it("should correctly serialize and deserialize branch nodes with child keys", async () => { // Ensures child node keys are preserved through serialization const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); // Create a branch node manually const leaf1 = Node.newLeafNode(encoder.encode("a"), encoder.encode("value-a")); leaf1.nodeKey = new NodeKey(1n, 2); const leaf2 = Node.newLeafNode(encoder.encode("b"), encoder.encode("value-b")); leaf2.nodeKey = new NodeKey(1n, 3); const branch = Node.newBranchNode(leaf1, leaf2); branch.nodeKey = new NodeKey(1n, 1); branch.leftNodeKey = leaf1.nodeKey.toBytes(); branch.rightNodeKey = leaf2.nodeKey.toBytes(); branch.computeHash(1n); // Serialize const serialized = branch.toBytes(); expect(serialized.length).toBeGreaterThan(0); // Deserialize const deserialized = Node.fromBytes(branch.nodeKey.toBytes(), serialized); // Verify child keys are preserved expect(deserialized.leftNodeKey).toEqual(branch.leftNodeKey); expect(deserialized.rightNodeKey).toEqual(branch.rightNodeKey); expect(deserialized.hash).toEqual(branch.hash); expect(deserialized.subtreeHeight).toBe(branch.subtreeHeight); expect(deserialized.size).toBe(branch.size); await ctx.cleanup(); }); it("should handle leaf node serialization round-trip", async () => { const ctx = await createTestDb(); const key = encoder.encode("test-key"); const value = encoder.encode("test-value"); const leaf = Node.newLeafNode(key, value); leaf.nodeKey = new NodeKey(5n, 10); leaf.computeHash(5n); const serialized = leaf.toBytes(); const deserialized = Node.fromBytes(leaf.nodeKey.toBytes(), serialized); expect(deserialized.key).toEqual(leaf.key); expect(deserialized.value).toEqual(leaf.value); expect(deserialized.hash).toEqual(leaf.hash); expect(deserialized.nodeKey?.version).toBe(5n); expect(deserialized.nodeKey?.nonce).toBe(10); await ctx.cleanup(); }); }); describe("Edge Cases", () => { it("should handle empty tree correctly", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); expect(mutableTree.getWorkingHash()).toBeNull(); expect(mutableTree.getSize()).toBe(0n); expect(mutableTree.getWorkingTree().height()).toBe(0); await ctx.cleanup(); }); it("should handle single key tree correctly", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); await mutableTree.set(encoder.encode("single"), encoder.encode("value")); const result = await mutableTree.saveVersion(); expect(mutableTree.getSize()).toBe(1n); expect(mutableTree.getWorkingTree().height()).toBe(0); // Single leaf has height 0 // Reload and verify const rootNodeKey = await nodeDB.getRoot(1n); const rootNode = await nodeDB.getNode(rootNodeKey!); const loadedTree = new ImmutableTree(rootNode!, nodeDB, 1n); expect(await loadedTree.get(encoder.encode("single"))).toEqual(encoder.encode("value")); expect(loadedTree.hash()).toEqual(result.hash); await ctx.cleanup(); }); it("should handle update of existing key correctly", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); const key = encoder.encode("update-key"); // Initial set const updated1 = await mutableTree.set(key, encoder.encode("value1")); expect(updated1).toBe(false); // New key // Update const updated2 = await mutableTree.set(key, encoder.encode("value2")); expect(updated2).toBe(true); // Existing key // Verify final value expect(await mutableTree.get(key)).toEqual(encoder.encode("value2")); await ctx.cleanup(); }); it("should maintain size correctly during mixed operations", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); // Add 5 keys for (let i = 0; i < 5; i++) { await mutableTree.set(encoder.encode(`key${i}`), encoder.encode(`value${i}`)); } expect(mutableTree.getSize()).toBe(5n); // Update 2 keys (size should stay same) await mutableTree.set(encoder.encode("key0"), encoder.encode("updated0")); await mutableTree.set(encoder.encode("key2"), encoder.encode("updated2")); expect(mutableTree.getSize()).toBe(5n); // Remove 2 keys await mutableTree.remove(encoder.encode("key1")); await mutableTree.remove(encoder.encode("key3")); expect(mutableTree.getSize()).toBe(3n); await ctx.cleanup(); }); }); describe("Version Management", () => { it("should handle version 0 correctly (empty initial state)", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree); expect(mutableTree.getVersion()).toBe(0n); expect(mutableTree.getWorkingVersion()).toBe(1n); await ctx.cleanup(); }); it("should increment version correctly after each save", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); // skipFastStorageUpgrade for (let i = 1; i <= 5; i++) { await mutableTree.set(encoder.encode(`key${i}`), encoder.encode(`value${i}`)); await mutableTree.saveVersion(); expect(mutableTree.getVersion()).toBe(BigInt(i)); expect(mutableTree.getWorkingVersion()).toBe(BigInt(i + 1)); } await ctx.cleanup(); }); }); describe("Memory and Reference Handling", () => { it("should not retain references to cleared child nodes after save", async () => { // After saving, child nodes should be cleared to free memory // This test verifies the cleanup happens const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const mutableTree = new MutableTree(nodeDB, workingTree, true); // Create a tree with multiple nodes for (let i = 0; i < 10; i++) { await mutableTree.set(encoder.encode(`key${i}`), encoder.encode(`value${i}`)); } await mutableTree.saveVersion(); // After save, child references in saved nodes should be cleared // But tree should still be accessible (nodes loaded from cache/db as needed) expect(await mutableTree.get(encoder.encode("key5"))).toEqual(encoder.encode("value5")); await ctx.cleanup(); }); }); });