edgevec 0.9.0

High-performance embedded vector database for Browser, Node, and Edge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/**
 * EdgeVec Batch Insert Demo - Cyberpunk Professional Edition
 * Week 12 Day 4 - W12.4 Deliverable
 *
 * @fileoverview Demonstrates EdgeVec WASM batch insert capabilities with
 * sequential vs batch comparison, error handling, and real-time metrics.
 *
 * @author WASM_SPECIALIST
 * @version 2.0.0
 * @license MIT
 */

// =============================================================================
// CONFIGURATION CONSTANTS
// =============================================================================

/**
 * @constant {Object} CONFIG - Application configuration constants
 */
const CONFIG = {
    /** @type {number} Minimum allowed vector count */
    MIN_VECTORS: 10,
    /** @type {number} Maximum allowed vector count */
    MAX_VECTORS: 100000,
    /** @type {number} Default vector count */
    DEFAULT_VECTORS: 1000,
    /** @type {number} Minimum allowed dimensions */
    MIN_DIMENSIONS: 2,
    /** @type {number} Maximum allowed dimensions */
    MAX_DIMENSIONS: 2048,
    /** @type {number} Default dimensions */
    DEFAULT_DIMENSIONS: 128,
    /** @type {number} UI update delay in milliseconds */
    UI_UPDATE_DELAY: 50,
    /** @type {number} Delay between comparison phases */
    COMPARISON_DELAY: 300,
};

/**
 * @constant {Object} PRESETS - Benchmark configuration presets
 */
const PRESETS = {
    C1: { vectors: 100, dims: 128, name: 'Small' },
    C2: { vectors: 1000, dims: 128, name: 'Medium' },
    C3: { vectors: 1000, dims: 512, name: 'High-D' },
    C4: { vectors: 5000, dims: 128, name: 'Large' },
};

/**
 * @constant {string[]} WASM_MODULE_PATHS - Possible paths for WASM module
 * IMPORTANT: Start server from edgevec/ root, NOT from wasm/examples/
 * Example: cd edgevec && python -m http.server 8080
 *          Then open: http://localhost:8080/wasm/examples/batch_insert.html
 */
const WASM_MODULE_PATHS = [
    '../../pkg/edgevec.js',      // From /wasm/examples/ → /pkg/
    '/pkg/edgevec.js',           // Absolute from root
    '../pkg/edgevec.js',         // From /wasm/ → /pkg/
    './pkg/edgevec.js',          // Fallback
];

// =============================================================================
// GLOBAL STATE
// =============================================================================

/** @type {Object|null} The loaded EdgeVec WASM module */
let edgeVecModule = null;

/** @type {Date} Application start time for logging */
const startTime = new Date();

// =============================================================================
// DOM ELEMENTS
// =============================================================================

/**
 * @constant {Object} DOM - Cached DOM element references
 */
const DOM = {
    // Status
    status: document.getElementById('status'),
    statusIcon: document.getElementById('statusIcon'),
    statusText: document.getElementById('statusText'),
    progressFill: document.getElementById('progressFill'),
    progressPhase: document.getElementById('progressPhase'),
    progressPercent: document.getElementById('progressPercent'),

    // Header info
    browserInfo: document.getElementById('browserInfo'),
    wasmSupport: document.getElementById('wasmSupport'),
    moduleStatus: document.getElementById('moduleStatus'),

    // Controls
    vectorCount: document.getElementById('vectorCount'),
    dimensions: document.getElementById('dimensions'),

    // Results
    sequentialResults: document.getElementById('sequentialResults'),
    batchResults: document.getElementById('batchResults'),
    speedupCard: document.getElementById('speedupCard'),

    // Sequential metrics
    seqCount: document.getElementById('seq-count'),
    seqTime: document.getElementById('seq-time'),
    seqAvg: document.getElementById('seq-avg'),
    seqThroughput: document.getElementById('seq-throughput'),

    // Batch metrics
    batchCount: document.getElementById('batch-count'),
    batchTime: document.getElementById('batch-time'),
    batchAvg: document.getElementById('batch-avg'),
    batchThroughput: document.getElementById('batch-throughput'),

    // Speedup
    speedupValue: document.getElementById('speedupValue'),
    speedupUnit: document.getElementById('speedupUnit'),
    speedupNote: document.getElementById('speedupNote'),

    // Terminal
    terminalOutput: document.getElementById('terminalOutput'),
};

