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