@mastra/pg 1.26.0-alpha.4 → 1.26.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
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from "crypto";
2
2
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
3
3
  import * as coreStorage from "@mastra/core/storage";
4
- import { AgentsStorage, BRANCH_SPAN_TYPES, BackgroundTasksStorage, BlobStore, ChannelsStorage, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, DatasetsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, EntityType, ExperimentsStorage, FactoryStorage, FavoritesStorage, KNOWLEDGE_ACTIVITY_SCHEMA, KNOWLEDGE_CURSORS_SCHEMA, KNOWLEDGE_MENTIONS_SCHEMA, KNOWLEDGE_NODES_SCHEMA, KNOWLEDGE_RECORDS_SCHEMA, KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA, KnowledgeConflictError, KnowledgeNotFoundError, KnowledgeStorage, MCPClientsStorage, MCPServersStorage, METRIC_DISTINCT_COLUMNS, MastraCompositeStore, MemoryStorage, NotificationsStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, PromptBlocksStorage, SchedulesStorage, ScorerDefinitionsStorage, ScoresStorage, SkillsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_BACKGROUND_TASKS, TABLE_CHANNEL_CONFIG, TABLE_CHANNEL_INSTALLATIONS, TABLE_CONFIGS, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, TABLE_FAVORITES, TABLE_KNOWLEDGE_ACTIVITY, TABLE_KNOWLEDGE_CURSORS, TABLE_KNOWLEDGE_MENTIONS, TABLE_KNOWLEDGE_NODES, TABLE_KNOWLEDGE_RECORDS, TABLE_KNOWLEDGE_SEMANTIC_OUTBOX, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, TABLE_MESSAGES, TABLE_NOTIFICATIONS, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, TABLE_RESOURCES, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, TABLE_SKILLS, TABLE_SKILL_BLOBS, TABLE_SKILL_VERSIONS, TABLE_SPANS, TABLE_THREADS, TABLE_THREAD_STATE, TABLE_TOOL_PROVIDER_CONNECTIONS, TABLE_WORKFLOW_DEFINITIONS, TABLE_WORKFLOW_SNAPSHOT, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, ThreadStateStorage, ToolProviderConnectionsStorage, TraceStatus, UniqueViolationError, WorkflowDefinitionsStorage, WorkflowsStorage, WorkspacesStorage, assertKnowledgeCeilingRaised, assertKnowledgeScopeWithinCeiling, calculatePagination, canonicalizeKnowledgeScope, createKnowledgeUlid, createStorageErrorId, createVectorErrorId, ensureDate, executeRetentionPrune, getDefaultValue, getSqlType, hasErrorCode, isKnowledgeScopeVisible, knowledgeScopeKey, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, listBranchesArgsSchema, listFeedbackArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listTracesArgsSchema, matchesExpectedWorkflowStatus, mergeWorkflowStepResult, normalizePerPage, normalizeScheduleTarget, parseDuration, parseKnowledgeNodeCursor, parseKnowledgeWikilinks, resolveRetentionTargets, retentionCutoffMs, runRetentionBatches, safelyParseJSON, storageMessageMatchesMetadataFilter, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
4
+ import { AgentsStorage, BRANCH_SPAN_TYPES, BackgroundTasksStorage, BlobStore, ChannelsStorage, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, DatasetsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, EntityType, ExperimentsStorage, FactoryStorage, FavoritesStorage, KNOWLEDGE_ACTIVITY_SCHEMA, KNOWLEDGE_CURSORS_SCHEMA, KNOWLEDGE_MENTIONS_SCHEMA, KNOWLEDGE_NODES_SCHEMA, KNOWLEDGE_RECORDS_SCHEMA, KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA, KnowledgeConflictError, KnowledgeNotFoundError, KnowledgeStorage, MCPClientsStorage, MCPServersStorage, METRIC_DISTINCT_COLUMNS, MastraCompositeStore, MemoryStorage, NotificationsStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, PromptBlocksStorage, SchedulesStorage, ScorerDefinitionsStorage, ScoresStorage, SkillsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_BACKGROUND_TASKS, TABLE_CHANNEL_CONFIG, TABLE_CHANNEL_INSTALLATIONS, TABLE_CONFIGS, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, TABLE_FAVORITES, TABLE_KNOWLEDGE_ACTIVITY, TABLE_KNOWLEDGE_CURSORS, TABLE_KNOWLEDGE_MENTIONS, TABLE_KNOWLEDGE_NODES, TABLE_KNOWLEDGE_RECORDS, TABLE_KNOWLEDGE_SEMANTIC_OUTBOX, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, TABLE_MESSAGES, TABLE_NOTIFICATIONS, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, TABLE_RESOURCES, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, TABLE_SKILLS, TABLE_SKILL_BLOBS, TABLE_SKILL_VERSIONS, TABLE_SPANS, TABLE_THREADS, TABLE_THREAD_STATE, TABLE_TOOL_PROVIDER_CONNECTIONS, TABLE_WORKFLOW_DEFINITIONS, TABLE_WORKFLOW_SNAPSHOT, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, ThreadStateStorage, ToolProviderConnectionsStorage, TraceStatus, UniqueViolationError, WorkflowDefinitionsStorage, WorkflowsStorage, WorkspacesStorage, assertKnowledgeCeilingRaised, assertKnowledgeScopeWithinCeiling, calculatePagination, canonicalizeKnowledgeScope, createKnowledgeUlid, createStorageErrorId, createVectorErrorId, ensureDate, executeRetentionPrune, getDefaultValue, getSqlType, hasErrorCode, isKnowledgeScopeVisible, knowledgeScopeKey, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, listBranchesArgsSchema, listFeedbackArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listTracesArgsSchema, matchesExpectedWorkflowStatus, mergeWorkflowStepResult, normalizePerPage, normalizeScheduleTarget, parseDuration, parseKnowledgeNodeCursor, parseKnowledgeWikilinks, resolveListOrderBy, resolveRetentionTargets, retentionCutoffMs, runRetentionBatches, safelyParseJSON, storageMessageMatchesMetadataFilter, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
5
5
  import { parseFieldKey, parseSqlIdentifier } from "@mastra/core/utils";
6
6
  import { MastraVector, validateTopK, validateUpsertInput } from "@mastra/core/vector";
7
7
  import { Mutex } from "async-mutex";
@@ -6112,6 +6112,14 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
6112
6112
  }
6113
6113
  async listDatasets(args) {
6114
6114
  try {
6115
+ const orderBy = resolveListOrderBy(args.orderBy, [
6116
+ "createdAt",
6117
+ "updatedAt",
6118
+ "name"
6119
+ ], {
6120
+ field: "createdAt",
6121
+ direction: "DESC"
6122
+ });
6115
6123
  const { page, perPage: perPageInput } = args.pagination;
6116
6124
  const tableName = getTableName$5({
6117
6125
  indexName: TABLE_DATASETS,
@@ -6167,7 +6175,7 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
6167
6175
  const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
6168
6176
  const limitValue = perPageInput === false ? total : perPage;
6169
6177
  return {
6170
- datasets: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6178
+ datasets: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6171
6179
  ...queryParams,
6172
6180
  limitValue,
6173
6181
  offset
@@ -6734,6 +6742,10 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
6734
6742
  */
6735
6743
  async #listItems(client, args) {
6736
6744
  try {
6745
+ const orderBy = resolveListOrderBy(args.orderBy, ["createdAt", "updatedAt"], {
6746
+ field: "createdAt",
6747
+ direction: "DESC"
6748
+ });
6737
6749
  const { page, perPage: perPageInput } = args.pagination;
6738
6750
  const tableName = getTableName$5({
6739
6751
  indexName: TABLE_DATASET_ITEMS,
@@ -6784,7 +6796,7 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
6784
6796
  const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
6785
6797
  const limitValue = perPageInput === false ? total : perPage;
6786
6798
  return {
6787
- items: (await client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6799
+ items: (await client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6788
6800
  ...queryParams,
6789
6801
  limitValue,
6790
6802
  offset
@@ -7344,6 +7356,10 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7344
7356
  }
7345
7357
  async listExperiments(args) {
7346
7358
  try {
7359
+ const orderBy = resolveListOrderBy(args.orderBy, ["createdAt", "status"], {
7360
+ field: "createdAt",
7361
+ direction: "DESC"
7362
+ });
7347
7363
  const { page, perPage: perPageInput } = args.pagination;
7348
7364
  const tableName = getTableName$5({
7349
7365
  indexName: TABLE_EXPERIMENTS,
@@ -7415,7 +7431,7 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7415
7431
  const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
7416
7432
  const limitValue = perPageInput === false ? total : perPage;
7417
7433
  return {
7418
- experiments: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7434
+ experiments: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7419
7435
  ...queryParams,
7420
7436
  limitValue,
7421
7437
  offset
@@ -7687,6 +7703,10 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7687
7703
  }
7688
7704
  async listExperimentResults(args) {
7689
7705
  try {
7706
+ const orderBy = resolveListOrderBy(args.orderBy, ["startedAt", "createdAt"], {
7707
+ field: "startedAt",
7708
+ direction: "ASC"
7709
+ });
7690
7710
  const { page, perPage: perPageInput } = args.pagination;
7691
7711
  const tableName = getTableName$5({
7692
7712
  indexName: TABLE_EXPERIMENT_RESULTS,
@@ -7734,7 +7754,7 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7734
7754
  const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
7735
7755
  const limitValue = perPageInput === false ? total : perPage;
7736
7756
  return {
7737
- results: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7757
+ results: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7738
7758
  ...queryParams,
7739
7759
  limitValue,
7740
7760
  offset
@@ -17273,7 +17293,7 @@ const TRACE_SELECT = `
17273
17293
  r."name" AS "name",
17274
17294
  r."entityId" AS "entityId",
17275
17295
  r."parentSpanId" AS "parentSpanId",
17276
- r."metadata" AS "metadata",
17296
+ r."metadataRaw" AS "metadata",
17277
17297
  r."input" AS "input",
17278
17298
  r."threadId" AS "threadId",
17279
17299
  r."resourceId" AS "resourceId",
@@ -17491,22 +17511,27 @@ function compileThreadPredicate(predicate, parameterOffset) {
17491
17511
  values: compiled.values
17492
17512
  };
17493
17513
  }
17494
- function compilePostgresTraceScope(schema, selection, relationCollections) {
17514
+ function compilePostgresTraceScope(schema, selection, relationCollections, deltaWindow) {
17495
17515
  const spanTable = qualifiedTable(schema, TABLE_SPAN_EVENTS);
17496
17516
  const scoreTable = qualifiedTable(schema, TABLE_SCORE_EVENTS);
17497
17517
  const feedbackTable = qualifiedTable(schema, TABLE_FEEDBACK_EVENTS);
17498
17518
  const values = [selection.timeRange.from, selection.timeRange.to];
17499
- const ctes = [`root_scope AS MATERIALIZED (
17500
- SELECT *
17501
- FROM ${spanTable} r
17502
- WHERE ${[
17519
+ const rootConditions = [
17503
17520
  `r."parentSpanId" IS NULL`,
17504
17521
  latestRootPredicate$1(spanTable),
17505
17522
  `NOT r."isPending"`,
17506
17523
  `r."endedAt" IS NOT NULL`,
17507
17524
  `r."startedAt" >= $1`,
17508
17525
  `r."startedAt" < $2`
17509
- ].join("\n AND ")}
17526
+ ];
17527
+ if (deltaWindow) {
17528
+ values.push(deltaWindow.xactId, deltaWindow.cursorId, deltaWindow.safeHorizon);
17529
+ rootConditions.push(`(r."xactId", r."cursorId") > ($3::xid8, $4::bigint)`, `r."xactId" < $5::xid8`);
17530
+ }
17531
+ const ctes = [`root_scope AS MATERIALIZED (
17532
+ SELECT *
17533
+ FROM ${spanTable} r
17534
+ WHERE ${rootConditions.join("\n AND ")}
17510
17535
  )`];
17511
17536
  if (relationCollections.has("spans")) ctes.push(`current_spans AS MATERIALIZED (
17512
17537
  SELECT
@@ -17575,8 +17600,18 @@ function compilePostgresTraceScope(schema, selection, relationCollections) {
17575
17600
  values
17576
17601
  };
17577
17602
  }
17578
- function compilePostgresTraceQuery(schema, plan, mode = "data") {
17579
- const { ctes, values } = compilePostgresTraceScope(schema, plan, collectRelationCollections(plan.where));
17603
+ function compilePostgresTraceQuery(schema, plan, mode = "data", safeHorizon) {
17604
+ const relationCollections = collectRelationCollections(plan.where);
17605
+ let deltaWindow;
17606
+ if (plan.paginationMode === "delta") {
17607
+ const watermark = coreStorage.getTraceQueryDeltaWatermark(plan, "pg");
17608
+ if (watermark === void 0 || safeHorizon === void 0) throw new Error("Delta query requires a cursor and safe horizon");
17609
+ deltaWindow = {
17610
+ ...decodeTraceDeltaWatermark(watermark),
17611
+ safeHorizon
17612
+ };
17613
+ }
17614
+ const { ctes, values } = compilePostgresTraceScope(schema, plan, relationCollections, deltaWindow);
17580
17615
  let predicateSql = "TRUE";
17581
17616
  if (plan.where) {
17582
17617
  const predicate = compilePredicate(plan.where, values.length + 1);
@@ -17584,7 +17619,7 @@ function compilePostgresTraceQuery(schema, plan, mode = "data") {
17584
17619
  values.push(...predicate.values);
17585
17620
  }
17586
17621
  ctes.push(`candidates AS (
17587
- SELECT ${TRACE_SELECT}
17622
+ SELECT ${TRACE_SELECT}${plan.paginationMode === "delta" ? ", r.\"xactId\", r.\"cursorId\"" : ""}
17588
17623
  FROM root_scope r
17589
17624
  WHERE ${predicateSql}
17590
17625
  )`);
@@ -17595,6 +17630,16 @@ SELECT COUNT(*)::text AS count
17595
17630
  FROM candidates`,
17596
17631
  values
17597
17632
  };
17633
+ if (plan.paginationMode === "delta") {
17634
+ values.push(plan.limit + 1);
17635
+ return {
17636
+ text: `${candidates}
17637
+ SELECT * FROM candidates
17638
+ ORDER BY "xactId" ASC, "cursorId" ASC
17639
+ LIMIT $${values.length}`,
17640
+ values
17641
+ };
17642
+ }
17598
17643
  if (plan.result === "groups") {
17599
17644
  const pageCondition = plan.cursor ? `AND "threadId" > $${values.length + 1}` : "";
17600
17645
  if (plan.cursor) values.push(plan.cursor.threadId);
@@ -17806,13 +17851,83 @@ async function getTraceQueryValues(client, schema, plan, timeoutMs) {
17806
17851
  valuesTruncated: rows.length > plan.limit
17807
17852
  });
17808
17853
  }
17854
+ function decodeTraceDeltaWatermark(watermark) {
17855
+ try {
17856
+ return decodeDeltaCursor(watermark);
17857
+ } catch {
17858
+ throw new coreStorage.TraceQueryCursorError("TRACE_QUERY_CURSOR_MALFORMED");
17859
+ }
17860
+ }
17861
+ function emptyDeltaWatermark(horizon, watermark) {
17862
+ if (watermark !== void 0 && BigInt(decodeTraceDeltaWatermark(watermark).xactId) >= BigInt(horizon)) return watermark;
17863
+ return encodeDeltaCursor(horizon, 0);
17864
+ }
17865
+ async function setRemainingTimeout(transaction, deadline) {
17866
+ const remainingTimeoutMs = Math.floor(deadline - performance.now());
17867
+ if (remainingTimeoutMs <= 0) throw new coreStorage.TraceQueryExecutionError();
17868
+ await transaction.query(`SELECT set_config('statement_timeout', $1, true)`, [`${remainingTimeoutMs}ms`]);
17869
+ }
17870
+ function traceRowToResult(row) {
17871
+ return {
17872
+ traceId: String(row.traceId),
17873
+ rootSpanId: String(row.rootSpanId),
17874
+ name: row.name,
17875
+ entityId: row.entityId ?? null,
17876
+ parentSpanId: row.parentSpanId ?? null,
17877
+ createdAt: asIsoTimestamp$1(row.startedAt),
17878
+ metadata: row.metadata ?? null,
17879
+ inputPreview: coreStorage.buildInputPreview(row.input) ?? null,
17880
+ threadId: row.threadId == null ? null : String(row.threadId),
17881
+ resourceId: row.resourceId == null ? null : String(row.resourceId),
17882
+ startedAt: asIsoTimestamp$1(row.startedAt),
17883
+ endedAt: asIsoTimestamp$1(row.endedAt),
17884
+ entityName: row.entityName == null ? null : String(row.entityName),
17885
+ entityType: row.entityType == null ? null : String(row.entityType),
17886
+ environment: row.environment == null ? null : String(row.environment),
17887
+ status: row.status
17888
+ };
17889
+ }
17809
17890
  async function queryTraces(client, schema, plan, timeoutMs) {
17891
+ if (plan.paginationMode === "delta") {
17892
+ assertDeltaPollingEnabled();
17893
+ const watermark = coreStorage.getTraceQueryDeltaWatermark(plan, "pg");
17894
+ if (watermark !== void 0) decodeTraceDeltaWatermark(watermark);
17895
+ const resolvedTimeoutMs = coreStorage.resolveTraceQueryTimeoutMs(timeoutMs);
17896
+ const deadline = performance.now() + resolvedTimeoutMs;
17897
+ return runWithPostgresTraceQueryTimeout(client, resolvedTimeoutMs, async (transaction) => {
17898
+ await setRemainingTimeout(transaction, deadline);
17899
+ const horizon = await readSafeXactHorizon(transaction);
17900
+ let rows = [];
17901
+ if (watermark !== void 0) {
17902
+ await setRemainingTimeout(transaction, deadline);
17903
+ const query = compilePostgresTraceQuery(schema, plan, "data", horizon);
17904
+ rows = await transaction.any(query.text, query.values);
17905
+ }
17906
+ const visible = rows.slice(0, plan.limit);
17907
+ const last = visible.at(-1);
17908
+ return coreStorage.traceQueryResponseSchema.parse({
17909
+ traces: visible.map(traceRowToResult),
17910
+ delta: {
17911
+ limit: plan.limit,
17912
+ hasMore: rows.length > plan.limit
17913
+ },
17914
+ deltaCursor: coreStorage.encodeTraceQueryDeltaCursor(plan, "pg", last ? encodeDeltaCursor(last.xactId, last.cursorId) : emptyDeltaWatermark(horizon, watermark))
17915
+ });
17916
+ }, { repeatableRead: true });
17917
+ }
17810
17918
  if (plan.paginationMode === "page") {
17811
17919
  const resolvedTimeoutMs = coreStorage.resolveTraceQueryTimeoutMs(timeoutMs);
17812
17920
  const deadline = performance.now() + resolvedTimeoutMs;
17813
17921
  const countQuery = compilePostgresTraceQuery(schema, plan, "count");
17814
17922
  const dataQuery = compilePostgresTraceQuery(schema, plan);
17815
- const { total, rows } = await runWithPostgresTraceQueryTimeout(client, resolvedTimeoutMs, async (transaction) => {
17923
+ const { total, rows, deltaCursor } = await runWithPostgresTraceQueryTimeout(client, resolvedTimeoutMs, async (transaction) => {
17924
+ let deltaCursor;
17925
+ if (deltaPollingFeatureEnabled() && typeof coreStorage.encodeTraceQueryDeltaCursor === "function") {
17926
+ await setRemainingTimeout(transaction, deadline);
17927
+ const horizon = await readSafeXactHorizon(transaction);
17928
+ deltaCursor = coreStorage.encodeTraceQueryDeltaCursor(plan, "pg", encodeDeltaCursor(horizon, 0));
17929
+ }
17930
+ if (deltaCursor !== void 0) await setRemainingTimeout(transaction, deadline);
17816
17931
  const countRows = await transaction.any(countQuery.text, countQuery.values);
17817
17932
  const remainingTimeoutMs = Math.floor(deadline - performance.now());
17818
17933
  if (remainingTimeoutMs <= 0) throw new coreStorage.TraceQueryExecutionError();
@@ -17820,29 +17935,14 @@ async function queryTraces(client, schema, plan, timeoutMs) {
17820
17935
  const rows = await transaction.any(dataQuery.text, dataQuery.values);
17821
17936
  return {
17822
17937
  total: Number(countRows[0]?.count ?? 0),
17823
- rows
17938
+ rows,
17939
+ deltaCursor
17824
17940
  };
17825
17941
  }, { repeatableRead: true });
17826
- const traces = rows.map((row) => ({
17827
- traceId: String(row.traceId),
17828
- rootSpanId: String(row.rootSpanId),
17829
- name: row.name,
17830
- entityId: row.entityId ?? null,
17831
- parentSpanId: row.parentSpanId ?? null,
17832
- createdAt: asIsoTimestamp$1(row.startedAt),
17833
- metadata: row.metadata ?? null,
17834
- inputPreview: coreStorage.buildInputPreview(row.input) ?? null,
17835
- threadId: row.threadId == null ? null : String(row.threadId),
17836
- resourceId: row.resourceId == null ? null : String(row.resourceId),
17837
- startedAt: asIsoTimestamp$1(row.startedAt),
17838
- endedAt: asIsoTimestamp$1(row.endedAt),
17839
- entityName: row.entityName == null ? null : String(row.entityName),
17840
- entityType: row.entityType == null ? null : String(row.entityType),
17841
- environment: row.environment == null ? null : String(row.environment),
17842
- status: row.status
17843
- }));
17942
+ const traces = rows.map(traceRowToResult);
17844
17943
  return coreStorage.traceQueryResponseSchema.parse({
17845
17944
  traces,
17945
+ ...deltaCursor === void 0 ? {} : { deltaCursor },
17846
17946
  pagination: {
17847
17947
  total,
17848
17948
  page: plan.page,
@@ -17865,24 +17965,7 @@ async function queryTraces(client, schema, plan, timeoutMs) {
17865
17965
  }) : null }
17866
17966
  });
17867
17967
  }
17868
- const traces = visibleRows.map((row) => ({
17869
- traceId: String(row.traceId),
17870
- rootSpanId: String(row.rootSpanId),
17871
- name: row.name,
17872
- entityId: row.entityId ?? null,
17873
- parentSpanId: row.parentSpanId ?? null,
17874
- createdAt: asIsoTimestamp$1(row.startedAt),
17875
- metadata: row.metadata ?? null,
17876
- inputPreview: coreStorage.buildInputPreview(row.input) ?? null,
17877
- threadId: row.threadId == null ? null : String(row.threadId),
17878
- resourceId: row.resourceId == null ? null : String(row.resourceId),
17879
- startedAt: asIsoTimestamp$1(row.startedAt),
17880
- endedAt: asIsoTimestamp$1(row.endedAt),
17881
- entityName: row.entityName == null ? null : String(row.entityName),
17882
- entityType: row.entityType == null ? null : String(row.entityType),
17883
- environment: row.environment == null ? null : String(row.environment),
17884
- status: row.status
17885
- }));
17968
+ const traces = visibleRows.map(traceRowToResult);
17886
17969
  const last = traces.at(-1);
17887
17970
  return coreStorage.traceQueryResponseSchema.parse({
17888
17971
  traces,
@@ -18621,7 +18704,7 @@ async function dangerouslyClearTracing(client, schema) {
18621
18704
  * Use it through `MastraCompositeStore` with a dedicated Postgres connection.
18622
18705
  */
18623
18706
  function wrapError(op, error, details) {
18624
- if (error instanceof MastraError || error instanceof coreStorage.TraceQueryExecutionError || error instanceof coreStorage.TraceQueryResourceLimitError) throw error;
18707
+ if (error instanceof MastraError || error instanceof coreStorage.TraceQueryCursorError || error instanceof coreStorage.TraceQueryExecutionError || error instanceof coreStorage.TraceQueryResourceLimitError) throw error;
18625
18708
  throw new MastraError({
18626
18709
  id: createStorageErrorId("PG", op, "FAILED"),
18627
18710
  domain: ErrorDomain.STORAGE,