@mastra/pg 1.33.0-alpha.1 → 1.33.0-alpha.2

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 (31) hide show
  1. package/dist/_types/@internal_core/dist/knowledge-compat/index.d.ts +0 -2
  2. package/dist/_types/@internal_core/dist/memory/index.d.ts +0 -2
  3. package/dist/docs/SKILL.md +1 -1
  4. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  5. package/dist/docs/references/docs-memory-semantic-recall.md +5 -1
  6. package/dist/docs/references/integrations-databases-dynamodb.md +4 -4
  7. package/dist/docs/references/integrations-databases-postgresql.md +4 -4
  8. package/dist/docs/references/reference-memory-memory-class.md +2 -2
  9. package/dist/docs/references/reference-rag-chunking-and-embedding.md +1 -1
  10. package/dist/docs/references/reference-rag-retrieval.md +11 -0
  11. package/dist/docs/references/reference-tools-vector-query-tool.md +1 -0
  12. package/dist/docs/references/reference-vectors-pg.md +1 -1
  13. package/dist/index.cjs +110 -170
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +109 -168
  16. package/dist/index.js.map +1 -1
  17. package/dist/shared/pool-error-guard.d.ts +23 -0
  18. package/dist/shared/pool-error-guard.d.ts.map +1 -0
  19. package/dist/shared/test-fixtures/terminate-backend.d.ts +2 -0
  20. package/dist/shared/test-fixtures/terminate-backend.d.ts.map +1 -0
  21. package/dist/storage/db/index.d.ts.map +1 -1
  22. package/dist/storage/domains/agents/index.d.ts.map +1 -1
  23. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  24. package/dist/storage/domains/observability/v-next/ddl.d.ts +2 -0
  25. package/dist/storage/domains/observability/v-next/ddl.d.ts.map +1 -1
  26. package/dist/storage/domains/observability/v-next/index.d.ts.map +1 -1
  27. package/dist/storage/factory-storage.d.ts +1 -22
  28. package/dist/storage/factory-storage.d.ts.map +1 -1
  29. package/dist/storage/index.d.ts.map +1 -1
  30. package/dist/vector/index.d.ts.map +1 -1
  31. package/package.json +9 -9
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@ import { MessageList } from "@mastra/core/agent";
16
16
  import { saveScorePayloadSchema } from "@mastra/core/evals";
17
17
  import { skillSnapshotFieldValuesEqual } from "@mastra/core/storage/domains/skills";
18
18
  import { isDeepStrictEqual } from "util";
19
- //#region src/shared/config.ts
19
+ // src/shared/config.ts
20
20
  /**
21
21
  * Type guard for pre-configured pg.Pool config
22
22
  */
@@ -63,8 +63,7 @@ const validateConfig = (name, config) => {
63
63
  ]) if (!config[key] || typeof config[key] !== "string" || config[key].trim() === "") throw new Error(`${name}: ${key} must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults.`);
64
64
  } else throw new Error(`${name}: invalid config. Provide either {pool}, {connectionString}, {host,port,database,user,password}, or a pg ClientConfig (e.g., Cloud SQL connector with \`stream\`).`);
65
65
  };
66
- //#endregion
67
- //#region src/shared/pool-config.ts
66
+ // src/shared/pool-config.ts
68
67
  /**
69
68
  * Builds the `pg.Pool` options for a connection-string based config.
70
69
  *
@@ -93,8 +92,40 @@ function buildConnectionStringPoolConfig(config, defaults) {
93
92
  idleTimeoutMillis: config.idleTimeoutMillis ?? defaults.idleTimeoutMillis
94
93
  };
95
94
  }
96
- //#endregion
97
- //#region src/shared/schema-name.ts
95
+ // src/shared/pool-error-guard.ts
96
+ /**
97
+ * A pool-level `error` listener only covers *idle* clients: pg hands ownership
98
+ * of a client to the borrower for the duration of a checkout and takes its own
99
+ * listener off. So a backend restart or network blip that lands on a client
100
+ * mid-transaction reaches an emitter with no listener, and Node escalates that
101
+ * to an uncaughtException that kills the process — the pool handler logs the
102
+ * idle siblings and the borrowed one still brings everything down.
103
+ *
104
+ * Attach a listener once per physical connection instead. `connect` fires when
105
+ * the pool establishes a client, so the client stays covered for its whole life
106
+ * and there is nothing to remove on release.
107
+ *
108
+ * That listener outlives the checkout, so it also sees the failures the pool is
109
+ * already reporting through its own idle listener. Follow `acquire`/`release`
110
+ * to tell the two apart and stay quiet while the client is idle — otherwise one
111
+ * dropped connection is announced twice, the second time as the wrong thing.
112
+ *
113
+ * The pool still discards the failed connection; this only keeps the failure
114
+ * reportable instead of fatal.
115
+ */
116
+ function guardCheckedOutClientErrors(pool, warn = console.warn) {
117
+ const borrowed = /* @__PURE__ */ new WeakSet();
118
+ pool.on("connect", (client) => {
119
+ borrowed.add(client);
120
+ client.on("error", (err) => {
121
+ if (!borrowed.has(client)) return;
122
+ warn(`PostgreSQL: client error while checked out (the pool discards this connection): ${err instanceof Error ? err.message : String(err)}`);
123
+ });
124
+ });
125
+ pool.on("acquire", (client) => borrowed.add(client));
126
+ pool.on("release", (_err, client) => borrowed.delete(client));
127
+ }
128
+ // src/shared/schema-name.ts
98
129
  const POSTGRES_IDENTIFIER_MAX_BYTES = 63;
