@mastra/pg 1.34.0-alpha.0 → 1.34.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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/dist/docs/SKILL.md +48 -0
  3. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  4. package/dist/docs/references/docs-deployment-workers.md +404 -0
  5. package/dist/docs/references/docs-memory-semantic-recall.md +483 -0
  6. package/dist/docs/references/docs-memory-working-memory.md +450 -0
  7. package/dist/docs/references/docs-storage.md +224 -0
  8. package/dist/docs/references/integrations-databases-clickhouse-managed-postgres.md +82 -0
  9. package/dist/docs/references/integrations-databases-dynamodb.md +286 -0
  10. package/dist/docs/references/integrations-databases-neon.md +222 -0
  11. package/dist/docs/references/integrations-databases-postgresql.md +592 -0
  12. package/dist/docs/references/integrations-vectors-pg.md +451 -0
  13. package/dist/docs/references/reference-memory-memory-class.md +237 -0
  14. package/dist/docs/references/reference-processors-message-history-processor.md +89 -0
  15. package/dist/docs/references/reference-processors-semantic-recall-processor.md +119 -0
  16. package/dist/docs/references/reference-processors-working-memory-processor.md +154 -0
  17. package/dist/docs/references/reference-rag-chunking-and-embedding.md +184 -0
  18. package/dist/docs/references/reference-rag-metadata-filters.md +238 -0
  19. package/dist/docs/references/reference-rag-overview.md +76 -0
  20. package/dist/docs/references/reference-rag-retrieval.md +668 -0
  21. package/dist/docs/references/reference-rag-vector-databases.md +808 -0
  22. package/dist/docs/references/reference-storage-composite.md +433 -0
  23. package/dist/docs/references/reference-storage-retention.md +310 -0
  24. package/dist/docs/references/reference-tools-vector-query-tool.md +500 -0
  25. package/dist/index.cjs +152 -48
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.js +152 -48
  28. package/dist/index.js.map +1 -1
  29. package/dist/storage/domains/background-tasks/index.d.ts +1 -0
  30. package/dist/storage/domains/background-tasks/index.d.ts.map +1 -1
  31. package/dist/storage/domains/experiments/index.d.ts +3 -3
  32. package/dist/storage/domains/experiments/index.d.ts.map +1 -1
  33. package/dist/storage/domains/observability/v-next/index.d.ts +1 -1
  34. package/dist/storage/domains/observability/v-next/index.d.ts.map +1 -1
  35. package/dist/storage/domains/observability/v-next/preview-compat.d.ts +3 -0
  36. package/dist/storage/domains/observability/v-next/preview-compat.d.ts.map +1 -1
  37. package/dist/storage/domains/observability/v-next/span-query.d.ts +3 -0
  38. package/dist/storage/domains/observability/v-next/span-query.d.ts.map +1 -1
  39. package/dist/storage/domains/observability/v-next/trace-aggregate.d.ts.map +1 -1
  40. package/dist/storage/domains/observability/v-next/trace-query.d.ts +7 -0
  41. package/dist/storage/domains/observability/v-next/trace-query.d.ts.map +1 -1
  42. package/dist/storage/test-utils.d.ts.map +1 -1
  43. package/package.json +3 -3
package/dist/index.cjs CHANGED
@@ -5285,6 +5285,7 @@ function rowToTask(row) {
5285
5285
  const suspendedAt = row.suspendedAtZ || row.suspendedAt;
5286
5286
  const completedAt = row.completedAtZ || row.completedAt;
5287
5287
  const leaseExpiresAt = row.leaseExpiresAtZ || row.leaseExpiresAt;
5288
+ const expiresAt = row.expiresAt != null ? row.expiresAtZ || row.expiresAt : void 0;
5288
5289
  return {
5289
5290
  id: row.id,
5290
5291
  status: row.status,
@@ -5306,10 +5307,13 @@ function rowToTask(row) {
5306
5307
  suspendedAt: suspendedAt ? suspendedAt instanceof Date ? suspendedAt : new Date(suspendedAt) : void 0,
5307
5308
  completedAt: completedAt ? completedAt instanceof Date ? completedAt : new Date(completedAt) : void 0,
5308
5309
  ownerId: row.ownerId ?? void 0,
5309
- leaseExpiresAt: leaseExpiresAt ? leaseExpiresAt instanceof Date ? leaseExpiresAt : new Date(leaseExpiresAt) : void 0
5310
+ leaseExpiresAt: leaseExpiresAt ? leaseExpiresAt instanceof Date ? leaseExpiresAt : new Date(leaseExpiresAt) : void 0,
5311
+ expiresAt: expiresAt ? expiresAt instanceof Date ? expiresAt : new Date(expiresAt) : void 0,
5312
+ metadata: parseJson$2(row.metadata)
5310
5313
  };
5311
5314
  }
5312
5315
  var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.BackgroundTasksStorage {
5316
+ supportsTaskExpiry = true;
5313
5317
  #db;
5314
5318
  #schema;
5315
5319
  #skipDefaultIndexes;
@@ -5350,7 +5354,9 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5350
5354
  "suspend_payload",
5351
5355
  "suspendedAt",
5352
5356
  "ownerId",
5353
- "leaseExpiresAt"
5357
+ "leaseExpiresAt",
5358
+ "expiresAt",
5359
+ "metadata"
5354
5360
  ]
5355
5361
  });
