@mastra/mongodb 1.27.1 → 1.28.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -11,7 +11,7 @@ let _mastra_core_agent = require("@mastra/core/agent");
11
11
  let _mastra_core_evals = require("@mastra/core/evals");
12
12
  let _mastra_core_storage_domains_skills = require("@mastra/core/storage/domains/skills");
13
13
  // package.json
14
- var version = "1.27.1";
14
+ var version = "1.28.0-alpha.0";
15
15
  // src/vector/filter.ts
16
16
  /**
17
17
  * Translator for MongoDB filter queries.
@@ -81,7 +81,298 @@ var MongoDBFilterTranslator = class extends _mastra_core_vector_filter.BaseFilte
81
81
  return filter === void 0 || filter === null || typeof filter === "object" && Object.keys(filter).length === 0;
82
82
  }
83
83
  };
84
+ // src/vector/ownership.ts
85
+ const retired = (v) => [...v.retiredTextIndexNames ?? [], ...v.retiredVectorIndexNames ?? []];
86
+ /** Whether `v` owns `name`: a current name with its flag, or a retired name of either role. */
87
+ const owns = (v, name) => v.ownsVectorIndex === true && v.searchIndexName === name || v.ownsTextIndex === true && v.textSearchIndexName === name || retired(v).includes(name);
88
+ /** Whether `v` references `name`: a current or retired name of either role. */
89
+ const uses = (v, name) => v.searchIndexName === name || v.textSearchIndexName === name || retired(v).includes(name);
90
+ /** The id `v` records for search index `name`, if any. */
91
+ function idFor(v, name) {
92
+ return v.indexIds?.find((e) => e.name === name)?.id;
93
+ }
94
+ /**
95
+ * Decides, per physical index owned by `own`, whether to drop it, hand it to a sibling, or release
96
+ * it (§3.4 T1). Any live sibling referencing a name blocks its drop (I11a); `observed` (the name's
97
+ * listed id, taken just before) only decides which ids may be written (I11b).
98
+ */
99
+ function planDeleteCleanup(own, siblings, observed) {
100
+ const live = siblings.filter((s) => !s.deleting);
101
+ const candidates = [
102
+ ...own.ownsVectorIndex === true ? [own.searchIndexName] : [],
103
+ ...own.ownsTextIndex === true && own.textSearchIndexName ? [own.textSearchIndexName] : [],
104
+ ...retired(own)
105
+ ];
106
+ const plan = {
107
+ drop: [],
108
+ transfers: [],
109
+ released: [],
110
+ rewrites: [],
111
+ kept: []
112
+ };
113
+ for (const name of new Set(candidates)) {
114
+ const ownId = idFor(own, name);
115
+ const confirmed = ownId !== void 0 && observed[name] === ownId ? ownId : void 0;
116
+ const owners = live.filter((s) => owns(s, name));
117
+ if (owners.length) {
118
+ plan.released.push(name);
119
+ if (confirmed) {
120
+ for (const s of owners) if (idFor(s, name) !== confirmed) plan.rewrites.push({
121
+ toId: s._id,
122
+ name,
123
+ id: confirmed
124
+ });
125
+ }
126
+ continue;
127
+ }
128
+ const recipient = live.filter((s) => uses(s, name)).sort((a, b) => a._id < b._id ? -1 : a._id > b._id ? 1 : 0)[0];
129
+ if (!recipient) {
130
+ plan.drop.push(name);
131
+ continue;
132
+ }
133
+ const id = confirmed ?? (ownId === void 0 ? observed[name] : void 0);
134
+ if (id === void 0) {
135
+ plan.kept.push(name);
136
+ continue;
137
+ }
138
+ plan.transfers.push({
139
+ toId: recipient._id,
140
+ field: recipient.textSearchIndexName === name ? "ownsTextIndex" : "ownsVectorIndex",
141
+ name,
142
+ id
143
+ });
144
+ if (confirmed && idFor(recipient, name) !== void 0 && idFor(recipient, name) !== confirmed) plan.rewrites.push({
145
+ toId: recipient._id,
146
+ name,
147
+ id: confirmed
148
+ });
149
+ }
150
+ return plan;
151
+ }
152
+ // src/vector/provisioning.ts
153
+ /**
154
+ * The update that undoes a P0 write of `written` over `previous` (§3.9): each field P0 wrote gets
155
+ * its previous value back, or is removed when `previous` lacked it. Nothing else is touched.
156
+ */
157
+ function rollbackRestore(previous, written) {
158
+ const $set = {};
159
+ const $unset = {};
160
+ for (const key of Object.keys(written)) if (previous[key] === void 0) $unset[key] = "";
161
+ else $set[key] = previous[key];
162
+ return {
163
+ $set,
164
+ $unset
165
+ };
166
+ }
167
+ const CREATE_TIMEOUT_MS = 6e4;
168
+ /** ObjectId timestamps are second-truncated; an id is foreign by timestamp only when MORE than this before creatingAt. */
169
+ const ID_TIMESTAMP_MARGIN_MS = 3e4;
170
+ /** A listing row that is present and not on its way out. */
171
+ function isLiveRow(row) {
172
+ return !!row && row.status !== "DELETING" && row.status !== "DOES_NOT_EXIST";
173
+ }
174
+ const HEX24 = /^[0-9a-f]{24}$/i;
175
+ /** Creation time embedded in an ObjectId-shaped id; undefined for anything else (Atlas Local ids may not be ObjectIds). */
176
+ function idTimestampMs(id) {
177
+ return HEX24.test(id) ? parseInt(id.slice(0, 8), 16) * 1e3 : void 0;
178
+ }
179
+ /** True only when both ids are 24-hex and `a` sorts after `b`; false otherwise. */
180
+ function isNewerId(a, b) {
181
+ return HEX24.test(a) && HEX24.test(b) && a.toLowerCase() > b.toLowerCase();
182
+ }
183
+ /** Server codes after which the create may or may not have landed: timeouts, shutdown, step-down, unreachable host. */
184
+ const MAYBE_LANDED_CODES = [
185
+ 6,
186
+ 7,
187
+ 50,
188
+ 89,
189
+ 91,
190
+ 189,
191
+ 262,
192
+ 9001,
193
+ 10107,
194
+ 11600,
195
+ 11602,
196
+ 13435,
197
+ 13436
198
+ ];
199
+ function p4OutcomeOf(error) {
200
+ return error instanceof mongodb.MongoServerError && typeof error.code === "number" && !MAYBE_LANDED_CODES.includes(error.code) ? {
201
+ kind: "refused",
202
+ error
203
+ } : {
204
+ kind: "unknown",
205
+ error
206
+ };
207
+ }
208
+ /** The §3.1 P5 table plus the id-timestamp rule. */
209
+ function classify(p4, row, creatingAt) {
210
+ if (p4.kind === "refused") return { kind: "not-created" };
211
+ if (p4.kind === "unknown") return row?.id ? {
212
+ kind: "uncertain",
213
+ candidateId: row.id
214
+ } : { kind: "pending" };
215
+ if (row && row.id !== p4.id) return {
216
+ kind: "foreign",
217
+ byTimestamp: false
218
+ };
219
+ const ts = idTimestampMs(p4.id);
220
+ if (ts !== void 0 && ts < creatingAt.getTime() - 3e4) return {
221
+ kind: "foreign",
222
+ byTimestamp: true
223
+ };
224
+ return {
225
+ kind: "proven",
226
+ id: p4.id
227
+ };
228
+ }
229
+ /**
230
+ * §4.2 for an abandoned `creating` doc: an absent name, or a row whose id another record holds or
231
+ * whose id time is more than the margin before `creatingAt`, is not this attempt's, so the doc goes.
232
+ * Anything else may be ours and is kept as uncertain. Rows of any status count as present.
233
+ */
234
+ function resolveCreating(row, creatingAt, heldIds) {
235
+ if (!row?.id || heldIds.has(row.id)) return {
236
+ action: "delete",
237
+ byTimestamp: false
238
+ };
239
+ const ts = idTimestampMs(row.id);
240
+ if (ts !== void 0 && ts < creatingAt.getTime() - 3e4) return {
241
+ action: "delete",
242
+ byTimestamp: true
243
+ };
244
+ return {
245
+ action: "uncertain",
246
+ candidateId: row.id
247
+ };
248
+ }
249
+ /**
250
+ * §3.8 step 3 for proven incarnation `R` of `name`, given its live `users` and the listed id
251
+ * `observed`. Any user blocks the drop (I11a). Owners come first: each is released, and rewritten
252
+ * to R only when the listing confirms R (I11b). Otherwise the lowest-`_id` user gets R, again only
253
+ * when the listing shows R; else nothing is transferred, as R is gone and the name may be a stranger's.
254
+ */
255
+ function planOrphanCleanup(name, R, observed, users) {
256
+ const owners = users.filter((u) => owns(u, name));
257
+ if (owners.length) return {
258
+ kind: "release",
259
+ owners: owners.map((o) => ({
260
+ toId: o._id,
261
+ ...observed === R && idFor(o, name) !== R ? { rewriteId: R } : {}
262
+ }))
263
+ };
264
+ const [recipient] = users.filter((u) => uses(u, name)).sort((a, b) => a._id < b._id ? -1 : a._id > b._id ? 1 : 0);
265
+ if (!recipient) return { kind: "drop" };
266
+ if (observed !== R) return { kind: "forget" };
267
+ const field = recipient.textSearchIndexName === name ? "ownsTextIndex" : "ownsVectorIndex";
268
+ return {
269
+ kind: "transfer",
270
+ toId: recipient._id,
271
+ field,
272
+ id: R
273
+ };
274
+ }
275
+ // src/vector/search-definition.ts
276
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
277
+ /** Recursively sort object keys; arrays keep their order. */
278
+ function canon(v) {
279
+ if (Array.isArray(v)) return v.map(canon);
280
+ if (!isObj(v)) return v;
281
+ return Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])]));
282
+ }
283
+ function normalizeMapping(m, index) {
284
+ if (!isObj(m)) return canon(m);
285
+ const out = { ...m };
286
+ if (m.type === "string") {
287
+ out.indexOptions ??= "offsets";
288
+ out.store ??= true;
289
+ out.norms ??= "include";
290
+ out.analyzer = m.analyzer ?? index.analyzer;
291
+ out.searchAnalyzer = m.searchAnalyzer ?? m.analyzer ?? index.searchAnalyzer;
292
+ }
293
+ if (m.type === "document" && m.dynamic === void 0) out.dynamic = false;
294
+ if (isObj(m.fields)) out.fields = normalizeFields(m.fields, index);
295
+ if (isObj(out.fields) && !Object.keys(out.fields).length) delete out.fields;
296
+ return canon(out);
297
+ }
298
+ function normalizeFields(fields, index) {
299
+ return Object.fromEntries(Object.entries(fields).map(([name, value]) => [name, (Array.isArray(value) ? value : [value]).map((m) => normalizeMapping(m, index)).sort((x, y) => cmp(JSON.stringify(x), JSON.stringify(y)))]));
300
+ }
301
+ const cmp = (x, y) => x < y ? -1 : x > y ? 1 : 0;
302
+ /** Canonical form of an Atlas Search index definition. Only the spec's listed defaults are filled in. */
303
+ function normalizeSearchDefinition(def) {
304
+ if (!isObj(def)) return def;
305
+ const out = { ...def };
306
+ out.analyzer = def.analyzer ?? "lucene.standard";
307
+ out.searchAnalyzer = def.searchAnalyzer ?? out.analyzer;
308
+ if (def.storedSource === false) delete out.storedSource;
309
+ if (isObj(def.mappings)) {
310
+ const m = { ...def.mappings };
311
+ if (m.dynamic === void 0) m.dynamic = false;
312
+ if (isObj(m.fields)) m.fields = normalizeFields(m.fields, {
313
+ analyzer: out.analyzer,
314
+ searchAnalyzer: out.searchAnalyzer
315
+ });
316
+ if (isObj(m.fields) && !Object.keys(m.fields).length) delete m.fields;
317
+ out.mappings = m;
318
+ }
319
+ return canon(out);
320
+ }
321
+ function searchDefinitionsEquivalent(a, b) {
322
+ return JSON.stringify(normalizeSearchDefinition(a)) === JSON.stringify(normalizeSearchDefinition(b));
323
+ }
84
324
  // src/vector/index.ts
325
+ /** A journal doc whose lease ran out on the server's clock; only such a doc is the reconciler's. */
326
+ const LEASE_EXPIRED = { $expr: { $lt: ["$leaseUntil", "$$NOW"] } };
327
+ /** Pipeline expression: `indexIds` with the entry for `name` set to `id` (I11b callers decide when). */
328
+ function indexIdsWith(name, id) {
329
+ return { $concatArrays: [{ $filter: {
330
+ input: { $ifNull: ["$indexIds", []] },
331
+ cond: { $ne: ["$$this.name", { $literal: name }] }
332
+ } }, { $literal: [{
333
+ name,
334
+ id
335
+ }] }] };
336
+ }
337
+ /** Pipeline `$set` fields every mutating registry write carries: backfilled generation, `rev + 1`, a fresh token. */
338
+ function mutationFields(claimToken = (0, _lukeed_uuid.v4)(), generation = (0, _lukeed_uuid.v4)()) {
339
+ return {
340
+ generation: { $ifNull: ["$generation", { $literal: generation }] },
341
+ rev: { $add: [{ $ifNull: ["$rev", 0] }, 1] },
342
+ claimToken: { $literal: claimToken }
343
+ };
344
+ }
345
+ /**
346
+ * Wrap each value in `$literal`, so a value starting with `$` is never read as an expression.
347
+ * `undefined` is written as `null`, which the driver does by default anyway: with the client's
348
+ * `ignoreUndefined` it would otherwise be stored as `{}`, which readers take for a set value (an
349
+ * absent `autoEmbed` would read as an auto-embedding index).
350
+ */
351
+ function literals(fields) {
352
+ return Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, { $literal: v ?? null }]));
353
+ }
354
+ /**
355
+ * A provisioning failure. `rollback` is true only when nothing was proven in the call, so the
356
+ * caller may still undo its P0 write (I4); the caller rethrows `error`.
357
+ */
358
+ var ProvisionAbort = class extends Error {
359
+ error;
360
+ rollback;
361
+ constructor(error, rollback) {
362
+ super("provisioning aborted");
363
+ this.error = error;
364
+ this.rollback = rollback;
365
+ }
366
+ };
367
+ /** Names a `deleting` entry is still responsible for dropping (its drop set, as rewritten by T1). */
368
+ function recordedDropSet(entry) {
369
+ return [.../* @__PURE__ */ new Set([
370
+ ...entry.ownsVectorIndex === true ? [entry.searchIndexName] : [],
371
+ ...entry.ownsTextIndex === true && entry.textSearchIndexName ? [entry.textSearchIndexName] : [],
372
+ ...entry.retiredTextIndexNames ?? [],
373
+ ...entry.retiredVectorIndexNames ?? []
374
+ ])];
375
+ }
85
376
  /** Name an index's embedding mode for a conflict message. */