// =============================================================================
// LOGGING SYSTEM
// =============================================================================

/**
 * Log level enumeration
 * @enum {string}
 */
const LogLevel = {
    INFO: 'info',
    SUCCESS: 'success',
    ERROR: 'error',
    WARN: 'warn',
};

/**
 * Get formatted timestamp for logging
 * @returns {string} Formatted timestamp [HH:MM:SS]
 */
function getTimestamp() {
    const now = new Date();
    const elapsed = now - startTime;
    const seconds = Math.floor(elapsed / 1000) % 60;
    const minutes = Math.floor(elapsed / 60000) % 60;
    const hours = Math.floor(elapsed / 3600000);
    return `[${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}]`;
}

/**
 * Log a message to the terminal output
 * @param {string} message - The message to log
 * @param {LogLevel} level - The log level
 */
function log(message, level = LogLevel.INFO) {
    const line = document.createElement('div');
    line.className = 'log-line';
    line.innerHTML = `
        <span class="log-time">${getTimestamp()}</span>
        <span class="log-level ${level}">${level.toUpperCase()}</span>
        <span class="log-message">${message}</span>
    `;
    DOM.terminalOutput.appendChild(line);
    DOM.terminalOutput.scrollTop = DOM.terminalOutput.scrollHeight;

    // Also log to console
    console.log(`${getTimestamp()} [${level.toUpperCase()}] ${message}`);
}

// =============================================================================
// STATUS & PROGRESS
// =============================================================================

/**
 * Show status message with type styling
 * @param {string} message - Status message to display
 * @param {'loading'|'success'|'error'} type - Status type
 */
function showStatus(message, type) {
    DOM.status.className = `status-bar visible ${type}`;
    DOM.statusText.textContent = message;

    const icons = {
        loading: '\u23F3',  // Hourglass
        success: '\u2714',  // Checkmark
        error: '\u2716',    // X mark
    };
    DOM.statusIcon.textContent = icons[type] || '';
}

/**
 * Hide the status bar
 */
function hideStatus() {
    DOM.status.className = 'status-bar';
}

/**
 * Update progress bar
 * @param {number} percent - Progress percentage (0-100)
 * @param {string} phase - Current phase description
 */
function updateProgress(percent, phase) {
    DOM.progressFill.style.width = `${percent}%`;
    DOM.progressPhase.textContent = phase;
    DOM.progressPercent.textContent = `${Math.round(percent)}%`;
}

// =============================================================================
// BROWSER DETECTION
// =============================================================================

/**
 * Detect and display browser information
 */
function displayBrowserInfo() {
    const ua = navigator.userAgent;
    let browser = 'Unknown';
    let version = '';

    if (ua.includes('Chrome')) {
        browser = 'Chrome';
        version = ua.match(/Chrome\/(\d+)/)?.[1] || '';
    } else if (ua.includes('Firefox')) {
        browser = 'Firefox';
        version = ua.match(/Firefox\/(\d+)/)?.[1] || '';
    } else if (ua.includes('Safari') && !ua.includes('Chrome')) {
        browser = 'Safari';
        version = ua.match(/Version\/(\d+)/)?.[1] || '';
    } else if (ua.includes('Edge')) {
        browser = 'Edge';
        version = ua.match(/Edge\/(\d+)/)?.[1] || '';
    }

    DOM.browserInfo.textContent = version ? `${browser} ${version}` : browser;
    log(`Browser detected: ${browser} ${version}`, LogLevel.INFO);

    // Check WebAssembly support
    const hasWasm = typeof WebAssembly === 'object'
        && typeof WebAssembly.instantiate === 'function';

    if (hasWasm) {
        DOM.wasmSupport.textContent = 'Supported';
        DOM.wasmSupport.classList.add('supported');
        log('WebAssembly: Supported', LogLevel.SUCCESS);
    } else {
        DOM.wasmSupport.textContent = 'NOT SUPPORTED';
        DOM.wasmSupport.classList.add('error');
        log('WebAssembly: NOT SUPPORTED', LogLevel.ERROR);
        showStatus('WebAssembly is not supported in this browser', 'error');
        disableAllButtons();
    }
}

// =============================================================================
// BUTTON STATE MANAGEMENT
// =============================================================================

