@mastra/libsql 1.8.1 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @mastra/libsql
2
2
 
3
+ ## 1.9.0-alpha.1
4
+
5
+ ### Minor Changes
6
+
7
+ - Use DiskANN vector_top_k() index for faster vector queries when available ([#14913](https://github.com/mastra-ai/mastra/pull/14913))
8
+
9
+ LibSQLVector.query() now automatically uses the existing DiskANN index for approximate nearest neighbor search instead of brute-force full table scans, providing 10-25x query speedups on larger datasets. Falls back to brute-force when no index exists.
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [[`16e34ca`](https://github.com/mastra-ai/mastra/commit/16e34caa98b9a114b17a6125e4e3fd87f169d0d0)]:
14
+ - @mastra/core@1.26.0-alpha.9
15
+
16
+ ## 1.8.2-alpha.0
17
+
18
+ ### Patch Changes
19
+
20
+ - Add `BackgroundTasksStorage` domain implementation so `@mastra/core` background task execution works with any storage adapter. ([#15307](https://github.com/mastra-ai/mastra/pull/15307))
21
+
22
+ - Updated dependencies [[`d63ffdb`](https://github.com/mastra-ai/mastra/commit/d63ffdbb2c11e76fe5ea45faab44bc15460f010c)]:
23
+ - @mastra/core@1.25.1-alpha.0
24
+
3
25
  ## 1.8.1
4
26
 
5
27
  ### Patch Changes
@@ -3,7 +3,7 @@ name: mastra-libsql
3
3
  description: Documentation for @mastra/libsql. Use when working with @mastra/libsql APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/libsql"
6
- version: "1.8.1"
6
+ version: "1.9.0-alpha.1"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.8.1",
2
+ "version": "1.9.0-alpha.1",
3
3
  "package": "@mastra/libsql",
4
4
  "exports": {},
5
5
  "modules": {}
package/dist/index.cjs CHANGED
@@ -511,6 +511,9 @@ var LibSQLVector = class extends vector.MastraVector {
511
511
  turso;
512
512
  maxRetries;
513
513
  initialBackoffMs;
514
+ overFetchMultiplier;
515
+ isMemoryDb;
516
+ vectorIndexes;
514
517
  constructor({
515
518
  url,
516
519
  authToken,
@@ -518,6 +521,7 @@ var LibSQLVector = class extends vector.MastraVector {
518
521
  syncInterval,
519
522
  maxRetries = 5,
520
523
  initialBackoffMs = 100,
524
+ vectorTopKOverFetchMultiplier = 10,
521
525
  id
522
526
  }) {
523
527
  super({ id });
@@ -529,10 +533,27 @@ var LibSQLVector = class extends vector.MastraVector {
529
533
  });
530
534
  this.maxRetries = maxRetries;
531
535
  this.initialBackoffMs = initialBackoffMs;
532
- if (url.includes(`file:`) || url.includes(`:memory:`)) {
536
+ if (!Number.isInteger(vectorTopKOverFetchMultiplier) || vectorTopKOverFetchMultiplier < 1) {
537
+ throw new Error("vectorTopKOverFetchMultiplier must be a positive integer");
538
+ }
539
+ this.overFetchMultiplier = vectorTopKOverFetchMultiplier;
540
+ this.isMemoryDb = url.includes(":memory:");
541
+ if (url.includes(`file:`) || this.isMemoryDb) {
533
542
  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));
534
543
  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));
535
544
  }
545
+ this.vectorIndexes = this.isMemoryDb ? Promise.resolve(/* @__PURE__ */ new Set()) : this.discoverVectorIndexes();
546
+ }
547
+ async discoverVectorIndexes() {
548
+ try {
549
+ const result = await this.turso.execute({
550
+ sql: `SELECT name FROM sqlite_master WHERE type='index' AND name LIKE '%_vector_idx'`,
551
+ args: []
552
+ });
553
+ return new Set(result.rows.map((row) => row.name));
554
+ } catch {
555
+ return /* @__PURE__ */ new Set();
556
+ }
536
557
  }
537
558
  async executeWriteOperationWithRetry(operation, isTransaction = false) {
538
559
  let attempts = 0;
@@ -566,6 +587,40 @@ var LibSQLVector = class extends vector.MastraVector {
566
587
  const translator = new LibSQLFilterTranslator();
567
588
  return translator.translate(filter);
568
589
  }
590
+ async hasVectorIndex(parsedIndexName) {
591
+ const indexes = await this.vectorIndexes;
592
+ return indexes.has(`${parsedIndexName}_vector_idx`);
593
+ }
594
+ async queryWithIndex(parsedIndexName, vectorStr, topK, filter, includeVector, minScore) {
595
+ const translatedFilter = this.transformFilter(filter);
596
+ const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter);
597
+ const hasFilter = filterQuery.length > 0;
598
+ const fetchCount = hasFilter ? topK * this.overFetchMultiplier : topK * 2;
599
+ const embeddingSelect = includeVector ? ", vector_extract(t.embedding) as embedding" : "";
600
+ const filterCondition = hasFilter ? filterQuery.replace(/^\s*WHERE\s+/i, "") : "";
601
+ const whereClause = hasFilter ? `WHERE ${filterCondition} AND score > ?` : "WHERE score > ?";
602
+ const query = `
603
+ WITH candidates AS (
604
+ SELECT t.vector_id AS id,
605
+ (1 - vector_distance_cos(t.embedding, vector32(?))) AS score,
606
+ t.metadata
607
+ ${embeddingSelect}
608
+ FROM vector_top_k('${parsedIndexName}_vector_idx', vector32(?), ?) AS v
609
+ JOIN "${parsedIndexName}" AS t ON t.rowid = v.id
610
+ )
611
+ SELECT * FROM candidates
612
+ ${whereClause}
613
+ ORDER BY score DESC
614
+ LIMIT ?`;
615
+ const args = [vectorStr, vectorStr, fetchCount, ...filterValues, minScore, topK];
616
+ const result = await this.turso.execute({ sql: query, args });
617
+ return result.rows.map(({ id, score, metadata, embedding }) => ({
618
+ id,
619
+ score,
620
+ metadata: JSON.parse(metadata ?? "{}"),
621
+ ...includeVector && embedding && { vector: JSON.parse(embedding) }
622
+ }));
623
+ }
569
624
  async query({
570
625
  indexName,
571
626
  queryVector,
@@ -596,6 +651,23 @@ var LibSQLVector = class extends vector.MastraVector {
596
651
  try {
597
652
  const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
598
653
  const vectorStr = `[${queryVector.join(",")}]`;
654
+ if (!this.isMemoryDb && await this.hasVectorIndex(parsedIndexName)) {
655
+ try {
656
+ const indexedResults = await this.queryWithIndex(
657
+ parsedIndexName,
658
+ vectorStr,
659
+ topK,
660
+ filter,
661
+ includeVector,
662
+ minScore
663
+ );
664
+ if (!filter || indexedResults.length >= topK) {
665
+ return indexedResults;
666
+ }
667
+ } catch (err) {
668
+ this.logger.warn("LibSQLVector: indexed query failed, falling back to brute-force", err);
669
+ }
670
+ }
599
671
  const translatedFilter = this.transformFilter(filter);
600
672
  const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter);
601
673
  filterValues.push(minScore);
@@ -729,6 +801,7 @@ var LibSQLVector = class extends vector.MastraVector {
729
801
  `,
730
802
  args: []
731
803
  });
804
+ void this.vectorIndexes.then((indexes) => indexes.add(`${parsedIndexName}_vector_idx`));
732
805
  }
733
806
  deleteIndex(args) {
734
807
  try {
@@ -751,6 +824,7 @@ var LibSQLVector = class extends vector.MastraVector {
751
824
  sql: `DROP TABLE IF EXISTS ${parsedIndexName}`,
752
825
  args: []
753
826
  });
827
+ void this.vectorIndexes.then((indexes) => indexes.delete(`${parsedIndexName}_vector_idx`));
754
828
  }
755
829
  async listIndexes() {
756
830
  try {
@@ -2884,6 +2958,235 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2884
2958
  };
2885
2959
  }
2886
2960
  };
2961
+ function serializeJson(v) {
2962
+ if (typeof v === "object" && v != null) return JSON.stringify(v);
2963
+ return v ?? null;
2964
+ }
2965
+ function parseJson(val) {
2966
+ if (val == null) return void 0;
2967
+ if (typeof val === "string") {
2968
+ try {
2969
+ return JSON.parse(val);
2970
+ } catch {
2971
+ return val;
2972
+ }
2973
+ }
2974
+ return val;
2975
+ }
2976
+ function rowToTask(row) {
2977
+ return {
2978
+ id: String(row.id),
2979
+ status: String(row.status),
2980
+ toolName: String(row.tool_name),
2981
+ toolCallId: String(row.tool_call_id),
2982
+ args: parseJson(row.args) ?? {},
2983
+ agentId: String(row.agent_id),
2984
+ threadId: row.thread_id != null ? String(row.thread_id) : void 0,
2985
+ resourceId: row.resource_id != null ? String(row.resource_id) : void 0,
2986
+ runId: String(row.run_id),
2987
+ result: parseJson(row.result),
2988
+ error: parseJson(row.error),
2989
+ retryCount: Number(row.retry_count),
2990
+ maxRetries: Number(row.max_retries),
2991
+ timeoutMs: Number(row.timeout_ms),
2992
+ createdAt: new Date(String(row.createdAt)),
2993
+ startedAt: row.startedAt ? new Date(String(row.startedAt)) : void 0,
2994
+ completedAt: row.completedAt ? new Date(String(row.completedAt)) : void 0
2995
+ };
2996
+ }
2997
+ var BackgroundTasksLibSQL = class extends storage.BackgroundTasksStorage {
2998
+ #db;
2999
+ #client;
3000
+ constructor(config) {
3001
+ super();
3002
+ const client = resolveClient(config);
3003
+ this.#client = client;
3004
+ this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
3005
+ }
3006
+ async init() {
3007
+ await this.#db.createTable({
3008
+ tableName: storage.TABLE_BACKGROUND_TASKS,
3009
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_BACKGROUND_TASKS]
3010
+ });
3011
+ }
3012
+ async dangerouslyClearAll() {
3013
+ await this.#db.deleteData({ tableName: storage.TABLE_BACKGROUND_TASKS });
3014
+ }
3015
+ async createTask(task) {
3016
+ await this.#db.insert({
3017
+ tableName: storage.TABLE_BACKGROUND_TASKS,
3018
+ record: {
3019
+ id: task.id,
3020
+ tool_call_id: task.toolCallId,
3021
+ tool_name: task.toolName,
3022
+ agent_id: task.agentId,
3023
+ thread_id: task.threadId ?? null,
3024
+ resource_id: task.resourceId ?? null,
3025
+ run_id: task.runId,
3026
+ status: task.status,
3027
+ args: task.args,
3028
+ result: task.result ?? null,
3029
+ error: task.error ?? null,
3030
+ retry_count: task.retryCount,
3031
+ max_retries: task.maxRetries,
3032
+ timeout_ms: task.timeoutMs,
3033
+ createdAt: task.createdAt.toISOString(),
3034
+ startedAt: task.startedAt?.toISOString() ?? null,
3035
+ completedAt: task.completedAt?.toISOString() ?? null
3036
+ }
3037
+ });
3038
+ }
3039
+ async updateTask(taskId, update) {
3040
+ const setClauses = [];
3041
+ const params = [];
3042
+ if ("status" in update) {
3043
+ setClauses.push("status = ?");
3044
+ params.push(update.status);
3045
+ }
3046
+ if ("result" in update) {
3047
+ setClauses.push("result = jsonb(?)");
3048
+ params.push(serializeJson(update.result));
3049
+ }
3050
+ if ("error" in update) {
3051
+ setClauses.push("error = jsonb(?)");
3052
+ params.push(serializeJson(update.error));
3053
+ }
3054
+ if ("retryCount" in update) {
3055
+ setClauses.push("retry_count = ?");
3056
+ params.push(update.retryCount);
3057
+ }
3058
+ if ("startedAt" in update) {
3059
+ setClauses.push("startedAt = ?");
3060
+ params.push(update.startedAt?.toISOString() ?? null);
3061
+ }
3062
+ if ("completedAt" in update) {
3063
+ setClauses.push("completedAt = ?");
3064
+ params.push(update.completedAt?.toISOString() ?? null);
3065
+ }
3066
+ if (setClauses.length === 0) return;
3067
+ params.push(taskId);
3068
+ await this.#client.execute({
3069
+ sql: `UPDATE ${storage.TABLE_BACKGROUND_TASKS} SET ${setClauses.join(", ")} WHERE id = ?`,
3070
+ args: params
3071
+ });
3072
+ }
3073
+ async getTask(taskId) {
3074
+ const result = await this.#client.execute({
3075
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_BACKGROUND_TASKS)} FROM ${storage.TABLE_BACKGROUND_TASKS} WHERE id = ?`,
3076
+ args: [taskId]
3077
+ });
3078
+ const row = result.rows[0];
3079
+ return row ? rowToTask(row) : null;
3080
+ }
3081
+ async listTasks(filter) {
3082
+ const conditions = [];
3083
+ const params = [];
3084
+ if (filter.status) {
3085
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
3086
+ conditions.push(`status IN (${statuses.map(() => "?").join(", ")})`);
3087
+ params.push(...statuses);
3088
+ }
3089
+ if (filter.agentId) {
3090
+ conditions.push("agent_id = ?");
3091
+ params.push(filter.agentId);
3092
+ }
3093
+ if (filter.threadId) {
3094
+ conditions.push("thread_id = ?");
3095
+ params.push(filter.threadId);
3096
+ }
3097
+ if (filter.runId) {
3098
+ conditions.push("run_id = ?");
3099
+ params.push(filter.runId);
3100
+ }
3101
+ if (filter.resourceId) {
3102
+ conditions.push("resource_id = ?");
3103
+ params.push(filter.resourceId);
3104
+ }
3105
+ if (filter.toolName) {
3106
+ conditions.push("tool_name = ?");
3107
+ params.push(filter.toolName);
3108
+ }
3109
+ const dateCol = filter.dateFilterBy === "startedAt" ? "startedAt" : filter.dateFilterBy === "completedAt" ? "completedAt" : "createdAt";
3110
+ if (filter.fromDate) {
3111
+ conditions.push(`${dateCol} >= ?`);
3112
+ params.push(filter.fromDate.toISOString());
3113
+ }
3114
+ if (filter.toDate) {
3115
+ conditions.push(`${dateCol} < ?`);
3116
+ params.push(filter.toDate.toISOString());
3117
+ }
3118
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3119
+ const countResult = await this.#client.execute({
3120
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_BACKGROUND_TASKS} ${where}`,
3121
+ args: [...params]
3122
+ });
3123
+ const total = Number(countResult.rows[0]?.count ?? 0);
3124
+ const orderCol = filter.orderBy === "startedAt" ? "startedAt" : filter.orderBy === "completedAt" ? "completedAt" : "createdAt";
3125
+ const direction = filter.orderDirection === "desc" ? "DESC" : "ASC";
3126
+ let sql = `SELECT ${buildSelectColumns(storage.TABLE_BACKGROUND_TASKS)} FROM ${storage.TABLE_BACKGROUND_TASKS} ${where} ORDER BY ${orderCol} ${direction}`;
3127
+ if (filter.perPage != null) {
3128
+ sql += " LIMIT ?";
3129
+ params.push(filter.perPage);
3130
+ if (filter.page != null) {
3131
+ sql += " OFFSET ?";
3132
+ params.push(filter.page * filter.perPage);
3133
+ }
3134
+ }
3135
+ const result = await this.#client.execute({ sql, args: params });
3136
+ return { tasks: result.rows.map((row) => rowToTask(row)), total };
3137
+ }
3138
+ async deleteTask(taskId) {
3139
+ await this.#client.execute({
3140
+ sql: `DELETE FROM ${storage.TABLE_BACKGROUND_TASKS} WHERE id = ?`,
3141
+ args: [taskId]
3142
+ });
3143
+ }
3144
+ async deleteTasks(filter) {
3145
+ const conditions = [];
3146
+ const params = [];
3147
+ if (filter.status) {
3148
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
3149
+ conditions.push(`status IN (${statuses.map(() => "?").join(", ")})`);
3150
+ params.push(...statuses);
3151
+ }
3152
+ const dateCol = filter.dateFilterBy === "startedAt" ? "startedAt" : filter.dateFilterBy === "completedAt" ? "completedAt" : "createdAt";
3153
+ if (filter.fromDate) {
3154
+ conditions.push(`${dateCol} >= ?`);
3155
+ params.push(filter.fromDate.toISOString());
3156
+ }
3157
+ if (filter.toDate) {
3158
+ conditions.push(`${dateCol} < ?`);
3159
+ params.push(filter.toDate.toISOString());
3160
+ }
3161
+ if (filter.agentId) {
3162
+ conditions.push("agent_id = ?");
3163
+ params.push(filter.agentId);
3164
+ }
3165
+ if (filter.runId) {
3166
+ conditions.push("run_id = ?");
3167
+ params.push(filter.runId);
3168
+ }
3169
+ if (conditions.length === 0) return;
3170
+ await this.#client.execute({
3171
+ sql: `DELETE FROM ${storage.TABLE_BACKGROUND_TASKS} WHERE ${conditions.join(" AND ")}`,
3172
+ args: params
3173
+ });
3174
+ }
3175
+ async getRunningCount() {
3176
+ const result = await this.#client.execute({
3177
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_BACKGROUND_TASKS} WHERE status = 'running'`,
3178
+ args: []
3179
+ });
3180
+ return Number(result.rows[0]?.count ?? 0);
3181
+ }
3182
+ async getRunningCountByAgent(agentId) {
3183
+ const result = await this.#client.execute({
3184
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_BACKGROUND_TASKS} WHERE status = 'running' AND agent_id = ?`,
3185
+ args: [agentId]
3186
+ });
3187
+ return Number(result.rows[0]?.count ?? 0);
3188
+ }
3189
+ };
2887
3190
  var BlobsLibSQL = class extends storage.BlobStore {
2888
3191
  #db;
2889
3192
  #client;
@@ -10639,6 +10942,7 @@ var LibSQLStore = class extends storage.MastraCompositeStore {
10639
10942
  const workspaces = new WorkspacesLibSQL(domainConfig);
10640
10943
  const skills = new SkillsLibSQL(domainConfig);
10641
10944
  const blobs = new BlobsLibSQL(domainConfig);
10945
+ const backgroundTasks = new BackgroundTasksLibSQL(domainConfig);
10642
10946
  this.stores = {
10643
10947
  scores,
10644
10948
  workflows,
@@ -10653,7 +10957,8 @@ var LibSQLStore = class extends storage.MastraCompositeStore {
10653
10957
  mcpServers,
10654
10958
  workspaces,
10655
10959
  skills,
10656
- blobs
10960
+ blobs,
10961
+ backgroundTasks
10657
10962
  };
10658
10963
  }
10659
10964
  };
@@ -10758,6 +11063,7 @@ Example Complex Query:
10758
11063
  }`;
10759
11064
 
10760
11065
  exports.AgentsLibSQL = AgentsLibSQL;
11066
+ exports.BackgroundTasksLibSQL = BackgroundTasksLibSQL;
10761
11067
  exports.BlobsLibSQL = BlobsLibSQL;
10762
11068
  exports.DatasetsLibSQL = DatasetsLibSQL;
10763
11069
  exports.DefaultStorage = LibSQLStore;