5356
5362
  await this.createDefaultIndexes();
@@ -5484,7 +5490,10 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5484
5490
  completedAtZ: task.completedAt?.toISOString() ?? null,
5485
5491
  ownerId: task.ownerId ?? null,
5486
5492
  leaseExpiresAt: task.leaseExpiresAt?.toISOString() ?? null,
5487
- leaseExpiresAtZ: task.leaseExpiresAt?.toISOString() ?? null
5493
+ leaseExpiresAtZ: task.leaseExpiresAt?.toISOString() ?? null,
5494
+ expiresAt: task.expiresAt?.toISOString() ?? null,
5495
+ expiresAtZ: task.expiresAt?.toISOString() ?? null,
5496
+ metadata: serializeJson(task.metadata)
5488
5497
  }
5489
5498
  });
5490
5499
  }
@@ -5540,6 +5549,16 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5540
5549
  const val = update.leaseExpiresAt?.toISOString() ?? null;
5541
5550
  params.push(val, val);
5542
5551
  }
5552
+ if ("expiresAt" in update) {
5553
+ setClauses.push(`"expiresAt" = $${paramIdx++}`);
5554
+ setClauses.push(`"expiresAtZ" = $${paramIdx++}`);
5555
+ const val = update.expiresAt?.toISOString() ?? null;
5556
+ params.push(val, val);
5557
+ }
5558
+ if ("metadata" in update) {
5559
+ setClauses.push(`"metadata" = $${paramIdx++}`);
5560
+ params.push(serializeJson(update.metadata));
5561
+ }
5543
5562
  if (setClauses.length === 0) return false;
5544
5563
  const table = getTableName$4(getSchemaName$4(this.#schema));
5545
5564
  params.push(taskId);
@@ -5562,6 +5581,13 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5562
5581
  params.push(options.expectedLeaseExpiresAt.toISOString());
5563
5582
  }
5564
5583
  }