/**
 * Disable all action buttons
 */
function disableAllButtons() {
    document.querySelectorAll('.btn').forEach(btn => {
        btn.disabled = true;
    });
}

/**
 * Enable all action buttons
 */
function enableAllButtons() {
    document.querySelectorAll('.btn').forEach(btn => {
        btn.disabled = false;
    });
}

// =============================================================================
// VECTOR GENERATION
// =============================================================================

/**
 * Generate random normalized vectors for testing
 * @param {number} count - Number of vectors to generate
 * @param {number} dims - Dimension of each vector
 * @returns {Float32Array[]} Array of normalized random vectors
 */
function generateRandomVectors(count, dims) {
    const vectors = [];

    for (let i = 0; i < count; i++) {
        const vector = new Float32Array(dims);
        let sumSquares = 0;

        // Generate random values in range [-1, 1]
        for (let j = 0; j < dims; j++) {
            vector[j] = Math.random() * 2 - 1;
            sumSquares += vector[j] * vector[j];
        }

        // Normalize to unit length
        const norm = Math.sqrt(sumSquares);
        if (norm > 0) {
            for (let j = 0; j < dims; j++) {
                vector[j] /= norm;
            }
        }

        vectors.push(vector);
    }

    return vectors;
}

// =============================================================================
// UTILITIES
// =============================================================================

/**
 * Sleep for specified milliseconds
 * @param {number} ms - Milliseconds to sleep
 * @returns {Promise<void>}
 */
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * Format a number with locale-specific formatting
 * @param {number} num - Number to format
 * @returns {string} Formatted number string
 */
function formatNumber(num) {
    return num.toLocaleString();
}

/**
 * Calculate throughput (vectors per second)
 * @param {number} count - Number of vectors
 * @param {number} timeMs - Time in milliseconds
 * @returns {string} Formatted throughput string
 */
function calculateThroughput(count, timeMs) {
    const perSecond = (count / timeMs) * 1000;
    if (perSecond >= 1000) {
        return `${(perSecond / 1000).toFixed(1)}K/s`;
    }
    return `${Math.round(perSecond)}/s`;
}

// =============================================================================
// CORE BENCHMARK FUNCTIONS
// =============================================================================

/**
 * Run sequential insert benchmark (baseline)
 * @returns {Promise<{count: number, totalTime: number, avgTime: number}>}
 */
async function runSequentialInsert() {
    const count = parseInt(DOM.vectorCount.value, 10);
    const dims = parseInt(DOM.dimensions.value, 10);

    log(`Sequential insert: ${formatNumber(count)} vectors x ${dims}D`, LogLevel.INFO);

    showStatus(`Generating ${formatNumber(count)} random ${dims}D vectors...`, 'loading');
    updateProgress(10, 'Generating vectors...');
    await sleep(CONFIG.UI_UPDATE_DELAY);

    const vectors = generateRandomVectors(count, dims);
    log(`Generated ${formatNumber(count)} test vectors`, LogLevel.INFO);

    showStatus(`Running sequential insert of ${formatNumber(count)} vectors...`, 'loading');
    updateProgress(30, 'Inserting vectors...');
    await sleep(CONFIG.UI_UPDATE_DELAY);

    try {
        // Create fresh index
        const config = new edgeVecModule.EdgeVecConfig(dims);
        const index = new edgeVecModule.EdgeVec(config);

        const startTime = performance.now();

        // Insert one-by-one with progress updates
        for (let i = 0; i < vectors.length; i++) {
            index.insert(vectors[i]);

            // Update progress every 10% or every 100 vectors for small batches
            if (i % Math.max(Math.floor(count / 10), 100) === 0) {
                const progress = 30 + (i / count) * 60;
                updateProgress(progress, `Inserting vector ${formatNumber(i + 1)}/${formatNumber(count)}...`);
                await sleep(1); // Minimal yield for UI
            }
        }

        const endTime = performance.now();
        const totalTime = endTime - startTime;
        const avgTime = totalTime / count;
        const throughput = calculateThroughput(count, totalTime);

        updateProgress(100, 'Complete');

        // Update UI
        DOM.seqCount.textContent = formatNumber(count);
        DOM.seqTime.textContent = `${totalTime.toFixed(2)} ms`;
        DOM.seqAvg.textContent = `${avgTime.toFixed(4)} ms`;
        DOM.seqThroughput.textContent = throughput;
        DOM.sequentialResults.classList.add('visible');

        log(`Sequential complete: ${totalTime.toFixed(2)}ms (${throughput})`, LogLevel.SUCCESS);
        showStatus('Sequential insert complete!', 'success');

        return { count, totalTime, avgTime };

    } catch (error) {
        log(`Sequential insert failed: ${error.message || error}`, LogLevel.ERROR);
        showStatus(`Sequential insert failed: ${error.message || error}`, 'error');
        throw error;
    }
}

