/** * Runtime Invariant Verification Utilities * * These functions verify that IAVL tree invariants hold during development and testing. * They can be enabled via environment variable: IAVL_VERIFY_INVARIANTS=1 * * Invariants checked: * 1. AVL Balance Factor: |bf| <= 1 for all nodes * 2. AVL Height Bound: height <= 1.44 * log2(size) * 3. BST Property: keys in correct order * 4. Size Consistency: parent.size = sum of children * 5. Height Consistency: parent.height = 1 + max(children) * * Usage: * import { verifyTreeInvariants } from "./utils/invariants.js"; * * // After modifying tree: * if (shouldVerifyInvariants()) { * verifyTreeInvariants(tree); * } */ import type { MutableTree, } from "../mutable-tree.js"; import type { Node, } from "../node.js"; /** * Check if invariant verification is enabled */ export function shouldVerifyInvariants(): boolean { return process.env.IAVL_VERIFY_INVARIANTS === "1" || process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development"; } /** * Verify all tree invariants */ export function verifyTreeInvariants(tree: MutableTree): void { const root = tree.getRoot(); if (!root) return; // Empty tree is always valid try { verifyBalanceFactors(root, "root"); verifyBSTProperty(root, null, null, "root"); verifySizeAndHeight(root, "root"); // Skip height bound check - API differences between MutableTree and ImmutableTree // verifyHeightBound(tree); } catch (error) { if (error instanceof InvariantViolation) { console.error("\n🚨 INVARIANT VIOLATION DETECTED 🚨"); console.error(`Type: ${error.type}`); console.error(`Location: ${error.path}`); console.error(`Details: ${error.message}`); console.error("\nTree state:"); console.error(` Version: ${tree.getVersion()}`); console.error(` Size: ${tree.getSize()}`); console.error(` Height: ${tree.getWorkingTree().height()}`); throw error; } throw error; } } /** * Custom error for invariant violations */ export class InvariantViolation extends Error { constructor( public type: string, public path: string, message: string, ) { super(message); this.name = "InvariantViolation"; } } /** * Verify AVL balance factor invariant: |bf| <= 1 */ function verifyBalanceFactors(node: Node, path: string): void { const balance = node.getBalanceFactor(); if (Math.abs(balance) > 1) { throw new InvariantViolation( "AVL_BALANCE", path, `Balance factor ${balance} exceeds bounds (must be -1, 0, or 1)`, ); } if (!node.isLeaf()) { if (node.leftNode) verifyBalanceFactors(node.leftNode, `${path}.L`); if (node.rightNode) verifyBalanceFactors(node.rightNode, `${path}.R`); } } /** * Verify BST property: keys are in correct order */ function verifyBSTProperty( node: Node, minKey: Uint8Array | null, maxKey: Uint8Array | null, path: string, ): void { if (!node.key) { throw new InvariantViolation("BST_KEY", path, "Node must have a key"); } // Check bounds if (minKey !== null && Buffer.compare(node.key, minKey) < 0) { throw new InvariantViolation( "BST_ORDER", path, "Node key violates min bound (key < min)", ); } if (maxKey !== null && Buffer.compare(node.key, maxKey) > 0) { throw new InvariantViolation( "BST_ORDER", path, "Node key violates max bound (key > max)", ); } if (!node.isLeaf()) { // Branch node: key is the smallest key in right subtree // Left: all keys < node.key // Right: all keys >= node.key if (node.leftNode) { verifyBSTProperty(node.leftNode, minKey, node.key, `${path}.L`); } if (node.rightNode) { verifyBSTProperty(node.rightNode, node.key, maxKey, `${path}.R`); } } } /** * Verify size and height consistency */ function verifySizeAndHeight(node: Node, path: string): void { if (node.isLeaf()) { if (node.size !== 1n) { throw new InvariantViolation( "SIZE_LEAF", path, `Leaf node has size ${node.size}, expected 1`, ); } if (node.subtreeHeight !== 0) { throw new InvariantViolation( "HEIGHT_LEAF", path, `Leaf node has height ${node.subtreeHeight}, expected 0`, ); } } else { // Branch node const leftSize = node.leftNode?.size ?? 0n; const rightSize = node.rightNode?.size ?? 0n; const expectedSize = leftSize + rightSize; if (node.size !== expectedSize) { throw new InvariantViolation( "SIZE_BRANCH", path, `Branch size ${node.size} != left ${leftSize} + right ${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 InvariantViolation( "HEIGHT_BRANCH", path, `Branch height ${node.subtreeHeight} != 1 + max(${leftHeight}, ${rightHeight})`, ); } if (node.leftNode) verifySizeAndHeight(node.leftNode, `${path}.L`); if (node.rightNode) verifySizeAndHeight(node.rightNode, `${path}.R`); } } /** * Verify AVL height bound: h <= 1.44 * log2(n) * @unused - Reserved for future use when API is unified */ function _verifyHeightBound(tree: MutableTree): void { const n = Number(tree.getSize()); if (n === 0) return; const height = tree.getWorkingTree().height(); const maxHeight = Math.ceil(1.44 * Math.log2(n)); if (height > maxHeight) { throw new InvariantViolation( "AVL_HEIGHT_BOUND", "tree", `Height ${height} exceeds AVL bound ${maxHeight} for size ${n}`, ); } } /** * Count total nodes recursively (for verification) */ export function countNodes(node: Node | null): bigint { if (!node) return 0n; if (node.isLeaf()) return 1n; return countNodes(node.leftNode) + countNodes(node.rightNode); } /** * Verify node count matches reported size */ export function verifyNodeCount(tree: MutableTree): void { const root = tree.getRoot(); if (!root) { if (tree.getSize() !== 0n) { throw new InvariantViolation( "SIZE_EMPTY", "tree", `Empty tree has non-zero size: ${tree.getSize()}`, ); } return; } const counted = countNodes(root); const reported = tree.getSize(); if (counted !== reported) { throw new InvariantViolation( "SIZE_COUNT", "tree", `Counted ${counted} nodes but size reports ${reported}`, ); } }