99
130
  const UNSAFE_SCHEMA_NAME_CHARS = /["'\\$\u0000-\u001f\u007f]/;
100
131
  /**
@@ -121,8 +152,7 @@ function schemaNamePrefix(name) {
121
152
  const sanitized = parseSchemaName(name).replace(/[^A-Za-z0-9_]/g, "_");
122
153
  return /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;
123
154
  }
124
- //#endregion
125
- //#region src/vector/filter.ts
155
+ // src/vector/filter.ts
126
156
  /**
127
157
  * Translates MongoDB-style filters to PG compatible filters.
128
158
  *
@@ -178,8 +208,7 @@ var PGFilterTranslator = class extends BaseFilterTranslator {
178
208
  return { $regex: flags ? `(?${flags})${pattern}` : pattern };
179
209
  }
180
210
  };
181
- //#endregion
182
- //#region src/vector/sql-builder.ts
211
+ // src/vector/sql-builder.ts
183
212
  const getTextExtractExpr = (key) => {
184
213
  const jsonPathKey = parseJsonPathKey(key);
185
214
  if (!key.includes(".")) return `metadata->>'${jsonPathKey}'`;
@@ -557,8 +586,7 @@ function buildFilterQuery(filter, minScore, topK) {
557
586
  values
558
587
  };
559
588
  }
560
- //#endregion
561
- //#region src/vector/index.ts
589
+ // src/vector/index.ts
562
590
  const DEFAULT_NAMESPACE = "default";
563
591
  const MAX_UPSERT_ROWS_PER_STATEMENT = Math.floor(65535 / 4);
564
592
  var PgVector = class extends MastraVector {
@@ -625,6 +653,7 @@ var PgVector = class extends MastraVector {
625
653
  };
626
654
  else throw new Error("PgVector: invalid configuration provided");
627
655
  this.pool = new pg$1.Pool(poolConfig);
656
+ guardCheckedOutClientErrors(this.pool, (message) => this.logger?.warn?.(message));
628
657
  this.pool.on("error", (err) => {
629
658
  this.logger?.warn?.("PgVector: idle pool client error (pool discards the client and reconnects on next checkout)", { err: err instanceof Error ? err.message : err });
630
659
  });
@@ -2023,8 +2052,7 @@ var PgVector = class extends MastraVector {
2023
2052
  }
2024
2053
  }
2025
2054
  };
2026
- //#endregion
2027
- //#region src/storage/client.ts
2055
+ // src/storage/client.ts
2028
2056
  /**
2029
2057
  * Truncate a query string for error messages.
2030
2058
  */
@@ -2406,8 +2434,7 @@ function buildConstraintName({ baseName, schemaName, maxLength = 63, hashWhenTru
2406
2434
  }
2407
2435
  return truncateIdentifier(fullName, maxLength);
2408
2436
  }
2409
- //#endregion
2410
- //#region src/storage/db/pg-errors.ts
2437
+ // src/storage/db/pg-errors.ts
2411
2438
  function asPgError(error) {
2412
2439
  return error ?? {};
2413
2440
  }
@@ -2435,8 +2462,7 @@ function isDuplicateSchemaError(error) {
2435
2462
  if (code === "23505" && constraint === "pg_namespace_nspname_index") return true;
2436
2463
  return /schema .* already exists/i.test(message);
2437
2464
  }
2438
- //#endregion
2439
- //#region src/storage/db/sanitize-json.ts
2465
+ // src/storage/db/sanitize-json.ts
2440
2466
  const repair = (value) => value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�").replaceAll("\0", "");
2441
2467
  function repairJson(value) {
2442
2468
  if (typeof value === "string") return repair(value);
@@ -2462,8 +2488,7 @@ function toPgJson(value) {
2462
2488
  if (json === void 0 || !/\\u(?:0000|[dD][89a-fA-F][0-9a-fA-F]{2})/.test(json)) return json;
2463
2489
  return JSON.stringify(repairJson(JSON.parse(json)));
2464
2490
  }
2465
- //#endregion
2466
- //#region src/storage/db/schema-snapshot.ts
2491
+ // src/storage/db/schema-snapshot.ts
2467
2492
  /**
2468
2493
  * Returns the snapshot currently installed on `client`, but only when it was
2469
2494
  * taken from the schema the caller operates on. A store configured for another
@@ -2545,8 +2570,7 @@ async function loadSchemaSnapshot(client, schemaName) {
2545
2570
  invalidIndexes
2546
2571
  };
2547
2572
  }
2548
- //#endregion
2549
- //#region src/storage/db/index.ts
2573
+ // src/storage/db/index.ts
2550
2574
  const POSTGRES_MAX_BIND_PARAMETERS$1 = 65535;
2551
2575
  /**
2552
2576
  * Resolves PgDomainConfig to a database client and schema.
@@ -2589,6 +2613,7 @@ function resolvePgConfig(config) {
2589
2613
  pool.on("error", (err) => {
2590
2614
  console.warn(`resolvePgConfig: idle pool client error (pool discards the client and reconnects on next checkout): ${err instanceof Error ? err.message : String(err)}`);
2591
2615
  });
2616
+ guardCheckedOutClientErrors(pool);
2592
2617
  const client = new PoolAdapter(pool);
2593
2618
  return {
2594
2619
  client,
@@ -4117,8 +4142,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
4117
4142
  await client.none(sql, values);
4118
4143
  }
4119
4144
  };
4120
- //#endregion
4121
- //#region src/storage/domains/utils.ts
4145
+ // src/storage/domains/utils.ts
4122
4146
  function getSchemaName$5(schema) {
4123
4147
  return schema ? `"${parseSchemaName(schema)}"` : void 0;
4124
4148
  }
@@ -4199,8 +4223,7 @@ function tenancyWhere(filters, startIndex) {
4199
4223
  nextIndex: idx
4200
4224
  };
4201
4225
  }
4202
- //#endregion
4203
- //#region src/storage/domains/agents/index.ts
4226
+ // src/storage/domains/agents/index.ts
4204
4227
  var AgentsPG = class AgentsPG extends AgentsStorage {
4205
4228
  #db;
4206
4229
  #schema;
@@ -5047,8 +5070,7 @@ var AgentsPG = class AgentsPG extends AgentsStorage {
5047
5070
  };
5048
5071
  }
5049
5072
  };
5050
- //#endregion
5051
- //#region src/storage/retention.ts
5073
+ // src/storage/retention.ts
5052
5074
  function cutoffFor(policy, anchorType, now = Date.now()) {
5053
5075
  const cutoffMs = retentionCutoffMs(policy, now);
5054
5076
  return anchorType === "epoch-ms" ? cutoffMs : new Date(cutoffMs);
@@ -5075,8 +5097,7 @@ function resolveTargets({ policies, descriptor, order }) {
5075
5097
  order
5076
5098
  });
5077
5099
  }
5078
- //#endregion
5079
- //#region src/storage/domains/background-tasks/index.ts
5100
+ // src/storage/domains/background-tasks/index.ts
5080
5101
  function getSchemaName$4(schema) {
5081
5102
  return schema ? `"${schema}"` : "\"public\"";
5082
5103
  }
@@ -5490,8 +5511,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends BackgroundTasksStorage {
5490
5511
  return Number(result?.count ?? 0);
5491
5512
  }
5492
5513
  };
5493
- //#endregion
5494
- //#region src/storage/domains/blobs/index.ts
5514
+ // src/storage/domains/blobs/index.ts
5495
5515
  var BlobsPG = class extends BlobStore {
5496
5516
  #db;
5497
5517
  #schema;
@@ -5593,8 +5613,7 @@ var BlobsPG = class extends BlobStore {
5593
5613
  };
5594
5614
  }
5595
5615
  };
5596
- //#endregion
5597
- //#region src/storage/domains/channels/index.ts
5616
+ // src/storage/domains/channels/index.ts
5598
5617
  var ChannelsPG = class ChannelsPG extends ChannelsStorage {
5599
5618
  #db;
5600
5619
  #schema;
@@ -5808,8 +5827,7 @@ var ChannelsPG = class ChannelsPG extends ChannelsStorage {
5808
5827
  };
5809
5828
  }
5810
5829
  };
5811
- //#endregion
5812
- //#region src/storage/domains/datasets/index.ts
5830
+ // src/storage/domains/datasets/index.ts
5813
5831
  /** Serialize a value for a jsonb column. Returns null for null/undefined. */
5814
5832
  function jsonbArg(value) {
5815
5833
  return value === void 0 || value === null ? null : toPgJson(value);
@@ -7080,8 +7098,7 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
7080
7098
  await this.#db.clearTable({ tableName: TABLE_DATASETS });
7081
7099
  }
7082
7100
  };
7083
- //#endregion
7084
- //#region src/storage/domains/experiments/index.ts
7101
+ // src/storage/domains/experiments/index.ts
7085
7102
  const DEFAULT_PRUNE_BATCH_SIZE = 1e3;
7086
7103
  var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7087
7104
  #db;
@@ -8027,8 +8044,7 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
8027
8044
  await this.#db.clearTable({ tableName: TABLE_EXPERIMENTS });
8028
8045
  }
