/** * Invariant Verification Tests * * These tests verify that fundamental invariants hold across random operations. * Invariants are properties that MUST always be true for a correct IAVL tree. * * Key Invariants: * 1. AVL Balance: |balance factor| <= 1 for all nodes * 2. AVL Height: height <= 1.44 * log2(size) * 3. BST Property: left.key < node.key <= right.key * 4. Size Consistency: node.size = leftChild.size + rightChild.size * 5. Height Consistency: node.height = 1 + max(leftChild.height, rightChild.height) * 6. Hash Determinism: Same operations → same hash * 7. Persistence: save → load → hash unchanged */ 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 { Node, } from "../node.js"; import { NodeDB, } from "../storage/node-db.js"; import { DEFAULT_OPTIONS, } from "../types/options.js"; const encoder = new TextEncoder(); /** * Seeded random generator for reproducible tests */ class Random { private seed: number; constructor(seed: number) { this.seed = seed; } next(): number { this.seed = (this.seed * 1103515245 + 12345) & 0x7fffffff; return this.seed / 0x7fffffff; } nextInt(max: number): number { return Math.floor(this.next() * max); } nextBytes(length: number): Uint8Array { const bytes = new Uint8Array(length); for (let i = 0; i < length; i++) { bytes[i] = this.nextInt(256); } return bytes; } } /** * Recursively verifies AVL balance factor invariant */ function verifyBalanceFactors(node: Node | null, path: string = "root"): void { if (!node) return; const balance = node.getBalanceFactor(); if (Math.abs(balance) > 1) { throw new Error( `AVL invariant violated at ${path}: balance factor = ${balance} (must be -1, 0, or 1)`, ); } if (!node.isLeaf()) { verifyBalanceFactors(node.leftNode, `${path}.left`); verifyBalanceFactors(node.rightNode, `${path}.right`); } } /** * Recursively verifies BST property */ function verifyBSTProperty(node: Node | null, minKey: Uint8Array | null = null, maxKey: Uint8Array | null = null): void { if (!node || !node.key) return; // Check against bounds if (minKey !== null && Buffer.compare(node.key, minKey) < 0) { throw new Error("BST invariant violated: node key < min bound"); } if (maxKey !== null && Buffer.compare(node.key, maxKey) > 0) { throw new Error("BST invariant violated: node key > max bound"); } if (!node.isLeaf()) { // For branch nodes, key is the smallest key in right subtree // Left subtree: all keys < node.key // Right subtree: all keys >= node.key verifyBSTProperty(node.leftNode, minKey, node.key); verifyBSTProperty(node.rightNode, node.key, maxKey); } } /** * Recursively verifies size and height consistency */ function verifySizeAndHeight(node: Node | null, path: string = "root"): void { if (!node) return; if (node.isLeaf()) { if (node.size !== 1n) { throw new Error(`Size invariant violated at ${path}: leaf has size ${node.size}, expected 1`); } if (node.subtreeHeight !== 0) { throw new Error(`Height invariant violated at ${path}: leaf has height ${node.subtreeHeight}, expected 0`); } } else { // Branch node // Skip verification if children are not loaded (cleared after save) // This happens when nodes have nodeKey/leftNodeKey/rightNodeKey but null leftNode/rightNode if (node.leftNode || node.rightNode) { const leftSize = node.leftNode?.size ?? 0n; const rightSize = node.rightNode?.size ?? 0n; const expectedSize = leftSize + rightSize; if (node.size !== expectedSize) { throw new Error( `Size invariant violated at ${path}: size = ${node.size}, expected ${expectedSize} (${leftSize} + ${rightSize})`, ); } const leftHeight = node.leftNode?.subtreeHeight ?? -1; const rightHeight = node.rightNode?.subtreeHeight ?? -1; const expectedHeight = 1 + Math.max(leftHeight, rightHeight); if (node.subtreeHeight !== expectedHeight) { throw new Error( `Height invariant violated at ${path}: height = ${node.subtreeHeight}, expected ${expectedHeight}`, ); } verifySizeAndHeight(node.leftNode, `${path}.left`); verifySizeAndHeight(node.rightNode, `${path}.right`); } // If children are cleared, we can't verify their contribution to size/height // This is normal after saveVersion() which clears references } } /** * Verifies all tree invariants */ function verifyAllInvariants(tree: MutableTree): void { const root = tree.getRoot(); if (!root) return; // Empty tree is valid // 1. AVL Balance verifyBalanceFactors(root); // 2. BST Property verifyBSTProperty(root); // 3. Size and Height Consistency verifySizeAndHeight(root); // 4. AVL Height Bound const n = Number(tree.getSize()); if (n > 0) { const maxHeight = Math.ceil(1.44 * Math.log2(n)); const height = tree.getWorkingTree().height(); if (height > maxHeight) { throw new Error( `AVL height bound violated: height = ${height}, max = ${maxHeight} for size = ${n}`, ); } } } describe("Invariant Verification", () => { describe("AVL Invariants After Random Operations", () => { it("should maintain all invariants after 100 random sets", 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); const rng = new Random(12345); // Deterministic seed for (let i = 0; i < 100; i++) { const key = rng.nextBytes(8); const value = rng.nextBytes(16); await tree.set(key, value); // Verify invariants after every operation verifyAllInvariants(tree); } await ctx.cleanup(); }); it("should maintain all invariants after mixed set/remove 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 tree = new MutableTree(nodeDB, workingTree); const rng = new Random(54321); const keys: Uint8Array[] = []; // Insert 50 keys for (let i = 0; i < 50; i++) { const key = rng.nextBytes(8); const value = rng.nextBytes(16); await tree.set(key, value); keys.push(key); if (i % 10 === 9) { verifyAllInvariants(tree); } } // Remove 25 keys randomly for (let i = 0; i < 25; i++) { const idx = rng.nextInt(keys.length); const key = keys[idx]; await tree.remove(key); keys.splice(idx, 1); if (i % 5 === 4) { verifyAllInvariants(tree); } } // Final verification verifyAllInvariants(tree); await ctx.cleanup(); }); it("should maintain invariants across save/load cycles", 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, true); const rng = new Random(99999); // Save 5 versions with random data for (let ver = 1; ver <= 5; ver++) { for (let i = 0; i < 10; i++) { const key = rng.nextBytes(8); const value = rng.nextBytes(16); await tree.set(key, value); } verifyAllInvariants(tree); await tree.saveVersion(); } // Load each version and verify invariants for (let ver = 1; ver <= 5; ver++) { await tree.loadVersion(BigInt(ver)); verifyAllInvariants(tree); } await ctx.cleanup(); }); }); describe("Hash Consistency Invariants", () => { it("should produce identical hash for identical trees", async () => { const operations = [ { key: "key1", value: "value1", }, { key: "key2", value: "value2", }, { key: "key3", value: "value3", }, { key: "key4", value: "value4", }, { key: "key5", value: "value5", }, ]; const hashes: Uint8Array[] = []; // Build same tree twice 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 tree = new MutableTree(nodeDB, workingTree, true); for (const op of operations) { await tree.set(encoder.encode(op.key), encoder.encode(op.value)); } const hash = tree.getWorkingHash(); expect(hash).not.toBeNull(); hashes.push(hash!); await ctx.cleanup(); } // Must be identical expect(Buffer.from(hashes[0]).equals(Buffer.from(hashes[1]))).toBe(true); }); it("should change hash when tree changes", 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); await tree.set(encoder.encode("key1"), encoder.encode("value1")); const hash1 = tree.getWorkingHash(); await tree.set(encoder.encode("key2"), encoder.encode("value2")); const hash2 = tree.getWorkingHash(); // Hash must change expect(Buffer.from(hash1!).equals(Buffer.from(hash2!))).toBe(false); // Hash should be stable const hash2b = tree.getWorkingHash(); expect(Buffer.from(hash2!).equals(Buffer.from(hash2b!))).toBe(true); await ctx.cleanup(); }); it("should preserve hash across save/load", 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, true); const rng = new Random(42); // Add random data for (let i = 0; i < 20; i++) { await tree.set(rng.nextBytes(8), rng.nextBytes(16)); } const hashBeforeSave = tree.getWorkingHash(); const result = await tree.saveVersion(); // Hash should match expect(Buffer.from(result.hash).equals(Buffer.from(hashBeforeSave!))).toBe(true); // Load and verify const rootNodeKey = await nodeDB.getRoot(result.version); const rootNode = await nodeDB.getNode(rootNodeKey!); const loadedTree = new ImmutableTree(rootNode!, nodeDB, result.version); // Hash should still match expect(Buffer.from(loadedTree.hash()!).equals(Buffer.from(hashBeforeSave!))).toBe(true); await ctx.cleanup(); }); }); describe("Size Tracking Invariants", () => { it("should track size correctly through random 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 tree = new MutableTree(nodeDB, workingTree); const rng = new Random(777); const mirror = new Map(); // Random sets and updates for (let i = 0; i < 100; i++) { const key = rng.nextBytes(4); const value = rng.nextBytes(8); const keyHex = Buffer.from(key).toString("hex"); await tree.set(key, value); mirror.set(keyHex, value); // Size should match mirror expect(tree.getSize()).toBe(BigInt(mirror.size)); } // Random removes const keys = Array.from(mirror.keys()); for (let i = 0; i < 30; i++) { const idx = rng.nextInt(keys.length); const keyHex = keys[idx]; const key = Buffer.from(keyHex, "hex"); await tree.remove(key); mirror.delete(keyHex); keys.splice(idx, 1); // Size should match mirror expect(tree.getSize()).toBe(BigInt(mirror.size)); } await ctx.cleanup(); }); }); describe("Structural Invariants After Rotations", () => { it("should maintain invariants after left-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 tree = new MutableTree(nodeDB, workingTree); // Trigger LL rotation: insert c, b, a (descending) await tree.set(encoder.encode("c"), encoder.encode("3")); await tree.set(encoder.encode("b"), encoder.encode("2")); await tree.set(encoder.encode("a"), encoder.encode("1")); // Triggers rotation verifyAllInvariants(tree); await ctx.cleanup(); }); it("should maintain invariants after right-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 tree = new MutableTree(nodeDB, workingTree); // Trigger RR rotation: insert a, b, c (ascending) await tree.set(encoder.encode("a"), encoder.encode("1")); await tree.set(encoder.encode("b"), encoder.encode("2")); await tree.set(encoder.encode("c"), encoder.encode("3")); // Triggers rotation verifyAllInvariants(tree); await ctx.cleanup(); }); it("should maintain invariants after left-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 tree = new MutableTree(nodeDB, workingTree); // Trigger LR rotation: insert c, a, b await tree.set(encoder.encode("c"), encoder.encode("3")); await tree.set(encoder.encode("a"), encoder.encode("1")); await tree.set(encoder.encode("b"), encoder.encode("2")); // Triggers rotation verifyAllInvariants(tree); await ctx.cleanup(); }); it("should maintain invariants after right-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 tree = new MutableTree(nodeDB, workingTree); // Trigger RL rotation: insert a, c, b await tree.set(encoder.encode("a"), encoder.encode("1")); await tree.set(encoder.encode("c"), encoder.encode("3")); await tree.set(encoder.encode("b"), encoder.encode("2")); // Triggers rotation verifyAllInvariants(tree); await ctx.cleanup(); }); }); describe("Invariants Under Stress", () => { it("should maintain invariants with 1000 random operations", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 10000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const tree = new MutableTree(nodeDB, workingTree); const rng = new Random(2025); const mirror = new Map(); // Mix of sets, updates, and removes for (let i = 0; i < 1000; i++) { const op = rng.nextInt(10); if (op < 7 || mirror.size === 0) { // 70% sets/updates const key = rng.nextBytes(6); const value = rng.nextBytes(12); await tree.set(key, value); mirror.set(Buffer.from(key).toString("hex"), value); } else { // 30% removes const keys = Array.from(mirror.keys()); const idx = rng.nextInt(keys.length); const keyHex = keys[idx]; const key = Buffer.from(keyHex, "hex"); await tree.remove(key); mirror.delete(keyHex); } // Verify every 50 operations if (i % 50 === 49) { verifyAllInvariants(tree); expect(tree.getSize()).toBe(BigInt(mirror.size)); } } // Final verification verifyAllInvariants(tree); await ctx.cleanup(); }); it("should maintain invariants across multiple versions with random data", async () => { const ctx = await createTestDb(); const nodeDB = new NodeDB(ctx.db, 10000, DEFAULT_OPTIONS); await nodeDB.initialize(); const workingTree = new ImmutableTree(null, nodeDB, 0n); const tree = new MutableTree(nodeDB, workingTree, true); const rng = new Random(31415); // Save 10 versions with random operations each for (let ver = 1; ver <= 10; ver++) { // 20 random operations per version for (let i = 0; i < 20; i++) { const key = rng.nextBytes(6); const value = rng.nextBytes(12); await tree.set(key, value); } verifyAllInvariants(tree); await tree.saveVersion(); } // Load each version and verify invariants for (let ver = 1; ver <= 10; ver++) { await tree.loadVersion(BigInt(ver)); verifyAllInvariants(tree); } await ctx.cleanup(); }); }); describe("Corner Cases", () => { it("should handle tree with all keys having same prefix", 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); // All keys start with "common-" for (let i = 0; i < 50; i++) { const key = encoder.encode(`common-key-${i.toString().padStart(5, "0")}`); const value = encoder.encode(`value${i}`); await tree.set(key, value); } verifyAllInvariants(tree); await ctx.cleanup(); }); it("should handle alternating small and large values", 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); const rng = new Random(11111); for (let i = 0; i < 50; i++) { const key = rng.nextBytes(4); // Alternate between small (1 byte) and large (1000 bytes) values const valueSize = i % 2 === 0 ? 1 : 1000; const value = rng.nextBytes(valueSize); await tree.set(key, value); } verifyAllInvariants(tree); await ctx.cleanup(); }); }); });