/**
 * Run batch insert benchmark (optimized)
 * @returns {Promise<{count: number, totalTime: number, avgTime: number}>}
 */
async function runBatchInsert() {
    const count = parseInt(DOM.vectorCount.value, 10);
    const dims = parseInt(DOM.dimensions.value, 10);

    log(`Batch insert: ${formatNumber(count)} vectors x ${dims}D`, LogLevel.INFO);

    showStatus(`Generating ${formatNumber(count)} random ${dims}D vectors...`, 'loading');
    updateProgress(10, 'Generating vectors...');
    await sleep(CONFIG.UI_UPDATE_DELAY);

    const vectors = generateRandomVectors(count, dims);
    log(`Generated ${formatNumber(count)} test vectors`, LogLevel.INFO);

    showStatus(`Running batch insert of ${formatNumber(count)} vectors...`, 'loading');
    updateProgress(50, 'Batch inserting...');
    await sleep(CONFIG.UI_UPDATE_DELAY);

    try {
        // Create fresh index
        const config = new edgeVecModule.EdgeVecConfig(dims);
        const index = new edgeVecModule.EdgeVec(config);

        const startTime = performance.now();

        // Insert as batch
        const result = index.insertBatch(vectors);

        const endTime = performance.now();
        const totalTime = endTime - startTime;
        const avgTime = totalTime / result.inserted;
        const throughput = calculateThroughput(result.inserted, totalTime);

        updateProgress(100, 'Complete');

        // Update UI
        DOM.batchCount.textContent = formatNumber(result.inserted);
        DOM.batchTime.textContent = `${totalTime.toFixed(2)} ms`;
        DOM.batchAvg.textContent = `${avgTime.toFixed(4)} ms`;
        DOM.batchThroughput.textContent = throughput;
        DOM.batchResults.classList.add('visible');

        log(`Batch complete: ${totalTime.toFixed(2)}ms (${throughput}) - ${result.inserted}/${result.total} inserted`, LogLevel.SUCCESS);
        showStatus(`Batch insert complete! (${formatNumber(result.inserted)}/${formatNumber(result.total)} vectors)`, 'success');

        return { count: result.inserted, totalTime, avgTime };

    } catch (error) {
        log(`Batch insert failed: ${error.message || error}`, LogLevel.ERROR);
        showStatus(`Batch insert failed: ${error.message || error}`, 'error');
        throw error;
    }
}

/**
 * Run comparison benchmark: sequential vs batch
 */
async function runComparison() {
    disableAllButtons();

    try {
        // Reset displays
        DOM.speedupCard.classList.remove('visible');
        DOM.sequentialResults.classList.remove('visible');
        DOM.batchResults.classList.remove('visible');

        log('Starting comparison benchmark...', LogLevel.INFO);
        log('='.repeat(50), LogLevel.INFO);

        // Run sequential first
        const seqResult = await runSequentialInsert();
        await sleep(CONFIG.COMPARISON_DELAY);

        // Run batch
        const batchResult = await runBatchInsert();

        // Calculate efficiency ratio
        const ratio = seqResult.totalTime / batchResult.totalTime;
        const count = parseInt(DOM.vectorCount.value, 10);
        DOM.speedupValue.textContent = ratio.toFixed(2) + 'x';

        // Update unit text and note based on ratio and batch size
        if (ratio > 1.05) {
            DOM.speedupUnit.textContent = 'faster (batch wins)';
            DOM.speedupNote.textContent = 'Batch reduces JS↔WASM boundary overhead.';
        } else if (ratio < 0.95) {
            DOM.speedupUnit.textContent = 'slower (sequential wins)';
            DOM.speedupNote.textContent = 'At this scale, both methods are equivalent. HNSW graph construction dominates.';
        } else {
            DOM.speedupUnit.textContent = 'equivalent';
            DOM.speedupNote.textContent = 'At larger scales, HNSW graph construction dominates and both methods converge.';
        }

        // Add scaling note for larger batches
        if (count >= 5000) {
            DOM.speedupNote.textContent += ' Batch still provides simpler API with single call.';
        }

        DOM.speedupCard.classList.add('visible');

        log('='.repeat(50), LogLevel.INFO);
        log(`EFFICIENCY: Batch ratio ${ratio.toFixed(2)}x vs sequential`, LogLevel.SUCCESS);

        showStatus('Comparison complete!', 'success');

    } catch (error) {
        log(`Comparison failed: ${error.message || error}`, LogLevel.ERROR);
        showStatus(`Comparison failed: ${error.message || error}`, 'error');
    } finally {
        enableAllButtons();
    }
}