86
377
  function describeEmbedding(config) {
87
378
  return config ? `autoEmbed (path "${config.path}", model "${config.model}")` : "client-side vectors";
@@ -110,6 +401,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
110
401
  * this process and lazily hydrated from the live index definition otherwise.
111
402
  * `_id` is excluded because it is materialised separately by the fallback path.
112
403
  */
404
+ /** Filter paths per logical index, with the physical index (`collection/searchIndex`) they were read from. */
113
405
  declaredFilterPaths = /* @__PURE__ */ new Map();
114
406
  /**
115
407
  * Per-index target: where the data lives, what the Atlas index is called, and whether
@@ -130,12 +422,31 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
130
422
  * command; `version` is retained for the unsupported-version error message.
131
423
  */
132
424
  rankFusionSupport;
425
+ /** Cached result of a successful transaction capability probe; a failed probe is never cached. */
426
+ transactionSupport;
427
+ /** @internal test seam; never set in production. */
428
+ testHooks;
133
429
  /**
134
430
  * Name of the mastra-owned collection that durably records the logical-index → target
135
431
  * mapping (`_id: <indexName>`). Kept separate from caller data so a BYO operational
136
432
  * collection is never polluted with mastra bookkeeping. Excluded from `listIndexes`.
137
433
  */
138
434
  static REGISTRY_COLLECTION = "__mastra_vector_indexes__";
435
+ /** The provisioning journal (§2.2): one doc per search-index create attempt. Excluded from `listIndexes`. */
436
+ static JOURNAL_COLLECTION = "__mastra_vector_ops__";
437
+ /** The journal's indexes, ensured once per instance; reset on failure so a later call retries. */
438
+ journalIndexes;
439
+ /** Set once the journal-index failure was logged, so a persistent failure warns once per instance. */
440
+ journalIndexWarned = false;
441
+ /**
442
+ * Registry reads and writes, and their transactions, never inherit the client's read preference
443
+ * or concerns (I7a): a read from a lagging secondary would miss a committed registration.
444
+ */
445
+ static TXN_OPTIONS = {
446
+ readPreference: "primary",
447
+ readConcern: { level: "majority" },
448
+ writeConcern: { w: "majority" }
449
+ };
139
450
  /**
140
451
  * Waits between attempts while a queried index is in INITIAL_SYNC, about six seconds in all.
141
452
  * On a live Atlas cluster the window lasted around two seconds for both a regular and an
@@ -149,6 +460,10 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
149
460
  2e3,
150
461
  2e3
151
462
  ];
463
+ /** Maximum number of matching `_id`s materialized by the pre-filter fallback. */
464
+ static MAX_PREFILTER_CANDIDATES = 1e5;
465
+ /** BSON array budget, reserving 4 MiB of the 16 MiB command limit for the rest of the pipeline. */
466
+ static MAX_PREFILTER_ID_BYTES = 12582912;
152
467
  /**
153
468
  * MongoDB query operators supported inside `$vectorSearch.filter`. Intentionally
154
469
  * conservative: filters using any operator outside this set fall back to the
@@ -220,7 +535,10 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
220
535
  isByo,
221
536
  allowWrites: isByo ? persisted.allowWrites ?? false : true,
222
537
  textSearchIndexName: persisted.textSearchIndexName,
223
- autoEmbed: persisted.autoEmbed
538
+ autoEmbed: persisted.autoEmbed,
539
+ ownsVectorIndex: persisted.ownsVectorIndex,
540
+ ownsTextIndex: persisted.ownsTextIndex,
541
+ ownsCollection: persisted.ownsCollection
224
542
  };
225
543
  this.indexTargets.set(indexName, target);
226
544
  return {
@@ -237,19 +555,6 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
237
555
  };
238
556
  }
239
557
  /**
240
- * True when another logical index (a different registry `_id`) on the same collection
241
- * references `physicalIndexName` as its vector or text search index. Used by deleteIndex
242
- * to preserve a shared Atlas index that a sibling logical index still depends on
243
- * (e.g. two BYO logical indexes on one collection sharing the default dynamic text index).
244
- */
245
- async isIndexNameReferencedElsewhere(indexName, collectionName, physicalIndexName) {
246
- return await this.db.collection(MongoDBVector.REGISTRY_COLLECTION).findOne({
247
- _id: { $ne: indexName },
248
- collectionName,
249
- $or: [{ searchIndexName: physicalIndexName }, { textSearchIndexName: physicalIndexName }]
250
- }) !== null;
251
- }
252
- /**
253
558
  * Reject metadata containing circular references BEFORE it reaches the driver.
254
559
  *
255
560
  * bson@7.x's iterative `calculateObjectSize` (used by `bulkWrite`) has no cycle
@@ -315,9 +620,254 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
315
620
  });
316
621
  return `${target.collectionName}_search_index`;
317
622
  }
623
+ /** The registry handle, pinned to the primary with majority concerns (I7a). */
624
+ registry() {
625
+ return this.db.collection(MongoDBVector.REGISTRY_COLLECTION, MongoDBVector.TXN_OPTIONS);
626
+ }
627
+ /** The journal handle, with the registry's I7a options. */
628
+ journal() {
629
+ const journal = this.db.collection(MongoDBVector.JOURNAL_COLLECTION, MongoDBVector.TXN_OPTIONS);
630
+ this.journalIndexes ??= journal.createIndexes([{ key: {
631
+ collectionName: 1,
632
+ name: 1,
633
+ state: 1
634
+ } }, { key: {
635
+ indexName: 1,
636
+ generation: 1
637
+ } }]).catch((error) => {
638
+ if (!this.journalIndexWarned) {
639
+ this.journalIndexWarned = true;
640
+ this.logger.warn(`could not create the indexes of ${MongoDBVector.JOURNAL_COLLECTION}; retrying on the next call: ${error}`);
641
+ }
642
+ this.journalIndexes = void 0;
643
+ });
644
+ return journal;
645
+ }
646
+ /** Run `fn` in a transaction with the I7a options. */
647
+ async inTransaction(fn) {
648
+ const session = this.client.startSession();
649
+ try {
650
+ let result;
651
+ await session.withTransaction(async () => {
652
+ result = await fn(session);
653
+ }, MongoDBVector.TXN_OPTIONS);
654
+ return result;
655
+ } finally {
656
+ await session.endSession();
657
+ }
658
+ }
659
+ /**
660
+ * The lazy reconciler (§4): resolves this collection's journal docs whose lease expired. An
661
+ * `intent` never reached Atlas and goes; a `creating` one goes when its name is absent or its
662
+ * row is explained, and otherwise becomes `uncertain` (I9). Every write is conditioned on the
663
+ * observed state, so concurrent reconcilers and a live op never double-apply. A `created` doc
664
+ * is recorded (P7, P7b or P7c), an `orphaned` one cleaned from §3.8 step 2. Never throws.
665
+ * Returns the ids of the docs it tried, so the call's handshake cleans a stale block only once.
666
+ */
667
+ async reconcile(collectionName) {
668
+ const tried = /* @__PURE__ */ new Set();
669
+ try {
670
+ const journal = this.journal();
671
+ const docs = await journal.find({
672
+ collectionName,
673
+ state: { $ne: "uncertain" },
674
+ ...LEASE_EXPIRED
675
+ }).sort({ leaseUntil: 1 }).limit(20).toArray();
676
+ for (const doc of docs) {
677
+ tried.add(doc._id);
678
+ try {
679
+ if (doc.state === "intent") await journal.findOneAndDelete({
680
+ _id: doc._id,
681
+ state: "intent",
682
+ ...LEASE_EXPIRED
683
+ });
684
+ else if (doc.state === "creating") await this.reconcileCreating(doc);
685
+ else if (doc.state === "created") await this.reconcileCreated(doc);
686
+ else if (doc.state === "orphaned") await this.cleanupOrphan(doc, 2);
687
+ } catch (error) {
688
+ this.logger.warn(`could not reconcile provisioning record ${doc._id} on "${collectionName}": ${error}`);
689
+ await this.expireLease(doc);
690
+ }
691
+ }
692
+ } catch (error) {
693
+ this.logger.warn(`could not reconcile the provisioning records of "${collectionName}": ${error}`);
694
+ }
695
+ return tried;
696
+ }
697
+ /** Expire a journal doc still in `doc.state` now, so any call retries it at once and behind older ones (R14). */
698
+ async expireLease(doc) {
699
+ await this.journal().updateOne({
700
+ _id: doc._id,
701
+ state: doc.state
702
+ }, [{ $set: { leaseUntil: "$$NOW" } }]).catch((error) => this.logger.warn(`could not expire provisioning record ${doc._id}: ${error}`));
703
+ }
704
+ /**
705
+ * §4.2 `created`: P7 with the stored id, else P7b (retired) or P7c (§3.8 from step 1), as the op
706
+ * would; their CONFLICT is only logged here. P7 and P7b take the doc in their transaction, so a
707
+ * second reconciler's transaction conflicts, then finds it gone and stops.
708
+ */
709
+ async reconcileCreated(doc) {
710
+ const { _id, indexName, collectionName, name, role, generation } = doc;
711
+ const R = doc.indexId;
712
+ const resolved = /* @__PURE__ */ new Error("reconcile: the record was resolved by another call");
713
+ const missed = /* @__PURE__ */ new Error("reconcile: the registration did not match");
714
+ const record = async (retire) => {
715
+ try {
716
+ await this.inTransaction(async (session) => {
717
+ if ((await this.journal().deleteOne({
718
+ _id,
719
+ state: "created",
720
+ ...LEASE_EXPIRED
721
+ }, { session })).deletedCount === 0) throw resolved;
722
+ if (!await this.recordOwnership(indexName, role, name, generation, R, session, retire)) throw missed;
723
+ });
724
+ return true;
725
+ } catch (error) {
726
+ if (error === missed) return false;
727
+ throw error;
728
+ }
729
+ };
730
+ const what = `search index "${name}" (id ${R}) on "${collectionName}" of provisioning record ${_id}`;
731
+ await this.testHooks?.beforeRecordOwnership?.(indexName, name);
732
+ try {
733
+ for (let round = 0; round < 3; round++) {
734
+ if (await record(false)) return;
735
+ const current = await this.readRegistryEntry(indexName);
736
+ if (!current || current.generation !== generation || current.deleting) {
737
+ const outcome = await this.cleanupOrphan(doc, 1);
738
+ this.logger.warn(`${what}: index "${indexName}" was removed or recreated; the index was ${outcome}`);
739
+ return;
740
+ }
741
+ if (await record(true)) {
742
+ this.logger.warn(`${what}: index "${indexName}" changed its target; kept as a retired index`);
743
+ return;
744
+ }
745
+ }
746
+ this.logger.warn(`${what}: index "${indexName}" kept changing; left for a later reconcile`);
747
+ await this.expireLease(doc);
748
+ } catch (error) {
749
+ if (error !== resolved) throw error;
750
+ }
751
+ }
752
+ /** §4.2 `creating`: list the name, then delete the doc or mark it `uncertain`. */
753
+ async reconcileCreating(doc) {
754
+ const { _id, collectionName, name } = doc;
755
+ const [row] = await this.listSearchIndexRows(this.db.collection(collectionName), name, "reconciler");
756
+ const heldIds = /* @__PURE__ */ new Set();
757
+ if (row) {
758
+ for (const e of await this.registry().find({ collectionName }).toArray()) for (const x of e.indexIds ?? []) heldIds.add(x.id);
759
+ for (const j of await this.journal().find({
760
+ collectionName,
761
+ _id: { $ne: _id }
762
+ }).toArray()) {
763
+ if (j.indexId) heldIds.add(j.indexId);
764
+ if (j.candidateId) heldIds.add(j.candidateId);
765
+ }
766
+ }
767
+ const creatingAt = doc.creatingAt ?? /* @__PURE__ */ new Date(0);
768
+ const resolution = resolveCreating(row, creatingAt, heldIds);
769
+ if (resolution.action === "delete") {
770
+ if (await this.journal().findOneAndDelete({
771
+ _id,
772
+ state: "creating"
773
+ }) && resolution.byTimestamp) this.warnForeignByTimestamp(name, collectionName, row.id, creatingAt);
774
+ return;
775
+ }
776
+ if ((await this.journal().updateOne({
777
+ _id,
778
+ state: "creating"
779
+ }, { $set: {
780
+ state: "uncertain",
781
+ candidateId: resolution.candidateId
782
+ } })).modifiedCount === 1) this.warnUncertain(name, collectionName, resolution.candidateId);
783
+ }
784
+ warnUncertain(name, collectionName, candidateId) {
785
+ this.logger.warn(`search index "${name}" on "${collectionName}" (id ${candidateId}) may have been created by Mastra; kept; drop it manually if unused`);
786
+ }
787
+ warnForeignByTimestamp(name, collectionName, id, creatingAt) {
788
+ this.logger.warn(`search index "${name}" on "${collectionName}" (id ${id}) is not recorded as created by Mastra: its id time ${new Date(idTimestampMs(id)).toISOString()} is more than ${ID_TIMESTAMP_MARGIN_MS / 1e3} s before the pre-list at ${creatingAt.toISOString()}`);
789
+ }
790
+ /**
791
+ * The only path for `createSearchIndexes`, `dropSearchIndex` and `updateSearchIndex` (I7a): on the
792
+ * primary, with no read or write concern, which the server rejects for these commands.
793
+ */
794
+ async runSearchIndexCommand(command, timeoutMS) {
795
+ if (timeoutMS) command = {
796
+ ...command,
797
+ maxTimeMS: timeoutMS
798
+ };
799
+ const run = () => this.db.command(command, {
800
+ readPreference: "primary",
801
+ ...timeoutMS ? { timeoutMS } : {}
802
+ });
803
+ const hook = this.testHooks?.createSearchIndexesCommand;
804
+ return "createSearchIndexes" in command && hook ? hook(command, run) : run();
805
+ }
806
+ /**
807
+ * List the search indexes named `name` on the primary with `readConcern: local` (I7a). The driver's
808
+ * listing cursor ignores the handle's and the client's settings, and takes a read preference only
809
+ * as a `ReadPreference` instance, so both are passed per call. A missing collection has none.
810
+ */
811
+ async listSearchIndexRows(collection, name, phase) {
812
+ const stubbed = this.testHooks?.listSearchIndexesStub?.(name, phase);
813
+ if (stubbed) return stubbed;
814
+ try {
815
+ return await collection.listSearchIndexes(name, {
816
+ readPreference: mongodb.ReadPreference.primary,
817
+ readConcern: { level: "local" }
818
+ }).toArray();
819
+ } catch (err) {
820
+ if (err?.codeName === "NamespaceNotFound" || err?.code === 26) return [];
821
+ throw err;
822
+ }
823
+ }
824
+ /** The id of the live row listed for `name`; a dying row is present but not ours (§3.1), so it counts as none. */
825
+ async liveIdOf(collection, name, phase) {
826
+ return (await this.listSearchIndexRows(collection, name, phase)).find(isLiveRow)?.id;
827
+ }
828
+ /**
829
+ * §2.3 refresh-time TOFU (Q5): for each owned name with no `indexIds` entry, list it and record the
830
+ * observed id. Filtered on the name still owned, no entry yet, and the call's P0 pin, so only a
831
+ * call whose P0 is still the latest write records it, and only once. A write advances `pin` in
832
+ * place, so the call's rollback (§3.9) still matches and undoes P0's fields; it keeps the id,
833
+ * which is TOFU proof of a name the registration already owned (§2.3), not part of P0's write.
834
+ * Best effort: delete-time TOFU (§3.7) covers a name it misses.
835
+ */
836
+ async tofuIndexIds(indexName, pin, names, collection) {
837
+ try {
838
+ const entry = await this.readRegistryEntry(indexName);
839
+ if (!entry || entry.generation !== pin.generation) return;
840
+ for (const { role, name } of names) {
841
+ const nameField = role === "vector" ? "searchIndexName" : "textSearchIndexName";
842
+ const ownsField = role === "vector" ? "ownsVectorIndex" : "ownsTextIndex";
843
+ if (entry[nameField] !== name || entry[ownsField] !== true || idFor(entry, name)) continue;
844
+ const id = await this.liveIdOf(collection, name, "tofu");
845
+ if (!id) continue;
846
+ await this.testHooks?.beforeTofuWrite?.(indexName, name);
847
+ const claimToken = (0, _lukeed_uuid.v4)();
848
+ if ((await this.registry().updateOne({
849
+ _id: indexName,
850
+ generation: pin.generation,
851
+ claimToken: pin.claimToken,
852
+ rev: pin.rev,
853
+ deleting: { $ne: true },
854
+ [nameField]: name,
855
+ [ownsField]: true,
856
+ indexIds: { $not: { $elemMatch: { name } } }
857
+ }, [{ $set: {
858
+ indexIds: indexIdsWith(name, id),
859
+ ...mutationFields(claimToken)
860
+ } }])).matchedCount === 0) return;
861
+ pin.claimToken = claimToken;
862
+ pin.rev += 1;
863
+ }
864
+ } catch (error) {
865
+ this.logger.warn(`could not record the listed search index ids of index "${indexName}": ${error}`);
866
+ }
867
+ }
318
868
  /** Read a logical-index target from the durable registry collection, if present. */
319
869
  async readRegistryEntry(indexName) {
320
- return await this.db.collection(MongoDBVector.REGISTRY_COLLECTION).findOne({ _id: indexName }) ?? null;
870
+ return await this.registry().findOne({ _id: indexName }) ?? null;
321
871
  }
322
872
  /**
323
873
  * Persist (upsert) a logical-index target so it survives a process restart. Idempotent
@@ -328,26 +878,994 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
328
878
  * still pins `_id`, an incompatible entry matches nothing, the upsert attempts an insert, and
329
879
  * the duplicate `_id` surfaces as a duplicate-key error (code 11000) instead of overwriting
330
880
  * the entry someone else registered. Callers that only refresh part of an entry omit it.
881
+ *
882
+ * Every write backfills `generation`, bumps `rev` and sets the `claimToken` in `entry` (a fresh
883
+ * one if absent). `expressions` are pipeline expressions set in the same stage, so they read the
884
+ * pre-write document. Returns what it left, or null when nothing matched without upsert.
331
885
  */
332
- async writeRegistryEntry(indexName, entry, claim) {
333
- await this.db.collection(MongoDBVector.REGISTRY_COLLECTION).updateOne({
886
+ async writeRegistryEntry(indexName, entry, claim, upsert = true, expressions = {}) {
887
+ const { claimToken = (0, _lukeed_uuid.v4)(), ...fields } = entry;
888
+ return this.p0Write({
334
889
  _id: indexName,
335
890
  ...claim
336
- }, { $set: {
891
+ }, (mutation) => [{ $set: {
892
+ ...literals({
893
+ indexName,
894
+ ...fields
895
+ }),
896
+ ...expressions,
897
+ ...mutation
898
+ } }], claimToken, upsert);
899
+ }
900
+ /**
901
+ * A P0 write. It returns the document as it was before the write, so a rollback restores what
902
+ * this write overwrote (not what the call read earlier) and removes the entry only when this
903
+ * write inserted it (I4). The pin is derived from that pre-image: the same `$ifNull` generation
904
+ * and `rev + 1` the pipeline computes. Null when nothing matched and nothing was inserted.
905
+ */
906
+ async p0Write(filter, update, claimToken, upsert) {
907
+ const generation = (0, _lukeed_uuid.v4)();
908
+ const result = await this.registry().findOneAndUpdate(filter, update(mutationFields(claimToken, generation)), {
909
+ upsert,
910
+ returnDocument: "before",
911
+ includeResultMetadata: true
912
+ });
913
+ const before = result.value;
914
+ if (!before && !result.lastErrorObject?.upserted) return null;
915
+ return {
916
+ before,
917
+ pin: {
918
+ generation: before?.generation ?? generation,
919
+ claimToken,
920
+ rev: (before?.rev ?? 0) + 1
921
+ }
922
+ };
923
+ }
924
+ /**
925
+ * P7: record that this store created search index `name` for `role`, with its proven `id`.
926
+ * Pinned on the registration's `generation` and on `name` still being its current name for the
927
+ * role, not on the call's `claimToken`, so an identical concurrent refresh never makes it miss.
928
+ * The id guard (I11b) requires the name's `indexIds` entry to be absent, `id`, or the R′ read
929
+ * just before; a newer R′ (another call's later create) is kept and logged. No upsert, so a
930
+ * deleted entry stays deleted. Bumps `rev` and sets a fresh `claimToken`, so a concurrent
931
+ * call's rollback never restores a snapshot from before this flag. Returns the id recorded
932
+ * for the name (`id`, or the newer R′ kept), or undefined when the write missed.
933
+ */
934
+ async recordOwnership(indexName, role, name, generation, id, session, retire = false) {
935
+ const registry = this.registry();
936
+ const nameField = role === "vector" ? "searchIndexName" : "textSearchIndexName";
937
+ const ownsField = role === "vector" ? "ownsVectorIndex" : "ownsTextIndex";
938
+ const retiredField = role === "vector" ? "retiredVectorIndexNames" : "retiredTextIndexNames";
939
+ const current = { $eq: [`$${nameField}`, { $literal: name }] };
940
+ const ownership = retire ? {
941
+ [ownsField]: { $cond: [
942
+ current,
943
+ true,
944
+ `$${ownsField}`
945
+ ] },
946
+ [retiredField]: { $cond: [
947
+ current,
948
+ `$${retiredField}`,
949
+ { $setUnion: [{ $ifNull: [`$${retiredField}`, []] }, { $literal: [name] }] }
950
+ ] }
951
+ } : { [ownsField]: { $literal: true } };
952
+ const recorded = (await registry.findOne({ _id: indexName }, { session }))?.indexIds?.find((e) => e.name === name)?.id;
953
+ let keep = id;
954
+ if (recorded && recorded !== id && isNewerId(recorded, id)) {
955
+ keep = recorded;
956
+ this.logger.warn(`search index "${name}" of index "${indexName}": kept the newer recorded id ${recorded} instead of ${id}, which this call created`);
957
+ }
958
+ return (await registry.updateOne({
959
+ _id: indexName,
960
+ generation,
961
+ deleting: { $ne: true },
962
+ ...retire ? {} : { [nameField]: name },
963
+ $or: [{ indexIds: { $not: { $elemMatch: { name } } } }, { indexIds: { $elemMatch: {
964
+ name,
965
+ id: { $in: recorded ? [id, recorded] : [id] }
966
+ } } }]
967
+ }, [{ $set: {
968
+ ...ownership,
969
+ indexIds: indexIdsWith(name, keep),
970
+ ...mutationFields()
971
+ } }], { session })).matchedCount === 1 ? keep : void 0;
972
+ }
973
+ /**
974
+ * Provision one search index (§3.1): the attach fast path (P1), the journal intent (P2), the P3
975
+ * check, the decisive pre-list (P3a), the fence (P3b), the create by raw command (P4), the
976
+ * verdict (P5), the durable proof (P6) and recording the proven id (P7). Never rolls back itself;
977
+ * every failure is a {@link ProvisionAbort} telling the caller whether it still may.
978
+ */
979
+ async provisionSearchIndex(args) {
980
+ const { indexName, collection, role, op, description, pin, check } = args;
981
+ const { name, type } = description;
982
+ const collectionName = collection.collectionName;
983
+ const leaseMs = this.testHooks?.leaseMs ?? 3e5;
984
+ const journal = this.journal();
985
+ const _id = `${pin.claimToken}:${role}`;
986
+ const identity = {
337
987
  indexName,
338
- ...entry
339
- } }, { upsert: true });
988
+ generation: pin.generation,
989
+ collectionName,
990
+ name,
991
+ type,
992
+ role
993
+ };
994
+ const stuck = (row) => new _mastra_core_error.MastraError({
995
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "CONFLICT"),
996
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
997
+ category: _mastra_core_error.ErrorCategory.USER,
998
+ details: {
999
+ indexName,
1000
+ collectionName
1001
+ },
1002
+ text: `search index "${name}" on "${collectionName}" is in status ${row.status} (id ${row.id}); the previous index under this name is still being removed. Retry. If it persists, drop it manually.`
1003
+ });
1004
+ const dropIntent = () => journal.findOneAndDelete({
1005
+ _id,
1006
+ state: "intent"
1007
+ });
1008
+ let hasIntent = false;
1009
+ let p4;
1010
+ try {
1011
+ const [listed] = await this.listSearchIndexRows(collection, name, "P1");
1012
+ if (listed) {
1013
+ if (!isLiveRow(listed)) throw stuck(listed);
1014
+ await check();
1015
+ const [again] = await this.listSearchIndexRows(collection, name, "P1");
1016
+ if (again) {
1017
+ if (!isLiveRow(again)) throw stuck(again);
1018
+ return {
1019
+ outcome: "attached",
1020
+ row: again
1021
+ };
1022
+ }
1023
+ }
1024
+ await journal.updateOne({
1025
+ _id,
1026
+ state: { $exists: false }
1027
+ }, [{ $set: {
1028
+ ...literals({
1029
+ ...identity,
1030
+ state: "intent"
1031
+ }),
1032
+ leaseUntil: { $add: ["$$NOW", leaseMs] },
1033
+ createdAt: "$$NOW"
1034
+ } }], { upsert: true });
1035
+ hasIntent = true;
1036
+ await this.testHooks?.afterProvisionIntent?.(indexName, name);
1037
+ await check();
1038
+ await this.testHooks?.beforeDecisivePreList?.(indexName, name);
1039
+ const [pre] = await this.listSearchIndexRows(collection, name, "P3a");
1040
+ if (pre) {
1041
+ await dropIntent();
1042
+ hasIntent = false;
1043
+ if (!isLiveRow(pre)) throw stuck(pre);
1044
+ return {
1045
+ outcome: "attached",
1046
+ row: pre
1047
+ };
1048
+ }
1049
+ await this.testHooks?.beforeAtlasCreate?.(indexName, name);
1050
+ const fenced = await journal.findOneAndUpdate({
1051
+ _id,
1052
+ state: "intent"
1053
+ }, [{ $set: {
1054
+ state: { $literal: "creating" },
1055
+ preListAbsent: { $literal: true },
1056
+ creatingAt: "$$NOW",
1057
+ leaseUntil: { $add: ["$$NOW", leaseMs] }
1058
+ } }], { returnDocument: "after" });
1059
+ hasIntent = false;
1060
+ if (!fenced) throw new _mastra_core_error.MastraError({
1061
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "CONFLICT"),
1062
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1063
+ category: _mastra_core_error.ErrorCategory.USER,
1064
+ details: {
1065
+ indexName,
1066
+ collectionName
1067
+ },
1068
+ text: `Index "${indexName}" was removed or recreated by another call while this one ran, so nothing was provisioned. Retry.`
1069
+ });
1070
+ const creatingAt = fenced.creatingAt;
1071
+ try {
1072
+ const id = (await this.runSearchIndexCommand({
1073
+ createSearchIndexes: collectionName,
1074
+ indexes: [description]
1075
+ }, CREATE_TIMEOUT_MS)).indexesCreated?.[0]?.id;
1076
+ p4 = id ? {
1077
+ kind: "ok",
1078
+ id: String(id)
1079
+ } : {
1080
+ kind: "unknown",
1081
+ error: /* @__PURE__ */ new Error("create returned no id")
1082
+ };
1083
+ } catch (error) {
1084
+ p4 = p4OutcomeOf(error);
1085
+ }
1086
+ await this.testHooks?.afterAtlasCreate?.(indexName, name);
1087
+ const [row] = await this.listSearchIndexRows(collection, name, "P5").catch(() => []);
1088
+ const verdict = classify(p4, row, creatingAt);
1089
+ if (verdict.kind === "proven") {
1090
+ await this.testHooks?.beforeProof?.(indexName, name);
1091
+ await journal.updateOne({ _id }, {
1092
+ $set: {
1093
+ state: "created",
1094
+ indexId: verdict.id
1095
+ },
1096
+ $setOnInsert: {
1097
+ ...identity,
1098
+ createdAt: /* @__PURE__ */ new Date(),
1099
+ leaseUntil: new Date(Date.now() + leaseMs)
1100
+ }
1101
+ }, { upsert: true });
1102
+ await this.testHooks?.beforeRecordOwnership?.(indexName, name);
1103
+ const conflict = (text, cleanup) => new ProvisionAbort(new _mastra_core_error.MastraError({
1104
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "CONFLICT"),
1105
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1106
+ category: _mastra_core_error.ErrorCategory.USER,
1107
+ details: {
1108
+ indexName,
1109
+ collectionName,
1110
+ searchIndexName: name,
1111
+ ...cleanup ? { cleanup } : {}
1112
+ },
1113
+ text
1114
+ }), false);
1115
+ const record = (retire) => this.inTransaction(async (session) => {
1116
+ const kept = await this.recordOwnership(indexName, role, name, pin.generation, verdict.id, session, retire);
1117
+ if (kept) await journal.deleteOne({ _id }, { session });
1118
+ return kept;
1119
+ });
1120
+ for (let round = 0; round < 3; round++) {
1121
+ const recorded = await record(false);
1122
+ if (recorded) return {
1123
+ outcome: "owned",
1124
+ id: recorded
1125
+ };
1126
+ const current = await this.readRegistryEntry(indexName);
1127
+ if (!current || current.generation !== pin.generation || current.deleting) {
1128
+ const now = /* @__PURE__ */ new Date();
1129
+ throw conflict("the registration was removed or recreated while this call ran; what it created was handed over or removed", await this.cleanupOrphan({
1130
+ _id,
1131
+ ...identity,
1132
+ state: "created",
1133
+ indexId: verdict.id,
1134
+ leaseUntil: now,
1135
+ createdAt: now
1136
+ }, 1, op));
1137
+ }
1138
+ if (await record(true)) throw conflict("the target changed concurrently; the index this call created is kept as a retired index of the registration and removed by deleteIndex");
1139
+ }
1140
+ throw conflict(`Index "${indexName}" kept changing while this call recorded search index "${name}" (id ${verdict.id}); it is kept under a cleanup record. Retry.`);
1141
+ }
1142
+ switch (verdict.kind) {
1143
+ case "uncertain":
1144
+ await journal.updateOne({ _id }, {
1145
+ $set: {
1146
+ state: "uncertain",
1147
+ candidateId: verdict.candidateId
1148
+ },
1149
+ $setOnInsert: {
1150
+ ...identity,
1151
+ createdAt: /* @__PURE__ */ new Date(),
1152
+ leaseUntil: new Date(Date.now() + leaseMs)
1153
+ }
1154
+ }, { upsert: true });
1155
+ this.warnUncertain(name, collectionName, verdict.candidateId);
1156
+ if (!isLiveRow(row)) throw new ProvisionAbort(stuck(row), false);
1157
+ return {
1158
+ outcome: "attached",
1159
+ row
1160
+ };
1161
+ case "pending": throw new ProvisionAbort(new _mastra_core_error.MastraError({
1162
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "FAILED"),
1163
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1164
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
1165
+ details: {
1166
+ indexName,
1167
+ collectionName
1168
+ },
1169
+ text: `The create of search index "${name}" on "${collectionName}" may or may not have reached Atlas. Retry.`
1170
+ }, p4.error), false);
1171
+ }
1172
+ await journal.deleteOne({ _id });
1173
+ if (row && !isLiveRow(row)) throw new ProvisionAbort(stuck(row), true);
1174
+ if (verdict.kind === "foreign") {
1175
+ if (verdict.byTimestamp) this.warnForeignByTimestamp(name, collectionName, p4.id, creatingAt);
1176
+ return {
1177
+ outcome: "attached",
1178
+ row
1179
+ };
1180
+ }
1181
+ const error = p4.error;
1182
+ const message = String(error?.message);
1183
+ if (error?.code === 2 && /duplicate index name/i.test(message) || error?.code === 68 || /is already defined for collection/i.test(message)) {
1184
+ await check();
1185
+ const [again] = await this.listSearchIndexRows(collection, name, "P5");
1186
+ if (again && !isLiveRow(again)) throw new ProvisionAbort(stuck(again), true);
1187
+ if (again) {
1188
+ this.logger.debug(`search index "${name}" on "${collectionName}": a concurrent create won (id ${again.id}); attached, not recorded as created by this call`);
1189
+ return {
1190
+ outcome: "attached",
1191
+ row: again
1192
+ };
1193
+ }
1194
+ }
1195
+ throw new ProvisionAbort(error, true);
1196
+ } catch (error) {
1197
+ if (error instanceof ProvisionAbort) throw error;
1198
+ if (hasIntent) await dropIntent().catch(() => {});
1199
+ throw new ProvisionAbort(error, !p4 || p4.kind === "refused");
1200
+ }
1201
+ }
1202
+ /**
1203
+ * Undo this call's P0 write after provisioning failed (§3.9). Pinned on the `generation`,
1204
+ * `claimToken` and `rev` P0 left (I4): any write since (a refresh, a P7, a claim, a delete
1205
+ * transaction) makes it miss, and then everything stays as it is. `restore` null means P0
1206
+ * inserted the entry, so it is removed; otherwise only the fields P0 wrote are restored, with
1207
+ * `rev` bumped and a fresh `claimToken`, so `rev` never goes down and a backfilled `generation`
1208
+ * stays. Callers never run it after a P7 of the same call. Best effort, so the caller still sees
1209
+ * the provisioning error. Returns true when the inserted entry was removed.
1210
+ */
1211
+ async rollbackRegistryEntry(indexName, pin, restore) {
1212
+ this.indexTargets.delete(indexName);
1213
+ this.declaredFilterPaths.delete(indexName);
1214
+ try {
1215
+ const registry = this.registry();
1216
+ const filter = {
1217
+ _id: indexName,
1218
+ generation: pin.generation,
1219
+ claimToken: pin.claimToken,
1220
+ rev: pin.rev,
1221
+ deleting: { $ne: true }
1222
+ };
1223
+ if (!restore) return (await registry.deleteOne(filter)).deletedCount === 1;
1224
+ await registry.updateOne(filter, {
1225
+ $set: {
1226
+ ...restore.$set,
1227
+ rev: pin.rev + 1,
1228
+ claimToken: (0, _lukeed_uuid.v4)()
1229
+ },
1230
+ ...Object.keys(restore.$unset).length ? { $unset: restore.$unset } : {}
1231
+ });
1232
+ } catch {}
1233
+ return false;
1234
+ }
1235
+ /** Refuse to reuse an entry whose deletion has started; only finishing the delete clears it. */
1236
+ assertNotDeleting(entry, op) {
1237
+ if (!entry?.deleting) return;
1238
+ throw new _mastra_core_error.MastraError({
1239
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "INDEX_DELETING"),
1240
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1241
+ category: _mastra_core_error.ErrorCategory.USER,
1242
+ details: { indexName: entry._id },
1243
+ text: `Index "${entry._id}" is being deleted. Retry deleteIndex({ indexName: "${entry._id}" }) to finish the deletion, then try again.`
1244
+ });
1245
+ }
1246
+ /**
1247
+ * Whether the deployment supports transactions (replica set or sharded cluster). Throws when
1248
+ * the check itself fails: a failed check must never be mistaken for a standalone server.
1249
+ */
1250
+ async probeTransactionSupport() {
1251
+ if (this.testHooks?.probeTransactions) return this.testHooks.probeTransactions();
1252
+ if (this.transactionSupport === void 0) {
1253
+ const hello = await this.db.admin().command({ hello: 1 });
1254
+ this.transactionSupport = Boolean(hello.setName) || hello.msg === "isdbgrid";
1255
+ }
1256
+ return this.transactionSupport;
1257
+ }
1258
+ /**
1259
+ * Run a delete decision in a transaction, or directly on a confirmed standalone server.
1260
+ * Returns only the result of the attempt that committed. Never rolls registry state back.
1261
+ */
1262
+ async runDeleteTransaction(indexName, fn) {
1263
+ const fail = (code, error) => new _mastra_core_error.MastraError({
1264
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", code),
1265
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1266
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
1267
+ details: { indexName },
1268
+ ...code === "OUTCOME_UNKNOWN" ? { text: `The delete of index "${indexName}" may or may not have committed. Retry deleteIndex({ indexName: "${indexName}" }); a not-registered error on retry means it completed. A retry deletes whatever is registered under this name then, and no read can tell the original registration from a re-created one: if another process may re-create it, coordinate with it first, and don't retry by name if you can't rule out a re-create.` } : {}
1269
+ }, error);
1270
+ let supported;
1271
+ try {
1272
+ supported = await this.probeTransactionSupport();
1273
+ } catch (error) {
1274
+ throw fail("CAPABILITY_CHECK_FAILED", error);
1275
+ }
1276
+ if (!supported) return await fn(void 0);
1277
+ const session = this.client.startSession();
1278
+ let result;
1279
+ let committed = false;
1280
+ try {
1281
+ await session.withTransaction(async () => {
1282
+ result = await fn(session);
1283
+ }, MongoDBVector.TXN_OPTIONS);
1284
+ committed = true;
1285
+ await this.testHooks?.afterDeleteCommit?.(indexName);
1286
+ return result;
1287
+ } catch (error) {
1288
+ if (committed || error?.hasErrorLabel?.("UnknownTransactionCommitResult")) throw fail("OUTCOME_UNKNOWN", error);
1289
+ if (error instanceof _mastra_core_error.MastraError) throw error;
1290
+ throw fail("FAILED", error);
1291
+ } finally {
1292
+ await session.endSession();
1293
+ }
1294
+ }
1295
+ /**
1296
+ * Whether `own` (read inside a delete transaction) is a newer lifetime than `entry` (the call's
1297
+ * first read): true means the registration to delete is finished and `own` replaced it. An entry
1298
+ * read without a generation can't tell a backfill from a replacement, so that refuses retryably.
1299
+ */
1300
+ replacedSince(entry, own) {
1301
+ if (entry.generation) return own.generation !== entry.generation;
1302
+ if (!own.generation) return false;
1303
+ throw new _mastra_core_error.MastraError({
1304
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", "CONFLICT"),
1305
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1306
+ category: _mastra_core_error.ErrorCategory.USER,
1307
+ details: { indexName: entry._id },
1308
+ text: `Index "${entry._id}" changed while deleteIndex ran, so nothing was dropped. Retry deleteIndex({ indexName: "${entry._id}" }).`
1309
+ });
1310
+ }
1311
+ /**
1312
+ * Delete a registration whose collection stays (BYO, or managed with `ownsCollection: false`).
1313
+ * Step 1 decides, in one transaction, which Mastra-created search indexes to drop and which to
1314
+ * hand to a sibling still using them; steps 2 and 3 drop the rest and remove the entry. A
1315
+ * `null` collection means it is gone, so every drop is already done.
1316
+ */
1317
+ async deleteKeepCollection(entry, collection) {
1318
+ const indexName = entry._id;
1319
+ const registry = this.registry();
1320
+ let work;
1321
+ if (entry.deleting && entry.deleteToken) work = {
1322
+ drop: recordedDropSet(entry),
1323
+ deleteToken: entry.deleteToken
1324
+ };
1325
+ else {
1326
+ const observed = {};
1327
+ for (const name of collection ? recordedDropSet(entry) : []) observed[name] = await this.liveIdOf(collection, name, "delete");
1328
+ let attempt = 0;
1329
+ let uncertain = [];
1330
+ work = await this.runDeleteTransaction(indexName, async (session) => {
1331
+ attempt++;
1332
+ uncertain = [];
1333
+ const own = await registry.findOne({ _id: indexName }, { session });
1334
+ if (!own || own.collectionName !== entry.collectionName || !(own.isByo || own.ownsCollection === false)) return "gone";
1335
+ if (this.replacedSince(entry, own)) return "gone";
1336
+ if (own.deleting && own.deleteToken) return {
1337
+ drop: recordedDropSet(own),
1338
+ deleteToken: own.deleteToken
1339
+ };
1340
+ const live = {
1341
+ collectionName: own.collectionName,
1342
+ _id: { $ne: indexName },
1343
+ deleting: { $ne: true }
1344
+ };
1345
+ const siblings = await registry.find(live, { session }).toArray();
1346
+ await this.testHooks?.insideDeleteTransaction?.(indexName, attempt);
1347
+ const plan = planDeleteCleanup(own, siblings, observed);
1348
+ const idOf = (name) => own.indexIds?.find((e) => e.name === name)?.id ?? observed[name];
1349
+ const drop = collection ? plan.drop.filter((name) => idOf(name)) : plan.drop;
1350
+ if (!await this.applyCleanupWrites(indexName, own.collectionName, plan, siblings, session)) throw new _mastra_core_error.MastraError({
1351
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", "CONFLICT"),
1352
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1353
+ category: _mastra_core_error.ErrorCategory.USER,
1354
+ details: { indexName },
1355
+ text: `Registrations using the search indexes of index "${indexName}" changed while deleteIndex ran, so nothing was dropped. Retry deleteIndex({ indexName: "${indexName}" }).`
1356
+ });
1357
+ const held = (await registry.find({
1358
+ collectionName: own.collectionName,
1359
+ _id: { $ne: indexName }
1360
+ }, { session }).toArray()).flatMap((d) => d.generation ? [d.generation] : []);
1361
+ uncertain = await this.journal().find({
1362
+ collectionName: own.collectionName,
1363
+ state: "uncertain",
1364
+ $or: [...own.generation ? [{ generation: own.generation }] : [], { generation: { $nin: held } }]
1365
+ }, { session }).toArray();
1366
+ if (uncertain.length) await this.journal().deleteMany({ _id: { $in: uncertain.map((d) => d._id) } }, { session });
1367
+ if (!drop.length) {
1368
+ await registry.deleteOne({ _id: indexName }, { session });
1369
+ return "handed-off";
1370
+ }
1371
+ const deleteToken = (0, _lukeed_uuid.v4)();
1372
+ await registry.updateOne({ _id: indexName }, {
1373
+ $set: {
1374
+ ownsVectorIndex: own.ownsVectorIndex === true && drop.includes(own.searchIndexName),
1375
+ ownsTextIndex: own.ownsTextIndex === true && !!own.textSearchIndexName && drop.includes(own.textSearchIndexName),
1376
+ retiredTextIndexNames: (own.retiredTextIndexNames ?? []).filter((n) => drop.includes(n)),
1377
+ retiredVectorIndexNames: (own.retiredVectorIndexNames ?? []).filter((n) => drop.includes(n)),
1378
+ indexIds: drop.flatMap((name) => {
1379
+ const id = idOf(name);
1380
+ return id ? [{
1381
+ name,
1382
+ id
1383
+ }] : [];
1384
+ }),
1385
+ deleting: true,
1386
+ deleteToken
1387
+ },
1388
+ $inc: { rev: 1 }
1389
+ }, { session });
1390
+ return {
1391
+ drop,
1392
+ deleteToken
1393
+ };
1394
+ });
1395
+ for (const d of uncertain) this.warnUncertain(d.name, d.collectionName, d.candidateId);
1396
+ }
1397
+ if (typeof work === "string") return;
1398
+ const { drop, deleteToken } = work;
1399
+ await this.testHooks?.afterDeleteStep1?.(indexName);
1400
+ for (const name of drop) {
1401
+ await this.testHooks?.beforeDeleteDrop?.(indexName, name);
1402
+ const current = await registry.findOne({
1403
+ _id: indexName,
1404
+ deleting: true,
1405
+ deleteToken
1406
+ });
1407
+ if (!current) return;
1408
+ const outcome = await this.handOverPendingDrop(entry.collectionName, indexName, deleteToken, name);
1409
+ if (outcome === "gone") return;
1410
+ if (outcome === "drop" && collection) await this.dropRecordedOrListed(entry.collectionName, name, idFor(current, name));
1411
+ }
1412
+ await this.testHooks?.beforeDeleteFinalize?.(indexName);
1413
+ await registry.deleteOne({
1414
+ _id: indexName,
1415
+ deleting: true,
1416
+ deleteToken
1417
+ });
1418
+ }
1419
+ /**
1420
+ * Write a delete plan's transfers (the owns flag, plus the id when the plan carries one) and id
1421
+ * rewrites, and log its kept names. Every user the plan chose (a recipient, or an owner of a
1422
+ * released name among `siblings`) gets `rev + 1` and a fresh `claimToken` (R4-2, R5-2), so a
1423
+ * pinned undo by its own op misses; the other live siblings get `rev + 1`. False when a recipient
1424
+ * no longer uses the name it was planned for, or an owner no longer owns the name it was to
1425
+ * rewrite, which only a deployment without transactions can see.
1426
+ */
1427
+ async applyCleanupWrites(indexName, collectionName, plan, siblings, session) {
1428
+ const registry = this.registry();
1429
+ for (const t of plan.transfers) {
1430
+ const nameField = t.field === "ownsTextIndex" ? "textSearchIndexName" : "searchIndexName";
1431
+ if ((await registry.updateOne({
1432
+ _id: t.toId,
1433
+ [nameField]: t.name,
1434
+ deleting: { $ne: true }
1435
+ }, [{ $set: {
1436
+ [t.field]: { $literal: true },
1437
+ ...t.id ? { indexIds: indexIdsWith(t.name, t.id) } : {}
1438
+ } }], { session })).matchedCount === 0) return false;
1439
+ }
1440
+ for (const r of plan.rewrites) if ((await registry.updateOne({
1441
+ _id: r.toId,
1442
+ deleting: { $ne: true },
1443
+ $or: [
1444
+ {
1445
+ searchIndexName: r.name,
1446
+ ownsVectorIndex: true
1447
+ },
1448
+ {
1449
+ textSearchIndexName: r.name,
1450
+ ownsTextIndex: true
1451
+ },
1452
+ { retiredTextIndexNames: r.name },
1453
+ { retiredVectorIndexNames: r.name }
1454
+ ]
1455
+ }, [{ $set: { indexIds: indexIdsWith(r.name, r.id) } }], { session })).matchedCount === 0) return false;
1456
+ const chosen = [.../* @__PURE__ */ new Set([...plan.transfers.map((t) => t.toId), ...siblings.filter((s) => !s.deleting && plan.released.some((n) => owns(s, n))).map((s) => s._id)])];
1457
+ for (const _id of chosen) await registry.updateOne({
1458
+ _id,
1459
+ deleting: { $ne: true }
1460
+ }, [{ $set: mutationFields() }], { session });
1461
+ await registry.updateMany({
1462
+ collectionName,
1463
+ _id: { $nin: [indexName, ...chosen] },
1464
+ deleting: { $ne: true }
1465
+ }, { $inc: { rev: 1 } }, { session });
1466
+ for (const name of plan.kept) this.logger.warn(`search index "${name}" on "${collectionName}": the incarnation index "${indexName}" recorded is gone or was replaced, and other registrations still reference the name; neither dropped nor handed over. Drop it manually if unused`);
1467
+ return true;
1468
+ }
1469
+ /**
1470
+ * Last check before a delete drops `name`: a registration that started using it after the delete
1471
+ * committed its drop set takes over the cleanup responsibility instead (or keeps it, if it
1472
+ * already owns the index), and the name leaves this delete's drop set. This is the delete half
1473
+ * of a write-then-read handshake with {@link assertNoPendingDrop}: each side writes its
1474
+ * registration state before reading the other's, and both reads go to the primary (the client's
1475
+ * default), which returns every committed write, so at least one side sees the conflict.
1476
+ * Returns `drop` when nothing uses the name, `kept` when it was handed over, `gone` when another
1477
+ * call finished this delete attempt.
1478
+ */
1479
+ async handOverPendingDrop(collectionName, indexName, deleteToken, name) {
1480
+ const registry = this.registry();
1481
+ const users = {
1482
+ collectionName,
1483
+ _id: { $ne: indexName },
1484
+ deleting: { $ne: true },
1485
+ $or: [
1486
+ { searchIndexName: name },
1487
+ { textSearchIndexName: name },
1488
+ { retiredTextIndexNames: name },
1489
+ { retiredVectorIndexNames: name }
1490
+ ]
1491
+ };
1492
+ for (let round = 0; round < 3; round++) {
1493
+ if (!await registry.findOne(users)) return "drop";
1494
+ await this.testHooks?.beforeDeleteHandover?.(indexName, name);
1495
+ const observed = { [name]: await this.liveIdOf(this.db.collection(collectionName), name, "delete") };
1496
+ const outcome = await this.runDeleteTransaction(indexName, async (session) => {
1497
+ const own = await registry.findOne({
1498
+ _id: indexName,
1499
+ deleting: true,
1500
+ deleteToken
1501
+ }, { session });
1502
+ if (!own) return "gone";
1503
+ const current = await registry.find(users, { session }).toArray();
1504
+ const plan = planDeleteCleanup({
1505
+ _id: indexName,
1506
+ searchIndexName: name,
1507
+ ownsVectorIndex: true,
1508
+ indexIds: own.indexIds
1509
+ }, current, observed);
1510
+ if (plan.drop.length) return "drop";
1511
+ if (!await this.applyCleanupWrites(indexName, collectionName, plan, current, session)) return "recheck";
1512
+ await registry.updateOne({
1513
+ _id: indexName,
1514
+ deleteToken
1515
+ }, {
1516
+ $set: {
1517
+ ownsVectorIndex: own.ownsVectorIndex === true && own.searchIndexName !== name,
1518
+ ownsTextIndex: own.ownsTextIndex === true && own.textSearchIndexName !== name
1519
+ },
1520
+ $pull: {
1521
+ retiredTextIndexNames: name,
1522
+ retiredVectorIndexNames: name,
1523
+ indexIds: { name }
1524
+ },
1525
+ $inc: { rev: 1 }
1526
+ }, { session });
1527
+ return "kept";
1528
+ });
1529
+ if (outcome !== "recheck") return outcome;
1530
+ }
1531
+ throw new _mastra_core_error.MastraError({
1532
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", "CONFLICT"),
1533
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1534
+ category: _mastra_core_error.ErrorCategory.USER,
1535
+ details: {
1536
+ indexName,
1537
+ searchIndexName: name
1538
+ },
1539
+ text: `Registrations using search index "${name}" kept changing while deleteIndex ran, so it was not dropped. Retry deleteIndex({ indexName: "${indexName}" }).`
1540
+ });
1541
+ }
1542
+ /**
1543
+ * §3.8: proven incarnation `doc.indexId` (R) of `doc.name` lost the registration of its lifetime.
1544
+ * Step 1 marks the journal doc `orphaned` (the cleaner half of the I7 handshake: written before
1545
+ * the users are read, so an attach either sees it or is seen). Step 3 decides in a transaction
1546
+ * that re-reads the doc and the users: any live user blocks the drop (I11a); owners are released,
1547
+ * else the lowest-`_id` user gets R when the listing confirms it; every user written gets
1548
+ * `rev + 1` and a fresh `claimToken` (R4-2). With no user, the decision to drop is written to the
1549
+ * doc (R11), so every later cleaner drops too instead of handing R to a later attacher, and step
1550
+ * 4 drops R by id. The doc goes only after the drop, so attaches stay refused (M8) until then. A
1551
+ * failed drop keeps the doc, logs at error and returns `failed`.
1552
+ */
1553
+ async cleanupOrphan(doc, fromStep, op = "CREATE_INDEX") {
1554
+ const { _id, indexName, collectionName, name } = doc;
1555
+ const R = doc.indexId;
1556
+ const journal = this.journal();
1557
+ const registry = this.registry();
1558
+ const renewLease = { leaseUntil: { $add: ["$$NOW", this.testHooks?.leaseMs ?? 3e5] } };
1559
+ if (fromStep === 1) {
1560
+ if ((await journal.updateOne({
1561
+ _id,
1562
+ state: { $in: ["created", "orphaned"] }
1563
+ }, [{ $set: {
1564
+ state: { $literal: "orphaned" },
1565
+ indexId: { $literal: R },
1566
+ ...renewLease
1567
+ } }])).matchedCount === 0) return "kept";
1568
+ await this.testHooks?.afterOrphanMarked?.(indexName, name);
1569
+ }
1570
+ const users = {
1571
+ collectionName,
1572
+ deleting: { $ne: true },
1573
+ $or: [
1574
+ { searchIndexName: name },
1575
+ { textSearchIndexName: name },
1576
+ { retiredTextIndexNames: name },
1577
+ { retiredVectorIndexNames: name }
1578
+ ]
1579
+ };
1580
+ const ownsName = [
1581
+ {
1582
+ searchIndexName: name,
1583
+ ownsVectorIndex: true
1584
+ },
1585
+ {
1586
+ textSearchIndexName: name,
1587
+ ownsTextIndex: true
1588
+ },
1589
+ { retiredTextIndexNames: name },
1590
+ { retiredVectorIndexNames: name }
1591
+ ];
1592
+ const recheck = /* @__PURE__ */ new Error("orphan cleanup: a user changed; recheck");
1593
+ for (let round = 0; round < 3; round++) {
1594
+ const observed = await this.liveIdOf(this.db.collection(collectionName), name, "orphan");
1595
+ let outcome;
1596
+ try {
1597
+ outcome = await this.inTransaction(async (session) => {
1598
+ const j = await journal.findOne({
1599
+ _id,
1600
+ state: "orphaned"
1601
+ }, { session });
1602
+ await this.testHooks?.afterOrphanJournalRead?.(indexName, name);
1603
+ if (!j) return "gone";
1604
+ if (j.dropDecided) return "drop";
1605
+ const current = await registry.find(users, { session }).toArray();
1606
+ const plan = planOrphanCleanup(name, R, observed, current);
1607
+ if (plan.kind === "drop") {
1608
+ await journal.updateOne({
1609
+ _id,
1610
+ state: "orphaned"
1611
+ }, [{ $set: {
1612
+ dropDecided: { $literal: true },
1613
+ ...renewLease
1614
+ } }], { session });
1615
+ return "drop";
1616
+ }
1617
+ const userOf = (toId) => current.find((u) => u._id === toId);
1618
+ const generationOf = (toId) => userOf(toId).generation ?? { $exists: false };
1619
+ if (plan.kind === "release") for (const o of plan.owners) {
1620
+ const held = idFor(userOf(o.toId), name);
1621
+ if (!o.rewriteId && held !== void 0 && held !== R) this.logger.warn(`search index "${name}" on "${collectionName}": index "${o.toId}" records id ${held}, not ${R} (cleanup record ${_id}); kept, as the listing does not confirm ${R}`);
1622
+ const rewrite = o.rewriteId ? { indexIds: indexIdsWith(name, o.rewriteId) } : {};
1623
+ if ((await registry.updateOne({
1624
+ _id: o.toId,
1625
+ generation: generationOf(o.toId),
1626
+ deleting: { $ne: true },
1627
+ $or: ownsName
1628
+ }, [{ $set: {
1629
+ ...rewrite,
1630
+ ...mutationFields()
1631
+ } }], { session })).matchedCount === 0) throw recheck;
1632
+ }
1633
+ else if (plan.kind === "transfer") {
1634
+ const nameField = plan.field === "ownsTextIndex" ? "textSearchIndexName" : "searchIndexName";
1635
+ const owned = {
1636
+ [plan.field]: { $literal: true },
1637
+ indexIds: indexIdsWith(name, plan.id)
1638
+ };
1639
+ if ((await registry.updateOne({
1640
+ _id: plan.toId,
1641
+ generation: generationOf(plan.toId),
1642
+ deleting: { $ne: true },
1643
+ [nameField]: name
1644
+ }, [{ $set: {
1645
+ ...owned,
1646
+ ...mutationFields()
1647
+ } }], { session })).matchedCount === 0) throw recheck;
1648
+ } else this.logger.warn(`search index "${name}" on "${collectionName}": the incarnation ${R} of cleanup record ${_id} is no longer listed, and registrations still reference the name; neither dropped nor handed over`);
1649
+ await journal.deleteOne({
1650
+ _id,
1651
+ state: "orphaned"
1652
+ }, { session });
1653
+ return plan.kind === "release" ? "released" : plan.kind === "transfer" ? "transferred" : "kept";
1654
+ });
1655
+ } catch (error) {
1656
+ if (error === recheck) continue;
1657
+ throw error;
1658
+ }
1659
+ if (outcome === "gone") return "kept";
1660
+ if (outcome !== "drop") return outcome;
1661
+ try {
1662
+ await this.testHooks?.beforeOrphanDrop?.(indexName, name);
1663
+ await this.dropSearchIndexById(collectionName, name, R);
1664
+ } catch (error) {
1665
+ this.logger.error(`could not drop search index "${name}" (id ${R}) on "${collectionName}"; cleanup record ${_id} keeps blocking the name: ${error}`);
1666
+ await this.expireLease({
1667
+ _id,
1668
+ state: "orphaned"
1669
+ });
1670
+ return "failed";
1671
+ }
1672
+ await journal.deleteOne({
1673
+ _id,
1674
+ state: "orphaned"
1675
+ });
1676
+ return "dropped";
1677
+ }
1678
+ throw new _mastra_core_error.MastraError({
1679
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "CONFLICT"),
1680
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1681
+ category: _mastra_core_error.ErrorCategory.USER,
1682
+ details: {
1683
+ indexName,
1684
+ collectionName,
1685
+ searchIndexName: name
1686
+ },
1687
+ text: `Registrations using search index "${name}" on "${collectionName}" kept changing during its cleanup (cleanup record ${_id}), so it was neither handed over nor dropped. Retry.`
1688
+ });
1689
+ }
1690
+ /**
1691
+ * Refuse to reference a search index that a delete in progress is about to drop. The attach half
1692
+ * of the handshake described on {@link handOverPendingDrop}: callers run it after writing their
1693
+ * registration, so either this read sees the pending drop or the delete's read sees the registration.
1694
+ *
1695
+ * It also re-reads this call's own entry, which a deleteIndex may have removed or started removing
1696
+ * since the write: provisioning then would leave a search index no registration records. Callers
1697
+ * run it last before provisioning. The entry must still record `collectionName` and every name in
1698
+ * `expected`, the targets this call provisions: another call may have retargeted it since, and
1699
+ * provisioning the old target would leave an index nothing records. A rewrite with the same
1700
+ * targets (an identical concurrent call) passes. Last, it must still carry `generation`, the one
1701
+ * this call's write left: a delete and an identical recreate (or an old-code recreate without a
1702
+ * generation) is another registration, and this call must not provision for it.
1703
+ */
1704
+ async assertNoPendingDrop(collectionName, indexName, names, op, expected, generation, reconciled) {
1705
+ await this.testHooks?.beforePendingDropCheck?.(indexName);
1706
+ const own = await this.registry().findOne({ _id: indexName });
1707
+ if (!own) throw new _mastra_core_error.MastraError({
1708
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "CONFLICT"),
1709
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1710
+ category: _mastra_core_error.ErrorCategory.USER,
1711
+ details: { indexName },
1712
+ text: `Index "${indexName}" was removed by another call while this one ran, so nothing was provisioned. Retry.`
1713
+ });
1714
+ this.assertNotDeleting(own, op);
1715
+ const recorded = {
1716
+ ...own,
1717
+ collectionName: own.collectionName ?? indexName,
1718
+ searchIndexName: own.searchIndexName ?? `${indexName}_vector_index`
1719
+ };
1720
+ const changed = Object.entries({
1721
+ collectionName,
1722
+ ...expected
1723
+ }).filter(([field, value]) => recorded[field] !== value).map(([field, value]) => `${field} "${String(recorded[field])}" instead of "${value}"`);
1724
+ if (changed.length) throw new _mastra_core_error.MastraError({
1725
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "CONFLICT"),
1726
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1727
+ category: _mastra_core_error.ErrorCategory.USER,
1728
+ details: { indexName },
1729
+ text: `Index "${indexName}" was changed by another call while this one ran (it now records ${changed.join(" and ")}), so nothing was provisioned. Check the index and retry.`
1730
+ });
1731
+ if (own.generation !== generation) throw new _mastra_core_error.MastraError({
1732
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "CONFLICT"),
1733
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1734
+ category: _mastra_core_error.ErrorCategory.USER,
1735
+ details: { indexName },
1736
+ text: `Index "${indexName}" was removed or recreated by another call while this one ran, so nothing was provisioned. Retry.`
1737
+ });
1738
+ const pending = await this.pendingDropError(collectionName, indexName, names, op, reconciled);
1739
+ if (pending) throw pending;
340
1740
  }
