@mastra/pg 1.31.3-alpha.0 → 1.32.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
@@ -6303,7 +6303,11 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
6303
6303
  const queryParams = [];
6304
6304
  let paramIndex = 1;
6305
6305
  if (args.filters) {
6306
- const { organizationId, projectId, candidateKey, candidateId, targetType, targetIds, name } = args.filters;
6306
+ const { organizationId, projectId, candidateKey, candidateId, targetType, targetIds, datasetIds, name } = args.filters;
6307
+ if (datasetIds !== void 0) {
6308
+ conditions.push(`"id" = ANY($${paramIndex++}::text[])`);
6309
+ queryParams.push(datasetIds);
6310
+ }
6307
6311
  if (organizationId !== void 0) {
6308
6312
  conditions.push(`"organizationId" = $${paramIndex++}`);
6309
6313
  queryParams.push(organizationId);
@@ -17094,9 +17098,27 @@ function readPreview(preview, payload, jsonEncoded = false) {
17094
17098
  }
17095
17099
  /** Older response builders may shorten previews or turn empty strings into null. */
17096
17100
  function buildSpanQueryResponse(...args) {
17097
- if (canGeneratePreviews) return coreStorage.buildSpanQueryResponse(...args);
17098
- const [plan, selected, payloads, metrics] = args;
17099
- const response = coreStorage.buildSpanQueryResponse(plan, selected, [], metrics);
17101
+ const [plan, selected, payloads, metrics = []] = args;
17102
+ const compatibleSelected = coreStorage.SPAN_QUERY_FIELD_REGISTRY ? selected : selected.map((row) => ({
17103
+ organizationId: row.organizationId,
17104
+ resourceId: row.resourceId,
17105
+ traceId: row.traceId,
17106
+ spanId: row.spanId,
17107
+ parentSpanId: row.parentSpanId,
17108
+ name: row.name,
17109
+ spanType: row.spanType,
17110
+ status: row.status,
17111
+ startedAt: row.startedAt,
17112
+ endedAt: row.endedAt,
17113
+ durationMs: row.durationMs,
17114
+ entityType: row.entityType,
17115
+ entityId: row.entityId,
17116
+ entityName: row.entityName,
17117
+ model: row.model,
17118
+ provider: row.provider
17119
+ }));
17120
+ if (canGeneratePreviews) return coreStorage.buildSpanQueryResponse(plan, compatibleSelected, payloads, metrics);
17121
+ const response = coreStorage.buildSpanQueryResponse(plan, compatibleSelected, [], metrics);
17100
17122
  const byIdentity = new Map(payloads.map((payload) => [coreStorage.spanQueryIdentityKey(payload), payload]));
17101
17123
  for (const span of response.spans) {
17102
17124
  const payload = byIdentity.get(coreStorage.spanQueryIdentityKey(span));
@@ -18366,6 +18388,7 @@ async function listLogsDelta(client, table, filters, after, limit) {
18366
18388
  function applyMetricFilters(acc, filters) {
18367
18389
  applyCommonFilters(acc, filters);
18368
18390
  applySingleOrArrayFilter(acc, "traceId", filters?.traceIds);
18391
+ applySingleOrArrayFilter(acc, "experimentId", filters?.experimentIds);
18369
18392
  applySingleOrArrayFilter(acc, "name", filters?.name);
18370
18393
  applySingleOrArrayFilter(acc, "provider", filters?.provider);
18371
18394
  applySingleOrArrayFilter(acc, "model", filters?.model);
@@ -19192,6 +19215,25 @@ const SPAN_FIELDS = {
19192
19215
  userId: "s.\"userId\"",
19193
19216
  organizationId: "s.\"organizationId\""
19194
19217
  };
19218
+ const SPAN_QUERY_FIELDS = {
19219
+ ...SPAN_FIELDS,
19220
+ traceId: "s.\"traceId\"",
19221
+ spanId: "s.\"spanId\"",
19222
+ parentSpanId: "s.\"parentSpanId\"",
19223
+ threadId: "s.\"threadId\"",
19224
+ resourceId: "s.\"resourceId\"",
19225
+ requestId: "s.\"requestId\"",
19226
+ serviceName: "s.\"serviceName\"",
19227
+ experimentId: "s.\"experimentId\"",
19228
+ environment: "s.\"environment\"",
19229
+ executionSource: "s.\"executionSource\"",
19230
+ parentEntityType: "s.\"parentEntityType\"",
19231
+ parentEntityId: "s.\"parentEntityId\"",
19232
+ parentEntityName: "s.\"parentEntityName\"",
19233
+ rootEntityType: "s.\"rootEntityType\"",
19234
+ rootEntityId: "s.\"rootEntityId\"",
19235
+ rootEntityName: "s.\"rootEntityName\""
19236
+ };
19195
19237
  const SCORE_FIELDS = {
19196
19238
  scorerId: "s.\"scorerId\"",
19197
19239
  scorerVersion: "s.\"scorerVersion\"",
@@ -20083,9 +20125,9 @@ async function queryThreads(client, schema, plan, timeoutMs) {
20083
20125
  }) : null }
20084
20126
  });
20085
20127
  }
20086
- /** Compile a span-row filter with exactly the same rules as trace span predicates. */
20128
+ /** Compile a direct span-query filter using its dedicated field mapping. */
20087
20129
  function compileSpanQueryPredicate(predicate, offset) {
20088
- return compileScalarPredicate(predicate, SPAN_FIELDS, offset);
20130
+ return compileScalarPredicate(predicate, SPAN_QUERY_FIELDS, offset);
20089
20131
  }
20090
20132
  //#endregion
20091
20133
  //#region src/storage/domains/observability/v-next/span-query.ts
@@ -20104,11 +20146,23 @@ const fields = [
20104
20146
  "entityId",
20105
20147
  "entityName",
20106
20148
  "entityVersionId",
20149
+ "parentEntityType",
20150
+ "parentEntityId",
20151
+ "parentEntityName",
20107
20152
  "parentEntityVersionId",
20153
+ "rootEntityType",
20154
+ "rootEntityId",
20155
+ "rootEntityName",
20108
20156
  "rootEntityVersionId",
20157
+ "threadId",
20109
20158
  "runId",
20110
20159
  "sessionId",
20111
- "userId"
20160
+ "userId",
20161
+ "requestId",
20162
+ "serviceName",
20163
+ "experimentId",
20164
+ "environment",
20165
+ "executionSource"
20112
20166
  ];
20113
20167
  const identities = identityFields.map((field) => `"${field}"`).join(", ");
20114
20168
  const identityOrder = identityFields.map((field) => `"${field}" COLLATE "C" ASC NULLS LAST`).join(", ");
@@ -20158,6 +20212,8 @@ function compilePostgresSpanQuery(schema, plan) {
20158
20212
  const after = afterCursor(plan, values);
20159
20213
  values.push(plan.limit + 1);
20160
20214
  const table = qualifiedTable(schema, TABLE_SPAN_EVENTS);
20215
+ const legacyModelFields = coreStorage.SPAN_QUERY_FIELD_REGISTRY ? "" : `CASE WHEN jsonb_typeof(attributes -> 'model') = 'string' THEN attributes ->> 'model' END AS model,
20216
+ CASE WHEN jsonb_typeof(attributes -> 'provider') = 'string' THEN attributes ->> 'provider' END AS provider,`;
20161
20217
  return {
20162
20218
  text: `WITH candidate_ids AS MATERIALIZED (
20163
20219
  SELECT DISTINCT ${identities} FROM ${table}
@@ -20166,8 +20222,7 @@ function compilePostgresSpanQuery(schema, plan) {
20166
20222
  ), current_spans AS MATERIALIZED (
20167
20223
  SELECT DISTINCT ON (${identities})
20168
20224
  ${fields.map((field) => `"${field}"`).join(", ")}, "startedAt", "endedAt", "cursorId"::text AS version,
20169
- CASE WHEN jsonb_typeof(attributes -> 'model') = 'string' THEN attributes ->> 'model' END AS model,
20170
- CASE WHEN jsonb_typeof(attributes -> 'provider') = 'string' THEN attributes ->> 'provider' END AS provider,
20225
+ ${legacyModelFields}
20171
20226
  (EXTRACT(EPOCH FROM ("endedAt" - "startedAt")) * 1000)::float8 AS "durationMs",
20172
20227
  CASE WHEN error IS NULL THEN 'success' ELSE 'error' END AS status,
20173
20228
  error IS NOT NULL AS "hasError"
@@ -20182,15 +20237,7 @@ function compilePostgresSpanQuery(schema, plan) {
20182
20237
  SELECT *, CASE WHEN "hasError" THEN 'error' ELSE NULL END AS error FROM current_spans
20183
20238
  )
20184
20239
  SELECT ${[
20185
- ...identityFields,
20186
- "parentSpanId",
20187
- "name",
20188
- "spanType",
20189
- "entityType",
20190
- "entityId",
20191
- "entityName",
20192
- "model",
20193
- "provider",
20240
+ ...fields,
20194
20241
  "startedAt",
20195
20242
  "endedAt",
20196
20243
  "durationMs",
@@ -20237,7 +20284,7 @@ async function querySpans(client, schema, plan, timeoutMs) {
20237
20284
  endedAt: endedAt.toISOString()
20238
20285
  }));
20239
20286
  const page = rows.slice(0, plan.limit);
20240
- if (!page.length) return coreStorage.buildSpanQueryResponse(plan, selected, [], []);
20287
+ if (!page.length) return buildSpanQueryResponse(plan, [], []);
20241
20288
  const remaining = async () => {
20242
20289
  const ms = Math.floor(deadline - performance.now());
20243
20290
  if (ms <= 0) throw new coreStorage.TraceQueryExecutionError();
@@ -20250,20 +20297,32 @@ async function querySpans(client, schema, plan, timeoutMs) {
20250
20297
  payloadValues.push(row.version);
20251
20298
  return `(${key} AND "cursorId" = $${payloadValues.length}::bigint)`;
20252
20299
  }).join(" OR ");
20253
- const payloads = (await tx.any(`SELECT ${identities},
20300
+ const payloadRows = await tx.any(`SELECT ${identities},
20301
+ CASE WHEN jsonb_typeof(attributes -> 'model') = 'string' THEN attributes ->> 'model' END AS model,
20302
+ CASE WHEN jsonb_typeof(attributes -> 'provider') = 'string' THEN attributes ->> 'provider' END AS provider,
20254
20303
  ${PREVIEW_PAYLOADS$1.map(([preview, payload]) => `"${preview}", CASE WHEN ${missingPreviewSql(`"${preview}"`)} THEN "${payload}" END AS "${payload}"`).join(",\n ")}
20255
- FROM ${qualifiedTable(schema, TABLE_SPAN_EVENTS)} WHERE ${payloadWhere}`, payloadValues)).map(toSpanQueryPayload);
20256
- await remaining();
20257
- const metricValues = [];
20258
- const metricWhere = selectedKeys(page, metricValues);
20259
- const metrics = await tx.any(`SELECT ${identities}, name, "estimatedCost", "costUnit",
20260
- "costMetadata" ->> 'allocation' AS allocation, COALESCE("costMetadata" ? 'error', false) AS "costError"
20261
- FROM (SELECT DISTINCT ON (${identities}, "metricId") ${identities}, name, "estimatedCost", "costUnit", "costMetadata" FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
20262
- WHERE (${metricWhere}) AND name LIKE 'mastra_model_%'
20263
- ORDER BY ${identities}, "metricId", "cursorId" DESC) m
20264
- LIMIT ${coreStorage.SPAN_QUERY_MAX_COST_METRICS + 1}`, metricValues);
20265
- if (metrics.length > coreStorage.SPAN_QUERY_MAX_COST_METRICS) throw new coreStorage.TraceQueryResourceLimitError();
20266
- return buildSpanQueryResponse(plan, selected, payloads, metrics);
20304
+ FROM ${qualifiedTable(schema, TABLE_SPAN_EVENTS)} WHERE ${payloadWhere}`, payloadValues);
20305
+ const payloads = payloadRows.map(toSpanQueryPayload);
20306
+ const metadata = new Map(payloadRows.map((row) => [coreStorage.spanQueryIdentityKey(row), row]));
20307
+ const hydrated = selected.map((row) => ({
20308
+ ...row,
20309
+ model: metadata.get(coreStorage.spanQueryIdentityKey(row))?.model ?? null,
20310
+ provider: metadata.get(coreStorage.spanQueryIdentityKey(row))?.provider ?? null
20311
+ }));
20312
+ let metrics = [];
20313
+ if (!coreStorage.SPAN_QUERY_FIELD_REGISTRY) {
20314
+ await remaining();
20315
+ const metricValues = [];
20316
+ const metricWhere = selectedKeys(page, metricValues);
20317
+ metrics = await tx.any(`SELECT ${identities}, name, "estimatedCost", "costUnit",
20318
+ "costMetadata" ->> 'allocation' AS allocation, COALESCE("costMetadata" ? 'error', false) AS "costError"
20319
+ FROM (SELECT DISTINCT ON (${identities}, "metricId") ${identities}, name, "estimatedCost", "costUnit", "costMetadata" FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
20320
+ WHERE (${metricWhere}) AND name LIKE 'mastra_model_%'
20321
+ ORDER BY ${identities}, "metricId", "cursorId" DESC) m
20322
+ LIMIT ${coreStorage.SPAN_QUERY_MAX_COST_METRICS + 1}`, metricValues);
20323
+ if (metrics.length > coreStorage.SPAN_QUERY_MAX_COST_METRICS) throw new coreStorage.TraceQueryResourceLimitError();
20324
+ }
20325
+ return buildSpanQueryResponse(plan, hydrated, payloads, metrics);
20267
20326
  }, { repeatableRead: true });
20268
20327
  }
20269
20328
  //#endregion
@@ -21307,7 +21366,7 @@ async function dangerouslyClearTracing(client, schema) {
21307
21366
  * application database — observability writes will degrade app performance.
21308
21367
  * Use it through `MastraCompositeStore` with a dedicated Postgres connection.
21309
21368
  */
21310
- const spanQueryFeatures = typeof coreStorage.planSpanQuery === "function" ? ["span-query"] : [];
21369
+ const spanQueryFeatures = typeof coreStorage.planSpanQuery === "function" ? ["span-query", "span-query-context-fields"] : [];
21311
21370
  function wrapError(op, error, details) {
21312
21371
  if (error instanceof MastraError || error instanceof coreStorage.TraceQueryCursorError || error instanceof coreStorage.TraceQueryExecutionError || error instanceof coreStorage.TraceQueryResourceLimitError) throw error;
21313
21372
  throw new MastraError({