|
| 1 | +import type { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver"; |
| 2 | +import { BSON, type Document } from "bson"; |
| 3 | +import type { UserConfig } from "../config.js"; |
| 4 | +import type { ConnectionManager } from "../connectionManager.js"; |
| 5 | + |
| 6 | +export type VectorFieldIndexDefinition = { |
| 7 | + type: "vector"; |
| 8 | + path: string; |
| 9 | + numDimensions: number; |
| 10 | + quantization: "none" | "scalar" | "binary"; |
| 11 | + similarity: "euclidean" | "cosine" | "dotProduct"; |
| 12 | +}; |
| 13 | + |
| 14 | +export type EmbeddingNamespace = `${string}.${string}`; |
| 15 | +export class VectorSearchEmbeddingsManager { |
| 16 | + constructor( |
| 17 | + private readonly config: UserConfig, |
| 18 | + private readonly connectionManager: ConnectionManager, |
| 19 | + private readonly embeddings: Map<EmbeddingNamespace, VectorFieldIndexDefinition[]> = new Map() |
| 20 | + ) { |
| 21 | + connectionManager.events.on("connection-close", () => { |
| 22 | + this.embeddings.clear(); |
| 23 | + }); |
| 24 | + } |
| 25 | + |
| 26 | + cleanupEmbeddingsForNamespace({ database, collection }: { database: string; collection: string }): void { |
| 27 | + const embeddingDefKey: EmbeddingNamespace = `${database}.${collection}`; |
| 28 | + this.embeddings.delete(embeddingDefKey); |
| 29 | + } |
| 30 | + |
| 31 | + async embeddingsForNamespace({ |
| 32 | + database, |
| 33 | + collection, |
| 34 | + }: { |
| 35 | + database: string; |
| 36 | + collection: string; |
| 37 | + }): Promise<VectorFieldIndexDefinition[]> { |
| 38 | + const provider = await this.assertAtlasSearchIsAvailable(); |
| 39 | + if (!provider) { |
| 40 | + return []; |
| 41 | + } |
| 42 | + |
| 43 | + // We only need the embeddings for validation now, so don't query them if |
| 44 | + // validation is disabled. |
| 45 | + if (this.config.disableEmbeddingsValidation) { |
| 46 | + return []; |
| 47 | + } |
| 48 | + |
| 49 | + const embeddingDefKey: EmbeddingNamespace = `${database}.${collection}`; |
| 50 | + const definition = this.embeddings.get(embeddingDefKey); |
| 51 | + |
| 52 | + if (!definition) { |
| 53 | + const allSearchIndexes = await provider.getSearchIndexes(database, collection); |
| 54 | + const vectorSearchIndexes = allSearchIndexes.filter((index) => index.type === "vectorSearch"); |
| 55 | + const vectorFields = vectorSearchIndexes |
| 56 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access |
| 57 | + .flatMap<Document>((index) => (index.latestDefinition?.fields as Document) ?? []) |
| 58 | + .filter((field) => this.isVectorFieldIndexDefinition(field)); |
| 59 | + |
| 60 | + this.embeddings.set(embeddingDefKey, vectorFields); |
| 61 | + return vectorFields; |
| 62 | + } |
| 63 | + |
| 64 | + return definition; |
| 65 | + } |
| 66 | + |
| 67 | + async findFieldsWithWrongEmbeddings( |
| 68 | + { |
| 69 | + database, |
| 70 | + collection, |
| 71 | + }: { |
| 72 | + database: string; |
| 73 | + collection: string; |
| 74 | + }, |
| 75 | + document: Document |
| 76 | + ): Promise<VectorFieldIndexDefinition[]> { |
| 77 | + const provider = await this.assertAtlasSearchIsAvailable(); |
| 78 | + if (!provider) { |
| 79 | + return []; |
| 80 | + } |
| 81 | + |
| 82 | + // While we can do our best effort to ensure that the embedding validation is correct |
| 83 | + // based on https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-quantization/ |
| 84 | + // it's a complex process so we will also give the user the ability to disable this validation |
| 85 | + if (this.config.disableEmbeddingsValidation) { |
| 86 | + return []; |
| 87 | + } |
| 88 | + |
| 89 | + const embeddings = await this.embeddingsForNamespace({ database, collection }); |
| 90 | + return embeddings.filter((emb) => !this.documentPassesEmbeddingValidation(emb, document)); |
| 91 | + } |
| 92 | + |
| 93 | + private async assertAtlasSearchIsAvailable(): Promise<NodeDriverServiceProvider | null> { |
| 94 | + const connectionState = this.connectionManager.currentConnectionState; |
| 95 | + if (connectionState.tag === "connected") { |
| 96 | + if (await connectionState.isSearchSupported()) { |
| 97 | + return connectionState.serviceProvider; |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + return null; |
| 102 | + } |
| 103 | + |
| 104 | + private isVectorFieldIndexDefinition(doc: Document): doc is VectorFieldIndexDefinition { |
| 105 | + return doc["type"] === "vector"; |
| 106 | + } |
| 107 | + |
| 108 | + private documentPassesEmbeddingValidation(definition: VectorFieldIndexDefinition, document: Document): boolean { |
| 109 | + const fieldPath = definition.path.split("."); |
| 110 | + let fieldRef: unknown = document; |
| 111 | + |
| 112 | + for (const field of fieldPath) { |
| 113 | + if (fieldRef && typeof fieldRef === "object" && field in fieldRef) { |
| 114 | + fieldRef = (fieldRef as Record<string, unknown>)[field]; |
| 115 | + } else { |
| 116 | + return true; |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + switch (definition.quantization) { |
| 121 | + // Because quantization is not defined by the user |
| 122 | + // we have to trust them in the format they use. |
| 123 | + case "none": |
| 124 | + return true; |
| 125 | + case "scalar": |
| 126 | + case "binary": |
| 127 | + if (fieldRef instanceof BSON.Binary) { |
| 128 | + try { |
| 129 | + const elements = fieldRef.toFloat32Array(); |
| 130 | + return elements.length === definition.numDimensions; |
| 131 | + } catch { |
| 132 | + // bits are also supported |
| 133 | + try { |
| 134 | + const bits = fieldRef.toBits(); |
| 135 | + return bits.length === definition.numDimensions; |
| 136 | + } catch { |
| 137 | + return false; |
| 138 | + } |
| 139 | + } |
| 140 | + } else { |
| 141 | + if (!Array.isArray(fieldRef)) { |
| 142 | + return false; |
| 143 | + } |
| 144 | + |
| 145 | + if (fieldRef.length !== definition.numDimensions) { |
| 146 | + return false; |
| 147 | + } |
| 148 | + |
| 149 | + if (!fieldRef.every((e) => this.isANumber(e))) { |
| 150 | + return false; |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + break; |
| 155 | + } |
| 156 | + |
| 157 | + return true; |
| 158 | + } |
| 159 | + |
| 160 | + private isANumber(value: unknown): boolean { |
| 161 | + if (typeof value === "number") { |
| 162 | + return true; |
| 163 | + } |
| 164 | + |
| 165 | + if ( |
| 166 | + value instanceof BSON.Int32 || |
| 167 | + value instanceof BSON.Decimal128 || |
| 168 | + value instanceof BSON.Double || |
| 169 | + value instanceof BSON.Long |
| 170 | + ) { |
| 171 | + return true; |
| 172 | + } |
| 173 | + |
| 174 | + return false; |
| 175 | + } |
| 176 | +} |
0 commit comments