341
- /** Remove a logical-index target from the durable registry (called by deleteIndex). */
342
- async deleteRegistryEntry(indexName) {
343
- await this.db.collection(MongoDBVector.REGISTRY_COLLECTION).deleteOne({ _id: indexName });
1741
+ /**
1742
+ * The read half of the I7 handshake: the `INDEX_DELETING` error for the first of `names` an
1743
+ * `orphaned` journal doc or another registration's `deleting` drop set covers, if any. A stale
1744
+ * orphan block is cleaned once per call (the call's own reconcile counts), then re-checked (P3).
1745
+ */
1746
+ async pendingDropError(collectionName, indexName, names, op, reconciled) {
1747
+ const registry = this.registry();
1748
+ const pending = {
1749
+ collectionName,
1750
+ name: { $in: names.filter((n) => !!n) },
1751
+ state: "orphaned"
1752
+ };
1753
+ const stale = await this.journal().findOne({
1754
+ ...pending,
1755
+ _id: { $nin: [...reconciled] },
1756
+ ...LEASE_EXPIRED
1757
+ });
1758
+ if (stale) {
1759
+ reconciled.add(stale._id);
1760
+ await this.cleanupOrphan(stale, 2, op).catch((error) => this.logger.warn(`could not clean up provisioning record ${stale._id} on "${collectionName}": ${error}`));
1761
+ }
1762
+ const orphan = await this.journal().findOne(pending);
1763
+ if (orphan) return new _mastra_core_error.MastraError({
1764
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "INDEX_DELETING"),
1765
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1766
+ category: _mastra_core_error.ErrorCategory.USER,
1767
+ details: {
1768
+ indexName,
1769
+ searchIndexName: orphan.name,
1770
+ cleanupRecord: orphan._id
1771
+ },
1772
+ text: `search index "${orphan.name}" on "${collectionName}" is pending removal of an index Mastra created (cleanup record ${orphan._id}). Retry: retrying runs the cleanup. If the drop keeps failing, the block remains and the failure is logged at error level.`
1773
+ });
1774
+ for (const other of await registry.find({
1775
+ collectionName,
1776
+ deleting: true,
1777
+ _id: { $ne: indexName }
1778
+ }).toArray()) {
1779
+ const name = other.ownsCollection === true && !other.isByo ? names.find(Boolean) : names.find((n) => n && recordedDropSet(other).includes(n));
1780
+ if (!name) continue;
1781
+ return new _mastra_core_error.MastraError({
1782
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", op, "INDEX_DELETING"),
1783
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1784
+ category: _mastra_core_error.ErrorCategory.USER,
1785
+ details: {
1786
+ indexName,
1787
+ searchIndexName: name,
1788
+ deletingIndexName: other._id
1789
+ },
1790
+ text: `The search index "${name}" is being dropped by a deleteIndex in progress (index "${other._id}"). Retry after it finishes; retrying is safe. If that delete was interrupted, retry deleteIndex({ indexName: "${other._id}" }) first. The delete may already have handed the index to this registration, in which case the registration was kept.`
1791
+ });
1792
+ }
344
1793
  }
