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 { NodeDB, } from "./storage/node-db.js"; import { DEFAULT_OPTIONS, } from "./types/options.js"; describe("MutableTree - Rotation and Balance Operations", () => { describe("Rotation Operations", () => { it("should perform right rotation 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); // Create unbalanced tree (left-heavy): // 3 // / // 2 // / // 1 await mutableTree.set(Buffer.from("3"), Buffer.from("three")); await mutableTree.set(Buffer.from("2"), Buffer.from("two")); await mutableTree.set(Buffer.from("1"), Buffer.from("one")); // Access private rotateRight method for testing type MutableTreePrivate = { rotateRight(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; const root = mutableTree.getRoot(); expect(root).not.toBeNull(); expect(root!.key).toEqual(Buffer.from("3")); // Rotate right on root const newRoot = await privateTree.rotateRight(root!); // After right rotation: // 2 // / \ // 1 3 expect(newRoot.key).toEqual(Buffer.from("2")); expect(newRoot.leftNode).not.toBeNull(); expect(newRoot.leftNode!.key).toEqual(Buffer.from("1")); expect(newRoot.rightNode).not.toBeNull(); expect(newRoot.rightNode!.key).toEqual(Buffer.from("3")); // Check heights and sizes are correct // After rotation: newRoot("2") has left=leaf("1"), right=branch("3" with 2 leaves) // Size = total number of leaves = 3 (keys "1", "2", "3") // Height = max(0, 1) + 1 = 2 expect(newRoot.subtreeHeight).toBe(2); expect(newRoot.size).toBe(3n); }); it("should perform left rotation 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); // Create unbalanced tree (right-heavy): // 1 // \ // 2 // \ // 3 await mutableTree.set(Buffer.from("1"), Buffer.from("one")); await mutableTree.set(Buffer.from("2"), Buffer.from("two")); await mutableTree.set(Buffer.from("3"), Buffer.from("three")); // Access private rotateLeft method for testing type MutableTreePrivate = { rotateLeft(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; const root = mutableTree.getRoot(); expect(root).not.toBeNull(); expect(root!.key).toEqual(Buffer.from("2")); // Root is branch with key="2" // Rotate left on root const newRoot = await privateTree.rotateLeft(root!); // After left rotation: // 3 // / \ // 2 (leaf 3) // / \ // 1 2 (leaves) // Note: Keys on branch nodes don't change during rotation expect(newRoot.key).toEqual(Buffer.from("3")); expect(newRoot.leftNode).not.toBeNull(); expect(newRoot.leftNode!.key).toEqual(Buffer.from("2")); // Original root, key unchanged expect(newRoot.rightNode).not.toBeNull(); expect(newRoot.rightNode!.key).toEqual(Buffer.from("3")); // Check heights and sizes are correct // After rotation: newRoot("3") has left=branch("2" with 2 leaves), right=leaf("3") // Size = total number of leaves = 3 (keys "1", "2", "3") // Height = max(1, 0) + 1 = 2 expect(newRoot.subtreeHeight).toBe(2); expect(newRoot.size).toBe(3n); }); it("should throw error when rotating right with manually created node without left child", 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); // Access private rotateRight method for testing type MutableTreePrivate = { rotateRight(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; // Manually create a branch node with only a right child (invalid tree state) const invalidNode = new Node(); invalidNode.key = Buffer.from("test"); invalidNode.subtreeHeight = 1; invalidNode.size = 1n; invalidNode.leftNode = null; // No left child invalidNode.rightNode = Node.newLeafNode(Buffer.from("right"), Buffer.from("value")); // Attempting right rotation should throw await expect(privateTree.rotateRight(invalidNode)).rejects.toThrow( "Cannot rotate right: node has no left child", ); }); it("should throw error when rotating left with manually created node without right child", 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); // Access private rotateLeft method for testing type MutableTreePrivate = { rotateLeft(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; // Manually create a branch node with only a left child (invalid tree state) const invalidNode = new Node(); invalidNode.key = Buffer.from("test"); invalidNode.subtreeHeight = 1; invalidNode.size = 1n; invalidNode.leftNode = Node.newLeafNode(Buffer.from("left"), Buffer.from("value")); invalidNode.rightNode = null; // No right child // Attempting left rotation should throw await expect(privateTree.rotateLeft(invalidNode)).rejects.toThrow( "Cannot rotate left: node has no right child", ); }); it("should maintain tree values after rotation", 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 left-heavy tree await mutableTree.set(Buffer.from("c"), Buffer.from("C")); await mutableTree.set(Buffer.from("b"), Buffer.from("B")); await mutableTree.set(Buffer.from("a"), Buffer.from("A")); // Access private rotateRight method type MutableTreePrivate = { rotateRight(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; const root = mutableTree.getRoot(); const newRoot = await privateTree.rotateRight(root!); // Verify all keys are still accessible (in-order traversal of leaves only) const keys: string[] = []; const values: string[] = []; const collectNodes = (node: Node | null): void => { if (!node) return; collectNodes(node.leftNode); // Only collect leaf nodes (which have values) if (node.isLeaf() && node.value) { keys.push(Buffer.from(node.key!).toString()); values.push(Buffer.from(node.value).toString()); } collectNodes(node.rightNode); }; collectNodes(newRoot); expect(keys).toEqual([ "a", "b", "c", ]); expect(values).toEqual([ "A", "B", "C", ]); }); it("should handle rotation with subtrees", 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 more complex tree: // 5 // / \ // 3 6 // / \ // 2 4 // / // 1 await mutableTree.set(Buffer.from("5"), Buffer.from("five")); await mutableTree.set(Buffer.from("3"), Buffer.from("three")); await mutableTree.set(Buffer.from("6"), Buffer.from("six")); await mutableTree.set(Buffer.from("2"), Buffer.from("two")); await mutableTree.set(Buffer.from("4"), Buffer.from("four")); await mutableTree.set(Buffer.from("1"), Buffer.from("one")); // Access private rotateRight method type MutableTreePrivate = { rotateRight(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; const root = mutableTree.getRoot(); const newRoot = await privateTree.rotateRight(root!); // After rotation: // 3 // / \ // 2 5 // / / \ // 1 4 6 expect(newRoot.key).toEqual(Buffer.from("3")); expect(newRoot.leftNode!.key).toEqual(Buffer.from("2")); expect(newRoot.rightNode!.key).toEqual(Buffer.from("5")); expect(newRoot.leftNode!.leftNode!.key).toEqual(Buffer.from("1")); expect(newRoot.rightNode!.leftNode!.key).toEqual(Buffer.from("4")); expect(newRoot.rightNode!.rightNode!.key).toEqual(Buffer.from("6")); // Verify size calculation expect(newRoot.size).toBe(6n); }); }); describe("Balance Operations", () => { it("should handle left-left case (single right rotation)", 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); // Access private balance method type MutableTreePrivate = { balance(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; // Manually create unbalanced left-left tree with balance > 1: // c // / // b // / // a // This has balance = 2 (left height 1, right height -1) const leafA = Node.newLeafNode(Buffer.from("a"), Buffer.from("A")); const leafB = Node.newLeafNode(Buffer.from("b"), Buffer.from("B")); const branchBWithA = new Node(); branchBWithA.key = Buffer.from("b"); branchBWithA.subtreeHeight = 1; branchBWithA.size = 2n; branchBWithA.leftNode = leafA; branchBWithA.rightNode = leafB; branchBWithA.nodeKey = null; const rootNode = new Node(); rootNode.key = Buffer.from("c"); rootNode.subtreeHeight = 2; rootNode.size = 2n; rootNode.leftNode = branchBWithA; rootNode.rightNode = null; rootNode.nodeKey = null; const balanced = await privateTree.balance(rootNode); // After balancing with left-left case (right rotation): // Should have balance factor within -1 to 1 expect(balanced.getBalanceFactor()).toBeLessThanOrEqual(1); expect(balanced.getBalanceFactor()).toBeGreaterThanOrEqual(-1); // Verify tree has correct size (2 leaves: a and b) expect(balanced.size).toBe(2n); }); it("should handle right-right case (single left rotation)", 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); // Access private balance method type MutableTreePrivate = { balance(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; // Manually create unbalanced right-right tree with balance < -1: // a // \ // b // \ // c // This has balance = -2 (left height -1, right height 1) const leafB = Node.newLeafNode(Buffer.from("b"), Buffer.from("B")); const leafC = Node.newLeafNode(Buffer.from("c"), Buffer.from("C")); const branchBWithC = new Node(); branchBWithC.key = Buffer.from("c"); branchBWithC.subtreeHeight = 1; branchBWithC.size = 2n; branchBWithC.leftNode = leafB; branchBWithC.rightNode = leafC; branchBWithC.nodeKey = null; const rootNode = new Node(); rootNode.key = Buffer.from("c"); rootNode.subtreeHeight = 2; rootNode.size = 2n; rootNode.leftNode = null; rootNode.rightNode = branchBWithC; rootNode.nodeKey = null; const balanced = await privateTree.balance(rootNode); // After balancing with right-right case (left rotation): // Should have balance factor within -1 to 1 expect(balanced.getBalanceFactor()).toBeLessThanOrEqual(1); expect(balanced.getBalanceFactor()).toBeGreaterThanOrEqual(-1); // Verify tree has correct size (2 leaves) expect(balanced.size).toBe(2n); }); it("should handle left-right case (double rotation)", 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); // Access private balance method type MutableTreePrivate = { balance(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; // Manually create unbalanced left-right tree: // d // / // b // \ // c // Left child has negative balance, requiring double rotation const leafB = Node.newLeafNode(Buffer.from("b"), Buffer.from("B")); const leafC = Node.newLeafNode(Buffer.from("c"), Buffer.from("C")); const branchBWithC = new Node(); branchBWithC.key = Buffer.from("c"); branchBWithC.subtreeHeight = 1; branchBWithC.size = 2n; branchBWithC.leftNode = leafB; branchBWithC.rightNode = leafC; branchBWithC.nodeKey = null; const rootNode = new Node(); rootNode.key = Buffer.from("d"); rootNode.subtreeHeight = 2; rootNode.size = 2n; rootNode.leftNode = branchBWithC; rootNode.rightNode = null; rootNode.nodeKey = null; const balanced = await privateTree.balance(rootNode); // After balancing with left-right case (double rotation): // Should have balance factor within -1 to 1 expect(balanced.getBalanceFactor()).toBeLessThanOrEqual(1); expect(balanced.getBalanceFactor()).toBeGreaterThanOrEqual(-1); // Verify tree has correct size expect(balanced.size).toBe(2n); }); it("should handle right-left case (double rotation)", 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); // Access private balance method type MutableTreePrivate = { balance(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; // Manually create unbalanced right-left tree: // c (root) // \ // c (branch) // / \ // b c (leaves) // Right child has positive balance, requiring double rotation const leafB = Node.newLeafNode(Buffer.from("b"), Buffer.from("B")); const leafC = Node.newLeafNode(Buffer.from("c"), Buffer.from("C")); const branchCWithB = new Node(); branchCWithB.key = Buffer.from("c"); branchCWithB.subtreeHeight = 1; branchCWithB.size = 2n; branchCWithB.leftNode = leafB; branchCWithB.rightNode = leafC; branchCWithB.nodeKey = null; const rootNode = new Node(); rootNode.key = Buffer.from("c"); rootNode.subtreeHeight = 2; rootNode.size = 2n; rootNode.leftNode = null; rootNode.rightNode = branchCWithB; rootNode.nodeKey = null; const balanced = await privateTree.balance(rootNode); // After balancing with right-left case (double rotation): // Should have balance factor within -1 to 1 expect(balanced.getBalanceFactor()).toBeLessThanOrEqual(1); expect(balanced.getBalanceFactor()).toBeGreaterThanOrEqual(-1); // Verify tree has correct size expect(balanced.size).toBe(2n); }); it("should not modify already balanced 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); // Create balanced tree: // 2 // / \ // 1 3 await mutableTree.set(Buffer.from("2"), Buffer.from("two")); await mutableTree.set(Buffer.from("1"), Buffer.from("one")); await mutableTree.set(Buffer.from("3"), Buffer.from("three")); // Access private balance method type MutableTreePrivate = { balance(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; const root = mutableTree.getRoot(); const balanced = await privateTree.balance(root!); // Should return same node (no rotation needed) expect(balanced).toBe(root); expect(balanced.getBalanceFactor()).toBeLessThanOrEqual(1); expect(balanced.getBalanceFactor()).toBeGreaterThanOrEqual(-1); }); it("should throw error when balancing persisted node", 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); // Access private balance method type MutableTreePrivate = { balance(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; // Create a persisted node (with nodeKey) const persistedNode = new Node(); persistedNode.key = Buffer.from("test"); persistedNode.subtreeHeight = 0; persistedNode.size = 1n; persistedNode.value = Buffer.from("value"); persistedNode.nodeKey = { version: 1n, nonce: 1, }; // Attempting to balance persisted node should throw await expect(privateTree.balance(persistedNode)).rejects.toThrow( "unexpected balance() call on persisted node", ); }); it("should maintain all values after 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 mutableTree = new MutableTree(nodeDB, workingTree); // Create unbalanced tree const keys = [ "5", "4", "3", "2", "1", ]; for (const key of keys) { await mutableTree.set(Buffer.from(key), Buffer.from(key.toUpperCase())); } // Access private balance method type MutableTreePrivate = { balance(node: Node): Promise }; const privateTree = mutableTree as unknown as MutableTreePrivate; const root = mutableTree.getRoot(); const balanced = await privateTree.balance(root!); // Verify all values are still accessible const values: string[] = []; const collectLeaves = (node: Node | null): void => { if (!node) return; collectLeaves(node.leftNode); if (node.isLeaf() && node.value) { values.push(Buffer.from(node.value).toString()); } collectLeaves(node.rightNode); }; collectLeaves(balanced); values.sort(); expect(values).toEqual([ "1", "2", "3", "4", "5", ]); }); }); });