8029
8046
  };
8030
- //#endregion
8031
- //#region src/storage/domains/favorites/index.ts
8047
+ // src/storage/domains/favorites/index.ts
8032
8048
  /**
8033
8049
  * Maps a favorite entity type to its parent entity table.
8034
8050
  */
@@ -8300,8 +8316,7 @@ var FavoritesPG = class FavoritesPG extends FavoritesStorage {
8300
8316
  }
8301
8317
  }
8302
8318
  };
8303
- //#endregion
8304
- //#region ../../packages/_internal-core/dist/knowledge-compat/index.js
8319
+ // ../../packages/_internal-core/dist/knowledge-compat/index.js
8305
8320
  const KNOWLEDGE_V2_CORE_FEATURE = "knowledge-v2";
8306
8321
  /** Hard cap on scope nodes returned by one `listScopeNodes` read. */
8307
8322
  const MAX_KNOWLEDGE_SCOPE_NODES = 1e3;
@@ -8935,8 +8950,7 @@ function createKnowledgeV2CoreLoader(features, loadStorageModule) {
8935
8950
  return knowledgeV2Core;
8936
8951
  };
8937
8952
  }
8938
- //#endregion
8939
- //#region src/storage/domains/knowledge/index.ts
8953
+ // src/storage/domains/knowledge/index.ts
8940
8954
  const loadKnowledgeV2Core = createKnowledgeV2CoreLoader(coreFeatures, () => import("@mastra/core/storage"));
8941
8955
  async function assertKnowledgeDescriptionWithinBoundCompat(description) {
8942
8956
  const { assertKnowledgeDescriptionWithinBound } = await loadKnowledgeV2Core();
@@ -10460,8 +10474,7 @@ var KnowledgePG = class extends KnowledgeStorage {
10460
10474
  });
10461
10475
  }
10462
10476
  };
10463
- //#endregion
10464
- //#region src/storage/domains/mcp-clients/index.ts
10477
+ // src/storage/domains/mcp-clients/index.ts
10465
10478
  const SNAPSHOT_FIELDS$5 = [
10466
10479
  "name",
10467
10480
  "description",
@@ -11022,8 +11035,7 @@ var MCPClientsPG = class MCPClientsPG extends MCPClientsStorage {
11022
11035
  };
11023
11036
  }
11024
11037
  };
