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 type { FastNode, } from "./storage/fast-node.js"; import { NodeDB, } from "./storage/node-db.js"; import { DEFAULT_OPTIONS, } from "./types/options.js"; describe("MutableTree - Get and Set Operations", () => { describe("get operations", () => { it("should return null for empty tree", 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 = new TextEncoder().encode("testkey"); const value = await mutableTree.get(key); expect(value).toBe(null); }); it("should get value from working tree", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); // Create a tree with a node const { Node, } = await import("./node.js"); const { NodeKey, } = await import("./node-key.js"); const key = new TextEncoder().encode("testkey"); const value = new TextEncoder().encode("testvalue"); const node = Node.newLeafNode(key, value); node.nodeKey = new NodeKey(1n, 1); node.computeHash(1n); const workingTree = new ImmutableTree(node, nodeDB, 1n, false); const mutableTree = new MutableTree(nodeDB, workingTree); const result = await mutableTree.get(key); expect(result).not.toBe(null); expect(result).toEqual(value); }); it("should return null for non-existent key", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); // Create a tree with a node const { Node, } = await import("./node.js"); const { NodeKey, } = await import("./node-key.js"); const key = new TextEncoder().encode("testkey"); const value = new TextEncoder().encode("testvalue"); const node = Node.newLeafNode(key, value); node.nodeKey = new NodeKey(1n, 1); node.computeHash(1n); const workingTree = new ImmutableTree(node, nodeDB, 1n, false); const mutableTree = new MutableTree(nodeDB, workingTree); const otherKey = new TextEncoder().encode("otherkey"); const result = await mutableTree.get(otherKey); expect(result).toBe(null); }); it("should get value from unsaved fast node additions", 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); // Manually add a fast node to unsaved additions (simulating a set operation) const { FastNode, } = await import("./storage/fast-node.js"); const key = new TextEncoder().encode("newkey"); const value = new TextEncoder().encode("newvalue"); const fastNode = new FastNode(key, value, 1n); const keyStr = Buffer.from(key).toString("hex"); // Access private field for testing type MutableTreePrivate = { unsavedFastNodeAdditions: Map }; (mutableTree as unknown as MutableTreePrivate).unsavedFastNodeAdditions.set(keyStr, fastNode); const result = await mutableTree.get(key); expect(result).not.toBe(null); expect(result).toEqual(value); }); it("should return null for key in unsaved removals", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); // Create a tree with a node const { Node, } = await import("./node.js"); const { NodeKey, } = await import("./node-key.js"); const key = new TextEncoder().encode("testkey"); const value = new TextEncoder().encode("testvalue"); const node = Node.newLeafNode(key, value); node.nodeKey = new NodeKey(1n, 1); node.computeHash(1n); const workingTree = new ImmutableTree(node, nodeDB, 1n, false); const mutableTree = new MutableTree(nodeDB, workingTree); // Mark key as removed (simulating a delete operation) const keyStr = Buffer.from(key).toString("hex"); type MutableTreePrivate = { unsavedFastNodeRemovals: Map }; (mutableTree as unknown as MutableTreePrivate).unsavedFastNodeRemovals.set(keyStr, true); const result = await mutableTree.get(key); // Should return null even though key exists in tree expect(result).toBe(null); }); it("should prioritize unsaved additions over tree data", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); // Create a tree with a node const { Node, } = await import("./node.js"); const { NodeKey, } = await import("./node-key.js"); const key = new TextEncoder().encode("testkey"); const oldValue = new TextEncoder().encode("oldvalue"); const node = Node.newLeafNode(key, oldValue); node.nodeKey = new NodeKey(1n, 1); node.computeHash(1n); const workingTree = new ImmutableTree(node, nodeDB, 1n, false); const mutableTree = new MutableTree(nodeDB, workingTree); // Add an unsaved update const { FastNode, } = await import("./storage/fast-node.js"); const newValue = new TextEncoder().encode("newvalue"); const fastNode = new FastNode(key, newValue, 2n); const keyStr = Buffer.from(key).toString("hex"); type MutableTreePrivate = { unsavedFastNodeAdditions: Map }; (mutableTree as unknown as MutableTreePrivate).unsavedFastNodeAdditions.set(keyStr, fastNode); const result = await mutableTree.get(key); // Should return new value from unsaved additions expect(result).not.toBe(null); expect(result).toEqual(newValue); expect(result).not.toEqual(oldValue); }); it("should skip fast storage checks when skipFastStorageUpgrade is true", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); // Create a tree with a node const { Node, } = await import("./node.js"); const { NodeKey, } = await import("./node-key.js"); const key = new TextEncoder().encode("testkey"); const value = new TextEncoder().encode("testvalue"); const node = Node.newLeafNode(key, value); node.nodeKey = new NodeKey(1n, 1); node.computeHash(1n); const workingTree = new ImmutableTree(node, nodeDB, 1n, true); const mutableTree = new MutableTree(nodeDB, workingTree, true); // Add an unsaved fast node (should be ignored) const { FastNode, } = await import("./storage/fast-node.js"); const newValue = new TextEncoder().encode("newvalue"); const fastNode = new FastNode(key, newValue, 2n); const keyStr = Buffer.from(key).toString("hex"); type MutableTreePrivate = { unsavedFastNodeAdditions: Map }; (mutableTree as unknown as MutableTreePrivate).unsavedFastNodeAdditions.set(keyStr, fastNode); const result = await mutableTree.get(key); // Should return old value from tree (ignoring unsaved additions) expect(result).not.toBe(null); expect(result).toEqual(value); expect(result).not.toEqual(newValue); }); }); }); describe("MutableTree - Set Operations", () => { describe("set operations", () => { it("should set a key-value pair in empty tree", 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 = Buffer.from("key"); const value = Buffer.from("value"); const updated = await mutableTree.set(key, value); expect(updated).toBe(false); // New insertion expect(mutableTree.getSize()).toBe(1n); expect(await mutableTree.get(key)).toEqual(value); }); it("should throw error when setting null value", 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 = Buffer.from("key"); await expect(mutableTree.set(key, null as unknown as Uint8Array)) .rejects .toThrow("Attempt to store nil value"); }); it("should update existing key-value pair", 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 = Buffer.from("key"); const value1 = Buffer.from("value1"); const value2 = Buffer.from("value2"); // First insertion const updated1 = await mutableTree.set(key, value1); expect(updated1).toBe(false); // New insertion expect(await mutableTree.get(key)).toEqual(value1); // Update const updated2 = await mutableTree.set(key, value2); expect(updated2).toBe(true); // Update expect(await mutableTree.get(key)).toEqual(value2); expect(mutableTree.getSize()).toBe(1n); // Size unchanged }); it("should insert multiple keys in ascending order", 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 keys = [ "a", "b", "c", "d", "e", ]; for (const k of keys) { const key = Buffer.from(k); const value = Buffer.from(`value-${k}`); const updated = await mutableTree.set(key, value); expect(updated).toBe(false); // All new insertions } expect(mutableTree.getSize()).toBe(BigInt(keys.length)); // Verify all keys exist for (const k of keys) { const key = Buffer.from(k); const value = await mutableTree.get(key); expect(value).toEqual(Buffer.from(`value-${k}`)); } }); it("should insert multiple keys in descending order", 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 keys = [ "e", "d", "c", "b", "a", ]; for (const k of keys) { const key = Buffer.from(k); const value = Buffer.from(`value-${k}`); const updated = await mutableTree.set(key, value); expect(updated).toBe(false); // All new insertions } expect(mutableTree.getSize()).toBe(BigInt(keys.length)); // Verify all keys exist for (const k of keys) { const key = Buffer.from(k); const value = await mutableTree.get(key); expect(value).toEqual(Buffer.from(`value-${k}`)); } }); it("should insert multiple keys in random order", 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 keys = [ "m", "d", "x", "a", "p", "f", "z", ]; for (const k of keys) { const key = Buffer.from(k); const value = Buffer.from(`value-${k}`); const updated = await mutableTree.set(key, value); expect(updated).toBe(false); // All new insertions } expect(mutableTree.getSize()).toBe(BigInt(keys.length)); // Verify all keys exist for (const k of keys) { const key = Buffer.from(k); const value = await mutableTree.get(key); expect(value).toEqual(Buffer.from(`value-${k}`)); } }); it("should handle mix of insertions and updates", 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); // Insert initial keys await mutableTree.set(Buffer.from("a"), Buffer.from("1")); await mutableTree.set(Buffer.from("b"), Buffer.from("2")); await mutableTree.set(Buffer.from("c"), Buffer.from("3")); expect(mutableTree.getSize()).toBe(3n); // Update existing keys const updated1 = await mutableTree.set(Buffer.from("b"), Buffer.from("22")); expect(updated1).toBe(true); expect(await mutableTree.get(Buffer.from("b"))).toEqual(Buffer.from("22")); // Insert new key const updated2 = await mutableTree.set(Buffer.from("d"), Buffer.from("4")); expect(updated2).toBe(false); expect(mutableTree.getSize()).toBe(4n); }); it("should track unsaved fast node additions", 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 = Buffer.from("key"); const value = Buffer.from("value"); await mutableTree.set(key, value); // Check unsaved additions (accessing private field for testing) type MutableTreePrivate = { unsavedFastNodeAdditions: Map }; const additions = (mutableTree as unknown as MutableTreePrivate).unsavedFastNodeAdditions; const keyStr = Buffer.from(key).toString("hex"); expect(additions.has(keyStr)).toBe(true); const fastNode = additions.get(keyStr); expect(fastNode?.key).toEqual(key); expect(fastNode?.value).toEqual(value); expect(fastNode?.versionLastUpdatedAt).toBe(1n); // Working version }); it("should skip fast storage when skipFastStorageUpgrade is true", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n, true); const mutableTree = new MutableTree(nodeDB, workingTree, true); const key = Buffer.from("key"); const value = Buffer.from("value"); await mutableTree.set(key, value); // Check unsaved additions should be empty type MutableTreePrivate = { unsavedFastNodeAdditions: Map }; const additions = (mutableTree as unknown as MutableTreePrivate).unsavedFastNodeAdditions; const keyStr = Buffer.from(key).toString("hex"); expect(additions.has(keyStr)).toBe(false); }); }); describe("Set Operation with Balancing", () => { it("should maintain AVL property after insertions", 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 tree = new MutableTree(nodeDB, workingTree); // Insert keys in ascending order (worst case for unbalanced tree) for (let i = 1; i <= 10; i++) { await tree.set(Buffer.from(`key${i}`), Buffer.from(`value${i}`)); } // Verify AVL property: all nodes have balance factor between -1 and 1 // eslint-disable-next-line @typescript-eslint/no-explicit-any const checkBalance = (node: any): void => { if (!node || node.isLeaf()) { return; } const balance = node.getBalanceFactor(); expect(balance).toBeLessThanOrEqual(1); expect(balance).toBeGreaterThanOrEqual(-1); checkBalance(node.leftNode); checkBalance(node.rightNode); }; checkBalance(tree.getRoot()); }); it("should keep tree height logarithmic", 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 tree = new MutableTree(nodeDB, workingTree); // Insert 15 keys in worst-case order (ascending) for (let i = 1; i <= 15; i++) { await tree.set(Buffer.from(`key${String(i).padStart(2, "0")}`), Buffer.from(`value${i}`)); } const root = tree.getRoot(); expect(root).not.toBeNull(); // For 15 nodes, balanced tree height should be ~4 (log2(15) ≈ 3.9) // Unbalanced tree would be height 14 expect(root!.subtreeHeight).toBeLessThanOrEqual(5); expect(root!.subtreeHeight).toBeGreaterThanOrEqual(3); }); it("should handle random insertions with balancing", 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 tree = new MutableTree(nodeDB, workingTree); // Insert keys in random-ish order const keys = [ "m", "d", "s", "a", "h", "p", "w", "b", "f", "k", "n", "r", "u", ]; for (const key of keys) { await tree.set(Buffer.from(key), Buffer.from(`value-${key}`)); } // Verify tree is balanced // eslint-disable-next-line @typescript-eslint/no-explicit-any const checkBalance = (node: any): void => { if (!node || node.isLeaf()) { return; } const balance = node.getBalanceFactor(); expect(balance).toBeLessThanOrEqual(1); expect(balance).toBeGreaterThanOrEqual(-1); checkBalance(node.leftNode); checkBalance(node.rightNode); }; const root = tree.getRoot(); checkBalance(root); // Verify all values are accessible for (const key of keys) { const value = await tree.get(Buffer.from(key)); expect(value).toEqual(Buffer.from(`value-${key}`)); } }); }); });