5584
+ if (options?.expectedSuspendedAt !== void 0) {
5585
+ if (options.expectedSuspendedAt === null) where += ` AND "suspendedAtZ" IS NULL`;
5586
+ else {
5587
+ where += ` AND "suspendedAtZ" = $${paramIdx++}`;
5588
+ params.push(options.expectedSuspendedAt.toISOString());
5589
+ }
5590
+ }
5565
5591
  return ((await this.#db.client.query(`UPDATE ${table} SET ${setClauses.join(", ")} WHERE ${where}`, params)).rowCount ?? 0) > 0;
5566
5592
  }
5567
5593
  async getTask(taskId) {
@@ -5604,7 +5630,9 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5604
5630
  conditions.push(`"tool_call_id" = $${paramIdx++}`);
5605
5631
  params.push(filter.toolCallId);
5606
5632
  }
5607
- const dateCol = filter.dateFilterBy === "startedAt" ? "\"startedAt\"" : filter.dateFilterBy === "suspendedAt" ? "\"suspendedAt\"" : filter.dateFilterBy === "completedAt" ? "\"completedAt\"" : "\"createdAt\"";
5633
+ const dateCol = filter.dateFilterBy === "startedAt" ? "\"startedAt\"" : filter.dateFilterBy === "suspendedAt" ? "\"suspendedAt\"" : filter.dateFilterBy === "completedAt" ? "\"completedAt\"" : filter.dateFilterBy === "expiresAt" ? "\"expiresAtZ\"" : "\"createdAt\"";
5634
+ if (filter.hasExpiresAt !== void 0) conditions.push(filter.hasExpiresAt ? "\"expiresAt\" IS NOT NULL" : "\"expiresAt\" IS NULL");
5635
+ if (filter.dateFilterBy === "expiresAt" && (filter.fromDate || filter.toDate)) conditions.push("\"expiresAt\" IS NOT NULL");
5608
5636
  if (filter.fromDate) {
5609
5637
  conditions.push(`${dateCol} >= $${paramIdx++}`);
5610
5638
  params.push(filter.fromDate.toISOString());
@@ -5645,7 +5673,9 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5645
5673
  conditions.push(`"status" IN (${placeholders.join(", ")})`);
5646
5674
  params.push(...statuses);
5647
5675
  }
5648
- const dateCol = filter.dateFilterBy === "startedAt" ? "\"startedAt\"" : filter.dateFilterBy === "suspendedAt" ? "\"suspendedAt\"" : filter.dateFilterBy === "completedAt" ? "\"completedAt\"" : "\"createdAt\"";
5676
+ const dateCol = filter.dateFilterBy === "startedAt" ? "\"startedAt\"" : filter.dateFilterBy === "suspendedAt" ? "\"suspendedAt\"" : filter.dateFilterBy === "completedAt" ? "\"completedAt\"" : filter.dateFilterBy === "expiresAt" ? "\"expiresAtZ\"" : "\"createdAt\"";
5677
+ if (filter.hasExpiresAt !== void 0) conditions.push(filter.hasExpiresAt ? "\"expiresAt\" IS NOT NULL" : "\"expiresAt\" IS NULL");
5678
+ if (filter.dateFilterBy === "expiresAt" && (filter.fromDate || filter.toDate)) conditions.push("\"expiresAt\" IS NOT NULL");
5649
5679
  if (filter.fromDate) {
5650
5680
  conditions.push(`${dateCol} >= $${paramIdx++}`);
5651
5681
  params.push(filter.fromDate.toISOString());
@@ -7261,6 +7291,19 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
7261
7291
  };
7262
7292
  // src/storage/domains/experiments/index.ts
7263
7293
  const DEFAULT_PRUNE_BATCH_SIZE = 1e3;
7294
+ /**
7295
+ * Column list for reading experiment rows. Each `timestamp` column comes back
7296
+ * twice: as itself, and as its `*Z` mirror derived in the query with
7297
+ * `AT TIME ZONE 'UTC'`. A plain `timestamp` otherwise round-trips through the
7298
+ * session timezone, and reading the stored `*Z` column instead would return the
7299
+ * insert time for rows written before the mirrors were filled in. Deriving it
7300
+ * here makes legacy rows read correctly with no backfill to run at startup.
7301
+ */
7302
+ function selectWithMirrors(schema) {
7303
+ return Object.entries(schema).flatMap(([name, definition]) => definition.type === "timestamp" ? [`"${name}"`, `"${name}" AT TIME ZONE 'UTC' AS "${name}Z"`] : [`"${name}"`]).join(", ");
7304
+ }
7305
+ const EXPERIMENT_COLUMNS = selectWithMirrors(_mastra_core_storage.EXPERIMENTS_SCHEMA);
7306
+ const EXPERIMENT_RESULT_COLUMNS = selectWithMirrors(_mastra_core_storage.EXPERIMENT_RESULTS_SCHEMA);
7264
7307
  var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.ExperimentsStorage {
7265
7308
  #db;
7266
7309
  #schema;
@@ -7269,9 +7312,9 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7269
7312
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_EXPERIMENTS, _mastra_core_storage.TABLE_EXPERIMENT_RESULTS];
7270
7313
  /**
7271
7314
  * Experiments prune as whole units: an aged experiment and its result rows go
7272
- * together, mirroring `deleteExperiment`. Anchored on `completedAt` (not the
7273
- * `completedAtZ` mirror, which carries a `DEFAULT NOW()` this domain never
7274
- * overrides — it holds insert time even for running rows). `completedAt` is
7315
+ * together, mirroring `deleteExperiment`. Anchored on `completedAt` rather
7316
+ * than its `completedAtZ` mirror: both are written together, but
7317
+ * `completedAt` is the column the retention index covers. `completedAt` is
7275
7318
  * written as a UTC ISO string and stays NULL while running, so
7276
7319
  * `completedAt < cutoff` is false for in-flight experiments.
7277
7320
  */
@@ -7591,7 +7634,11 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7591
7634
  startedAt: null,
7592
7635
  completedAt: null,
7593
7636
  createdAt: nowIso,
7594
- updatedAt: nowIso
7637
+ updatedAt: nowIso,
7638
+ startedAtZ: null,
7639
+ completedAtZ: null,
7640
+ createdAtZ: nowIso,
7641
+ updatedAtZ: nowIso
7595
7642
  }
7596
7643
  });
7597
7644
  return {
@@ -7680,12 +7727,14 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7680
7727
  values.push(input.skippedCount);
7681
7728
  }
7682
7729
  if (input.startedAt !== void 0) {
7683
- setClauses.push(`"startedAt" = $${paramIndex++}`);
7684
- values.push(input.startedAt?.toISOString() ?? null);
7730
+ const iso = input.startedAt?.toISOString() ?? null;
7731
+ setClauses.push(`"startedAt" = $${paramIndex++}`, `"startedAtZ" = $${paramIndex++}`);
7732
+ values.push(iso, iso);
7685
7733
  }