11025
- //#endregion
11026
- //#region src/storage/domains/mcp-servers/index.ts
11038
+ // src/storage/domains/mcp-servers/index.ts
11027
11039
  const SNAPSHOT_FIELDS$4 = [
11028
11040
  "name",
11029
11041
  "version",
@@ -11605,8 +11617,7 @@ var MCPServersPG = class MCPServersPG extends MCPServersStorage {
11605
11617
  };
11606
11618
  }
11607
11619
  };
11608
- //#endregion
11609
- //#region ../../packages/_internal-core/dist/memory/index.js
11620
+ // ../../packages/_internal-core/dist/memory/index.js
11610
11621
  /**
11611
11622
  * Shared rules for observational memory lifecycle writes. Every storage adapter applies
11612
11623
  * these inside its own atomic section (lock, transaction, or conditional update), so the
@@ -11691,8 +11702,7 @@ function isAppendOnlySince(storedObservations, snapshotObservations) {
11691
11702
  const snapshot = snapshotObservations ?? "";
11692
11703
  return stored === snapshot || stored.startsWith(snapshot);
11693
11704
  }
11694
- //#endregion
11695
- //#region src/storage/db/run-fencing.ts
11705
+ // src/storage/db/run-fencing.ts
11696
11706
  /**
11697
11707
  * Epoch milliseconds on the database clock. `clock_timestamp()` rather than
11698
11708
  * `now()`: a statement can wait on a row lock, and lease math must use the
@@ -11724,8 +11734,7 @@ function withRunFence(client, claimsTable, fence, operation, write) {
11724
11734
  return write(t);
11725
11735
  });
11726
11736
  }
11727
- //#endregion
11728
- //#region src/storage/domains/memory/index.ts
11737
+ // src/storage/domains/memory/index.ts
11729
11738
  /**
11730
11739
  * Local constant for the observational memory table name.
11731
11740
  * Defined locally to avoid a static import that crashes on older @mastra/core
@@ -14557,8 +14566,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
14557
14566
  }
14558
14567
  }
14559
14568
  };
14560
- //#endregion
14561
- //#region src/storage/domains/notifications/index.ts
14569
+ // src/storage/domains/notifications/index.ts
14562
14570
  const COMPOSITE_PRIMARY_KEY$1 = TABLE_CONFIGS[TABLE_NOTIFICATIONS].compositePrimaryKey;
14563
14571
  const statusTimestamp = (status, now) => {
14564
14572
  if (status === "delivered") return { deliveredAt: now };
@@ -15061,8 +15069,7 @@ var NotificationsPG = class NotificationsPG extends NotificationsStorage {
15061
15069
  return row ? rowToNotification(row) : void 0;
15062
15070
  }
15063
15071
  };
15064
- //#endregion
15065
- //#region src/storage/domains/observability/index.ts
15072
+ // src/storage/domains/observability/index.ts
15066
15073
  var ObservabilityPG = class ObservabilityPG extends ObservabilityStorage {
15067
15074
  /**
15068
15075
  * Retention-eligible tables. The observability domain has a single physical
@@ -15733,8 +15740,7 @@ var ObservabilityPG = class ObservabilityPG extends ObservabilityStorage {
15733
15740
  }
15734
15741
  }
15735
15742
  };
15736
- //#endregion
15737
- //#region src/storage/domains/observability/v-next/signal-schema.ts
15743
+ // src/storage/domains/observability/v-next/signal-schema.ts
15738
15744
  const CURSOR_ID_COLUMN = {
15739
15745
  name: "cursorId",
15740
15746
  type: "bigserial"
@@ -16385,8 +16391,7 @@ const TEXT_ARRAY_COLUMNS = new Set(columnNamesByType(ALL_EVENT_COLUMNS, "text[]"
16385
16391
  const METRIC_TYPED_COLUMNS = typedColumnNames(METRIC_EVENT_COLUMNS);
16386
16392
  const SCORE_TYPED_COLUMNS = typedColumnNames(SCORE_EVENT_COLUMNS);
16387
16393
  const FEEDBACK_TYPED_COLUMNS = typedColumnNames(FEEDBACK_EVENT_COLUMNS);
16388
- //#endregion
16389
- //#region src/storage/domains/observability/v-next/ddl.ts
16394
+ // src/storage/domains/observability/v-next/ddl.ts
16390
16395
  /**
16391
16396
  * Raw DDL for Postgres v-next observability tables.
16392
16397
  *
@@ -16783,8 +16788,7 @@ function additiveColumns(schema) {
16783
16788
  function allIndexDDL(schema) {
16784
16789
  return tableIndexes().map((spec) => indexDDL(schema, spec));
16785
16790
  }
16786
- //#endregion
16787
- //#region src/storage/domains/observability/v-next/discovery.ts
16791
+ // src/storage/domains/observability/v-next/discovery.ts
16788
16792
  const DEFAULT_TTL_SECONDS = 300;
16789
16793
  const DEFAULT_LOOKBACK_SECONDS = 2592e3;
16790
16794
  /** All signal tables that contain a column. Used by cross-signal discovery. */
@@ -17019,8 +17023,7 @@ async function getMetricLabelValues(client, schema, args, config) {
17019
17023
  if (args.limit) filtered = filtered.slice(0, args.limit);
17020
17024
  return { values: filtered };
17021
17025
  }