345
1794
  /**
346
- * $rankFusion is available in MongoDB >= 8.0. It is generally available from 8.1; on 8.0.x it
347
- * may require a MongoDB support case to enable (see the $rankFusion docs), but where enabled —
348
- * e.g. Atlas 8.0.x clusters — it runs. We therefore gate at >= 8.0 (rejecting only clearly
349
- * unsupported older servers) and let the server be the final authority: if $rankFusion is not
350
- * actually enabled on an 8.0.x deployment, the query itself surfaces the server error.
1795
+ * Delete a managed registration with recorded ownership (`ownsCollection: true`) by dropping
1796
+ * its collection, which removes every search index on it. Refuses with `IN_USE` while any other
1797
+ * registration points at the collection. Same token protocol as `deleteKeepCollection`.
1798
+ */
1799
+ async deleteManagedCollection(entry) {
1800
+ const indexName = entry._id;
1801
+ const collectionName = entry.collectionName;
1802
+ const registry = this.registry();
1803
+ const othersFilter = {
1804
+ collectionName,
1805
+ _id: { $ne: indexName }
1806
+ };
1807
+ const inUse = (others) => new _mastra_core_error.MastraError({
1808
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", "IN_USE"),
1809
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1810
+ category: _mastra_core_error.ErrorCategory.USER,
1811
+ details: {
1812
+ indexName,
1813
+ collectionName,
1814
+ usedBy: others.map((o) => o._id).join(", ")
1815
+ },
1816
+ text: `Collection "${collectionName}" of index "${indexName}" is still used by ${others.map((o) => `"${o._id}"`).join(", ")}. Nothing was dropped. Delete those indexes first, then retry deleteIndex({ indexName: "${indexName}" }).`
1817
+ });
1818
+ let deleteToken = entry.deleting ? entry.deleteToken : void 0;
1819
+ if (!deleteToken) {
1820
+ let attempt = 0;
1821
+ const work = await this.runDeleteTransaction(indexName, async (session) => {
1822
+ attempt++;
1823
+ const own = await registry.findOne({ _id: indexName }, { session });
1824
+ if (!own || own.collectionName !== collectionName || own.isByo || own.ownsCollection !== true) return "gone";
1825
+ if (this.replacedSince(entry, own)) return "gone";
1826
+ if (own.deleting && own.deleteToken) return { deleteToken: own.deleteToken };
1827
+ const others = await registry.find(othersFilter, { session }).toArray();
1828
+ await this.testHooks?.insideDeleteTransaction?.(indexName, attempt);
1829
+ if (others.length) throw inUse(others);
1830
+ const token = (0, _lukeed_uuid.v4)();
1831
+ await registry.updateOne({ _id: indexName }, {
1832
+ $set: {
1833
+ deleting: true,
1834
+ deleteToken: token
1835
+ },
1836
+ $inc: { rev: 1 }
1837
+ }, { session });
1838
+ return { deleteToken: token };
1839
+ });
1840
+ if (work === "gone") return;
1841
+ deleteToken = work.deleteToken;
1842
+ }
1843
+ await this.testHooks?.afterDeleteStep1?.(indexName);
1844
+ await this.testHooks?.beforeDeleteDrop?.(indexName, collectionName);
1845
+ const others = await registry.find(othersFilter).toArray();
1846
+ if (!await registry.findOne({
1847
+ _id: indexName,
1848
+ deleting: true,
1849
+ deleteToken
1850
+ })) return;
1851
+ if (others.length) throw inUse(others);
1852
+ try {
1853
+ await this.db.collection(collectionName).drop();
1854
+ } catch (err) {
1855
+ const code = err?.codeName ?? err?.code;
1856
+ if (code !== "NamespaceNotFound" && code !== 26) throw err;
1857
+ }
1858
+ this.collections.delete(collectionName);
1859
+ await this.testHooks?.beforeDeleteFinalize?.(indexName);
1860
+ await registry.deleteOne({
1861
+ _id: indexName,
1862
+ deleting: true,
1863
+ deleteToken
1864
+ });
1865
+ }
1866
+ /**
1867
+ * $rankFusion is available in MongoDB >= 8.0, so the gate rejects only older servers and lets the
1868
+ * server be the final authority on anything else.
351
1869
  */
