@mastra/libsql 1.8.2-alpha.0 → 1.9.0-alpha.1

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
@@ -509,6 +509,9 @@ var LibSQLVector = class extends MastraVector {
509
509
  turso;
510
510
  maxRetries;
511
511
  initialBackoffMs;
512
+ overFetchMultiplier;
513
+ isMemoryDb;
514
+ vectorIndexes;
512
515
  constructor({
513
516
  url,
514
517
  authToken,
@@ -516,6 +519,7 @@ var LibSQLVector = class extends MastraVector {
516
519
  syncInterval,
517
520
  maxRetries = 5,
518
521
  initialBackoffMs = 100,
522
+ vectorTopKOverFetchMultiplier = 10,
519
523
  id
520
524
  }) {
521
525
  super({ id });
@@ -527,10 +531,27 @@ var LibSQLVector = class extends MastraVector {
527
531
  });
528
532
  this.maxRetries = maxRetries;
529
533
  this.initialBackoffMs = initialBackoffMs;
530
- if (url.includes(`file:`) || url.includes(`:memory:`)) {
534
+ if (!Number.isInteger(vectorTopKOverFetchMultiplier) || vectorTopKOverFetchMultiplier < 1) {
535
+ throw new Error("vectorTopKOverFetchMultiplier must be a positive integer");
536
+ }
537
+ this.overFetchMultiplier = vectorTopKOverFetchMultiplier;
538
+ this.isMemoryDb = url.includes(":memory:");
539
+ if (url.includes(`file:`) || this.isMemoryDb) {
531
540
  this.turso.execute("PRAGMA journal_mode=WAL;").then(() => this.logger.debug("LibSQLStore: PRAGMA journal_mode=WAL set.")).catch((err) => this.logger.warn("LibSQLStore: Failed to set PRAGMA journal_mode=WAL.", err));
532
541
  this.turso.execute("PRAGMA busy_timeout = 5000;").then(() => this.logger.debug("LibSQLStore: PRAGMA busy_timeout=5000 set.")).catch((err) => this.logger.warn("LibSQLStore: Failed to set PRAGMA busy_timeout=5000.", err));
533
542
  }
543
+ this.vectorIndexes = this.isMemoryDb ? Promise.resolve(/* @__PURE__ */ new Set()) : this.discoverVectorIndexes();
544
+ }
545
+ async discoverVectorIndexes() {
546
+ try {
547
+ const result = await this.turso.execute({
548
+ sql: `SELECT name FROM sqlite_master WHERE type='index' AND name LIKE '%_vector_idx'`,
549
+ args: []
550
+ });
551
+ return new Set(result.rows.map((row) => row.name));
552
+ } catch {
553
+ return /* @__PURE__ */ new Set();
554
+ }
534
555
  }
535
556
  async executeWriteOperationWithRetry(operation, isTransaction = false) {
536
557
  let attempts = 0;
@@ -564,6 +585,40 @@ var LibSQLVector = class extends MastraVector {
564
585
  const translator = new LibSQLFilterTranslator();
565
586
  return translator.translate(filter);
566
587
  }
588
+ async hasVectorIndex(parsedIndexName) {
589
+ const indexes = await this.vectorIndexes;
590
+ return indexes.has(`${parsedIndexName}_vector_idx`);
591
+ }
592
+ async queryWithIndex(parsedIndexName, vectorStr, topK, filter, includeVector, minScore) {
593
+ const translatedFilter = this.transformFilter(filter);
594
+ const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter);
595
+ const hasFilter = filterQuery.length > 0;
596
+ const fetchCount = hasFilter ? topK * this.overFetchMultiplier : topK * 2;
597
+ const embeddingSelect = includeVector ? ", vector_extract(t.embedding) as embedding" : "";
598
+ const filterCondition = hasFilter ? filterQuery.replace(/^\s*WHERE\s+/i, "") : "";
599
+ const whereClause = hasFilter ? `WHERE ${filterCondition} AND score > ?` : "WHERE score > ?";
600
+ const query = `
601
+ WITH candidates AS (
602
+ SELECT t.vector_id AS id,
603
+ (1 - vector_distance_cos(t.embedding, vector32(?))) AS score,
604
+ t.metadata
605
+ ${embeddingSelect}
606
+ FROM vector_top_k('${parsedIndexName}_vector_idx', vector32(?), ?) AS v
607
+ JOIN "${parsedIndexName}" AS t ON t.rowid = v.id
608
+ )
609
+ SELECT * FROM candidates
610
+ ${whereClause}
611
+ ORDER BY score DESC
612
+ LIMIT ?`;
613
+ const args = [vectorStr, vectorStr, fetchCount, ...filterValues, minScore, topK];
614
+ const result = await this.turso.execute({ sql: query, args });
615
+ return result.rows.map(({ id, score, metadata, embedding }) => ({
616
+ id,
617
+ score,
618
+ metadata: JSON.parse(metadata ?? "{}"),
619
+ ...includeVector && embedding && { vector: JSON.parse(embedding) }
620
+ }));
621
+ }
567
622
  async query({
568
623
  indexName,
569
624
  queryVector,
@@ -594,6 +649,23 @@ var LibSQLVector = class extends MastraVector {
594
649
  try {
595
650
  const parsedIndexName = parseSqlIdentifier(indexName, "index name");
596
651
  const vectorStr = `[${queryVector.join(",")}]`;
652
+ if (!this.isMemoryDb && await this.hasVectorIndex(parsedIndexName)) {
653
+ try {
654
+ const indexedResults = await this.queryWithIndex(
655
+ parsedIndexName,
656
+ vectorStr,
657
+ topK,
658
+ filter,
659
+ includeVector,
660
+ minScore
661
+ );
662
+ if (!filter || indexedResults.length >= topK) {
663
+ return indexedResults;
664
+ }
665
+ } catch (err) {
666
+ this.logger.warn("LibSQLVector: indexed query failed, falling back to brute-force", err);
667
+ }
668
+ }
597
669
  const translatedFilter = this.transformFilter(filter);
598
670
  const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter);
599
671
  filterValues.push(minScore);
@@ -727,6 +799,7 @@ var LibSQLVector = class extends MastraVector {
727
799
  `,
728
800
  args: []
729
801
  });
802
+ void this.vectorIndexes.then((indexes) => indexes.add(`${parsedIndexName}_vector_idx`));
730
803
  }
731
804
  deleteIndex(args) {
732
805
  try {
@@ -749,6 +822,7 @@ var LibSQLVector = class extends MastraVector {
749
822
  sql: `DROP TABLE IF EXISTS ${parsedIndexName}`,
750
823
  args: []
751
824
  });
825
+ void this.vectorIndexes.then((indexes) => indexes.delete(`${parsedIndexName}_vector_idx`));
752
826
  }
753
827
  async listIndexes() {
754
828
  try {