17022
- //#endregion
17023
- //#region src/storage/domains/observability/v-next/filters.ts
17026
+ // src/storage/domains/observability/v-next/filters.ts
17024
17027
  function newFilterAccumulator(startIndex = 1) {
17025
17028
  return {
17026
17029
  conditions: [],
@@ -17095,8 +17098,7 @@ function applySingleOrArrayFilter(acc, column, value, prefix = "") {
17095
17098
  function whereOrEmpty(acc) {
17096
17099
  return acc.conditions.length ? `WHERE ${acc.conditions.join(" AND ")}` : "";
17097
17100
  }
17098
- //#endregion
17099
- //#region src/storage/domains/observability/v-next/preview-compat.ts
17101
+ // src/storage/domains/observability/v-next/preview-compat.ts
17100
17102
  const generator = coreStorage.buildStoredPreview;
17101
17103
  const canGeneratePreviews = typeof generator === "function";
17102
17104
  /** SQL detection only; preview formatting stays in TypeScript. Empty strings are intentional. */
@@ -17153,8 +17155,7 @@ function buildSpanQueryResponse(...args) {
17153
17155
  }
17154
17156
  return response;
17155
17157
  }
17156
- //#endregion
17157
- //#region src/storage/domains/observability/v-next/review-status.ts
17158
+ // src/storage/domains/observability/v-next/review-status.ts
17158
17159
  const FEEDBACK_REVIEW_STATUSES = ["needs-review", "reviewed"];
17159
17160
  function isFeedbackReviewStatus(value) {
17160
17161
  return FEEDBACK_REVIEW_STATUSES.some((status) => status === value);
@@ -17178,8 +17179,7 @@ function parseUpdateFeedbackReviewStatusArgs(args) {
17178
17179
  reviewStatus: args.reviewStatus
17179
17180
  };
17180
17181
  }
17181
- //#endregion
17182
- //#region src/storage/domains/observability/v-next/sql.ts
17182
+ // src/storage/domains/observability/v-next/sql.ts
17183
17183
  /**
17184
17184
  * SQL helpers for the v-next Postgres observability domain.
17185
17185
  *
@@ -17309,8 +17309,7 @@ const SCORE_SELECT_COLUMNS = `
17309
17309
  ${buildSelectColumns(SCORE_EVENT_COLUMNS)}`;
17310
17310
  const FEEDBACK_SELECT_COLUMNS = `
17311
17311
  ${buildSelectColumns(FEEDBACK_EVENT_COLUMNS)}`;
17312
- //#endregion
17313
- //#region src/storage/domains/observability/v-next/helpers.ts
17312
+ // src/storage/domains/observability/v-next/helpers.ts
17314
17313
  const PROMOTED_KEYS = /* @__PURE__ */ new Set([
17315
17314
  "experimentId",
17316
17315
  "entityType",
@@ -17747,8 +17746,7 @@ function rowToFeedbackRecord(row) {
17747
17746
  scope: parsedJson(row.scope) ?? void 0
17748
17747
  };
17749
17748
  }
17750
- //#endregion
17751
- //#region src/storage/domains/observability/v-next/polling.ts
17749
+ // src/storage/domains/observability/v-next/polling.ts
17752
17750
  /**
17753
17751
  * Delta-polling helpers for the v-next Postgres observability domain.
17754
17752
  *
@@ -17817,8 +17815,7 @@ function decodeDeltaCursor(cursor) {
17817
17815
  async function readSafeXactHorizon(client) {
17818
17816
  return validatePgInteger((await client.one(`SELECT pg_snapshot_xmin(pg_current_snapshot())::text AS "xactId"`)).xactId);
17819
17817
  }
17820
- //#endregion
17821
- //#region src/storage/domains/observability/v-next/listing.ts
17818
+ // src/storage/domains/observability/v-next/listing.ts
17822
17819
  function responseItems(key, items) {
17823
17820
  return { [key]: items };
17824
17821
  }
@@ -17905,8 +17902,7 @@ async function listSignalDelta(config) {
17905
17902
  deltaCursor
17906
17903
  };
17907
17904
  }
17908
- //#endregion
17909
- //#region src/storage/domains/observability/v-next/olap.ts
17905
+ // src/storage/domains/observability/v-next/olap.ts
17910
17906
  /**
17911
17907
  * Shared OLAP helpers for the v-next Postgres observability domain.
17912
17908
  *
@@ -18110,8 +18106,7 @@ const COMPLEX_GROUP_BY_EXCLUDED = /* @__PURE__ */ new Set([
18110
18106
  "tags",
18111
18107
  "requestContext"
18112
18108
  ]);
18113
- //#endregion
18114
- //#region src/storage/domains/observability/v-next/feedback.ts
18109
+ // src/storage/domains/observability/v-next/feedback.ts
18115
18110
  /**
18116
18111
  * Feedback operations for the v-next Postgres observability domain.
18117
18112
  *
@@ -18349,8 +18344,7 @@ async function getFeedbackPercentiles(client, schema, args) {
18349
18344
  `;
18350
18345
  return { series: percentileSeriesFromRows(await client.manyOrNone(sql, acc.params), args.percentiles) };
18351
18346
  }
18352
- //#endregion
18353
- //#region src/storage/domains/observability/v-next/logs.ts
18347
+ // src/storage/domains/observability/v-next/logs.ts
18354
18348
  /**
18355
18349
  * Log operations for the v-next Postgres observability domain.
18356
18350
  */
@@ -18402,8 +18396,7 @@ async function listLogsDelta(client, table, filters, after, limit) {
18402
18396
  mapRow: rowToLogRecord
18403
18397
  });
18404
18398
  }
18405
- //#endregion
18406
- //#region src/storage/domains/observability/v-next/metrics.ts
18399
+ // src/storage/domains/observability/v-next/metrics.ts
18407
18400
  /**
18408
18401
  * Metric operations for the v-next Postgres observability domain.
18409
18402
  *
@@ -18640,8 +18633,7 @@ async function getMetricPercentiles(client, schema, args) {
18640
18633
  `;
18641
18634
  return { series: percentileSeriesFromRows(await client.manyOrNone(sql, acc.params), args.percentiles) };
18642
18635
  }
18643
- //#endregion
18644
- //#region src/storage/domains/observability/v-next/partitioning.ts
18636
+ // src/storage/domains/observability/v-next/partitioning.ts
18645
18637
  const DEFAULT_FUTURE_DAYS = 14;
18646
18638
  async function detectTimescale(client) {
18647
18639
  const row = await client.oneOrNone(`SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'timescaledb') AS "exists"`);
@@ -18800,8 +18792,7 @@ async function setupPartitioning(client, schema, options = {}) {
18800
18792
  return "native";
18801
18793
  }
18802
18794
  }
18803
- //#endregion
18804
- //#region src/storage/domains/observability/v-next/retention.ts
18795
+ // src/storage/domains/observability/v-next/retention.ts
18805
18796
  /**
18806
18797
  * Age-based retention for the v-next Postgres observability domain.
18807
18798
  *
@@ -18921,8 +18912,7 @@ async function pruneTimescaleTable({ client, schema, table, cutoff, options }) {
18921
18912
  done: true
18922
18913
  };
18923
18914
  }
18924
- //#endregion
18925
- //#region src/storage/domains/observability/v-next/scores.ts
18915
+ // src/storage/domains/observability/v-next/scores.ts
18926
18916
  /**
18927
18917
  * Score operations for the v-next Postgres observability domain.
18928
18918
  *
@@ -19201,8 +19191,7 @@ async function getScorePercentiles(client, schema, args) {
19201
19191
  `;
19202
19192
  return { series: percentileSeriesFromRows(await client.manyOrNone(sql, acc.params), args.percentiles) };
19203
19193
  }
19204
- //#endregion
19205
- //#region src/storage/domains/observability/v-next/trace-query.ts
19194
+ // src/storage/domains/observability/v-next/trace-query.ts
19206
19195
  const TRACE_STATUS_SQL = `CASE WHEN r."error" IS NOT NULL THEN 'error' ELSE 'success' END`;
19207
19196
  /** Core versions without the field reject it in strict query results, so it is only returned when core knows it. */
19208
19197
  const timeToFirstChunkSupported = "timeToFirstChunkMs" in coreStorage.TRACE_QUERY_FIELD_REGISTRY.trace;
@@ -20194,8 +20183,7 @@ function compileSpanQueryPredicate(predicate, offset) {
20194
20183
  function compileThreadQueryPredicate(predicate, offset) {
20195
20184
  return compileScalarPredicate(predicate, Object.fromEntries(Object.keys(coreStorage.THREAD_QUERY_FIELD_REGISTRY).map((field) => [field, `s."${field}"`])), offset);
20196
20185
  }
20197
- //#endregion
20198
- //#region src/storage/domains/observability/v-next/span-query.ts
20186
+ // src/storage/domains/observability/v-next/span-query.ts
20199
20187
  const identityFields = [
20200
20188
  "organizationId",
20201
20189
  "resourceId",
@@ -20408,8 +20396,7 @@ async function querySpans(client, schema, plan, timeoutMs) {
20408
20396
  return buildSpanQueryResponse(plan, hydrated, payloads, metrics);
20409
20397
  }, { repeatableRead: true });
20410
20398
  }
20411
- //#endregion
20412
- //#region src/storage/domains/observability/v-next/thread-query.ts
20399
+ // src/storage/domains/observability/v-next/thread-query.ts
20413
20400
  const contextFields = [
20414
20401
  "resourceId",
20415
20402
  "userId",
@@ -20640,8 +20627,7 @@ async function queryThreadRows(client, schema, plan, timeoutMs, strategy = "auto
20640
20627
  }) : null }