352
1870
  async assertRankFusionSupported() {
353
1871
  if (!this.rankFusionSupport) {
@@ -364,7 +1882,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
364
1882
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "UNSUPPORTED"),
365
1883
  domain: _mastra_core_error.ErrorDomain.STORAGE,
366
1884
  category: _mastra_core_error.ErrorCategory.USER,
367
- text: `hybridQuery uses $rankFusion, which requires MongoDB >= 8.0 (found ${this.rankFusionSupport.version}). On 8.0.x it may need a MongoDB support case to enable; upgrade to >= 8.1, or run query() and textQuery() separately and fuse client-side.`
1885
+ text: `hybridQuery uses $rankFusion, which requires MongoDB >= 8.0 (found ${this.rankFusionSupport.version}). Upgrade to 8.0 or later, or run query() and textQuery() separately and fuse client-side.`
368
1886
  });
369
1887
  }
370
1888
  /** Validates a text upsert: `documents` is present, and `metadata`/`ids` line up with it. */
@@ -472,6 +1990,10 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
472
1990
  * "index not found" or "index not ready" errors on subsequent operations.
473
1991
  */
474
1992
  async createIndex(params) {
1993
+ return this.createIndexAttempt(params, false);
1994
+ }
1995
+ /** `refresh` marks the single retry after losing a registration race to a compatible entry. */
1996
+ async createIndexAttempt(params, refresh) {
475
1997
  const { indexName, dimension, metric = "cosine", filterFields, collectionName, searchIndexName, allowWrites, autoEmbed: autoEmbedParam } = params;
476
1998
  const autoEmbed = autoEmbedParam ?? (dimension === void 0 ? this.defaultAutoEmbed : void 0);
477
1999
  let mongoMetric;
@@ -497,36 +2019,53 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
497
2019
  const targetCollection = collectionName ?? indexName;
498
2020
  const targetSearchIndex = searchIndexName ?? `${indexName}_vector_index`;
499
2021
  const isByo = collectionName !== void 0;
2022
+ const reconciled = await this.reconcile(targetCollection);
500
2023
  let collection;
2024
+ let collectionCreated = false;
501
2025
  try {
502
- if (!await this.db.listCollections({ name: targetCollection }).hasNext()) {
2026
+ const existingEntry = await this.readRegistryEntry(indexName);
2027
+ this.assertNotDeleting(existingEntry, "CREATE_INDEX");
2028
+ await this.testHooks?.afterCreateIndexRead?.(indexName);
2029
+ if (existingEntry && existingEntry.collectionName !== targetCollection) throw new _mastra_core_error.MastraError({
2030
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_INDEX", "CONFLICT"),
2031
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2032
+ category: _mastra_core_error.ErrorCategory.USER,
2033
+ details: { indexName },
2034
+ text: `Index "${indexName}" is already registered against collection "${existingEntry.collectionName}", but this createIndex call resolves to "${targetCollection}". Call deleteIndex({ indexName: "${indexName}" }) first to retarget it.`
2035
+ });
2036
+ if (!await this.db.listCollections({ name: targetCollection }, { readPreference: mongodb.ReadPreference.primary }).hasNext()) {
503
2037
  if (isByo) throw new _mastra_core_error.MastraError({
504
2038
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_INDEX", "INVALID_ARGS"),
505
2039
  domain: _mastra_core_error.ErrorDomain.STORAGE,
506
2040
  category: _mastra_core_error.ErrorCategory.USER,
507
2041
  text: `collectionName "${targetCollection}" does not exist. Create and populate the collection before indexing it.`
508
2042
  });
509
- await this.db.createCollection(targetCollection);
2043
+ try {
2044
+ await this.db.createCollection(targetCollection, { validationLevel: "off" });
2045
+ collectionCreated = true;
2046
+ } catch (error) {
2047
+ if (error?.code !== 48 && error?.codeName !== "NamespaceExists") throw error;
2048
+ }
510
2049
  }
511
2050
  collection = await this.getCollection(targetCollection);
512
2051
  const indexNameInternal = targetSearchIndex;
513
2052
  const defaultTextSearchIndex = `${targetCollection}_search_index`;
514
- const existingEntry = await this.readRegistryEntry(indexName);
515
- if (existingEntry && existingEntry.collectionName !== targetCollection) throw new _mastra_core_error.MastraError({
2053
+ const effectiveIsByo = existingEntry ? existingEntry.isByo ?? false : isByo;
2054
+ const effectiveWritable = effectiveIsByo ? allowWrites ?? existingEntry?.allowWrites ?? false : true;
2055
+ if (effectiveIsByo && allowWrites === true) this.logger.warn(`createIndex({ allowWrites: true }) is deprecated and will be removed in the next major version. Keep bring-your-own index "${indexName}" read-only: write embeddings from your application or use autoEmbed.`);
2056
+ if (targetSearchIndex === defaultTextSearchIndex || targetSearchIndex === existingEntry?.textSearchIndexName) throw new _mastra_core_error.MastraError({
516
2057
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_INDEX", "CONFLICT"),
517
2058
  domain: _mastra_core_error.ErrorDomain.STORAGE,
518
2059
  category: _mastra_core_error.ErrorCategory.USER,
519
2060
  details: { indexName },
520
- text: `Index "${indexName}" is already registered against collection "${existingEntry.collectionName}", but this createIndex call resolves to "${targetCollection}". Call deleteIndex({ indexName: "${indexName}" }) first to retarget it.`
2061
+ text: `searchIndexName "${targetSearchIndex}" collides with the full-text search index name for collection "${targetCollection}". Choose a different vector searchIndexName.`
521
2062
  });
522
- const effectiveIsByo = existingEntry ? existingEntry.isByo ?? false : isByo;
523
- const effectiveWritable = effectiveIsByo ? allowWrites ?? existingEntry?.allowWrites ?? false : true;
524
- if (targetSearchIndex === defaultTextSearchIndex || targetSearchIndex === existingEntry?.textSearchIndexName) throw new _mastra_core_error.MastraError({
2063
+ if (existingEntry?.retiredTextIndexNames?.includes(targetSearchIndex)) throw new _mastra_core_error.MastraError({
525
2064
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_INDEX", "CONFLICT"),
526
2065
  domain: _mastra_core_error.ErrorDomain.STORAGE,
527
2066
  category: _mastra_core_error.ErrorCategory.USER,
528
2067
  details: { indexName },
529
- text: `searchIndexName "${targetSearchIndex}" collides with the full-text search index name for collection "${targetCollection}". Choose a different vector searchIndexName.`
2068
+ text: `searchIndexName "${targetSearchIndex}" was a full-text search index of index "${indexName}"; choose a different name.`
530
2069
  });
531
2070
  const textSearchIndexName = effectiveIsByo ? existingEntry?.textSearchIndexName : existingEntry?.textSearchIndexName ?? defaultTextSearchIndex;
532
2071
  const resolvedAutoEmbed = autoEmbed ? {
@@ -534,8 +2073,8 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
534
2073
  path: autoEmbed.path ?? this.documentFieldName
535
2074
  } : void 0;
536
2075
  const existingAutoEmbed = existingEntry?.autoEmbed;
537
- const embeddingChanged = Boolean(existingAutoEmbed) !== Boolean(resolvedAutoEmbed) || existingAutoEmbed && resolvedAutoEmbed && (existingAutoEmbed.path !== resolvedAutoEmbed.path || existingAutoEmbed.model !== resolvedAutoEmbed.model);
538
- if (existingEntry && embeddingChanged) throw new _mastra_core_error.MastraError({
2076
+ const sameEmbedding = (other) => Boolean(other) === Boolean(resolvedAutoEmbed) && (!other || !resolvedAutoEmbed || other.path === resolvedAutoEmbed.path && other.model === resolvedAutoEmbed.model);
2077
+ if (existingEntry && !sameEmbedding(existingAutoEmbed)) throw new _mastra_core_error.MastraError({
539
2078
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_INDEX", "CONFLICT"),
540
2079
  domain: _mastra_core_error.ErrorDomain.STORAGE,
541
2080
  category: _mastra_core_error.ErrorCategory.USER,
@@ -544,33 +2083,84 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
544
2083
  });
545
2084
  const registryClaim = {
546
2085
  collectionName: targetCollection,
2086
+ deleting: { $ne: true },
547
2087
  ...resolvedAutoEmbed ? {
548
2088
  "autoEmbed.path": resolvedAutoEmbed.path,
549
2089
  "autoEmbed.model": resolvedAutoEmbed.model
550
- } : { autoEmbed: null }
2090
+ } : { autoEmbed: null },
2091
+ ...existingEntry ? { generation: existingEntry.generation ?? { $exists: false } } : { claimToken: { $exists: false } },
2092
+ textSearchIndexName: { $ne: targetSearchIndex },
2093
+ retiredTextIndexNames: { $ne: targetSearchIndex }
551
2094
  };
2095
+ const claimToken = (0, _lukeed_uuid.v4)();
2096
+ const ownsCollection = existingEntry ? existingEntry.ownsCollection : collectionCreated;
2097
+ const p0Fields = {
2098
+ collectionName: targetCollection,
2099
+ searchIndexName: targetSearchIndex,
2100
+ isByo: effectiveIsByo,
2101
+ allowWrites: effectiveWritable,
2102
+ ...textSearchIndexName && !existingEntry?.textSearchIndexName ? { textSearchIndexName } : {},
2103
+ dimension,
2104
+ ...resolvedAutoEmbed ? {} : { metric },
2105
+ autoEmbed: resolvedAutoEmbed,
2106
+ ...existingEntry ? {} : { ownsCollection }
2107
+ };
2108
+ const newName = { $literal: targetSearchIndex };
2109
+ const retiredVector = { $ifNull: ["$retiredVectorIndexNames", []] };
2110
+ const keepVector = { $or: [{ $eq: ["$searchIndexName", newName] }, { $eq: [{ $type: "$searchIndexName" }, "missing"] }] };
2111
+ const vectorRename = {
2112
+ ownsVectorIndex: { $cond: [
2113
+ keepVector,
2114
+ "$ownsVectorIndex",
2115
+ { $in: [newName, retiredVector] }
2116
+ ] },
2117
+ retiredVectorIndexNames: { $cond: [
2118
+ keepVector,
2119
+ "$retiredVectorIndexNames",
2120
+ { $setDifference: [{ $setUnion: [retiredVector, { $cond: [
2121
+ { $eq: ["$ownsVectorIndex", true] },
2122
+ ["$searchIndexName"],
2123
+ []
2124
+ ] }] }, [newName]] }
2125
+ ] }
2126
+ };
2127
+ let p0;
552
2128
  try {
553
- await this.writeRegistryEntry(indexName, {
554
- collectionName: targetCollection,
555
- searchIndexName: targetSearchIndex,
556
- isByo: effectiveIsByo,
557
- allowWrites: effectiveWritable,
558
- textSearchIndexName,
559
- dimension,
560
- ...resolvedAutoEmbed ? {} : { metric },
561
- autoEmbed: resolvedAutoEmbed
562
- }, registryClaim);
2129
+ p0 = await this.writeRegistryEntry(indexName, {
2130
+ ...p0Fields,
2131
+ claimToken
2132
+ }, registryClaim, !existingEntry, vectorRename);
563
2133
  } catch (error) {
564
2134
  if (error?.code !== 11e3) throw error;
2135
+ p0 = null;
2136
+ }
2137
+ if (!p0) {
2138
+ this.indexTargets.delete(indexName);
2139
+ if (collectionCreated && !await this.registry().findOne({ collectionName: targetCollection }).catch(() => true)) {
2140
+ this.collections.delete(targetCollection);
2141
+ await collection.drop().catch(() => {});
2142
+ }
565
2143
  const winner = await this.readRegistryEntry(indexName);
2144
+ this.assertNotDeleting(winner, "CREATE_INDEX");
2145
+ const sameCollection = winner?.collectionName === targetCollection;
2146
+ if (!existingEntry?.generation && !refresh && winner && sameCollection && sameEmbedding(winner.autoEmbed)) return await this.createIndexAttempt(params, true);
2147
+ const differs = winner ? [...sameCollection ? [] : [`collection "${winner.collectionName}" instead of "${targetCollection}"`], ...sameEmbedding(winner.autoEmbed) ? [] : [`${describeEmbedding(winner.autoEmbed)} instead of ${describeEmbedding(resolvedAutoEmbed)}`]] : [];
566
2148
  throw new _mastra_core_error.MastraError({
567
2149
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_INDEX", "CONFLICT"),
568
2150
  domain: _mastra_core_error.ErrorDomain.STORAGE,
569
2151
  category: _mastra_core_error.ErrorCategory.USER,
570
2152
  details: { indexName },
571
- text: winner ? `Index "${indexName}" was registered concurrently against collection "${winner.collectionName}" with ${describeEmbedding(winner.autoEmbed)}, but this createIndex call resolves to collection "${targetCollection}" with ${describeEmbedding(resolvedAutoEmbed)}. Call deleteIndex({ indexName: "${indexName}" }) first to rebuild it.` : `Index "${indexName}" was registered concurrently by another process and removed again before this call could read it. Retry createIndex.`
2153
+ text: differs.length ? `Index "${indexName}" was registered concurrently by another call with ${differs.join(" and ")}. Nothing was changed. Use the registered target, or pick a different indexName.` : `Index "${indexName}" was registered or removed concurrently by another call while this one ran. Nothing was changed. Retry createIndex.`
572
2154
  });
573
2155
  }
2156
+ const { pin, before: p0Before } = p0;
2157
+ await this.tofuIndexIds(indexName, pin, [{
2158
+ role: "vector",
2159
+ name: targetSearchIndex
2160
+ }, ...textSearchIndexName ? [{
2161
+ role: "text",
2162
+ name: textSearchIndexName
2163
+ }] : []], collection);
574
2164
  this.indexTargets.set(indexName, {
575
2165
  collectionName: targetCollection,
576
2166
  searchIndexName: targetSearchIndex,
@@ -581,7 +2171,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
581
2171
  });
582
2172
  const embeddingField = this.embeddingFieldName;
583
2173
  const numDimensions = dimension;
584
- const declaredMetadataPaths = this.buildDeclaredMetadataPaths(filterFields);
2174
+ const declaredMetadataPaths = this.buildDeclaredMetadataPaths(filterFields, effectiveIsByo);
585
2175
  const autoEmbedPath = resolvedAutoEmbed?.path;
586
2176
  let searchField;
587
2177
  if (autoEmbed) {
@@ -615,16 +2205,64 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
615
2205
  path
616
2206
  }))
617
2207
  ];
618
- if (await this.createSearchIndexIgnoringExisting(collection, {
619
- definition: { fields },
620
- name: indexNameInternal,
621
- type: "vectorSearch"
622
- })) this.declaredFilterPaths.set(indexName, new Set(documentIsEmbedded ? declaredMetadataPaths : [this.documentFieldName, ...declaredMetadataPaths]));
623
- if (!effectiveIsByo) await this.createSearchIndexIgnoringExisting(collection, {
624
- definition: { mappings: { dynamic: true } },
625
- name: textSearchIndexName ?? defaultTextSearchIndex,
626
- type: "search"
2208
+ const check = () => this.assertNoPendingDrop(targetCollection, indexName, [indexNameInternal, textSearchIndexName], "CREATE_INDEX", {
2209
+ searchIndexName: indexNameInternal,
2210
+ ...effectiveIsByo ? {} : { textSearchIndexName: textSearchIndexName ?? defaultTextSearchIndex }
2211
+ }, pin.generation, reconciled);
2212
+ let vector;
2213
+ try {
2214
+ vector = await this.provisionSearchIndex({
2215
+ indexName,
2216
+ collection,
2217
+ role: "vector",
2218
+ op: "CREATE_INDEX",
2219
+ description: {
2220
+ definition: { fields },
2221
+ name: indexNameInternal,
2222
+ type: "vectorSearch"
2223
+ },
2224
+ pin,
2225
+ check
2226
+ });
2227
+ } catch (abort) {
2228
+ const { error, rollback } = abort instanceof ProvisionAbort ? abort : {
2229
+ error: abort,
2230
+ rollback: true
2231
+ };
2232
+ if (rollback) {
2233
+ if (await this.rollbackRegistryEntry(indexName, pin, p0Before ? rollbackRestore(p0Before, {
2234
+ indexName,
2235
+ ...p0Fields,
2236
+ ownsVectorIndex: true,
2237
+ retiredVectorIndexNames: true
2238
+ }) : null) && collectionCreated && !await this.registry().findOne({ collectionName: targetCollection }).catch(() => true)) {
2239
+ this.collections.delete(targetCollection);
2240
+ await collection.drop().catch(() => {});
2241
+ }
2242
+ }
2243
+ throw error;
2244
+ }
2245
+ if (vector.outcome === "owned") this.declaredFilterPaths.set(indexName, {
2246
+ source: `${targetCollection}/${targetSearchIndex}`,
2247
+ paths: new Set(documentIsEmbedded ? declaredMetadataPaths : [this.documentFieldName, ...declaredMetadataPaths])
627
2248
  });
2249
+ if (!effectiveIsByo) try {
2250
+ await this.provisionSearchIndex({
2251
+ indexName,
2252
+ collection,
2253
+ role: "text",
2254
+ op: "CREATE_INDEX",
2255
+ description: {
2256
+ definition: { mappings: { dynamic: true } },
2257
+ name: textSearchIndexName ?? defaultTextSearchIndex,
2258
+ type: "search"
2259
+ },
2260
+ pin,
2261
+ check
2262
+ });
2263
+ } catch (abort) {
2264
+ throw abort instanceof ProvisionAbort ? abort.error : abort;
2265
+ }
628
2266
  } catch (error) {
629
2267
  if (error instanceof _mastra_core_error.MastraError) throw error;
630
2268
  throw new _mastra_core_error.MastraError({
@@ -635,33 +2273,42 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
635
2273
  }
636
2274
  }
637
2275
  /**
638
- * Creates an Atlas Search index, treating IndexAlreadyExists as a no-op so
639
- * `createIndex` stays idempotent per index. Returns true when the index was
640
- * actually created by this call.
2276
+ * The only search-index drop (I1): by `id`, so only that incarnation goes. `IndexNotFound` and
2277
+ * `NamespaceNotFound` mean it is already gone (with its collection, for the latter), which
2278
+ * counts as done, so a retried delete still clears its registry entry.
641
2279
  */
642
- async createSearchIndexIgnoringExisting(collection, description) {
2280
+ async dropSearchIndexById(collectionName, name, id) {
2281
+ await this.testHooks?.beforeSearchIndexDrop?.(collectionName, name, id);
643
2282
  try {
644
- await collection.createSearchIndex(description);
645
- return true;
646
- } catch (error) {
647
- if (error?.codeName === "IndexAlreadyExists") return false;
648
- throw error;
649
- }
650
- }
651
- /**
652
- * Drop an Atlas Search index, treating "index not found" as a no-op so deleteIndex is
653
- * retry-safe: an index a prior (interrupted) delete already removed does not fail the retry
654
- * that still needs to clear the registry entry.
655
- */
656
- async dropSearchIndexIgnoringMissing(collection, name) {
657
- try {
658
- await collection.dropSearchIndex(name);
2283
+ await this.runSearchIndexCommand({
2284
+ dropSearchIndex: collectionName,
2285
+ id
2286
+ });
659
2287
  } catch (err) {
660
2288
  const code = err?.codeName ?? err?.code;
661
2289
  if (!(code === "IndexNotFound" || code === "SearchIndexNotFound" || code === 27 || code === "NamespaceNotFound" || code === 26)) throw err;
662
2290
  }
663
2291
  }
664
2292
  /**
2293
+ * Drop `name` by its recorded `id`. A legacy name with none is listed and dropped by the observed
2294
+ * id (§3.7, delete-time TOFU); absent means done. Residual X2: an external drop and recreate
2295
+ * before this listing makes the observed id the stranger's.
2296
+ */
2297
+ async dropRecordedOrListed(collectionName, name, id) {
2298
+ id ??= await this.liveIdOf(this.db.collection(collectionName), name, "delete");
2299
+ if (id) await this.dropSearchIndexById(collectionName, name, id);
2300
+ }
2301
+ /** Atlas Search reads a dotted mapping key as a literal field name, so nested paths need `document` mappings. */
2302
+ toSearchFieldMappings(paths) {
2303
+ return Object.fromEntries([...new Set(paths.map((p) => p[0]))].map((head) => {
2304
+ const nested = paths.filter((p) => p[0] === head && p.length > 1).map((p) => p.slice(1));
2305
+ return [head, nested.length ? {
2306
+ type: "document",
2307
+ fields: this.toSearchFieldMappings(nested)
2308
+ } : [{ type: "string" }]];
2309
+ }));
2310
+ }
2311
+ /**
665
2312
  * Provision an Atlas Search (BM25/full-text) index on the index's collection and record
666
2313
  * it as the text-search index that `textQuery`/`hybridQuery` will target.
667
2314
  *
@@ -679,40 +2326,167 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
679
2326
  */
680
2327
  async createSearchIndex(params) {
681
2328
  const { indexName, fields, searchIndexName, waitUntilReady = false } = params;
2329
+ this.indexTargets.delete(indexName);
682
2330
  const target = await this.resolveIndexTarget(indexName);
683
2331
  const { collectionName } = target;
2332
+ const reconciled = await this.reconcile(collectionName);
684
2333
  const name = searchIndexName ?? (fields?.length ? `${collectionName}_${indexName}_search_fields_index` : `${collectionName}_search_index`);
685
- if (name === target.searchIndexName) throw new _mastra_core_error.MastraError({
2334
+ await this.testHooks?.afterCreateSearchIndexTarget?.(indexName);
2335
+ const previous = await this.readRegistryEntry(indexName);
2336
+ this.assertNotDeleting(previous, "CREATE_SEARCH_INDEX");
2337
+ const concurrentConflict = (what) => new _mastra_core_error.MastraError({
2338
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_SEARCH_INDEX", "CONFLICT"),
2339
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2340
+ category: _mastra_core_error.ErrorCategory.USER,
2341
+ details: { indexName },
2342
+ text: `Index "${indexName}" was ${what} by another call while createSearchIndex ran, so nothing was provisioned. Check the index and retry.`
2343
+ });
2344
+ if (target.registered && !previous) throw concurrentConflict("removed");
2345
+ if (name === target.searchIndexName || name === previous?.searchIndexName) throw new _mastra_core_error.MastraError({
686
2346
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_SEARCH_INDEX", "CONFLICT"),
687
2347
  domain: _mastra_core_error.ErrorDomain.STORAGE,
688
2348
  category: _mastra_core_error.ErrorCategory.USER,
689
2349
  details: { indexName },
690
2350
  text: `searchIndexName "${name}" collides with the vectorSearch index name for index "${indexName}". Choose a different full-text searchIndexName.`
691
2351
  });
2352
+ if (previous?.retiredVectorIndexNames?.includes(name)) throw new _mastra_core_error.MastraError({
2353
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_SEARCH_INDEX", "CONFLICT"),
2354
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2355
+ category: _mastra_core_error.ErrorCategory.USER,
2356
+ details: { indexName },
2357
+ text: `searchIndexName "${name}" was a vector search index of index "${indexName}"; choose a different name.`
2358
+ });
2359
+ const sameName = !!previous && name === previous.textSearchIndexName;
2360
+ await this.testHooks?.afterCreateSearchIndexRead?.(indexName);
2361
+ const claimToken = (0, _lukeed_uuid.v4)();
2362
+ const textFields = {
2363
+ textSearchIndexName: name,
2364
+ ...sameName ? {} : { ownsTextIndex: false }
2365
+ };
2366
+ let provisioned = false;
2367
+ let p0 = null;
2368
+ let written = textFields;
692
2369
  try {
693
2370
  const collection = await this.getCollection(collectionName);
694
2371
  const definition = fields?.length ? { mappings: {
695
2372
  dynamic: false,
696
- fields: Object.fromEntries(fields.map((f) => [f, [{ type: "string" }]]))
2373
+ fields: this.toSearchFieldMappings(fields.map((f) => f.split(".")))
697
2374
  } } : { mappings: { dynamic: true } };
698
- await this.writeRegistryEntry(indexName, {
699
- collectionName: target.collectionName,
700
- searchIndexName: target.searchIndexName,
701
- isByo: target.isByo,
702
- allowWrites: target.allowWrites,
703
- textSearchIndexName: name
704
- });
2375
+ if (previous) {
2376
+ const retired = { $ifNull: ["$retiredTextIndexNames", []] };
2377
+ const rename = (mutation) => [{ $set: {
2378
+ retiredTextIndexNames: { $setDifference: [{ $setUnion: [retired, { $cond: [
2379
+ { $and: [{ $eq: ["$ownsTextIndex", true] }, { $eq: [{ $type: "$textSearchIndexName" }, "string"] }] },
2380
+ ["$textSearchIndexName"],
2381
+ []
2382
+ ] }] }, { $literal: [name] }] },
2383
+ ownsTextIndex: { $cond: [
2384
+ { $in: [{ $literal: name }, retired] },
2385
+ true,
2386
+ false
2387
+ ] },
2388
+ textSearchIndexName: { $literal: name },
2389
+ ...mutation
2390
+ } }];
2391
+ const observed = {
2392
+ _id: indexName,
2393
+ claimToken: previous.claimToken ?? null,
2394
+ textSearchIndexName: previous.textSearchIndexName ?? null,
2395
+ deleting: { $ne: true }
2396
+ };
2397
+ written = sameName ? textFields : {
2398
+ ...textFields,
2399
+ retiredTextIndexNames: null
2400
+ };
2401
+ p0 = await this.p0Write(observed, sameName ? (mutation) => [{ $set: {
2402
+ ...literals(textFields),
2403
+ ...mutation
2404
+ } }] : rename, claimToken, false);
2405
+ if (!p0) {
2406
+ const current = await this.readRegistryEntry(indexName);
2407
+ this.assertNotDeleting(current, "CREATE_SEARCH_INDEX");
2408
+ throw concurrentConflict(current ? "changed" : "removed");
2409
+ }
2410
+ } else {
2411
+ written = {
2412
+ indexName,
2413
+ collectionName: target.collectionName,
2414
+ searchIndexName: target.searchIndexName,
2415
+ isByo: target.isByo,
2416
+ allowWrites: target.allowWrites,
2417
+ ...textFields
2418
+ };
2419
+ try {
2420
+ p0 = await this.writeRegistryEntry(indexName, {
2421
+ ...written,
2422
+ claimToken
2423
+ }, { claimToken: { $exists: false } });
2424
+ } catch (error) {
2425
+ if (error?.code === 11e3) throw concurrentConflict("registered");
2426
+ throw error;
2427
+ }
2428
+ }
2429
+ await this.tofuIndexIds(indexName, p0.pin, [{
2430
+ role: "text",
2431
+ name
2432
+ }], collection);
705
2433
  this.indexTargets.set(indexName, {
706
2434
  ...target,
707
2435
  textSearchIndexName: name
708
2436
  });
709
- if (!await this.createSearchIndexIgnoringExisting(collection, {
710
- definition,
711
- name,
712
- type: "search"
713
- })) await collection.updateSearchIndex(name, definition);
2437
+ let created;
2438
+ try {
2439
+ created = await this.provisionSearchIndex({
2440
+ indexName,
2441
+ collection,
2442
+ role: "text",
2443
+ op: "CREATE_SEARCH_INDEX",
2444
+ description: {
2445
+ definition,
2446
+ name,
2447
+ type: "search"
2448
+ },
2449
+ pin: p0.pin,
2450
+ check: async () => {
2451
+ await this.assertNoPendingDrop(collectionName, indexName, [name], "CREATE_SEARCH_INDEX", { textSearchIndexName: name }, p0.pin.generation, reconciled);
2452
+ await this.testHooks?.beforeSearchIndexProvision?.(indexName);
2453
+ }
2454
+ });
2455
+ } catch (abort) {
2456
+ if (!(abort instanceof ProvisionAbort)) throw abort;
2457
+ if (!abort.rollback) provisioned = true;
2458
+ throw abort.error;
2459
+ }
2460
+ const ours = sameName && previous?.ownsTextIndex || previous?.retiredTextIndexNames?.includes(name);
2461
+ const listedId = created.outcome === "attached" ? created.row?.id : void 0;
2462
+ const recordedId = ours ? (await this.readRegistryEntry(indexName))?.indexIds?.find((e) => e.name === name)?.id : void 0;
2463
+ if (created.outcome === "owned") {} else if (listedId && listedId === recordedId) await this.runSearchIndexCommand({
2464
+ updateSearchIndex: collection.collectionName,
2465
+ id: listedId,
2466
+ definition
2467
+ });
2468
+ else {
2469
+ if (ours) this.logger.warn(`search index "${name}" on "${collectionName}" is ${listedId ? `listed with id ${listedId}` : "not listed"} but recorded with ${recordedId ? `id ${recordedId}` : "no id"}; treated as not created by Mastra and not modified`);
2470
+ const [existing] = await this.listSearchIndexRows(collection, name, "P1");
2471
+ if (!searchDefinitionsEquivalent(existing?.latestDefinition, definition)) {
2472
+ const hint = !target.isByo && target.ownsTextIndex === void 0 ? ` If Mastra created this index (registered by an earlier version), call claimLegacyIndex({ indexName: "${indexName}" }) once, then retry.` : "";
2473
+ throw new _mastra_core_error.MastraError({
2474
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_SEARCH_INDEX", "CONFLICT"),
2475
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2476
+ category: _mastra_core_error.ErrorCategory.USER,
2477
+ details: {
2478
+ indexName,
2479
+ collectionName
2480
+ },
2481
+ text: `Full-text search index "${name}" already exists on collection "${collectionName}" with a different mapping, and Mastra did not create it, so it will not be modified. Pass a different searchIndexName, or update or drop the existing index yourself.${hint}`
2482
+ });
2483
+ }
2484
+ }
2485
+ provisioned = true;
714
2486
  if (waitUntilReady) await this.waitForSearchIndexReady({ indexName });
715
2487
  } catch (error) {
2488
+ if (!provisioned && p0) await this.rollbackRegistryEntry(indexName, p0.pin, p0.before ? rollbackRestore(p0.before, written) : null);
2489
+ if (error instanceof _mastra_core_error.MastraError) throw error;
716
2490
  throw new _mastra_core_error.MastraError({
717
2491
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CREATE_SEARCH_INDEX", "FAILED"),
718
2492
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -757,13 +2531,8 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
757
2531
  }, error);
758
2532
  }
759
2533
  }
760
- /**
761
- * Run a hybrid search that fuses vector similarity and full-text (BM25) results
762
- * using MongoDB's server-side $rankFusion aggregation stage. Requires MongoDB >= 8.0
763
- * (see {@link assertRankFusionSupported}: generally available from 8.1; on 8.0.x it may
764
- * need a MongoDB support case to enable, and runs where enabled, e.g. Atlas 8.0.x).
765
- */
766
2534
  async hybridQuery(params) {
2535
+ if ("vector" in params || "text" in params) return this.hybridQueryBranches(params);
767
2536
  const { indexName, queryVector, queryText, model, query, paths, topK = 10, filter, weights, numCandidates, metadataMode = "field", textSearchIndexName } = params;
768
2537
  if (model && !queryText) throw new _mastra_core_error.MastraError({
769
2538
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "INVALID_ARGS"),
@@ -797,66 +2566,32 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
797
2566
  });
798
2567
  const textIndex = textSearchIndexName ?? await this.resolveTextSearchIndexName(indexName);
799
2568
  try {
800
- const collection = await this.getCollection(collectionName, true);
801
- const metadataFilter = this.transformMetadataFilter(this.transformFilter(filter), metadataMode);
802
- const hasMetadataFilter = Object.keys(metadataFilter).length > 0;
803
2569
  const perBranch = Math.min(1e4, Math.max(topK * 4, 20));
804
2570
  const candidates = Math.min(1e4, Math.max(perBranch, numCandidates ?? topK * 20));
805
- const vectorSearch = {
806
- index: searchIndexName,
807
- path: autoEmbed ? autoEmbed.path : this.embeddingFieldName,
808
- ...queryText ? { query: { text: queryText } } : { queryVector },
809
- ...model ? { model } : {},
810
- numCandidates: candidates,
811
- limit: perBranch
812
- };
813
- if (hasMetadataFilter) {
814
- let declaredPaths;
815
- try {
816
- declaredPaths = await this.getDeclaredFilterPaths(indexName);
817
- } catch {
818
- declaredPaths = /* @__PURE__ */ new Set();
819
- }
820
- if (this.canPushDownFilter(metadataFilter, declaredPaths)) vectorSearch.filter = metadataFilter;
821
- else {
822
- const candidateIds = await collection.aggregate([{ $match: metadataFilter }, { $project: { _id: 1 } }]).map((doc) => doc._id).toArray();
823
- if (candidateIds.length === 0) return [];
824
- vectorSearch.filter = { _id: { $in: candidateIds } };
2571
+ return await this.runHybridPipeline({
2572
+ indexName,
2573
+ collectionName,
2574
+ searchIndexName,
2575
+ autoEmbed,
2576
+ metadataMode,
2577
+ filter,
2578
+ weights,
2579
+ topK,
2580
+ vector: {
2581
+ ...queryText ? { query: queryText } : { queryVector },
2582
+ ...model ? { model } : {},
2583
+ numCandidates: candidates,
2584
+ limit: perBranch
2585
+ },
2586
+ text: {
2587
+ query,
2588
+ paths,
2589
+ searchIndexName: textIndex,
2590
+ limit: perBranch
825
2591
  }
826
- }
827
- const textPipeline = [
828
- { $search: {
829
- index: textIndex,
830
- text: {
831
- query,
832
- path: paths
833
- }
834
- } },
835
- ...hasMetadataFilter ? [{ $match: metadataFilter }] : [],
836
- { $limit: perBranch }
837
- ];
838
- const combination = weights ? { weights: {
839
- vector: weights.vector ?? 1,
840
- text: weights.text ?? 1
841
- } } : void 0;
842
- const pipeline = [
843
- { $rankFusion: {
844
- input: { pipelines: {
845
- vector: [{ $vectorSearch: vectorSearch }],
846
- text: textPipeline
847
- } },
848
- ...combination ? { combination } : {}
849
- } },
850
- { $limit: Math.min(1e4, topK) },
851
- ...this.buildProjection(metadataMode, false, "score", autoEmbed?.path)
852
- ];
853
- return (await collection.aggregate(pipeline).toArray()).map((r) => ({
854
- id: this.idToString(r._id),
855
- score: typeof r.score === "number" ? r.score : 0,
856
- metadata: r.metadata,
857
- document: r.document
858
- }));
2592
+ });
859
2593
  } catch (error) {
2594
+ if (error instanceof _mastra_core_error.MastraError) throw error;
860
2595
  throw new _mastra_core_error.MastraError({
861
2596
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "FAILED"),
862
2597
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -864,6 +2599,192 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
864
2599
  }, error);
865
2600
  }
866
2601
  }
2602
+ async hybridQueryBranches(params) {
2603
+ this.validateHybridQueryBranchParams(params);
2604
+ const { indexName, vector, text, rerank, topK = 10, filter, weights, includeVector = false } = params;
2605
+ const defaultLimit = Math.min(1e4, Math.max(topK * 4, 20));
2606
+ const vectorLimit = vector.limit ?? defaultLimit;
2607
+ const textLimit = text.limit ?? defaultLimit;
2608
+ const candidates = vector.numCandidates ?? Math.min(1e4, vectorLimit * 20);
2609
+ try {
2610
+ await this.assertRankFusionSupported();
2611
+ const { collectionName, searchIndexName, autoEmbed, isByo } = await this.resolveIndexTarget(indexName);
2612
+ if (!isByo && (vector.searchIndexName !== void 0 || text.searchIndexName !== void 0)) throw new _mastra_core_error.MastraError({
2613
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "INVALID_ARGS"),
2614
+ text: `vector.searchIndexName and text.searchIndexName are only supported for bring-your-own collections. Managed index "${indexName}" uses its registered search indexes.`,
2615
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2616
+ category: _mastra_core_error.ErrorCategory.USER,
2617
+ details: { indexName }
2618
+ });
2619
+ if (vector.query !== void 0 && !autoEmbed) throw new _mastra_core_error.MastraError({
2620
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "NOT_AUTO_EMBED"),
2621
+ text: `Index "${indexName}" was not created with autoEmbed. Supply vector.queryVector instead of vector.query.`,
2622
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2623
+ category: _mastra_core_error.ErrorCategory.USER,
2624
+ details: { indexName }
2625
+ });
2626
+ if (vector.queryVector !== void 0 && autoEmbed) throw new _mastra_core_error.MastraError({
2627
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "INVALID_ARGS"),
2628
+ text: `Index "${indexName}" was created with autoEmbed, so MongoDB only accepts query text for it. Supply vector.query instead of vector.queryVector.`,
2629
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2630
+ category: _mastra_core_error.ErrorCategory.USER,
2631
+ details: { indexName }
2632
+ });
2633
+ if (includeVector && autoEmbed) throw new _mastra_core_error.MastraError({
2634
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "INVALID_ARGS"),
2635
+ text: `includeVector is not supported on autoEmbed index "${indexName}": MongoDB keeps the generated embeddings in its own internal database, so they are not on the returned documents.`,
2636
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2637
+ category: _mastra_core_error.ErrorCategory.USER,
2638
+ details: { indexName }
2639
+ });
2640
+ const textIndex = text.searchIndexName ?? await this.resolveTextSearchIndexName(indexName);
2641
+ const { searchIndexName: vectorIndexOverride, ...vectorInput } = vector;
2642
+ return await this.runHybridPipeline({
2643
+ indexName,
2644
+ collectionName,
2645
+ searchIndexName: vectorIndexOverride ?? searchIndexName,
2646
+ pushDownFilter: vectorIndexOverride === void 0,
2647
+ autoEmbed,
2648
+ includeVector,
2649
+ metadataMode: isByo ? "document" : "field",
2650
+ filter,
2651
+ weights,
2652
+ topK,
2653
+ vector: {
2654
+ ...vectorInput,
2655
+ numCandidates: candidates,
2656
+ limit: vectorLimit
2657
+ },
2658
+ text: {
2659
+ query: text.query,
2660
+ paths: text.paths,
2661
+ searchIndexName: textIndex,
2662
+ limit: textLimit
2663
+ },
2664
+ rerank
2665
+ });
2666
+ } catch (error) {
2667
+ if (error instanceof _mastra_core_error.MastraError && error.category === _mastra_core_error.ErrorCategory.USER) throw error;
2668
+ throw new _mastra_core_error.MastraError({
2669
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "FAILED"),
2670
+ text: rerank ? "hybridQuery with native $rerank failed. Check Atlas Native Reranking support, model availability, and that rerank.paths exist in every candidate document." : "hybridQuery failed. Check the collection, search indexes, and $rankFusion support.",
2671
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2672
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2673
+ details: { indexName }
2674
+ }, error);
2675
+ }
2676
+ }
2677
+ /** Builds and runs the $rankFusion pipeline shared by both hybridQuery shapes. */
2678
+ async runHybridPipeline({ indexName, collectionName, searchIndexName, pushDownFilter = true, autoEmbed, includeVector = false, metadataMode, filter, weights, topK, vector, text, rerank }) {
2679
+ const collection = await this.getCollection(collectionName, true);
2680
+ const metadataFilter = this.transformMetadataFilter(this.transformFilter(filter), metadataMode);
2681
+ const hasMetadataFilter = Object.keys(metadataFilter).length > 0;
2682
+ const vectorSearch = {
2683
+ index: searchIndexName,
2684
+ path: autoEmbed ? autoEmbed.path : this.embeddingFieldName,
2685
+ ...vector.query !== void 0 ? { query: { text: vector.query } } : { queryVector: vector.queryVector },
2686
+ ...vector.model !== void 0 ? { model: vector.model } : {},
2687
+ numCandidates: vector.numCandidates,
2688
+ limit: vector.limit
2689
+ };
2690
+ if (hasMetadataFilter) {
2691
+ let declaredPaths = /* @__PURE__ */ new Set();
2692
+ if (pushDownFilter) try {
2693
+ declaredPaths = await this.getDeclaredFilterPaths(indexName);
2694
+ } catch {
2695
+ declaredPaths = /* @__PURE__ */ new Set();
2696
+ }
2697
+ if (this.canPushDownFilter(metadataFilter, declaredPaths)) vectorSearch.filter = metadataFilter;
2698
+ else {
2699
+ const candidateIds = await this.collectCandidateIds(collection, metadataFilter, indexName, "HYBRID_QUERY");
2700
+ if (candidateIds.length === 0) return [];
2701
+ vectorSearch.filter = { _id: { $in: candidateIds } };
2702
+ }
2703
+ }
2704
+ const pipeline = [
2705
+ { $rankFusion: {
2706
+ input: { pipelines: {
2707
+ vector: [{ $vectorSearch: vectorSearch }],
2708
+ text: [
2709
+ { $search: {
2710
+ index: text.searchIndexName,
2711
+ text: {
2712
+ query: text.query,
2713
+ path: text.paths
2714
+ }
2715
+ } },
2716
+ ...hasMetadataFilter ? [{ $match: metadataFilter }] : [],
2717
+ { $limit: text.limit }
2718
+ ]
2719
+ } },
2720
+ ...weights ? { combination: { weights: {
2721
+ vector: weights.vector ?? 1,
2722
+ text: weights.text ?? 1
2723
+ } } } : {}
2724
+ } },
2725
+ ...rerank ? [{ $rerank: {
2726
+ query: { text: rerank.query },
2727
+ path: rerank.paths,
2728
+ model: rerank.model ?? "rerank-2.5",
2729
+ numDocsToRerank: rerank.numDocsToRerank
2730
+ } }] : [],
2731
+ { $limit: Math.min(1e4, topK) },
2732
+ ...this.buildProjection(metadataMode, includeVector, "score", autoEmbed?.path)
2733
+ ];
2734
+ return (await collection.aggregate(pipeline).toArray()).map((row) => ({
2735
+ id: this.idToString(row._id),
2736
+ score: typeof row.score === "number" ? row.score : 0,
2737
+ metadata: row.metadata,
2738
+ document: row.document,
2739
+ ...includeVector ? { vector: row.vector } : {}
2740
+ }));
2741
+ }
2742
+ validateHybridQueryBranchParams(params) {
2743
+ const fail = (text) => {
2744
+ throw new _mastra_core_error.MastraError({
2745
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "HYBRID_QUERY", "INVALID_ARGS"),
2746
+ text,
2747
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2748
+ category: _mastra_core_error.ErrorCategory.USER
2749
+ });
2750
+ };
2751
+ const nonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
2752
+ const integer = (value, name, max = 1e4) => {
2753
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max) fail(`${name} must be an integer from 1 to ${max}.`);
2754
+ };
2755
+ const paths = (value, name) => {
2756
+ if (!Array.isArray(value) || value.length === 0 || !value.every(nonEmptyString)) fail(`${name} must be a non-empty array of non-empty field paths.`);
2757
+ };
2758
+ if (!params || !nonEmptyString(params.indexName)) fail("indexName must be a non-empty string.");
2759
+ const { vector, text, rerank, weights } = params;
2760
+ if (!vector || typeof vector !== "object") fail("vector retrieval configuration is required.");
2761
+ if (vector.queryVector !== void 0 === (vector.query !== void 0)) fail("Supply exactly one of vector.queryVector or vector.query.");
2762
+ if (vector.queryVector !== void 0) {
2763
+ if (!Array.isArray(vector.queryVector) || vector.queryVector.length === 0 || !vector.queryVector.every((value) => typeof value === "number" && Number.isFinite(value))) fail("vector.queryVector must be a non-empty array of finite numbers.");
2764
+ } else if (!nonEmptyString(vector.query)) fail("vector.query must be a non-empty string.");
2765
+ if (vector.model !== void 0 && (vector.query === void 0 || !nonEmptyString(vector.model))) fail("vector.model must be a non-empty string and requires vector.query.");
2766
+ if (!text || !nonEmptyString(text.query)) fail("text.query must be a non-empty string.");
2767
+ paths(text.paths, "text.paths");
2768
+ if (text.searchIndexName !== void 0 && !nonEmptyString(text.searchIndexName)) fail("text.searchIndexName must be a non-empty string.");
2769
+ if (vector.searchIndexName !== void 0 && !nonEmptyString(vector.searchIndexName)) fail("vector.searchIndexName must be a non-empty string.");
2770
+ if (params.topK !== void 0) integer(params.topK, "topK");
2771
+ if (vector.limit !== void 0) integer(vector.limit, "vector.limit");
2772
+ if (text.limit !== void 0) integer(text.limit, "text.limit");
2773
+ if (vector.numCandidates !== void 0) integer(vector.numCandidates, "vector.numCandidates");
2774
+ if (params.includeVector !== void 0 && typeof params.includeVector !== "boolean") fail("includeVector must be a boolean.");
2775
+ if (weights !== void 0) {
2776
+ if (!weights || typeof weights !== "object") fail("weights must be an object.");
2777
+ const values = [weights.vector ?? 1, weights.text ?? 1];
2778
+ if (values.some((value) => typeof value !== "number" || !Number.isFinite(value) || value < 0)) fail("weights.vector and weights.text must be finite, non-negative numbers.");
2779
+ if (values.every((value) => value === 0)) fail("At least one fusion weight must be positive.");
2780
+ }
2781
+ if (rerank !== void 0) {
2782
+ if (!rerank || !nonEmptyString(rerank.query)) fail("rerank.query must be a non-empty string.");
2783
+ paths(rerank.paths, "rerank.paths");
2784
+ integer(rerank.numDocsToRerank, "rerank.numDocsToRerank", 1e3);
2785
+ if (rerank.model !== void 0 && !nonEmptyString(rerank.model)) fail("rerank.model must be a non-empty string.");
2786
+ }
2787
+ }
867
2788
  /**
868
2789
  * Waits for the index to be ready.
869
2790
  *
@@ -933,8 +2854,8 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
933
2854
  try {
934
2855
  const collection = await this.getCollection(collectionName);
935
2856
  if (!autoEmbed) {
936
- const stats = await this.describeIndex({ indexName });
937
- await this.validateVectorDimensions(vectors, stats.dimension);
2857
+ const { dimension } = await this.readVectorIndexDefinition(indexName);
2858
+ await this.validateVectorDimensions(vectors, dimension);
938
2859
  }
939
2860
  const rowCount = (autoEmbed ? documents : vectors)?.length ?? 0;
940
2861
  const generatedIds = ids || Array.from({ length: rowCount }, () => (0, _lukeed_uuid.v4)());
@@ -943,10 +2864,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
943
2864
  const id = generatedIds[idx];
944
2865
  const meta = metadata?.[idx] || {};
945
2866
  const doc = documents?.[idx];
946
- const normalizedMeta = Object.keys(meta).reduce((acc, key) => {
947
- acc[key] = meta[key] instanceof Date ? meta[key].toISOString() : meta[key];
948
- return acc;
949
- }, {});
2867
+ const normalizedMeta = this.normalizeMetadata(meta);
950
2868
  const updateDoc = {
951
2869
  ...autoEmbed ? {} : { [this.embeddingFieldName]: vector },
952
2870
  [this.metadataFieldName]: normalizedMeta
@@ -1053,8 +2971,8 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1053
2971
  const pushDocument = !documentFilterExpr || !autoEmbed && (!verifyDocumentPath || declaredPaths.has(documentTextField)) && this.canPushDownFilter(documentFilter, /* @__PURE__ */ new Set());
1054
2972
  const pushed = [...hasMetadataFilter && pushMetadata ? [metadataFilter] : [], ...documentFilterExpr && pushDocument ? [documentFilterExpr] : []];
1055
2973
  if (!pushMetadata || !pushDocument) {
1056
- const preFilter = [...hasMetadataFilter && !pushMetadata ? [metadataFilter] : [], ...documentFilterExpr && !pushDocument ? [documentFilterExpr] : []];
1057
- const candidateIds = await collection.aggregate([{ $match: preFilter.length > 1 ? { $and: preFilter } : preFilter[0] }, { $project: { _id: 1 } }]).map((doc) => doc._id).toArray();
2974
+ const allPredicates = [...[...hasMetadataFilter && !pushMetadata ? [metadataFilter] : [], ...documentFilterExpr && !pushDocument ? [documentFilterExpr] : []], ...pushed];
2975
+ const candidateIds = await this.collectCandidateIds(collection, allPredicates.length > 1 ? { $and: allPredicates } : allPredicates[0], indexName, "QUERY");
1058
2976
  if (candidateIds.length === 0) return [];
1059
2977
  pushed.unshift({ _id: { $in: candidateIds } });
1060
2978
  }
@@ -1069,6 +2987,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1069
2987
  document: result.document
1070
2988
  }));