7686
7734
  if (input.completedAt !== void 0) {
7687
- setClauses.push(`"completedAt" = $${paramIndex++}`);
7688
- values.push(input.completedAt?.toISOString() ?? null);
7735
+ const iso = input.completedAt?.toISOString() ?? null;
7736
+ setClauses.push(`"completedAt" = $${paramIndex++}`, `"completedAtZ" = $${paramIndex++}`);
7737
+ values.push(iso, iso);
7689
7738
  }
7690
7739
  values.push(input.id);
7691
7740
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE "id" = $${paramIndex}`, values);
@@ -7714,7 +7763,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7714
7763
  });
7715
7764
  const { conditions, params } = tenancyWhere(filters, 2);
7716
7765
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
7717
- const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7766
+ const result = await client.oneOrNone(`SELECT ${EXPERIMENT_COLUMNS} FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7718
7767
  return result ? this.transformExperimentRow(result) : null;
7719
7768
  } catch (error) {
7720
7769
  throw new _mastra_core_error.MastraError({
@@ -7801,7 +7850,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7801
7850
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
7802
7851
  const limitValue = perPageInput === false ? total : perPage;
7803
7852
  return {
7804
- experiments: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7853
+ experiments: (await this.#db.readClient.manyOrNone(`SELECT ${EXPERIMENT_COLUMNS} FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7805
7854
  ...queryParams,
7806
7855
  limitValue,
7807
7856
  offset
@@ -7879,9 +7928,11 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7879
7928
  return t.one(`INSERT INTO ${resultsTable} (
7880
7929
  "id", "experimentId", "itemId", "itemDatasetVersion", "organizationId", "projectId",
7881
7930
  "input", "output", "groundTruth", "metadata", "error", "startedAt", "completedAt",
7882
- "retryCount", "attempt", "traceId", "status", "tags", "toolMockReport", "createdAt"
7883
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
7884
- RETURNING *`, [
7931
+ "retryCount", "attempt", "traceId", "status", "tags", "toolMockReport", "createdAt",
7932
+ "startedAtZ", "completedAtZ", "createdAtZ"
7933
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20,
7934
+ $21, $22, $23)
7935
+ RETURNING ${EXPERIMENT_RESULT_COLUMNS}`, [
7885
7936
  id,
7886
7937
  input.experimentId,
7887
7938
  input.itemId,
@@ -7901,6 +7952,9 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7901
7952
  input.status ?? null,
7902
7953
  purgeMetadata || input.tags == null ? null : toPgJson(input.tags),
7903
7954
  purgeMetadata || input.toolMockReport == null ? null : toPgJson(input.toolMockReport),
7955
+ nowIso,
7956
+ input.startedAt.toISOString(),
7957
+ input.completedAt.toISOString(),
7904
7958
  nowIso
7905
7959
  ]);
7906
7960
  });
@@ -7927,6 +7981,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7927
7981
  const row = await this.#db.client.tx(async (t) => {
7928
7982
  const owner = await t.oneOrNone(`SELECT "datasetId" FROM ${experimentsTable} WHERE "id" = $1`, [input.experimentId]);
7929
7983
  const purgeMetadata = await this.#resolvePurgeMetadata(t, owner?.datasetId, input.itemId);
7984
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
7930
7985
  const existing = await t.oneOrNone(`SELECT "id" FROM ${tableName} WHERE "experimentId" = $1 AND "itemId" = $2 AND COALESCE("attempt", 0) = $3 FOR UPDATE`, [
7931
7986
  input.experimentId,
7932
7987
  input.itemId,
@@ -7937,9 +7992,11 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7937
7992
  return t.one(`INSERT INTO ${tableName} (
7938
7993
  "id", "experimentId", "itemId", "itemDatasetVersion", "organizationId", "projectId",
7939
7994
  "input", "output", "groundTruth", "metadata", "error", "startedAt", "completedAt",
7940
- "retryCount", "attempt", "traceId", "status", "tags", "toolMockReport", "createdAt"
7941
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
7942
- RETURNING *`, [
7995
+ "retryCount", "attempt", "traceId", "status", "tags", "toolMockReport", "createdAt",
7996
+ "startedAtZ", "completedAtZ", "createdAtZ"
7997
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20,
7998
+ $21, $22, $23)
7999
+ RETURNING ${EXPERIMENT_RESULT_COLUMNS}`, [
7943
8000
  id,
7944
8001
  input.experimentId,
7945
8002
  input.itemId,
@@ -7959,15 +8016,19 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7959
8016
  input.status ?? null,
7960
8017
  purgeMetadata || input.tags == null ? null : toPgJson(input.tags),
7961
8018
  purgeMetadata || input.toolMockReport == null ? null : toPgJson(input.toolMockReport),
7962
- (/* @__PURE__ */ new Date()).toISOString()
8019
+ nowIso,
8020
+ input.startedAt.toISOString(),
8021
+ input.completedAt.toISOString(),
8022
+ nowIso
7963
8023
  ]);
7964
8024
  }
7965
8025
  return t.one(`UPDATE ${tableName} SET
7966
8026
  "itemDatasetVersion" = $2, "organizationId" = $3, "projectId" = $4,
7967
8027
  "input" = $5, "output" = $6, "groundTruth" = $7, "metadata" = $8, "error" = $9,
7968
8028
  "startedAt" = $10, "completedAt" = $11, "retryCount" = $12, "attempt" = $13,
7969
- "traceId" = $14, "status" = $15, "tags" = $16, "toolMockReport" = $17
7970
- WHERE "id" = $1 RETURNING *`, [
8029
+ "traceId" = $14, "status" = $15, "tags" = $16, "toolMockReport" = $17,
8030
+ "startedAtZ" = $18, "completedAtZ" = $19
8031
+ WHERE "id" = $1 RETURNING ${EXPERIMENT_RESULT_COLUMNS}`, [
7971
8032
  existing.id,
7972
8033
  input.itemDatasetVersion ?? null,
7973
8034
  input.organizationId ?? null,
@@ -7984,7 +8045,9 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7984
8045
  input.traceId ?? null,
7985
8046
  input.status ?? null,
7986
8047
  purgeMetadata || input.tags == null ? null : toPgJson(input.tags),
7987
- purgeMetadata || input.toolMockReport == null ? null : toPgJson(input.toolMockReport)
8048
+ purgeMetadata || input.toolMockReport == null ? null : toPgJson(input.toolMockReport),
8049
+ input.startedAt.toISOString(),
8050
+ input.completedAt.toISOString()
7988
8051
  ]);
7989
8052
  });
7990
8053
  return this.transformExperimentResultRow(row);
@@ -8018,7 +8081,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
8018
8081
  "tags" = CASE WHEN $4 THEN NULL WHEN $5 THEN $6::jsonb ELSE "tags" END,
8019
8082
  "comment" = CASE WHEN $4 THEN NULL WHEN $7 THEN $8 ELSE "comment" END
8020
8083
  WHERE "id" = $1${input.experimentId !== void 0 ? " AND \"experimentId\" = $9" : ""}
8021
- RETURNING *`, [
8084
+ RETURNING ${EXPERIMENT_RESULT_COLUMNS}`, [
8022
8085
  input.id,
8023
8086
  input.status !== void 0,
8024
8087
  input.status ?? null,
@@ -8061,7 +8124,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
8061
8124
  });
8062
8125
  const { conditions, params } = tenancyWhere(filters, 2);
8063
8126
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
8064
- const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
8127
+ const result = await client.oneOrNone(`SELECT ${EXPERIMENT_RESULT_COLUMNS} FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
8065
8128
  return result ? this.transformExperimentResultRow(result) : null;
8066
8129
  } catch (error) {
8067
8130
  throw new _mastra_core_error.MastraError({
@@ -8124,7 +8187,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
8124
8187
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
8125
8188
  const limitValue = perPageInput === false ? total : perPage;
8126
8189
  return {
8127
- results: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
8190
+ results: (await this.#db.readClient.manyOrNone(`SELECT ${EXPERIMENT_RESULT_COLUMNS} FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
8128
8191
  ...queryParams,
8129
8192
  limitValue,
8130
8193
  offset
@@ -19543,6 +19606,13 @@ const timeToFirstChunkSortSupported = _mastra_core_storage.TRACE_QUERY_ORDER_FIE
19543
19606
  /** Same rule for time to first token: returned and sorted only when core knows the field. */
19544
19607
  const timeToFirstTokenSupported = "timeToFirstTokenMs" in _mastra_core_storage.TRACE_QUERY_FIELD_REGISTRY.trace;
19545
19608
  const timeToFirstTokenSortSupported = _mastra_core_storage.TRACE_QUERY_ORDER_FIELDS?.includes("timeToFirstTokenMs") === true;
19609
+ /**
19610
+ * Outcome fields follow the same rule: core before them rejects their predicates and strict rows,
19611
+ * so they are only returned and declared when core knows them.
19612
+ */
19613
+ const spanQueryOutcomeFieldsSupported = "outcome" in (_mastra_core_storage.SPAN_QUERY_FIELD_REGISTRY ?? {});
19614
+ const traceQueryOutcomeFieldsSupported = "outcome" in (_mastra_core_storage.TRACE_QUERY_FIELD_REGISTRY?.trace ?? {});
19615
+ const outcomeFeatures = [...spanQueryOutcomeFieldsSupported ? ["span-query-outcome-fields"] : [], ...traceQueryOutcomeFieldsSupported ? ["trace-query-outcome-fields"] : []];
19546
19616
  const timingFeatures = [
19547
19617
  ...timeToFirstChunkSupported ? ["trace-query-time-to-first-chunk"] : [],
19548
19618
  ...timeToFirstChunkSortSupported ? ["trace-query-time-to-first-chunk-sort"] : [],
@@ -19589,6 +19659,8 @@ const TRACE_FIELDS = {
19589
19659
  spanType: "r.\"spanType\"",
19590
19660
  environment: "r.\"environment\"",
19591
19661
  status: TRACE_STATUS_SQL,
19662
+ outcome: "r.\"outcome\"",
19663
+ stopReason: "r.\"stopReason\"",
19592
19664
  tags: "r.\"tags\""
19593
19665
  };
19594
19666
  const SPAN_FIELDS = {
@@ -19602,6 +19674,8 @@ const SPAN_FIELDS = {
19602
19674
  timeToFirstChunkMs: "s.\"timeToFirstChunkMs\"",
19603
19675
  timeToFirstTokenMs: "s.\"timeToFirstTokenMs\"",
19604
19676
  status: "s.\"status\"",
19677
+ outcome: "s.\"outcome\"",
19678
+ stopReason: "s.\"stopReason\"",
19605
19679
  error: "s.\"error\"",
19606
19680
  entityType: "s.\"entityType\"",
19607
19681
  entityId: "s.\"entityId\"",
@@ -19675,7 +19749,10 @@ const TRACE_SELECT = `
19675
19749
  r."entityName" AS "entityName",
19676
19750
  r."entityType" AS "entityType",
19677
19751
  r."environment" AS "environment",
19678
- ${TRACE_STATUS_SQL} AS "status"`;
19752
+ ${TRACE_STATUS_SQL} AS "status",
19753
+ r."outcome" AS "outcome",
19754
+ r."stopReason" AS "stopReason",
19755
+ r."stopReasonContext" AS "stopReasonContext"`;
19679
19756
  function fieldSql(registry, field) {
19680
19757
  const sql = registry[field];
19681
19758
  if (sql === void 0) throw new Error(`Unsupported trusted trace-query field: ${field}`);
@@ -20032,8 +20109,8 @@ function compilePostgresTraceScope(schema, selection, relationCollections, scope
20032
20109
  s."traceId",
20033
20110
  s."name",
20034
20111
  s."spanType",
20035
- CASE WHEN jsonb_typeof(s."attributes" -> 'model') = 'string' THEN s."attributes" ->> 'model' END AS "model",
20036
- CASE WHEN jsonb_typeof(s."attributes" -> 'provider') = 'string' THEN s."attributes" ->> 'provider' END AS "provider",
20112
+ COALESCE(s."model", CASE WHEN jsonb_typeof(s."attributes" -> 'model') = 'string' THEN s."attributes" ->> 'model' END) AS "model",
20113
+ COALESCE(s."provider", CASE WHEN jsonb_typeof(s."attributes" -> 'provider') = 'string' THEN s."attributes" ->> 'provider' END) AS "provider",
20037
20114
  s."startedAt",
20038
20115
  CASE WHEN s."isPending" THEN NULL ELSE s."endedAt" END AS "endedAt",
20039
20116
  CASE
@@ -20043,6 +20120,8 @@ function compilePostgresTraceScope(schema, selection, relationCollections, scope
20043
20120
  s."timeToFirstChunkMs",
20044
20121
  s."timeToFirstTokenMs",
20045
20122
  CASE WHEN s."error" IS NOT NULL THEN 'error' ELSE 'success' END AS "status",
20123
+ s."outcome",
20124
+ s."stopReason",
20046
20125
  s."error",
20047
20126
  s."entityType",
20048
20127
  s."entityId",
@@ -20420,7 +20499,12 @@ function traceRowToResult(row) {
20420
20499
  entityName: row.entityName == null ? null : String(row.entityName),
20421
20500
  entityType: row.entityType == null ? null : String(row.entityType),
20422
20501
  environment: row.environment == null ? null : String(row.environment),
20423
- status: row.status
20502
+ status: row.status,
20503
+ ...traceQueryOutcomeFieldsSupported && {
20504
+ outcome: row.outcome == null ? null : String(row.outcome),
20505
+ stopReason: row.stopReason == null ? null : String(row.stopReason),
20506
+ stopReasonContext: row.stopReasonContext ?? null
20507
+ }
20424
20508
  };
20425
20509
  }
20426
20510
  async function queryTraces(client, schema, plan, timeoutMs) {
@@ -20573,7 +20657,9 @@ const fields = [
20573
20657
  "environment",
20574
20658
  "executionSource",
20575
20659
  "timeToFirstChunkMs",
20576
- "timeToFirstTokenMs"
20660
+ "timeToFirstTokenMs",
20661
+ "outcome",
20662
+ "stopReason"
20577
20663
  ];
20578
20664
  const identities = identityFields.map((field) => `"${field}"`).join(", ");
20579
20665
  const identityOrder = identityFields.map((field) => `"${field}" COLLATE "C" ASC NULLS LAST`).join(", ");
@@ -20623,8 +20709,6 @@ function compilePostgresSpanSelection(schema, plan) {
20623
20709
  };
20624
20710
  values.push(...predicate.values);
20625
20711
  const table = qualifiedTable(schema, TABLE_SPAN_EVENTS);
20626
- const legacyModelFields = _mastra_core_storage.SPAN_QUERY_FIELD_REGISTRY ? "" : `CASE WHEN jsonb_typeof(attributes -> 'model') = 'string' THEN attributes ->> 'model' END AS model,
20627
- CASE WHEN jsonb_typeof(attributes -> 'provider') = 'string' THEN attributes ->> 'provider' END AS provider,`;
20628
20712
  return {
20629
20713
  ctes: [
20630
20714
  `candidate_ids AS MATERIALIZED (
@@ -20635,7 +20719,7 @@ function compilePostgresSpanSelection(schema, plan) {
20635
20719
  `current_spans AS MATERIALIZED (
20636
20720
  SELECT DISTINCT ON (${identities})
20637
20721
  ${fields.map((field) => `"${field}"`).join(", ")}, "startedAt", "endedAt", "cursorId"::text AS version,
20638
- ${legacyModelFields}
20722
+ "model", "provider",
20639
20723
  (EXTRACT(EPOCH FROM ("endedAt" - "startedAt")) * 1000)::float8 AS "durationMs",
20640
20724
  CASE WHEN error IS NULL THEN 'success' ELSE 'error' END AS status,
20641
20725
  error IS NOT NULL AS "hasError"
@@ -20705,10 +20789,14 @@ async function querySpans(client, schema, plan, timeoutMs) {
20705
20789
  return runWithPostgresTraceQueryTimeout(client, timeoutMs, async (tx) => {
20706
20790
  const query = compilePostgresSpanQuery(schema, plan);
20707
20791
  const rows = await tx.any(query.text, query.values);
20708
- const selected = rows.map(({ version: _version, startedAt, endedAt, timeToFirstChunkMs, timeToFirstTokenMs, ...row }) => ({
20792
+ const selected = rows.map(({ version: _version, startedAt, endedAt, timeToFirstChunkMs, timeToFirstTokenMs, outcome, stopReason, ...row }) => ({
20709
20793
  ...row,
20710
20794
  ...timeToFirstChunkSupported && { timeToFirstChunkMs },
20711
20795
  ...timeToFirstTokenSupported && { timeToFirstTokenMs },
20796
+ ...spanQueryOutcomeFieldsSupported && {
20797
+ outcome,
20798
+ stopReason
20799
+ },
20712
20800
  startedAt: startedAt.toISOString(),
20713
20801
  endedAt: endedAt.toISOString()
20714
20802
  }));
@@ -20726,18 +20814,22 @@ async function querySpans(client, schema, plan, timeoutMs) {
20726
20814
  payloadValues.push(row.version);
20727
20815
  return `(${key} AND "cursorId" = $${payloadValues.length}::bigint)`;
20728
20816
  }).join(" OR ");
20729
- const payloadRows = await tx.any(`SELECT ${identities},
20730
- CASE WHEN jsonb_typeof(attributes -> 'model') = 'string' THEN attributes ->> 'model' END AS model,
20731
- CASE WHEN jsonb_typeof(attributes -> 'provider') = 'string' THEN attributes ->> 'provider' END AS provider,
20817
+ const payloadRows = await tx.any(`SELECT ${identities}, "stopReasonContext",
20818
+ COALESCE("model", CASE WHEN jsonb_typeof(attributes -> 'model') = 'string' THEN attributes ->> 'model' END) AS model,
20819
+ COALESCE("provider", CASE WHEN jsonb_typeof(attributes -> 'provider') = 'string' THEN attributes ->> 'provider' END) AS provider,
20732
20820
  ${PREVIEW_PAYLOADS$1.map(([preview, payload]) => `"${preview}", CASE WHEN ${missingPreviewSql(`"${preview}"`)} THEN "${payload}" END AS "${payload}"`).join(",\n ")}
20733
20821
  FROM ${qualifiedTable(schema, TABLE_SPAN_EVENTS)} WHERE ${payloadWhere}`, payloadValues);
20734
20822
  const payloads = payloadRows.map(toSpanQueryPayload);
20735
20823
  const metadata = new Map(payloadRows.map((row) => [_mastra_core_storage.spanQueryIdentityKey(row), row]));
20736
- const hydrated = selected.map((row) => ({
20737
- ...row,
20738
- model: metadata.get(_mastra_core_storage.spanQueryIdentityKey(row))?.model ?? null,
20739
- provider: metadata.get(_mastra_core_storage.spanQueryIdentityKey(row))?.provider ?? null
20740
- }));
20824
+ const hydrated = selected.map((row) => {
20825
+ const stored = metadata.get(_mastra_core_storage.spanQueryIdentityKey(row));
20826
+ return {
20827
+ ...row,
20828
+ model: stored?.model ?? null,
20829
+ provider: stored?.provider ?? null,
20830
+ ...spanQueryOutcomeFieldsSupported && { stopReasonContext: stored?.stopReasonContext ?? null }
20831
+ };
20832
+ });
20741
20833
  let metrics = [];
20742
20834
  if (!_mastra_core_storage.SPAN_QUERY_FIELD_REGISTRY) {
20743
20835
  await remaining();
@@ -20979,6 +21071,8 @@ const DIMENSION_SQL = {
20979
21071
  entityId: "r.\"entityId\"",
20980
21072
  environment: "r.\"environment\"",
20981
21073
  status: TRACE_STATUS_SQL,
21074
+ outcome: "r.\"outcome\"",
21075
+ stopReason: "r.\"stopReason\"",
20982
21076
  serviceName: "r.\"serviceName\"",
20983
21077
  executionSource: "r.\"executionSource\"",
20984
21078
  threadId: "r.\"threadId\"",
@@ -21001,6 +21095,8 @@ const SPAN_DIMENSION_SQL = Object.fromEntries([
21001
21095
  "rootEntityName",
21002
21096
  "environment",
21003
21097
  "status",
21098
+ "outcome",
21099
+ "stopReason",
21004
21100
  "serviceName",
21005
21101
  "executionSource",
21006
21102
  "threadId",
@@ -21008,7 +21104,9 @@ const SPAN_DIMENSION_SQL = Object.fromEntries([
21008
21104
  "userId",
21009
21105
  "sessionId",
21010
21106
  "organizationId",
21011
- "experimentId"
21107
+ "experimentId",
21108
+ "model",
21109
+ "provider"
21012
21110
  ].map((field) => [field, `r."${field}"`]));
21013
21111
  const PERCENTILES = {
21014
21112
  "duration.p50": .5,
@@ -22061,8 +22159,12 @@ async function dangerouslyClearTracing(client, schema) {
22061
22159
  * application database — observability writes will degrade app performance.
22062
22160
  * Use it through `MastraCompositeStore` with a dedicated Postgres connection.
22063
22161
  */
22064
- const spanQueryFeatures = typeof _mastra_core_storage.planSpanQuery === "function" ? ["span-query", "span-query-context-fields"] : [];
22065
- const spanAggregateFeatures = typeof _mastra_core_storage.planSpanAggregate === "function" ? ["span-aggregate"] : [];
22162
+ const spanQueryFeatures = typeof _mastra_core_storage.planSpanQuery === "function" ? [
22163
+ "span-query",
22164
+ "span-query-context-fields",
22165
+ ..."model" in (_mastra_core_storage.SPAN_QUERY_FIELD_REGISTRY ?? {}) ? ["span-query-model-fields"] : []
22166
+ ] : [];
22167
+ const spanAggregateFeatures = typeof _mastra_core_storage.planSpanAggregate === "function" ? ["span-aggregate", ..."model" in (_mastra_core_storage.SPAN_AGGREGATE_DIMENSION_REGISTRY ?? {}) ? ["span-aggregate-model-dimensions"] : []] : [];
22066
22168
  function wrapError(op, error, details) {
22067
22169
  if (error instanceof _mastra_core_error.MastraError || error instanceof _mastra_core_storage.TraceQueryCursorError || error instanceof _mastra_core_storage.TraceQueryExecutionError || error instanceof _mastra_core_storage.TraceQueryResourceLimitError) throw error;
22068
22170
  throw new _mastra_core_error.MastraError({
@@ -22274,6 +22376,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
22274
22376
  "feedback",
22275
22377
  "trace-query-context-ids",
22276
22378
  ...timingFeatures,
22379
+ ...outcomeFeatures,
22277
22380
  "trace-query-root-span-fields",
22278
22381
  "trace-query-root-entity-id"
22279
22382
  ];
@@ -22299,6 +22402,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
22299
22402
  "feedback",
22300
22403
  "trace-query-context-ids",
22301
22404
  ...timingFeatures,
22405
+ ...outcomeFeatures,
22302
22406
  "trace-query-root-span-fields",
22303
22407
  "trace-query-root-entity-id"
22304
22408
  ];