20641
20628
  };
20642
20629
  }
20643
- //#endregion
20644
- //#region src/storage/domains/observability/v-next/trace-aggregate.ts
20630
+ // src/storage/domains/observability/v-next/trace-aggregate.ts
20645
20631
  /** Trace-root column expressions (alias `r`) for each groupable dimension; same values `where` sees. */
20646
20632
  const DIMENSION_SQL = {
20647
20633
  entityType: "r.\"entityType\"",
@@ -20967,8 +20953,7 @@ async function runAggregate(client, plan, compiled, timeoutMs) {
20967
20953
  truncated
20968
20954
  };
20969
20955
  }
20970
- //#endregion
20971
- //#region src/storage/domains/observability/v-next/traces.ts
20956
+ // src/storage/domains/observability/v-next/traces.ts
20972
20957
  /**
20973
20958
  * Trace / branch list reads for the v-next Postgres observability domain.
20974
20959
  *
@@ -21582,8 +21567,7 @@ async function listBranchesDelta(client, span, filters, after, limit) {
21582
21567
  async function readBranchesStreamHeadCursor(client, span, filters) {
21583
21568
  return encodeDeltaCursor(await readSafeXactHorizon(client), 0);
21584
21569
  }
21585
- //#endregion
21586
- //#region src/storage/domains/observability/v-next/tracing.ts
21570
+ // src/storage/domains/observability/v-next/tracing.ts
21587
21571
  async function writeSpanRows(client, schema, rows) {
21588
21572
  const deduped = dedupeSpanRows(rows);
21589
21573
  const insert = buildInsert(schema, TABLE_SPAN_EVENTS, deduped, spanConflictClause(Object.keys(deduped[0] ?? {})));
@@ -21712,8 +21696,7 @@ async function dangerouslyClearTracing(client, schema) {
21712
21696
  const span = qualifiedTable(schema, TABLE_SPAN_EVENTS);
21713
21697
  await client.none(`TRUNCATE TABLE ${span} RESTART IDENTITY`);
21714
21698
  }
21715
- //#endregion
21716
- //#region src/storage/domains/observability/v-next/index.ts
21699
+ // src/storage/domains/observability/v-next/index.ts
21717
21700
  /**
21718
21701
  * Postgres v-next observability storage domain.
21719
21702
  *
@@ -21801,7 +21784,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
21801
21784
  else if (await detectPartman(this.#client)) mode = "partman";
21802
21785
  else mode = "native";
21803
21786
  const ddlMode = mode === "timescale" ? "timescale" : "partitioned";
21804
- try {
21787
+ if (!await this.#client.oneOrNone("SELECT 1 FROM information_schema.schemata WHERE schema_name = $1", [this.#schema])) try {
21805
21788
  await this.#client.none(schemaDDL(this.#schema));
21806
21789
  } catch (error) {
21807
21790
  if (!isDuplicateSchemaError(error)) throw error;
@@ -22152,8 +22135,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
22152
22135
  }
22153
22136
  }
22154
22137
  };
22155
- //#endregion
22156
- //#region src/storage/domains/prompt-blocks/index.ts
22138
+ // src/storage/domains/prompt-blocks/index.ts
22157
22139
  const SNAPSHOT_FIELDS$3 = [
22158
22140
  "name",
22159
22141
  "description",
@@ -22730,8 +22712,7 @@ var PromptBlocksPG = class PromptBlocksPG extends PromptBlocksStorage {
22730
22712
  };
22731
22713
  }
22732
22714
  };
22733
- //#endregion
22734
- //#region src/storage/domains/schedules/index.ts
22715
+ // src/storage/domains/schedules/index.ts
22735
22716
  function getSchemaName$2(schema) {
22736
22717
  return schema ? `"${schema}"` : "\"public\"";
22737
22718
  }
@@ -23099,8 +23080,7 @@ var SchedulesPG = class SchedulesPG extends SchedulesStorage {
23099
23080
  ${limitClause}`, params)).map(rowToTrigger);
23100
23081
  }
23101
23082
  };
23102
- //#endregion
23103
- //#region src/storage/domains/scorer-definitions/index.ts
23083
+ // src/storage/domains/scorer-definitions/index.ts
23104
23084
  const SNAPSHOT_FIELDS$2 = [
23105
23085
  "name",
23106
23086
  "description",
@@ -23700,8 +23680,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends ScorerDefinitionsSto
23700
23680
  };
23701
23681
  }
23702
23682
  };
23703
- //#endregion
23704
- //#region src/storage/domains/scores/index.ts
23683
+ // src/storage/domains/scores/index.ts
23705
23684
  /**
23706
23685
  * Appends multi-tenant scope conditions to a query. Mutates `conditions`/`queryParams`.
23707
23686
  * Returns the next positional parameter index.
@@ -24163,8 +24142,7 @@ var ScoresPG = class ScoresPG extends ScoresStorage {
24163
24142
  }
24164
24143
  }
24165
24144
  };
24166
- //#endregion
24167
- //#region src/storage/domains/skills/index.ts
24145
+ // src/storage/domains/skills/index.ts
24168
24146
  const SNAPSHOT_FIELDS$1 = [
24169
24147
  "name",
24170
24148
  "description",
@@ -24860,8 +24838,7 @@ var SkillsPG = class SkillsPG extends SkillsStorage {
24860
24838
  };
24861
24839
  }
24862
24840
  };
24863
- //#endregion
24864
- //#region src/storage/domains/thread-state/index.ts
24841
+ // src/storage/domains/thread-state/index.ts
24865
24842
  const COMPOSITE_PRIMARY_KEY = ["threadId", "type"];
24866
24843
  /**
24867
24844
  * PostgreSQL implementation of {@link ThreadStateStorage}.
@@ -25026,8 +25003,7 @@ var ThreadStatePG = class ThreadStatePG extends ThreadStateStorage {
25026
25003
  }
25027
25004
  }
25028
25005
  };
25029
- //#endregion
25030
- //#region src/storage/domains/tool-provider-connections/index.ts
25006
+ // src/storage/domains/tool-provider-connections/index.ts
25031
25007
  function normaliseScope(raw) {
25032
25008
  const value = raw == null ? "per-author" : String(raw);
25033
25009
  if (value === "shared") return "shared";
@@ -25282,8 +25258,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends ToolProv
25282
25258
  }
25283
25259
  }
25284
25260
  };
25285
- //#endregion
25286
- //#region src/storage/domains/workflow-definitions/index.ts
25261
+ // src/storage/domains/workflow-definitions/index.ts
25287
25262
  function rowToDefinition(row) {
25288
25263
  const inputSchema = parseJsonResilient(row.inputSchema);
25289
25264
  const outputSchema = parseJsonResilient(row.outputSchema);
@@ -25483,8 +25458,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends WorkflowDefiniti
25483
25458
  await this.#db.client.none(`DELETE FROM ${tableName} WHERE "id" = $1`, [id]);
25484
25459
  }
25485
25460
  };
25486
- //#endregion
25487
- //#region src/storage/domains/workflows/index.ts
25461
+ // src/storage/domains/workflows/index.ts
25488
25462
  function getSchemaName(schema) {
25489
25463
  return schema ? `"${schema}"` : "\"public\"";
25490
25464
  }
@@ -26213,8 +26187,7 @@ var WorkflowsPG = class WorkflowsPG extends WorkflowsStorage {
26213
26187
  }
26214
26188
  }
26215
26189
  };
26216
- //#endregion
26217
- //#region src/storage/domains/workspaces/index.ts
26190
+ // src/storage/domains/workspaces/index.ts
26218
26191
  const SNAPSHOT_FIELDS = [
26219
26192
  "name",
26220
26193
  "description",
@@ -26835,8 +26808,7 @@ var WorkspacesPG = class WorkspacesPG extends WorkspacesStorage {
26835
26808
  };
26836
26809
  }
26837
26810
  };
26838
- //#endregion
26839
- //#region src/storage/factory-storage.ts
26811
+ // src/storage/factory-storage.ts
26840
26812
  const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
26841
26813
  const PG_UNIQUE_VIOLATION = "23505";
26842
26814
  const COLUMN_DDL = {
@@ -27128,38 +27100,6 @@ var PgFactoryStorageOps = class {
27128
27100
  * Supports serializable app-table transactions for cross-replica invariant
27129
27101
  * enforcement and `authDatabase()` exposing the shared pool.
27130
27102
  */