1071
2989
  } catch (error) {
2990
+ if (error instanceof _mastra_core_error.MastraError) throw error;
1072
2991
  throw new _mastra_core_error.MastraError({
1073
2992
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "QUERY", "FAILED"),
1074
2993
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1078,6 +2997,42 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1078
2997
  }
1079
2998
  }
1080
2999
  /**
3000
+ * Runs a filter that `$vectorSearch` cannot apply itself and returns the matching `_id`s.
3001
+ * Reads one id past {@link MongoDBVector.MAX_PREFILTER_CANDIDATES} so an oversized set fails
3002
+ * with a USER error instead of exhausting memory or the 16 MB command limit.
3003
+ */
3004
+ async collectCandidateIds(collection, match, indexName, operation) {
3005
+ const max = MongoDBVector.MAX_PREFILTER_CANDIDATES;
3006
+ const maxBytes = MongoDBVector.MAX_PREFILTER_ID_BYTES;
3007
+ const ids = [];
3008
+ let bytes = 5;
3009
+ const cursor = collection.aggregate([
3010
+ { $match: match },
3011
+ { $project: { _id: 1 } },
3012
+ { $limit: max + 1 }
3013
+ ]);
3014
+ try {
3015
+ for await (const doc of cursor) {
3016
+ bytes += mongodb.BSON.calculateObjectSize({ [ids.length]: doc._id }) - 5;
3017
+ if (ids.length >= max || bytes > maxBytes) throw new _mastra_core_error.MastraError({
3018
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", operation, "TOO_MANY_CANDIDATES"),
3019
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3020
+ category: _mastra_core_error.ErrorCategory.USER,
3021
+ details: {
3022
+ indexName,
3023
+ maxCandidates: max,
3024
+ maxCandidateBytes: maxBytes
3025
+ },
3026
+ text: `The filter for index "${indexName}" cannot run inside $vectorSearch and exceeds the pre-filter limit of ${max} matching documents or ${maxBytes} BSON bytes of candidate _ids. Declare the filtered fields with createIndex({ filterFields }) so the filter runs inside $vectorSearch, or narrow the filter.`
3027
+ });
3028
+ ids.push(doc._id);
3029
+ }
3030
+ } finally {
3031
+ await cursor.close();
3032
+ }
3033
+ return ids;
3034
+ }
3035
+ /**
1081
3036
  * Runs a `$vectorSearch` pipeline, retrying while the index is in INITIAL_SYNC.
1082
3037
  *
1083
3038
  * While Atlas first builds a vector search index it usually answers with an empty result, but
@@ -1111,7 +3066,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1111
3066
  async listIndexes() {
1112
3067
  try {
1113
3068
  const names = /* @__PURE__ */ new Set();
