import { beforeEach, describe, expect, it, } from "vitest"; import { MemDB, } from "../db/mem-db.js"; import { createTestDb, type TestDbContext, } from "../db/test-db-factory.js"; import { ImmutableTree, } from "../immutable-tree.js"; import { MutableTree, } from "../mutable-tree.js"; import { Node, } from "../node.js"; import { getRootKey, } from "../node-key.js"; import { stringToBytes, } from "../utils/bytes.js"; import { NodeDB, } from "./node-db.js"; /** * Tests for storage version migration (hash-based to version+nonce format). * Based on Go IAVL v1.3.5 migrate_test.go */ describe("Storage Migration", () => { let ctx: TestDbContext; let ndb: NodeDB; beforeEach(async () => { ctx = await createTestDb(); ndb = new NodeDB(ctx.db, 100, { }); await ndb.initialize(); }); afterEach(async () => { await ctx.cleanup(); }); describe("legacy version tracking", () => { it("should return -1n when no legacy versions exist", async () => { const legacyVersion = await ndb.getLegacyLatestVersion(); expect(legacyVersion).toBe(-1n); }); it("should detect legacy versions when present", async () => { // Create a legacy root entry manually // Legacy root format: 'r' + version (8 bytes big-endian) const version = 5n; const legacyRootKey = new Uint8Array(9); legacyRootKey[0] = 0x72; // 'r' const view = new DataView(legacyRootKey.buffer); view.setBigInt64(1, BigInt.asIntN(64, version), false); // Create a simple legacy node const leafNode = new Node(); leafNode.key = stringToBytes("test"); leafNode.value = stringToBytes("value"); leafNode.version = version; leafNode.size = 1n; leafNode.height = 0; // Save as legacy format (will be detected by Node.fromBytes) const hash = leafNode.computeHash(version); leafNode.hash = hash; leafNode.isLegacy = true; // Store the legacy node const legacyNodeKey = new Uint8Array(33); legacyNodeKey[0] = 0x6E; // 'n' legacyNodeKey.set(hash, 1); await ctx.db.set(legacyNodeKey, leafNode.toBytes()); // Store the legacy root pointing to this hash await ctx.db.set(legacyRootKey, hash); // Now check if getLegacyLatestVersion detects it const detectedVersion = await ndb.getLegacyLatestVersion(); expect(detectedVersion).toBe(version); }); it("should cache legacy latest version", async () => { // Create legacy root for version 10 const version = 10n; const legacyRootKey = new Uint8Array(9); legacyRootKey[0] = 0x72; // 'r' const view = new DataView(legacyRootKey.buffer); view.setBigInt64(1, BigInt.asIntN(64, version), false); const dummyHash = new Uint8Array(32).fill(1); await ctx.db.set(legacyRootKey, dummyHash); // First call should scan database const firstCall = await ndb.getLegacyLatestVersion(); expect(firstCall).toBe(version); // Second call should use cached value (no database scan) const secondCall = await ndb.getLegacyLatestVersion(); expect(secondCall).toBe(version); expect(secondCall).toBe(firstCall); }); }); describe("legacy node operations", () => { it("should retrieve legacy nodes", async () => { // Create and store a legacy node const leafNode = new Node(); leafNode.key = stringToBytes("legacy-key"); leafNode.value = stringToBytes("legacy-value"); leafNode.version = 1n; leafNode.size = 1n; leafNode.height = 0; const hash = leafNode.computeHash(1n); leafNode.hash = hash; leafNode.isLegacy = true; // Store with legacy key format const legacyNodeKey = new Uint8Array(33); legacyNodeKey[0] = 0x6E; // 'n' legacyNodeKey.set(hash, 1); await ctx.db.set(legacyNodeKey, leafNode.toBytes()); // Retrieve all legacy nodes const legacyNodes = await ndb.legacyNodes(); expect(legacyNodes.length).toBe(1); expect(legacyNodes[0].key).toEqual(stringToBytes("legacy-key")); expect(legacyNodes[0].value).toEqual(stringToBytes("legacy-value")); expect(legacyNodes[0].isLegacy).toBe(true); }); it("should return empty array when no legacy nodes exist", async () => { const legacyNodes = await ndb.legacyNodes(); expect(legacyNodes).toEqual([]); }); it("should load legacy nodes via getNode", async () => { // Create a legacy node const leafNode = new Node(); leafNode.key = stringToBytes("key1"); leafNode.value = stringToBytes("value1"); leafNode.version = 1n; leafNode.size = 1n; leafNode.height = 0; const hash = leafNode.computeHash(1n); leafNode.hash = hash; leafNode.isLegacy = true; // Store with legacy key format const legacyNodeKey = new Uint8Array(33); legacyNodeKey[0] = 0x6E; // 'n' legacyNodeKey.set(hash, 1); await ctx.db.set(legacyNodeKey, leafNode.toBytes()); // Load via getNode using hash as key (legacy format) const loadedNode = await ndb.getNode(hash); expect(loadedNode).not.toBeNull(); expect(loadedNode?.key).toEqual(stringToBytes("key1")); expect(loadedNode?.value).toEqual(stringToBytes("value1")); expect(loadedNode?.isLegacy).toBe(true); }); }); describe("legacy root operations", () => { it("should load legacy roots via getRoot", async () => { // Use a fresh DB to avoid test pollution const freshDb = new MemDB(); const freshNdb = new NodeDB(freshDb, 100, { }); await freshNdb.initialize(); const version = 3n; // Create a simple node const rootNode = new Node(); rootNode.key = stringToBytes("root-key"); rootNode.value = stringToBytes("root-value"); rootNode.version = version; rootNode.size = 1n; rootNode.height = 0; const hash = rootNode.computeHash(version); rootNode.hash = hash; rootNode.isLegacy = true; // Store the node with legacy key const legacyNodeKey = new Uint8Array(33); legacyNodeKey[0] = 0x6E; // 'n' legacyNodeKey.set(hash, 1); await freshDb.set(legacyNodeKey, rootNode.toBytes()); // Store legacy root reference const legacyRootKey = new Uint8Array(9); legacyRootKey[0] = 0x72; // 'r' const view = new DataView(legacyRootKey.buffer); view.setBigInt64(1, BigInt.asIntN(64, version), false); await freshDb.set(legacyRootKey, hash); // Load root - should find legacy version const rootKey = await freshNdb.getRoot(version); expect(rootKey).not.toBeNull(); // Legacy roots return the 32-byte hash expect(rootKey!.length).toBe(32); expect(rootKey).toEqual(hash); }); it("should prefer new format roots over legacy", async () => { const version = 100n; // Use a version unlikely to have test pollution // Create a new-format root const newRootKey = getRootKey(version); // Store new format root explicitly in metadata // Root metadata key: 'm' + 'root_' + version const rootMetadataKey = new Uint8Array([0x6D, ...stringToBytes(`root_${version}`)]); await ctx.db.set(rootMetadataKey, newRootKey); // Store the actual node const newFormatKey = new Uint8Array(1 + 12); newFormatKey[0] = 0x73; // 's' newFormatKey.set(newRootKey, 1); const newNode = new Node(); newNode.key = stringToBytes("new-key"); newNode.value = stringToBytes("new-value"); newNode.version = version; newNode.size = 1n; newNode.height = 0; newNode.nodeKey = { version, nonce: 1, }; await ctx.db.set(newFormatKey, newNode.toBytes()); // Also create a legacy root const legacyRootKey = new Uint8Array(9); legacyRootKey[0] = 0x72; // 'r' const view = new DataView(legacyRootKey.buffer); view.setBigInt64(1, BigInt.asIntN(64, version), false); const legacyHash = new Uint8Array(32).fill(1); await ctx.db.set(legacyRootKey, legacyHash); // getRoot should prefer new format const rootKey = await ndb.getRoot(version); expect(rootKey).not.toBeNull(); expect(rootKey).toEqual(newRootKey); // Should get new format key, not legacy hash }); }); describe("mixed legacy and new format", () => { it("should handle tree with new saves after legacy data", async () => { // This tests the lazy migration - legacy data can coexist with new format // Step 1: Simulate legacy data (version 1) const legacyVersion = 1n; const legacyNode = new Node(); legacyNode.key = stringToBytes("legacy"); legacyNode.value = stringToBytes("data"); legacyNode.version = legacyVersion; legacyNode.size = 1n; legacyNode.height = 0; const legacyHash = legacyNode.computeHash(legacyVersion); legacyNode.hash = legacyHash; legacyNode.isLegacy = true; // Store legacy node const legacyNodeKey = new Uint8Array(33); legacyNodeKey[0] = 0x6E; // 'n' legacyNodeKey.set(legacyHash, 1); await ctx.db.set(legacyNodeKey, legacyNode.toBytes()); // Store legacy root const legacyRootKey = new Uint8Array(9); legacyRootKey[0] = 0x72; // 'r' const view = new DataView(legacyRootKey.buffer); view.setBigInt64(1, BigInt.asIntN(64, legacyVersion), false); await ctx.db.set(legacyRootKey, legacyHash); // Set metadata to indicate versions exist const firstVersionKey = new Uint8Array([0x6D, ...stringToBytes("first_version")]); const latestVersionKey = new Uint8Array([0x6D, ...stringToBytes("latest_version")]); const firstVersionBytes = new Uint8Array(8); const latestVersionBytes = new Uint8Array(8); const firstView = new DataView(firstVersionBytes.buffer); const latestView = new DataView(latestVersionBytes.buffer); firstView.setBigInt64(0, legacyVersion, false); latestView.setBigInt64(0, legacyVersion, false); await ctx.db.set(firstVersionKey, firstVersionBytes); await ctx.db.set(latestVersionKey, latestVersionBytes); // Re-initialize NodeDB to pick up metadata const ndb2 = new NodeDB(ctx.db, 100, { }); await ndb2.initialize(); // Check legacy version is detected const legacyLatest = await ndb2.getLegacyLatestVersion(); expect(legacyLatest).toBe(legacyVersion); // Step 2: Create a new tree and save data (will use new format) // We create a fresh tree that doesn't know about the legacy version // This simulates the lazy migration - old data stays in legacy format const workingTree2 = new ImmutableTree(null, ndb2, 0n); const tree2 = new MutableTree(ndb2, workingTree2, true); // skipFastStorage=true // Make a save with new data (this will be version legacyVersion+1) await tree2.set(stringToBytes("new-key"), stringToBytes("new-value")); const { version: newVersion, } = await tree2.saveVersion(); // The tree created its first version (version 2, since latest was 1) // Verify new format was used (root should use new key format) const newRoot = await ndb2.getRoot(newVersion); expect(newRoot).not.toBeNull(); // New format uses 12-byte keys (version + nonce) expect(newRoot!.length).toBe(12); // Verify the system handled mixed formats without crashing // (The legacy data is still there, just not actively used by the new tree) expect(newVersion).toBeGreaterThanOrEqual(legacyVersion); }); }); });