27131
- /**
27132
- * A pool-level `error` listener only covers *idle* clients: pg hands ownership
27133
- * of a client to the borrower for the duration of a checkout and takes its own
27134
- * listener off. So a backend restart or network blip that lands on a client
27135
- * mid-transaction reaches an emitter with no listener, and Node escalates that
27136
- * to an uncaughtException that kills the process — the pool handler logs the
27137
- * idle siblings and the borrowed one still brings everything down.
27138
- *
27139
- * Attach a listener once per physical connection instead. `connect` fires when
27140
- * the pool establishes a client, so the client stays covered for its whole life
27141
- * and there is nothing to remove on release.
27142
- *
27143
- * That listener outlives the checkout, so it also sees the failures the pool is
27144
- * already reporting through its own idle listener. Follow `acquire`/`release`
27145
- * to tell the two apart and stay quiet while the client is idle — otherwise one
27146
- * dropped connection is announced twice, the second time as the wrong thing.
27147
- *
27148
- * The pool still discards the failed connection; this only keeps the failure
27149
- * reportable instead of fatal.
27150
- */
27151
- function guardCheckedOutClientErrors(pool, warn = console.warn) {
27152
- const borrowed = /* @__PURE__ */ new WeakSet();
27153
- pool.on("connect", (client) => {
27154
- borrowed.add(client);
27155
- client.on("error", (err) => {
27156
- if (!borrowed.has(client)) return;
27157
- warn(`PgFactoryStorage: client error while checked out (the pool discards this connection): ${err instanceof Error ? err.message : String(err)}`);
27158
- });
27159
- });
27160
- pool.on("acquire", (client) => borrowed.add(client));
27161
- pool.on("release", (_err, client) => borrowed.delete(client));
27162
- }
27163
27103
  var PgFactoryStorage = class extends FactoryStorage {
27164
27104
  ops;
27165
27105
  #pool;
@@ -27285,8 +27225,7 @@ var PgFactoryStorage = class extends FactoryStorage {
27285
27225
  }
27286
27226
  }