/**
 * Test error handling with invalid inputs
 */
async function testErrors() {
    const dims = parseInt(DOM.dimensions.value, 10);

    disableAllButtons();
    showStatus('Testing error handling...', 'loading');

    log('Starting error handling tests...', LogLevel.INFO);
    log('='.repeat(50), LogLevel.INFO);

    const results = [];

    try {
        const config = new edgeVecModule.EdgeVecConfig(dims);
        const index = new edgeVecModule.EdgeVec(config);

        // Test 1: Empty batch - should throw EMPTY_BATCH
        log('Test 1: Empty batch', LogLevel.INFO);
        try {
            index.insertBatch([]);
            results.push({ test: 'EMPTY_BATCH', passed: false, error: 'No error thrown' });
            log('  FAIL: No error thrown for empty batch', LogLevel.ERROR);
        } catch (err) {
            const errStr = String(err.message || err);
            const passed = errStr.includes('EMPTY_BATCH') || errStr.toLowerCase().includes('empty');
            results.push({ test: 'EMPTY_BATCH', passed, error: errStr });
            log(`  ${passed ? 'PASS' : 'FAIL'}: ${errStr}`, passed ? LogLevel.SUCCESS : LogLevel.ERROR);
        }

        // Test 2: Dimension mismatch
        log('Test 2: Dimension mismatch', LogLevel.INFO);
        try {
            const wrongDimVec = new Float32Array(dims + 10);
            for (let i = 0; i < wrongDimVec.length; i++) wrongDimVec[i] = Math.random();
            index.insertBatch([wrongDimVec]);
            results.push({ test: 'DIMENSION_MISMATCH', passed: false, error: 'No error thrown' });
            log('  FAIL: No error thrown for dimension mismatch', LogLevel.ERROR);
        } catch (err) {
            const errStr = String(err.message || err);
            const passed = errStr.includes('DIMENSION') || errStr.toLowerCase().includes('dimension');
            results.push({ test: 'DIMENSION_MISMATCH', passed, error: errStr });
            log(`  ${passed ? 'PASS' : 'FAIL'}: ${errStr}`, passed ? LogLevel.SUCCESS : LogLevel.ERROR);
        }

        // Test 3: Invalid vector (NaN)
        log('Test 3: Invalid vector (NaN)', LogLevel.INFO);
        try {
            const nanVec = new Float32Array(dims);
            nanVec[0] = NaN;
            index.insertBatch([nanVec]);
            results.push({ test: 'INVALID_VECTOR (NaN)', passed: false, error: 'No error thrown' });
            log('  FAIL: No error thrown for NaN vector', LogLevel.ERROR);
        } catch (err) {
            const errStr = String(err.message || err);
            const passed = errStr.includes('INVALID') || errStr.toLowerCase().includes('nan') || errStr.toLowerCase().includes('finite');
            results.push({ test: 'INVALID_VECTOR (NaN)', passed, error: errStr });
            log(`  ${passed ? 'PASS' : 'FAIL'}: ${errStr}`, passed ? LogLevel.SUCCESS : LogLevel.ERROR);
        }

        // Test 4: Invalid vector (Infinity)
        log('Test 4: Invalid vector (Infinity)', LogLevel.INFO);
        try {
            const infVec = new Float32Array(dims);
            infVec[0] = Infinity;
            index.insertBatch([infVec]);
            results.push({ test: 'INVALID_VECTOR (Inf)', passed: false, error: 'No error thrown' });
            log('  FAIL: No error thrown for Infinity vector', LogLevel.ERROR);
        } catch (err) {
            const errStr = String(err.message || err);
            const passed = errStr.includes('INVALID') || errStr.toLowerCase().includes('infinity') || errStr.toLowerCase().includes('finite');
            results.push({ test: 'INVALID_VECTOR (Inf)', passed, error: errStr });
            log(`  ${passed ? 'PASS' : 'FAIL'}: ${errStr}`, passed ? LogLevel.SUCCESS : LogLevel.ERROR);
        }

        // Summary
        const passed = results.filter(r => r.passed).length;
        const total = results.length;

        log('='.repeat(50), LogLevel.INFO);
        log(`ERROR HANDLING RESULTS: ${passed}/${total} tests passed`, passed === total ? LogLevel.SUCCESS : LogLevel.WARN);

        if (passed === total) {
            showStatus(`All ${total} error tests passed!`, 'success');
        } else {
            showStatus(`${passed}/${total} error tests passed`, 'error');
        }

    } catch (error) {
        log(`Error testing failed: ${error.message || error}`, LogLevel.ERROR);
        showStatus(`Error testing failed: ${error.message || error}`, 'error');
    } finally {
        enableAllButtons();
    }
}