1114
- const registered = await this.db.collection(MongoDBVector.REGISTRY_COLLECTION).find({}, { projection: {
3069
+ const registered = await this.registry().find({}, { projection: {
1115
3070
  _id: 1,
1116
3071
  collectionName: 1
1117
3072
  } }).toArray();
@@ -1123,7 +3078,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1123
3078
  const collections = await this.db.listCollections().toArray();
1124
3079
  for (const col of collections) {
1125
3080
  const name = col.name;
1126
- if (name === MongoDBVector.REGISTRY_COLLECTION) continue;
3081
+ if (name === MongoDBVector.REGISTRY_COLLECTION || name === MongoDBVector.JOURNAL_COLLECTION) continue;
1127
3082
  if (names.has(name) || registeredCollections.has(name)) continue;
1128
3083
  try {
1129
3084
  if ((await this.db.collection(name).listSearchIndexes().toArray()).some((idx) => idx.name === `${name}_vector_index`)) names.add(name);
@@ -1146,38 +3101,17 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1146
3101
  */
1147
3102
  async describeIndex({ indexName }) {
1148
3103
  try {
1149
- const { collectionName, searchIndexName, autoEmbed } = await this.resolveIndexTarget(indexName);
3104
+ const { collectionName, autoEmbed } = await this.resolveIndexTarget(indexName);
1150
3105
  const collection = await this.getCollection(collectionName, true);
3106
+ const { dimension, metric } = await this.readVectorIndexDefinition(indexName);
1151
3107
  const embeddedFieldName = autoEmbed ? autoEmbed.path : this.embeddingFieldName;
1152
- const count = await collection.countDocuments({
1153
- [embeddedFieldName]: { $exists: true },
1154
- _id: { $ne: "__index_metadata__" }
1155
- });
1156
- const indexNameInternal = searchIndexName;
1157
- const indexData = (await collection.listSearchIndexes().toArray()).find((idx) => idx.name === indexNameInternal);
1158
- if (!indexData) throw new _mastra_core_error.MastraError({
1159
- id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DESCRIBE_INDEX", "NOT_FOUND"),
1160
- domain: _mastra_core_error.ErrorDomain.STORAGE,
1161
- category: _mastra_core_error.ErrorCategory.USER,
1162
- details: { indexName },
1163
- text: `Atlas Search index "${indexNameInternal}" does not exist on collection "${indexName}". The collection may predate Mastra or the index may have been dropped externally.`
1164
- });
1165
- const vectorField = indexData.latestDefinition?.fields?.find((f) => f.type === "vector" || f.type === "autoEmbed");
1166
- if (!vectorField) throw new _mastra_core_error.MastraError({
1167
- id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DESCRIBE_INDEX", "INVALID"),
1168
- domain: _mastra_core_error.ErrorDomain.STORAGE,
1169
- category: _mastra_core_error.ErrorCategory.USER,
1170
- details: { indexName },
1171
- text: `Atlas Search index "${indexNameInternal}" exists but has no vector field. The index may have been created outside of Mastra or without vector configuration.`
1172
- });
1173
3108
  return {
1174
- dimension: vectorField.type === "autoEmbed" ? vectorField.numDimensions ?? 1024 : vectorField.numDimensions,
1175
- count,
1176
- metric: vectorField.type === "autoEmbed" && vectorField.similarity === void 0 ? void 0 : {
1177
- cosine: "cosine",
1178
- euclidean: "euclidean",
1179
- dotProduct: "dotproduct"
1180
- }[vectorField.similarity] ?? "cosine"
3109
+ dimension,
3110
+ count: await collection.countDocuments({
3111
+ [embeddedFieldName]: { $exists: true },
3112
+ _id: { $ne: "__index_metadata__" }
3113
+ }),
3114
+ metric
1181
3115
  };
1182
3116
  } catch (error) {
1183
3117
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -1189,35 +3123,81 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1189
3123
  }, error);
1190
3124
  }
1191
3125
  }
3126
+ /**
3127
+ * Reads dimension and metric from the Atlas vectorSearch index definition. Unlike
3128
+ * {@link describeIndex} it never counts documents, so writes can validate dimensions
3129
+ * without scanning the collection.
3130
+ */
3131
+ async readVectorIndexDefinition(indexName) {
3132
+ const { collectionName, searchIndexName } = await this.resolveIndexTarget(indexName);
3133
+ const indexData = (await (await this.getCollection(collectionName, true)).listSearchIndexes().toArray()).find((idx) => idx.name === searchIndexName);
3134
+ if (!indexData) throw new _mastra_core_error.MastraError({
3135
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DESCRIBE_INDEX", "NOT_FOUND"),
3136
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3137
+ category: _mastra_core_error.ErrorCategory.USER,
3138
+ details: {
3139
+ indexName,
3140
+ collectionName
3141
+ },
3142
+ text: `Atlas Search index "${searchIndexName}" does not exist on collection "${collectionName}". The collection may predate Mastra or the index may have been dropped externally.`
3143
+ });
3144
+ const vectorField = indexData.latestDefinition?.fields?.find((f) => f.type === "vector" || f.type === "autoEmbed");
3145
+ if (!vectorField) throw new _mastra_core_error.MastraError({
3146
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DESCRIBE_INDEX", "INVALID"),
3147
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3148
+ category: _mastra_core_error.ErrorCategory.USER,
3149
+ details: { indexName },
3150
+ text: `Atlas Search index "${searchIndexName}" exists but has no vector field. The index may have been created outside of Mastra or without vector configuration.`
3151
+ });
3152
+ return {
3153
+ dimension: vectorField.type === "autoEmbed" ? vectorField.numDimensions ?? 1024 : vectorField.numDimensions,
3154
+ metric: vectorField.type === "autoEmbed" && vectorField.similarity === void 0 ? void 0 : {
3155
+ cosine: "cosine",
3156
+ euclidean: "euclidean",
3157
+ dotProduct: "dotproduct"
3158
+ }[vectorField.similarity] ?? "cosine"
3159
+ };
3160
+ }
1192
3161
  async deleteIndex({ indexName }) {
1193
- const { collectionName, searchIndexName, isByo, textSearchIndexName, registered } = await this.resolveIndexTarget(indexName);
1194
- const collection = await this.getCollection(collectionName, false);
3162
+ this.indexTargets.delete(indexName);
1195
3163
  try {
1196
- if (collection) {
1197
- if (isByo) {
1198
- if (!await this.isIndexNameReferencedElsewhere(indexName, collectionName, searchIndexName)) await this.dropSearchIndexIgnoringMissing(collection, searchIndexName);
1199
- if (textSearchIndexName && !await this.isIndexNameReferencedElsewhere(indexName, collectionName, textSearchIndexName)) await this.dropSearchIndexIgnoringMissing(collection, textSearchIndexName);
1200
- } else {
1201
- if (!registered) {
1202
- let hasManagedVectorIndex = false;
1203
- try {
1204
- hasManagedVectorIndex = (await collection.listSearchIndexes().toArray()).some((idx) => idx.name === `${indexName}_vector_index`);
1205
- } catch {}
1206
- if (!hasManagedVectorIndex) throw new Error(`Index "${indexName}" is not registered and collection "${collectionName}" carries no "${indexName}_vector_index" search index — refusing to drop a collection this store cannot verify it manages.`);
1207
- }
1208
- try {
1209
- await collection.drop();
1210
- } catch (err) {
1211
- const code = err?.codeName ?? err?.code;
1212
- if (code !== "NamespaceNotFound" && code !== 26) throw err;
1213
- }
1214
- this.collections.delete(collectionName);
1215
- }
3164
+ const entry = await this.readRegistryEntry(indexName);
3165
+ if (entry) await this.reconcile(entry.collectionName);
3166
+ if (entry && (entry.isByo || entry.ownsCollection === false)) {
3167
+ const exists = await this.db.listCollections({ name: entry.collectionName }, { readPreference: mongodb.ReadPreference.primary }).hasNext();
3168
+ await this.deleteKeepCollection(entry, exists ? this.db.collection(entry.collectionName) : null);
3169
+ this.declaredFilterPaths.delete(indexName);
3170
+ this.indexTargets.delete(indexName);
3171
+ return;
3172
+ }
3173
+ if (entry) {
3174
+ if (entry.ownsCollection !== true) throw new _mastra_core_error.MastraError({
3175
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", "OWNERSHIP_UNKNOWN"),
3176
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3177
+ category: _mastra_core_error.ErrorCategory.USER,
3178
+ details: {
3179
+ indexName,
3180
+ collectionName: entry.collectionName
3181
+ },
3182
+ text: `Index "${indexName}" was registered by an earlier version that did not record whether this store created collection "${entry.collectionName}". Nothing was dropped. If Mastra created it, call claimLegacyIndex({ indexName: "${indexName}" }) first.`
3183
+ });
3184
+ await this.deleteManagedCollection(entry);
1216
3185
  this.declaredFilterPaths.delete(indexName);
1217
3186
  this.indexTargets.delete(indexName);
1218
- await this.deleteRegistryEntry(indexName);
1219
- } else throw new Error(`Index (Collection) "${indexName}" does not exist`);
3187
+ return;
3188
+ }
3189
+ throw new _mastra_core_error.MastraError({
3190
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", "NOT_REGISTERED"),
3191
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3192
+ category: _mastra_core_error.ErrorCategory.USER,
3193
+ details: {
3194
+ indexName,
3195
+ collectionName: indexName
3196
+ },
3197
+ text: `Index "${indexName}" is not registered, so this store cannot verify that it created collection "${indexName}". Nothing was dropped. If Mastra created it before the registry existed, call claimLegacyIndex({ indexName }) first.`
3198
+ });
1220
3199
  } catch (error) {
3200
+ if (error instanceof _mastra_core_error.MastraError) throw error;
1221
3201
  throw new _mastra_core_error.MastraError({
1222
3202
  id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "DELETE_INDEX", "FAILED"),
1223
3203
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1227,6 +3207,235 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1227
3207
  }
1228
3208
  }
1229
3209
  /**
3210
+ * One-time upgrade helper for managed indexes created before `@mastra/mongodb@1.15.0`, or registered by 1.15–1.27 without ownership records. Calling it asserts that Mastra created the collection and its recorded search indexes; `deleteIndex()` will then drop the collection and all its data.
3211
+ */
3212
+ async claimLegacyIndex({ indexName }) {
3213
+ const reconciled = await this.reconcile(indexName);
3214
+ const registry = this.registry();
3215
+ const vectorIndex = `${indexName}_vector_index`;
3216
+ const refuse = (code, text, details = {}) => new _mastra_core_error.MastraError({
3217
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CLAIM_LEGACY_INDEX", code),
3218
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3219
+ category: _mastra_core_error.ErrorCategory.USER,
3220
+ details: {
3221
+ indexName,
3222
+ ...details
3223
+ },
3224
+ text
3225
+ });
3226
+ const byo = (entry) => refuse("BYO", `Index "${indexName}" is a bring-your-own index on collection "${entry.collectionName}". Its collection belongs to the caller and cannot be claimed.`, { collectionName: entry.collectionName });
3227
+ const conflict = (current) => refuse("CONFLICT", current ? `Index "${indexName}" now targets collection "${current.collectionName}" (vector index "${current.searchIndexName}"), not the one this claim validated. Nothing was claimed.` : `Index "${indexName}" was removed while it was being claimed. Nothing was claimed.`, {
3228
+ collectionName: current?.collectionName ?? null,
3229
+ searchIndexName: current?.searchIndexName ?? null
3230
+ });
3231
+ const otherUsers = () => registry.find({
3232
+ collectionName: indexName,
3233
+ _id: { $ne: indexName }
3234
+ }, { projection: { _id: 1 } }).toArray();
3235
+ const inUse = (others) => refuse("IN_USE", `Collection "${indexName}" is used by ${others.map((o) => `"${o._id}"`).join(", ")}, so it cannot be claimed for index "${indexName}". Nothing was claimed.`, {
3236
+ collectionName: indexName,
3237
+ usedBy: others.map((o) => o._id).join(", ")
3238
+ });
3239
+ const relistConflict = () => refuse("CONFLICT", "index changed while it was being claimed; nothing was claimed; retry");
3240
+ /** The live id listed for each name, on the primary (I7a). */
3241
+ const listIds = async (collectionName, names) => {
3242
+ const ids = {};
3243
+ for (const name of names) ids[name] = await this.liveIdOf(this.db.collection(collectionName), name, "claim");
3244
+ return ids;
3245
+ };
3246
+ /** Every id recorded for a claimed name is the one the re-list shows (§3.10 step 4). */
3247
+ const idsMatch = (indexIds, names, relisted) => (indexIds ?? []).every((e) => !names.includes(e.name) || relisted[e.name] === e.id);
3248
+ /** Pipeline stages adding `ids[name]` to `indexIds` for each owned claimed name with no entry yet (Q5 TOFU). */
3249
+ const tofuStages = (ids, vectorName, textName) => {
3250
+ const stage = (name, owned) => ({ $set: { indexIds: { $cond: [
3251
+ { $and: [owned, { $not: [{ $in: [{ $literal: name }, { $ifNull: ["$indexIds.name", []] }] }] }] },
3252
+ indexIdsWith(name, ids[name]),
3253
+ "$indexIds"
3254
+ ] } } });
3255
+ return [...ids[vectorName] ? [stage(vectorName, { $eq: ["$ownsVectorIndex", true] })] : [], ...textName && ids[textName] ? [stage(textName, { $and: [{ $eq: ["$textSearchIndexName", { $literal: textName }] }, { $eq: ["$ownsTextIndex", true] }] })] : []];
3256
+ };
3257
+ /**
3258
+ * §3.10 step 5, after an undo missed (or another write landed first): a cleaner may have handed
3259
+ * responsibility to the entry (R4-2, R5-2), so it stays; the claim succeeds only if the entry is
3260
+ * still on the claimed target and records what the re-list shows. On the insert path
3261
+ * (`requireLive`) every claimed name must also be listed live (R16).
3262
+ */
3263
+ const settle = async (collectionName, searchIndexName, names, relisted, requireLive = false) => {
3264
+ this.indexTargets.delete(indexName);
3265
+ const current = await this.readRegistryEntry(indexName);
3266
+ if (current && current.deleting !== true && current.isByo !== true && current.collectionName === collectionName && current.searchIndexName === searchIndexName && current.ownsCollection === true && idsMatch(current.indexIds, names, relisted) && (!requireLive || names.every((n) => relisted[n] !== void 0))) return;
3267
+ throw relistConflict();
3268
+ };
3269
+ const claimRegistered = async (seen) => {
3270
+ const { collectionName, searchIndexName, textSearchIndexName } = seen;
3271
+ const names = [searchIndexName, ...textSearchIndexName ? [textSearchIndexName] : []];
3272
+ const listed = await listIds(collectionName, names);
3273
+ const claimToken = (0, _lukeed_uuid.v4)();
3274
+ const backfill = (0, _lukeed_uuid.v4)();
3275
+ const before = await registry.findOneAndUpdate({
3276
+ _id: indexName,
3277
+ isByo: { $ne: true },
3278
+ collectionName,
3279
+ searchIndexName,
3280
+ deleting: { $ne: true },
3281
+ generation: seen.generation ?? { $exists: false }
3282
+ }, [{ $set: {
3283
+ ownsCollection: { $literal: true },
3284
+ ownsVectorIndex: { $ifNull: ["$ownsVectorIndex", true] },
3285
+ ...textSearchIndexName ? { ownsTextIndex: { $ifNull: ["$ownsTextIndex", true] } } : {},
3286
+ ...mutationFields(claimToken, backfill)
3287
+ } }, ...tofuStages(listed, searchIndexName, textSearchIndexName)], { returnDocument: "before" });
3288
+ this.indexTargets.delete(indexName);
3289
+ if (!before) {
3290
+ const current = await this.readRegistryEntry(indexName);
3291
+ this.assertNotDeleting(current, "CLAIM_LEGACY_INDEX");
3292
+ if (current && current.isByo !== true && current.collectionName === collectionName && current.searchIndexName === searchIndexName && current.ownsCollection === true) return;
3293
+ throw conflict(current);
3294
+ }
3295
+ await this.testHooks?.afterClaimWrite?.(indexName);
3296
+ const written = {
3297
+ generation: before.generation ?? backfill,
3298
+ rev: (before.rev ?? 0) + 1
3299
+ };
3300
+ /** Restore the fields this claim wrote; true when the entry was still as the claim left it. */
3301
+ const undo = async () => {
3302
+ await this.testHooks?.beforeClaimUndo?.(indexName);
3303
+ const restore = (v) => v === void 0 ? "$$REMOVE" : { $literal: v };
3304
+ const undone = await registry.updateOne({
3305
+ _id: indexName,
3306
+ generation: written.generation,
3307
+ claimToken,
3308
+ rev: written.rev
3309
+ }, [{ $set: {
3310
+ ownsCollection: restore(before.ownsCollection),
3311
+ ownsVectorIndex: restore(before.ownsVectorIndex),
3312
+ ownsTextIndex: restore(before.ownsTextIndex),
3313
+ indexIds: restore(before.indexIds),
3314
+ ...mutationFields()
3315
+ } }]);
3316
+ this.indexTargets.delete(indexName);
3317
+ return undone.matchedCount === 1;
3318
+ };
3319
+ let relisted;
3320
+ let after;
3321
+ try {
3322
+ relisted = await listIds(collectionName, names);
3323
+ after = await this.readRegistryEntry(indexName);
3324
+ } catch (error) {
3325
+ if (!await undo().catch((undoError) => {
3326
+ this.logger.error(`claimLegacyIndex("${indexName}") could not verify its claim or undo it, so the registration may still record that Mastra created collection "${collectionName}": ${undoError}`);
3327
+ return true;
3328
+ })) this.logger.warn(`claimLegacyIndex("${indexName}") could not verify its claim, and the registration changed since, so the claim was not undone: it may still record that Mastra created collection "${collectionName}"`);
3329
+ throw error;
3330
+ }
3331
+ if (after?.claimToken === claimToken) {
3332
+ if (idsMatch(after.indexIds, names, relisted)) return;
3333
+ if (await undo()) throw relistConflict();
3334
+ }
3335
+ await settle(collectionName, searchIndexName, names, relisted);
3336
+ };
3337
+ try {
3338
+ const entry = await this.readRegistryEntry(indexName);
3339
+ await this.testHooks?.afterClaimRead?.(indexName);
3340
+ if (entry) {
3341
+ this.assertNotDeleting(entry, "CLAIM_LEGACY_INDEX");
3342
+ if (entry.isByo === true) throw byo(entry);
3343
+ return await claimRegistered(entry);
3344
+ }
3345
+ const claimed = this.db.collection(indexName);
3346
+ const textIndex = `${indexName}_search_index`;
3347
+ const searchIndexes = [];
3348
+ const tofuIds = {};
3349
+ for (const name of [vectorIndex, textIndex]) {
3350
+ const rows = await this.listSearchIndexRows(claimed, name, "claim");
3351
+ if (rows.length) searchIndexes.push(name);
3352
+ tofuIds[name] = rows.find(isLiveRow)?.id;
3353
+ }
3354
+ if (!searchIndexes.includes(vectorIndex)) throw refuse("NOT_FOUND", `No collection "${indexName}" with vector index "${vectorIndex}" exists, so there is no legacy managed index to claim.`, { collectionName: indexName });
3355
+ const before = await otherUsers();
3356
+ if (before.length) throw inUse(before);
3357
+ const names = searchIndexes;
3358
+ const claimToken = (0, _lukeed_uuid.v4)();
3359
+ const generation = (0, _lukeed_uuid.v4)();
3360
+ await this.testHooks?.beforeClaimInsert?.(indexName);
3361
+ try {
3362
+ await registry.insertOne({
3363
+ _id: indexName,
3364
+ indexName,
3365
+ collectionName: indexName,
3366
+ searchIndexName: vectorIndex,
3367
+ isByo: false,
3368
+ allowWrites: true,
3369
+ ownsCollection: true,
3370
+ ownsVectorIndex: true,
3371
+ ...searchIndexes.includes(textIndex) ? {
3372
+ textSearchIndexName: textIndex,
3373
+ ownsTextIndex: true
3374
+ } : {},
3375
+ generation,
3376
+ rev: 1,
3377
+ claimToken
3378
+ });
3379
+ } catch (error) {
3380
+ if (error?.code !== 11e3) throw error;
3381
+ this.indexTargets.delete(indexName);
3382
+ const winner = await this.readRegistryEntry(indexName);
3383
+ if (winner?.isByo === true) throw byo(winner);
3384
+ if (!winner || winner.collectionName !== indexName || winner.searchIndexName !== vectorIndex) throw conflict(winner);
3385
+ this.assertNotDeleting(winner, "CLAIM_LEGACY_INDEX");
3386
+ return await claimRegistered(winner);
3387
+ }
3388
+ this.indexTargets.delete(indexName);
3389
+ await this.testHooks?.afterClaimWrite?.(indexName);
3390
+ let pending;
3391
+ let after;
3392
+ let relisted;
3393
+ try {
3394
+ pending = await this.pendingDropError(indexName, indexName, names, "CLAIM_LEGACY_INDEX", reconciled);
3395
+ after = await otherUsers();
3396
+ relisted = await listIds(indexName, names);
3397
+ } catch (error) {
3398
+ await registry.deleteOne({
3399
+ _id: indexName,
3400
+ generation,
3401
+ claimToken,
3402
+ rev: 1
3403
+ }).catch((undoError) => this.logger.error(`claimLegacyIndex("${indexName}") could not verify its claim or undo it, so the registration may still record that Mastra created collection "${indexName}": ${undoError}`));
3404
+ this.indexTargets.delete(indexName);
3405
+ throw error;
3406
+ }
3407
+ const present = names.every((n) => tofuIds[n] !== void 0 && relisted[n] === tofuIds[n]);
3408
+ const refusal = after.length ? inUse(after) : pending ?? (present ? void 0 : relistConflict());
3409
+ if (!refusal) {
3410
+ if ((await registry.updateOne({
3411
+ _id: indexName,
3412
+ generation,
3413
+ claimToken,
3414
+ rev: 1
3415
+ }, [{ $set: mutationFields() }, ...tofuStages(tofuIds, vectorIndex, names.includes(textIndex) ? textIndex : void 0)])).matchedCount === 1) return;
3416
+ return await settle(indexName, vectorIndex, names, relisted, true);
3417
+ }
3418
+ await this.testHooks?.beforeClaimUndo?.(indexName);
3419
+ const undone = await registry.deleteOne({
3420
+ _id: indexName,
3421
+ generation,
3422
+ claimToken,
3423
+ rev: 1
3424
+ });
3425
+ this.indexTargets.delete(indexName);
3426
+ if (undone.deletedCount === 1) throw refusal;
3427
+ await settle(indexName, vectorIndex, names, relisted, true);
3428
+ } catch (error) {
3429
+ if (error instanceof _mastra_core_error.MastraError) throw error;
3430
+ throw new _mastra_core_error.MastraError({
3431
+ id: (0, _mastra_core_storage.createVectorErrorId)("MONGODB", "CLAIM_LEGACY_INDEX", "FAILED"),
3432
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3433
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
3434
+ details: { indexName }
3435
+ }, error);
3436
+ }
3437
+ }
3438
+ /**
1230
3439
  * Updates a vector by its ID with the provided vector and/or metadata.
1231
3440
  * @param indexName - The name of the index containing the vector.
1232
3441
  * @param id - The ID of the vector to update.
@@ -1267,17 +3476,11 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1267
3476
  text: `Index "${indexName}" was created with autoEmbed, so MongoDB owns the embeddings and a vector cannot be written directly. Upsert the document with new text instead.`
1268
3477
  });
1269
3478
  if (update.vector) {
1270
- const stats = await this.describeIndex({ indexName });
1271
- await this.validateVectorDimensions([update.vector], stats.dimension);
3479
+ const { dimension } = await this.readVectorIndexDefinition(indexName);
3480
+ await this.validateVectorDimensions([update.vector], dimension);
1272
3481
  updateDoc[this.embeddingFieldName] = update.vector;
1273
3482
  }
1274
- if (update.metadata) {
1275
- const normalizedMeta = Object.keys(update.metadata).reduce((acc, key) => {
1276
- acc[key] = update.metadata[key] instanceof Date ? update.metadata[key].toISOString() : update.metadata[key];
1277
- return acc;
1278
- }, {});
1279
- updateDoc[this.metadataFieldName] = normalizedMeta;
1280
- }
3483
+ if (update.metadata) updateDoc[this.metadataFieldName] = this.normalizeMetadata(update.metadata);
1281
3484
  if ("id" in params && params.id) await collection.findOneAndUpdate({ _id: this.buildIdMatch(params.id) }, { $set: updateDoc });
1282
3485
  else if ("filter" in params && params.filter) {
1283
3486
  const filter = params.filter;
@@ -1443,13 +3646,21 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1443
3646
  * qualified filter paths stored in the index, e.g. `category` → `metadata.category`.
1444
3647
  * Blank entries are dropped and duplicates collapsed. A name already carrying the
1445
3648
  * `metadata.` prefix is left untouched so callers can pass either form.
3649
+ *
3650
+ * A bring-your-own collection keeps its fields at the document root, where document-mode
3651
+ * filters address them, so its names are declared as given. `_id` and `document` are
3652
+ * skipped there because createIndex always declares them.
1446
3653
  */
1447
- buildDeclaredMetadataPaths(filterFields) {
3654
+ buildDeclaredMetadataPaths(filterFields, isByo = false) {
1448
3655
  if (!filterFields?.length) return [];
1449
3656
  const paths = /* @__PURE__ */ new Set();
1450
3657
  for (const field of filterFields) {
1451
3658
  const trimmed = field?.trim();
1452
3659
  if (!trimmed) continue;
3660
+ if (isByo) {
3661
+ if (trimmed !== "_id" && trimmed !== this.documentFieldName) paths.add(trimmed);
3662
+ continue;
3663
+ }
1453
3664
  paths.add(trimmed.startsWith(`${this.metadataFieldName}.`) ? trimmed : `${this.metadataFieldName}.${trimmed}`);
1454
3665
  }
1455
3666
  return [...paths];
@@ -1461,16 +3672,20 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1461
3672
  * metadata filter can be pushed down into `$vectorSearch.filter`.
1462
3673
  */
1463
3674
  async getDeclaredFilterPaths(indexName) {
1464
- const cached = this.declaredFilterPaths.get(indexName);
1465
- if (cached) return cached;
1466
3675
  const { collectionName, searchIndexName } = await this.resolveIndexTarget(indexName);
3676
+ const source = `${collectionName}/${searchIndexName}`;
3677
+ const cached = this.declaredFilterPaths.get(indexName);
3678
+ if (cached?.source === source) return cached.paths;
1467
3679
  const collection = await this.getCollection(collectionName, true);
1468
3680
  const indexNameInternal = searchIndexName;
1469
3681
  const indexData = (await collection.listSearchIndexes().toArray()).find((idx) => idx.name === indexNameInternal);
1470
3682
  const paths = /* @__PURE__ */ new Set();
1471
3683
  if (indexData?.status !== "READY") return paths;
1472
3684
  for (const field of indexData.latestDefinition?.fields ?? []) if (field?.type === "filter" && typeof field.path === "string" && field.path !== "_id") paths.add(field.path);
1473
- this.declaredFilterPaths.set(indexName, paths);
3685
+ this.declaredFilterPaths.set(indexName, {
3686
+ source,
3687
+ paths
3688
+ });
1474
3689
  return paths;
1475
3690
  }
1476
3691
  /**
@@ -1514,6 +3729,13 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1514
3729
  if (typeof id === "string" && mongodb.ObjectId.isValid(id) && /^[0-9a-fA-F]{24}$/.test(id)) return { $in: [id, new mongodb.ObjectId(id)] };
1515
3730
  return id;
1516
3731
  }
3732
+ /**
3733
+ * Convert Date values to ISO strings. Object.fromEntries keeps a `__proto__` key as data
3734
+ * instead of replacing the prototype and losing it.
3735
+ */
3736
+ normalizeMetadata(meta) {
3737
+ return Object.fromEntries(Object.entries(meta).map(([key, value]) => [key, value instanceof Date ? value.toISOString() : value]));
3738
+ }
1517
3739
  transformFilter(filter) {
1518
3740
  const translator = new MongoDBFilterTranslator();
1519
3741
  if (!filter) return {};
@@ -1530,24 +3752,15 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1530
3752
  transformMetadataFilter(filter, metadataMode = "field") {
1531
3753
  if (!filter || typeof filter !== "object") return filter;
1532
3754
  if (Array.isArray(filter)) return filter.map((item) => this.transformMetadataFilter(item, metadataMode));
1533
- if (metadataMode === "document") {
1534
- const transformed = {};
1535
- for (const [key, value] of Object.entries(filter)) if (key.startsWith("$")) {
1536
- if (Array.isArray(value)) transformed[key] = value.map((item) => this.transformMetadataFilter(item, metadataMode));
1537
- else if (typeof value === "object" && value !== null) transformed[key] = this.transformMetadataFilter(value, metadataMode);
1538
- else transformed[key] = value;
1539
- } else transformed[key] = value;
1540
- return transformed;
1541
- }
1542
- const transformed = {};
1543
- for (const [key, value] of Object.entries(filter)) if (key.startsWith("$")) {
1544
- if (Array.isArray(value)) transformed[key] = value.map((item) => this.transformMetadataFilter(item, metadataMode));
1545
- else if (typeof value === "object" && value !== null) transformed[key] = this.transformMetadataFilter(value, metadataMode);
1546
- else transformed[key] = value;
1547
- } else if (key.startsWith("metadata.")) transformed[key] = value;
1548
- else if (this.isMetadataField(key)) transformed[`metadata.${key}`] = value;
1549
- else transformed[key] = value;
1550
- return transformed;
3755
+ return Object.fromEntries(Object.entries(filter).map(([key, value]) => {
3756
+ if (key.startsWith("$")) {
3757
+ if (Array.isArray(value)) return [key, value.map((item) => this.transformMetadataFilter(item, metadataMode))];
3758
+ if (typeof value === "object" && value !== null) return [key, this.transformMetadataFilter(value, metadataMode)];
3759
+ return [key, value];
3760
+ }
3761
+ if (metadataMode === "field" && !key.startsWith("metadata.") && this.isMetadataField(key)) return [`metadata.${key}`, value];
3762
+ return [key, value];
3763
+ }));
1551
3764
  }
1552
3765
  /**
1553
3766
  * Determine if a field should be treated as a metadata field.
@@ -1555,6 +3768,7 @@ var MongoDBVector = class MongoDBVector extends _mastra_core_vector.MastraVector
1555
3768
  * that doesn't start with underscore (MongoDB system fields).
1556
3769
  */
1557
3770
  isMetadataField(key) {
3771
+ if (key === "__proto__") return true;
1558
3772
  if (key.startsWith("_")) return false;
1559
3773
  if ([
1560
3774
  "_id",