27287
27227
  };
27288
- //#endregion
27289
- //#region src/storage/index.ts
27228
+ // src/storage/index.ts
27290
27229
  /** Default maximum number of connections in the pool */
27291
27230
  const DEFAULT_MAX_CONNECTIONS = 20;
27292
27231
  /** Default idle timeout in milliseconds */
@@ -27458,6 +27397,7 @@ var PostgresStore = class extends MastraCompositeStore {
27458
27397
  pool.on("error", (err) => {
27459
27398
  this.logger?.warn?.("PostgresStore: idle pool client error (pool discards the client and reconnects on next checkout)", { err: err instanceof Error ? err.message : err });
27460
27399
  });
27400
+ guardCheckedOutClientErrors(pool, (message) => this.logger?.warn?.(message));
27461
27401
  return pool;
27462
27402
  }
27463
27403
  #buildPool(config) {
@@ -27597,9 +27537,12 @@ var PostgresStoreVNext = class extends PostgresStore {
27597
27537
  const observabilityClient = built.client;
27598
27538
  this.#observabilityPool = built.pool;
27599
27539
  this.#ownsObservabilityPool = built.owned;
27600
- if (built.owned) built.pool.on("error", (err) => {
27601
- this.logger?.warn?.("PostgresStoreVNext: idle observability pool client error (pool discards the client and reconnects on next checkout)", { err: err instanceof Error ? err.message : err });
27602
- });
27540
+ if (built.owned) {
27541
+ guardCheckedOutClientErrors(built.pool, (message) => this.logger?.warn?.(message));
27542
+ built.pool.on("error", (err) => {
27543
+ this.logger?.warn?.("PostgresStoreVNext: idle observability pool client error (pool discards the client and reconnects on next checkout)", { err: err instanceof Error ? err.message : err });
27544
+ });
27545
+ }
27603
27546
  const observability = new ObservabilityStoragePostgresVNext({
27604
27547
  client: observabilityClient,
27605
27548
  schemaName: obsConfig.schemaName ?? config.schemaName,
@@ -27653,8 +27596,7 @@ var PostgresStoreVNext = class extends PostgresStore {
27653
27596
  }
27654
27597
  }
27655
27598
  };
27656
- //#endregion
27657
- //#region src/vector/prompt.ts
27599
+ // src/vector/prompt.ts
27658
27600
  /**
27659
27601
  * Vector store specific prompt that details supported operators and examples.
27660
27602
  * This prompt helps users construct valid filters for PG Vector.
@@ -27756,7 +27698,6 @@ Example Complex Query:
27756
27698
  ]}
27757
27699
  ]
27758
27700
  }`;
27759
- //#endregion
27760
27701
  export { AgentsPG, BackgroundTasksPG, BlobsPG, ChannelsPG, DatasetsPG, ExperimentsPG, FavoritesPG, KnowledgePG, MCPClientsPG, MCPServersPG, MemoryPG, NotificationsPG, ObservabilityPG, ObservabilityStoragePostgresVNext, PGVECTOR_PROMPT, PgFactoryStorage, PgVector, PoolAdapter, PostgresStore, PostgresStoreVNext, PromptBlocksPG, SchedulesPG, ScorerDefinitionsPG, ScoresPG, SkillsPG, ThreadStatePG, ToolProviderConnectionsPG, WorkflowDefinitionsPG, WorkflowsPG, WorkspacesPG, exportSchemas };
27761
27702
 
27762
27703
  //# sourceMappingURL=index.js.map