|
| 1 | +import type { ModelProfile } from "../core/ModelProfile"; |
| 2 | +import type { MetadataStore, Page, VectorStore } from "../core/types"; |
| 3 | +import type { VectorBackend } from "../VectorBackend"; |
| 4 | +import type { EmbeddingRunner } from "../embeddings/EmbeddingRunner"; |
| 5 | +import { runPromotionSweep } from "../core/SalienceEngine"; |
| 6 | +import type { QueryResult } from "./QueryResult"; |
| 7 | + |
| 8 | +export interface QueryOptions { |
| 9 | + modelProfile: ModelProfile; |
| 10 | + embeddingRunner: EmbeddingRunner; |
| 11 | + vectorStore: VectorStore; |
| 12 | + metadataStore: MetadataStore; |
| 13 | + vectorBackend: VectorBackend; |
| 14 | + topK?: number; |
| 15 | +} |
| 16 | + |
| 17 | +function dot(a: Float32Array, b: Float32Array): number { |
| 18 | + const len = Math.min(a.length, b.length); |
| 19 | + let sum = 0; |
| 20 | + for (let i = 0; i < len; i++) { |
| 21 | + sum += a[i] * b[i]; |
| 22 | + } |
| 23 | + return sum; |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Concatenates an array of equal-length vectors into a single flat buffer. |
| 28 | + * @param vectors - Must be non-empty; every element must have the same length. |
| 29 | + */ |
| 30 | +function concatVectors(vectors: Float32Array[]): Float32Array { |
| 31 | + const dim = vectors[0].length; |
| 32 | + const out = new Float32Array(vectors.length * dim); |
| 33 | + for (let i = 0; i < vectors.length; i++) { |
| 34 | + out.set(vectors[i], i * dim); |
| 35 | + } |
| 36 | + return out; |
| 37 | +} |
| 38 | + |
| 39 | +async function scorePages( |
| 40 | + queryEmbedding: Float32Array, |
| 41 | + pages: Page[], |
| 42 | + vectorStore: VectorStore, |
| 43 | + vectorBackend: VectorBackend, |
| 44 | + maxResults: number, |
| 45 | +): Promise<Array<{ page: Page; score: number }>> { |
| 46 | + if (pages.length === 0) return []; |
| 47 | + |
| 48 | + const [firstPage] = pages; |
| 49 | + const dim = firstPage.embeddingDim; |
| 50 | + const offsets = pages.map((p) => p.embeddingOffset); |
| 51 | + |
| 52 | + // If all pages share the same embedding dimension and it matches the query, |
| 53 | + // use the vector backend for fast scoring. |
| 54 | + const uniformDim = pages.every((p) => p.embeddingDim === dim); |
| 55 | + const canUseBackend = uniformDim && queryEmbedding.length === dim; |
| 56 | + |
| 57 | + if (canUseBackend) { |
| 58 | + const embeddings = await vectorStore.readVectors(offsets, dim); |
| 59 | + const matrix = concatVectors(embeddings); |
| 60 | + const scores = await vectorBackend.dotMany(queryEmbedding, matrix, dim, pages.length); |
| 61 | + const topk = await vectorBackend.topKFromScores(scores, Math.min(maxResults, pages.length)); |
| 62 | + return topk.map((r) => ({ page: pages[r.index], score: r.score })); |
| 63 | + } |
| 64 | + |
| 65 | + // Fallback: compute dot product per page. |
| 66 | + const scored = await Promise.all( |
| 67 | + pages.map(async (page) => { |
| 68 | + const vec = await vectorStore.readVector(page.embeddingOffset, page.embeddingDim); |
| 69 | + return { page, score: dot(queryEmbedding, vec) }; |
| 70 | + }), |
| 71 | + ); |
| 72 | + |
| 73 | + scored.sort((a, b) => b.score - a.score || a.page.pageId.localeCompare(b.page.pageId)); |
| 74 | + return scored.slice(0, Math.min(maxResults, scored.length)); |
| 75 | +} |
| 76 | + |
| 77 | +export async function query( |
| 78 | + queryText: string, |
| 79 | + options: QueryOptions, |
| 80 | +): Promise<QueryResult> { |
| 81 | + const { |
| 82 | + modelProfile, |
| 83 | + embeddingRunner, |
| 84 | + vectorStore, |
| 85 | + metadataStore, |
| 86 | + vectorBackend, |
| 87 | + topK = 10, |
| 88 | + } = options; |
| 89 | + |
| 90 | + const nowIso = new Date().toISOString(); |
| 91 | + |
| 92 | + const embeddings = await embeddingRunner.embed([queryText]); |
| 93 | + if (embeddings.length !== 1) { |
| 94 | + throw new Error("Embedding provider returned unexpected number of embeddings"); |
| 95 | + } |
| 96 | + const queryEmbedding = embeddings[0]; |
| 97 | + |
| 98 | + // Score resident (hotpath) pages first. |
| 99 | + const hotpathEntries = await metadataStore.getHotpathEntries("page"); |
| 100 | + const hotpathIds = hotpathEntries.map((e) => e.entityId); |
| 101 | + |
| 102 | + const hotpathPages = (await Promise.all( |
| 103 | + hotpathIds.map((id) => metadataStore.getPage(id)), |
| 104 | + )).filter((p): p is Page => p !== undefined); |
| 105 | + |
| 106 | + const hotpathResults = await scorePages( |
| 107 | + queryEmbedding, |
| 108 | + hotpathPages, |
| 109 | + vectorStore, |
| 110 | + vectorBackend, |
| 111 | + topK, |
| 112 | + ); |
| 113 | + |
| 114 | + const seen = new Set(hotpathResults.map((r) => r.page.pageId)); |
| 115 | + |
| 116 | + // If we still need more results, score remaining pages (warm/cold). |
| 117 | + const remaining = Math.max(0, topK - hotpathResults.length); |
| 118 | + const coldResults: Array<{ page: Page; score: number }> = []; |
| 119 | + |
| 120 | + if (remaining > 0) { |
| 121 | + const allPages = await metadataStore.getAllPages(); |
| 122 | + const candidates = allPages.filter((p) => !seen.has(p.pageId)); |
| 123 | + |
| 124 | + const scored = await scorePages( |
| 125 | + queryEmbedding, |
| 126 | + candidates, |
| 127 | + vectorStore, |
| 128 | + vectorBackend, |
| 129 | + remaining, |
| 130 | + ); |
| 131 | + |
| 132 | + coldResults.push(...scored); |
| 133 | + } |
| 134 | + |
| 135 | + const combined = [...hotpathResults, ...coldResults]; |
| 136 | + combined.sort((a, b) => b.score - a.score); |
| 137 | + |
| 138 | + // Ensure combined results are sorted by descending score for top-K semantics. |
| 139 | + combined.sort((a, b) => b.score - a.score); |
| 140 | + |
| 141 | + // Update activity for returned pages |
| 142 | + await Promise.all(combined.map(async ({ page }) => { |
| 143 | + const activity = await metadataStore.getPageActivity(page.pageId); |
| 144 | + const updated = { |
| 145 | + pageId: page.pageId, |
| 146 | + queryHitCount: (activity?.queryHitCount ?? 0) + 1, |
| 147 | + lastQueryAt: nowIso, |
| 148 | + communityId: activity?.communityId, |
| 149 | + }; |
| 150 | + await metadataStore.putPageActivity(updated); |
| 151 | + })); |
| 152 | + |
| 153 | + // Recompute salience and run promotion sweep for pages returned in this query. |
| 154 | + await runPromotionSweep(combined.map((r) => r.page.pageId), metadataStore); |
| 155 | + |
| 156 | + return { |
| 157 | + pages: combined.map((r) => r.page), |
| 158 | + scores: combined.map((r) => r.score), |
| 159 | + metadata: { |
| 160 | + queryText, |
| 161 | + topK, |
| 162 | + returned: combined.length, |
| 163 | + timestamp: nowIso, |
| 164 | + modelId: modelProfile.modelId, |
| 165 | + }, |
| 166 | + }; |
| 167 | +} |
0 commit comments