|
| 1 | +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; |
| 2 | +import { AntflyVectorStore } from '../antfly-store.js'; |
| 3 | +import type { EmbeddingDocument } from '../types.js'; |
| 4 | + |
| 5 | +const ANTFLY_URL = process.env.ANTFLY_URL ?? 'http://localhost:8080/api/v1'; |
| 6 | +const TABLE = `test-antfly-${Date.now()}`; |
| 7 | + |
| 8 | +// Skip entire suite if antfly is not available |
| 9 | +const isAntflyAvailable = async (): Promise<boolean> => { |
| 10 | + try { |
| 11 | + const resp = await fetch(`${ANTFLY_URL}/tables`); |
| 12 | + return resp.ok; |
| 13 | + } catch { |
| 14 | + return false; |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +function makeDocs(count: number, prefix = 'doc'): EmbeddingDocument[] { |
| 19 | + const snippets = [ |
| 20 | + 'export function authenticate(token: string): boolean { return jwt.verify(token, SECRET); }', |
| 21 | + 'export function validateUser(userId: string): Promise<User> { return db.users.findOne({ id: userId }); }', |
| 22 | + 'export function handleError(err: Error): Response { logger.error(err); return new Response(err.message, { status: 500 }); }', |
| 23 | + 'export async function retryWithBackoff<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> { /* backoff */ }', |
| 24 | + 'export function searchDocuments(query: string, limit = 10): Promise<SearchResult[]> { return vectorStore.search(query); }', |
| 25 | + 'export class RateLimiter { private tokens: number; consume(): boolean { return this.tokens-- > 0; } }', |
| 26 | + 'export class EventBus { private listeners = new Map(); emit(event: string, data: unknown) { /* emit */ } }', |
| 27 | + 'export async function healthCheck(): Promise<HealthStatus> { return Promise.all([checkDB(), checkVector()]); }', |
| 28 | + 'export function indexRepository(path: string): Promise<void> { return vectorStore.add(scanner.scan(path)); }', |
| 29 | + 'export function parseConfig(path: string): Config { return JSON.parse(fs.readFileSync(path, "utf-8")); }', |
| 30 | + ]; |
| 31 | + |
| 32 | + return Array.from({ length: count }, (_, i) => ({ |
| 33 | + id: `${prefix}-${i}`, |
| 34 | + text: snippets[i % snippets.length], |
| 35 | + metadata: { type: 'function', file: `src/${prefix}-${i}.ts`, line: i * 10 }, |
| 36 | + })); |
| 37 | +} |
| 38 | + |
| 39 | +function sleep(ms: number): Promise<void> { |
| 40 | + return new Promise((r) => setTimeout(r, ms)); |
| 41 | +} |
| 42 | + |
| 43 | +describe.runIf(await isAntflyAvailable())('AntflyVectorStore', () => { |
| 44 | + let store: AntflyVectorStore; |
| 45 | + |
| 46 | + beforeAll(async () => { |
| 47 | + store = new AntflyVectorStore({ baseUrl: ANTFLY_URL, table: TABLE }); |
| 48 | + await store.initialize(); |
| 49 | + }, 30_000); |
| 50 | + |
| 51 | + afterAll(async () => { |
| 52 | + try { |
| 53 | + await store.clear(); |
| 54 | + await store.close(); |
| 55 | + } catch { |
| 56 | + // Best-effort cleanup |
| 57 | + } |
| 58 | + }); |
| 59 | + |
| 60 | + it('creates table on initialize (idempotent)', async () => { |
| 61 | + // Second initialize should not throw |
| 62 | + const store2 = new AntflyVectorStore({ baseUrl: ANTFLY_URL, table: TABLE }); |
| 63 | + await expect(store2.initialize()).resolves.not.toThrow(); |
| 64 | + await store2.close(); |
| 65 | + }); |
| 66 | + |
| 67 | + it('inserts and retrieves documents by key', async () => { |
| 68 | + const docs = makeDocs(3); |
| 69 | + await store.add(docs); |
| 70 | + |
| 71 | + // Wait for antfly to process |
| 72 | + await sleep(3000); |
| 73 | + |
| 74 | + const result = await store.get('doc-0'); |
| 75 | + expect(result).not.toBeNull(); |
| 76 | + expect(result!.id).toBe('doc-0'); |
| 77 | + expect(result!.text).toContain('authenticate'); |
| 78 | + expect(result!.metadata).toHaveProperty('type', 'function'); |
| 79 | + }, 15_000); |
| 80 | + |
| 81 | + it('upserts on duplicate key', async () => { |
| 82 | + const original = await store.get('doc-0'); |
| 83 | + expect(original).not.toBeNull(); |
| 84 | + |
| 85 | + // Re-insert same key with different text |
| 86 | + await store.add([ |
| 87 | + { |
| 88 | + id: 'doc-0', |
| 89 | + text: 'UPDATED: export function authenticate(token: string, opts?: AuthOptions): boolean { /* v2 */ }', |
| 90 | + metadata: { type: 'function', file: 'src/auth-v2.ts', line: 1 }, |
| 91 | + }, |
| 92 | + ]); |
| 93 | + |
| 94 | + await sleep(2000); |
| 95 | + |
| 96 | + const updated = await store.get('doc-0'); |
| 97 | + expect(updated).not.toBeNull(); |
| 98 | + expect(updated!.text).toContain('UPDATED'); |
| 99 | + expect(updated!.metadata).toHaveProperty('file', 'src/auth-v2.ts'); |
| 100 | + }, 15_000); |
| 101 | + |
| 102 | + it('searches by semantic query', async () => { |
| 103 | + // Insert more docs for better search results |
| 104 | + await store.add(makeDocs(10, 'search')); |
| 105 | + await sleep(5000); |
| 106 | + |
| 107 | + const results = await store.searchText('authentication and user validation'); |
| 108 | + expect(results.length).toBeGreaterThan(0); |
| 109 | + expect(results[0]).toHaveProperty('id'); |
| 110 | + expect(results[0]).toHaveProperty('score'); |
| 111 | + expect(results[0]).toHaveProperty('metadata'); |
| 112 | + }, 20_000); |
| 113 | + |
| 114 | + it('respects search limit', async () => { |
| 115 | + const results = await store.searchText('authentication function', { limit: 3 }); |
| 116 | + expect(results.length).toBeLessThanOrEqual(3); |
| 117 | + }, 10_000); |
| 118 | + |
| 119 | + it('respects scoreThreshold', async () => { |
| 120 | + const allResults = await store.searchText('authentication'); |
| 121 | + const filtered = await store.searchText('authentication', { scoreThreshold: 999 }); |
| 122 | + expect(filtered.length).toBe(0); |
| 123 | + expect(allResults.length).toBeGreaterThan(0); |
| 124 | + }, 10_000); |
| 125 | + |
| 126 | + it('deletes documents', async () => { |
| 127 | + await store.add([ |
| 128 | + { id: 'to-delete-1', text: 'temporary document one', metadata: {} }, |
| 129 | + { id: 'to-delete-2', text: 'temporary document two', metadata: {} }, |
| 130 | + ]); |
| 131 | + await sleep(2000); |
| 132 | + |
| 133 | + await store.delete(['to-delete-1', 'to-delete-2']); |
| 134 | + |
| 135 | + const result = await store.get('to-delete-1'); |
| 136 | + expect(result).toBeNull(); |
| 137 | + }, 15_000); |
| 138 | + |
| 139 | + it('counts documents', async () => { |
| 140 | + // Ensure data exists |
| 141 | + await store.add(makeDocs(2, 'cnt')); |
| 142 | + await sleep(3000); |
| 143 | + |
| 144 | + const count = await store.count(); |
| 145 | + expect(count).toBeGreaterThan(0); |
| 146 | + }, 15_000); |
| 147 | + |
| 148 | + it('gets all documents', async () => { |
| 149 | + // Ensure we have data |
| 150 | + const count = await store.count(); |
| 151 | + if (count === 0) { |
| 152 | + await store.add(makeDocs(3, 'getall')); |
| 153 | + await sleep(3000); |
| 154 | + } |
| 155 | + |
| 156 | + const all = await store.getAll(); |
| 157 | + expect(all.length).toBeGreaterThan(0); |
| 158 | + expect(all[0]).toHaveProperty('id'); |
| 159 | + expect(all[0]).toHaveProperty('score', 1); // Full scan = score 1 |
| 160 | + expect(all[0]).toHaveProperty('metadata'); |
| 161 | + }, 15_000); |
| 162 | + |
| 163 | + it('searches by document ID', async () => { |
| 164 | + // Ensure we have data |
| 165 | + const count = await store.count(); |
| 166 | + if (count === 0) { |
| 167 | + await store.add(makeDocs(5, 'sbd')); |
| 168 | + await sleep(5000); |
| 169 | + } |
| 170 | + |
| 171 | + // Find a doc that exists |
| 172 | + const all = await store.getAll({ limit: 1 }); |
| 173 | + if (all.length === 0) return; // Skip if still empty |
| 174 | + |
| 175 | + const results = await store.searchByDocumentId(all[0].id); |
| 176 | + expect(results.length).toBeGreaterThan(0); |
| 177 | + }, 20_000); |
| 178 | + |
| 179 | + it('returns empty for searchByDocumentId with missing ID', async () => { |
| 180 | + const results = await store.searchByDocumentId('nonexistent-id'); |
| 181 | + expect(results).toEqual([]); |
| 182 | + }, 10_000); |
| 183 | + |
| 184 | + it('returns model info', () => { |
| 185 | + const info = store.getModelInfo(); |
| 186 | + expect(info.dimension).toBe(384); |
| 187 | + expect(info.modelName).toBe('BAAI/bge-small-en-v1.5'); |
| 188 | + }); |
| 189 | + |
| 190 | + it('returns storage size', async () => { |
| 191 | + const size = await store.getStorageSize(); |
| 192 | + expect(size).toBeGreaterThanOrEqual(0); |
| 193 | + }, 10_000); |
| 194 | + |
| 195 | + it('handles empty table search', async () => { |
| 196 | + // Create a fresh empty table |
| 197 | + const emptyTable = `test-empty-${Date.now()}`; |
| 198 | + const emptyStore = new AntflyVectorStore({ baseUrl: ANTFLY_URL, table: emptyTable }); |
| 199 | + await emptyStore.initialize(); |
| 200 | + |
| 201 | + const results = await emptyStore.searchText('anything'); |
| 202 | + expect(results).toEqual([]); |
| 203 | + |
| 204 | + // Cleanup |
| 205 | + await emptyStore.clear(); |
| 206 | + await emptyStore.close(); |
| 207 | + }, 15_000); |
| 208 | + |
| 209 | + it('search() with embedding vector throws', async () => { |
| 210 | + await expect(store.search([0.1, 0.2, 0.3])).rejects.toThrow( |
| 211 | + 'does not accept pre-computed embeddings' |
| 212 | + ); |
| 213 | + }); |
| 214 | + |
| 215 | + it('throws when not initialized', async () => { |
| 216 | + const uninitialized = new AntflyVectorStore({ baseUrl: ANTFLY_URL, table: 'nope' }); |
| 217 | + await expect(uninitialized.searchText('test')).rejects.toThrow('not initialized'); |
| 218 | + // Empty add is a no-op (early return before assertReady) |
| 219 | + await expect(uninitialized.add([])).resolves.not.toThrow(); |
| 220 | + // Non-empty add should throw |
| 221 | + await expect(uninitialized.add(makeDocs(1))).rejects.toThrow('not initialized'); |
| 222 | + }); |
| 223 | + |
| 224 | + it('detects model mismatch', async () => { |
| 225 | + const mismatchStore = new AntflyVectorStore({ |
| 226 | + baseUrl: ANTFLY_URL, |
| 227 | + table: TABLE, |
| 228 | + model: 'nomic-ai/nomic-embed-text-v1.5', // Different model than the table was created with |
| 229 | + }); |
| 230 | + |
| 231 | + await expect(mismatchStore.initialize()).rejects.toThrow('Model mismatch'); |
| 232 | + }, 10_000); |
| 233 | + |
| 234 | + it('clears all data', async () => { |
| 235 | + await store.clear(); |
| 236 | + |
| 237 | + const count = await store.count(); |
| 238 | + expect(count).toBe(0); |
| 239 | + |
| 240 | + const all = await store.getAll(); |
| 241 | + expect(all).toEqual([]); |
| 242 | + }, 15_000); |
| 243 | + |
| 244 | + it('handles delete with empty array', async () => { |
| 245 | + // Should not throw |
| 246 | + await expect(store.delete([])).resolves.not.toThrow(); |
| 247 | + }); |
| 248 | + |
| 249 | + it('handles add with empty array', async () => { |
| 250 | + // Should not throw |
| 251 | + await expect(store.add([])).resolves.not.toThrow(); |
| 252 | + }); |
| 253 | +}); |
0 commit comments