// =============================================================================
// PRESET HANDLING
// =============================================================================

/**
 * Apply a preset configuration
 * @param {number} vectors - Number of vectors
 * @param {number} dims - Number of dimensions
 */
function applyPreset(vectors, dims) {
    DOM.vectorCount.value = vectors;
    DOM.dimensions.value = dims;
    log(`Applied preset: ${formatNumber(vectors)} vectors x ${dims}D`, LogLevel.INFO);
}

// =============================================================================
// INITIALIZATION
// =============================================================================

/**
 * Initialize the demo application
 */
async function init() {
    log('EdgeVec Batch Insert Demo v2.0.0', LogLevel.INFO);
    log('Initializing...', LogLevel.INFO);

    displayBrowserInfo();

    showStatus('Loading EdgeVec WASM module...', 'loading');
    updateProgress(0, 'Locating module...');

    try {
        let module = null;
        let loadedPath = null;

        for (let i = 0; i < WASM_MODULE_PATHS.length; i++) {
            const path = WASM_MODULE_PATHS[i];
            updateProgress((i / WASM_MODULE_PATHS.length) * 50, `Trying ${path}...`);

            try {
                module = await import(path);
                loadedPath = path;
                break;
            } catch (e) {
                log(`Path ${path}: Not found`, LogLevel.WARN);
            }
        }

        if (!module) {
            throw new Error(
                'Could not load EdgeVec WASM module. ' +
                'Build with: wasm-pack build --target web --release'
            );
        }

        updateProgress(70, 'Initializing WASM...');

        // Initialize WASM module
        if (module.default) {
            await module.default();
        }

        edgeVecModule = module;

        updateProgress(100, 'Ready');
        DOM.moduleStatus.textContent = 'Loaded';
        DOM.moduleStatus.classList.add('supported');

        log(`WASM module loaded from: ${loadedPath}`, LogLevel.SUCCESS);
        hideStatus();

        // Attach event listeners
        document.getElementById('runSequential').addEventListener('click', async () => {
            disableAllButtons();
            try {
                await runSequentialInsert();
            } finally {
                enableAllButtons();
            }
        });

        document.getElementById('runBatch').addEventListener('click', async () => {
            disableAllButtons();
            try {
                await runBatchInsert();
            } finally {
                enableAllButtons();
            }
        });

        document.getElementById('runComparison').addEventListener('click', runComparison);
        document.getElementById('testErrors').addEventListener('click', testErrors);

        // Preset buttons
        document.querySelectorAll('.preset-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const vectors = parseInt(btn.dataset.vectors, 10);
                const dims = parseInt(btn.dataset.dims, 10);
                applyPreset(vectors, dims);
            });
        });

        log('Demo ready. Select a preset or configure manually.', LogLevel.SUCCESS);

    } catch (error) {
        DOM.moduleStatus.textContent = 'Failed';
        DOM.moduleStatus.classList.add('error');
        log(`WASM loading failed: ${error.message}`, LogLevel.ERROR);
        showStatus(`Failed to load WASM module: ${error.message}`, 'error');
        disableAllButtons();
    }
}

// Start initialization when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}