@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.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let _mastra_core_error = require("@mastra/core/error");
25
24
  let _mastra_core_storage = require("@mastra/core/storage");
26
25
  _mastra_core_storage = __toESM(_mastra_core_storage, 1);
@@ -40,7 +39,7 @@ let _mastra_core_agent = require("@mastra/core/agent");
40
39
  let _mastra_core_evals = require("@mastra/core/evals");
41
40
  let _mastra_core_storage_domains_skills = require("@mastra/core/storage/domains/skills");
42
41
  let util = require("util");
43
- //#region src/shared/config.ts
42
+ // src/shared/config.ts
44
43
  /**
45
44
  * Type guard for pre-configured pg.Pool config
46
45
  */
@@ -87,8 +86,7 @@ const validateConfig = (name, config) => {
87
86
  ]) 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.`);
88
87
  } 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\`).`);
89
88
  };
90
- //#endregion
91
- //#region src/shared/pool-config.ts
89
+ // src/shared/pool-config.ts
92
90
  /**
93
91
  * Builds the `pg.Pool` options for a connection-string based config.
94
92
  *
@@ -117,8 +115,40 @@ function buildConnectionStringPoolConfig(config, defaults) {
117
115
  idleTimeoutMillis: config.idleTimeoutMillis ?? defaults.idleTimeoutMillis
118
116
  };
119
117
  }
120
- //#endregion
121
- //#region src/shared/schema-name.ts
118
+ // src/shared/pool-error-guard.ts
119
+ /**
120
+ * A pool-level `error` listener only covers *idle* clients: pg hands ownership
121
+ * of a client to the borrower for the duration of a checkout and takes its own
122
+ * listener off. So a backend restart or network blip that lands on a client
123
+ * mid-transaction reaches an emitter with no listener, and Node escalates that
124
+ * to an uncaughtException that kills the process — the pool handler logs the
125
+ * idle siblings and the borrowed one still brings everything down.
126
+ *
127
+ * Attach a listener once per physical connection instead. `connect` fires when
128
+ * the pool establishes a client, so the client stays covered for its whole life
129
+ * and there is nothing to remove on release.
130
+ *
131
+ * That listener outlives the checkout, so it also sees the failures the pool is
132
+ * already reporting through its own idle listener. Follow `acquire`/`release`
133
+ * to tell the two apart and stay quiet while the client is idle — otherwise one
134
+ * dropped connection is announced twice, the second time as the wrong thing.
135
+ *
136
+ * The pool still discards the failed connection; this only keeps the failure
137
+ * reportable instead of fatal.
138
+ */
139
+ function guardCheckedOutClientErrors(pool, warn = console.warn) {
140
+ const borrowed = /* @__PURE__ */ new WeakSet();
141
+ pool.on("connect", (client) => {
142
+ borrowed.add(client);
143
+ client.on("error", (err) => {
144
+ if (!borrowed.has(client)) return;
145
+ warn(`PostgreSQL: client error while checked out (the pool discards this connection): ${err instanceof Error ? err.message : String(err)}`);
146
+ });
147
+ });
148
+ pool.on("acquire", (client) => borrowed.add(client));
149
+ pool.on("release", (_err, client) => borrowed.delete(client));
150
+ }
151
+ // src/shared/schema-name.ts
122
152
  const POSTGRES_IDENTIFIER_MAX_BYTES = 63;
123
153
  const UNSAFE_SCHEMA_NAME_CHARS = /["'\\$\u0000-\u001f\u007f]/;
124
154
  /**
@@ -145,8 +175,7 @@ function schemaNamePrefix(name) {
145
175
  const sanitized = parseSchemaName(name).replace(/[^A-Za-z0-9_]/g, "_");
146
176
  return /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;
147
177
  }
148
- //#endregion
149
- //#region src/vector/filter.ts
178
+ // src/vector/filter.ts
150
179
  /**
151
180
  * Translates MongoDB-style filters to PG compatible filters.
152
181
  *
@@ -202,8 +231,7 @@ var PGFilterTranslator = class extends _mastra_core_vector_filter.BaseFilterTran
202
231
  return { $regex: flags ? `(?${flags})${pattern}` : pattern };
203
232
  }
204
233
  };
205
- //#endregion
206
- //#region src/vector/sql-builder.ts
234
+ // src/vector/sql-builder.ts
207
235
  const getTextExtractExpr = (key) => {
208
236
  const jsonPathKey = parseJsonPathKey(key);
209
237
  if (!key.includes(".")) return `metadata->>'${jsonPathKey}'`;
@@ -581,8 +609,7 @@ function buildFilterQuery(filter, minScore, topK) {
581
609
  values
582
610
  };
583
611
  }
584
- //#endregion
585
- //#region src/vector/index.ts
612
+ // src/vector/index.ts
586
613
  const DEFAULT_NAMESPACE = "default";
587
614
  const MAX_UPSERT_ROWS_PER_STATEMENT = Math.floor(65535 / 4);
588
615
  var PgVector = class extends _mastra_core_vector.MastraVector {
@@ -649,6 +676,7 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
649
676
  };
650
677
  else throw new Error("PgVector: invalid configuration provided");
651
678
  this.pool = new pg.Pool(poolConfig);
679
+ guardCheckedOutClientErrors(this.pool, (message) => this.logger?.warn?.(message));
652
680
  this.pool.on("error", (err) => {
653
681
  this.logger?.warn?.("PgVector: idle pool client error (pool discards the client and reconnects on next checkout)", { err: err instanceof Error ? err.message : err });
654
682
  });
@@ -2047,8 +2075,7 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
2047
2075
  }
2048
2076
  }
2049
2077
  };
2050
- //#endregion
2051
- //#region src/storage/client.ts
2078
+ // src/storage/client.ts
2052
2079
  /**
2053
2080
  * Truncate a query string for error messages.
2054
2081
  */
@@ -2430,8 +2457,7 @@ function buildConstraintName({ baseName, schemaName, maxLength = 63, hashWhenTru
2430
2457
  }
2431
2458
  return truncateIdentifier(fullName, maxLength);
2432
2459
  }
2433
- //#endregion
2434
- //#region src/storage/db/pg-errors.ts
2460
+ // src/storage/db/pg-errors.ts
2435
2461
  function asPgError(error) {
2436
2462
  return error ?? {};
2437
2463
  }
@@ -2459,8 +2485,7 @@ function isDuplicateSchemaError(error) {
2459
2485
  if (code === "23505" && constraint === "pg_namespace_nspname_index") return true;
2460
2486
  return /schema .* already exists/i.test(message);
2461
2487
  }
2462
- //#endregion
2463
- //#region src/storage/db/sanitize-json.ts
2488
+ // src/storage/db/sanitize-json.ts
2464
2489
  const repair = (value) => value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�").replaceAll("\0", "");
2465
2490
  function repairJson(value) {
2466
2491
  if (typeof value === "string") return repair(value);
@@ -2486,8 +2511,7 @@ function toPgJson(value) {
2486
2511
  if (json === void 0 || !/\\u(?:0000|[dD][89a-fA-F][0-9a-fA-F]{2})/.test(json)) return json;
2487
2512
  return JSON.stringify(repairJson(JSON.parse(json)));
2488
2513
  }
2489
- //#endregion
2490
- //#region src/storage/db/schema-snapshot.ts
2514
+ // src/storage/db/schema-snapshot.ts
2491
2515
  /**
2492
2516
  * Returns the snapshot currently installed on `client`, but only when it was
2493
2517
  * taken from the schema the caller operates on. A store configured for another
@@ -2569,8 +2593,7 @@ async function loadSchemaSnapshot(client, schemaName) {
2569
2593
  invalidIndexes
2570
2594
  };
2571
2595
  }
2572
- //#endregion
2573
- //#region src/storage/db/index.ts
2596
+ // src/storage/db/index.ts
2574
2597
  const POSTGRES_MAX_BIND_PARAMETERS$1 = 65535;
2575
2598
  /**
2576
2599
  * Resolves PgDomainConfig to a database client and schema.
@@ -2613,6 +2636,7 @@ function resolvePgConfig(config) {
2613
2636
  pool.on("error", (err) => {
2614
2637
  console.warn(`resolvePgConfig: idle pool client error (pool discards the client and reconnects on next checkout): ${err instanceof Error ? err.message : String(err)}`);
2615
2638
  });
2639
+ guardCheckedOutClientErrors(pool);
2616
2640
  const client = new PoolAdapter(pool);
2617
2641
  return {
2618
2642
  client,
@@ -4141,8 +4165,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
4141
4165
  await client.none(sql, values);
4142
4166
  }
4143
4167
  };
4144
- //#endregion
4145
- //#region src/storage/domains/utils.ts
4168
+ // src/storage/domains/utils.ts
4146
4169
  function getSchemaName$5(schema) {
4147
4170
  return schema ? `"${parseSchemaName(schema)}"` : void 0;
4148
4171
  }
@@ -4223,8 +4246,7 @@ function tenancyWhere(filters, startIndex) {
4223
4246
  nextIndex: idx
4224
4247
  };
4225
4248
  }
4226
- //#endregion
4227
- //#region src/storage/domains/agents/index.ts
4249
+ // src/storage/domains/agents/index.ts
4228
4250
  var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4229
4251
  #db;
4230
4252
  #schema;
@@ -5071,8 +5093,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
5071
5093
  };
5072
5094
  }
5073
5095
  };
5074
- //#endregion
5075
- //#region src/storage/retention.ts
5096
+ // src/storage/retention.ts
5076
5097
  function cutoffFor(policy, anchorType, now = Date.now()) {
5077
5098
  const cutoffMs = (0, _mastra_core_storage.retentionCutoffMs)(policy, now);
5078
5099
  return anchorType === "epoch-ms" ? cutoffMs : new Date(cutoffMs);
@@ -5099,8 +5120,7 @@ function resolveTargets({ policies, descriptor, order }) {
5099
5120
  order
5100
5121
  });
5101
5122
  }
5102
- //#endregion
5103
- //#region src/storage/domains/background-tasks/index.ts
5123
+ // src/storage/domains/background-tasks/index.ts
5104
5124
  function getSchemaName$4(schema) {
5105
5125
  return schema ? `"${schema}"` : "\"public\"";
5106
5126
  }
@@ -5514,8 +5534,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5514
5534
  return Number(result?.count ?? 0);
5515
5535
  }
5516
5536
  };
5517
- //#endregion
5518
- //#region src/storage/domains/blobs/index.ts
5537
+ // src/storage/domains/blobs/index.ts
5519
5538
  var BlobsPG = class extends _mastra_core_storage.BlobStore {
5520
5539
  #db;
5521
5540
  #schema;
@@ -5617,8 +5636,7 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5617
5636
  };
5618
5637
  }
5619
5638
  };
5620
- //#endregion
5621
- //#region src/storage/domains/channels/index.ts
5639
+ // src/storage/domains/channels/index.ts
5622
5640
  var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5623
5641
  #db;
5624
5642
  #schema;
@@ -5832,8 +5850,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5832
5850
  };
5833
5851
  }
5834
5852
  };
5835
- //#endregion
5836
- //#region src/storage/domains/datasets/index.ts
5853
+ // src/storage/domains/datasets/index.ts
5837
5854
  /** Serialize a value for a jsonb column. Returns null for null/undefined. */
5838
5855
  function jsonbArg(value) {
5839
5856
  return value === void 0 || value === null ? null : toPgJson(value);
@@ -7104,8 +7121,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
7104
7121
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_DATASETS });
7105
7122
  }
7106
7123
  };
7107
- //#endregion
7108
- //#region src/storage/domains/experiments/index.ts
7124
+ // src/storage/domains/experiments/index.ts
7109
7125
  const DEFAULT_PRUNE_BATCH_SIZE = 1e3;
7110
7126
  var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.ExperimentsStorage {
7111
7127
  #db;
@@ -8051,8 +8067,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
8051
8067
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_EXPERIMENTS });
8052
8068
  }
8053
8069
  };
8054
- //#endregion
8055
- //#region src/storage/domains/favorites/index.ts
8070
+ // src/storage/domains/favorites/index.ts
8056
8071
  /**
8057
8072
  * Maps a favorite entity type to its parent entity table.
8058
8073
  */
@@ -8324,8 +8339,7 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
8324
8339
  }
8325
8340
  }
8326
8341
  };
8327
- //#endregion
8328
- //#region ../../packages/_internal-core/dist/knowledge-compat/index.js
8342
+ // ../../packages/_internal-core/dist/knowledge-compat/index.js
8329
8343
  const KNOWLEDGE_V2_CORE_FEATURE = "knowledge-v2";
8330
8344
  /** Hard cap on scope nodes returned by one `listScopeNodes` read. */
8331
8345
  const MAX_KNOWLEDGE_SCOPE_NODES = 1e3;
@@ -8959,8 +8973,7 @@ function createKnowledgeV2CoreLoader(features, loadStorageModule) {
8959
8973
  return knowledgeV2Core;
8960
8974
  };
8961
8975
  }
8962
- //#endregion
8963
- //#region src/storage/domains/knowledge/index.ts
8976
+ // src/storage/domains/knowledge/index.ts
8964
8977
  const loadKnowledgeV2Core = createKnowledgeV2CoreLoader(_mastra_core_features.coreFeatures, () => import("@mastra/core/storage"));
8965
8978
  async function assertKnowledgeDescriptionWithinBoundCompat(description) {
8966
8979
  const { assertKnowledgeDescriptionWithinBound } = await loadKnowledgeV2Core();
@@ -10484,8 +10497,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
10484
10497
  });
10485
10498
  }
10486
10499
  };
10487
- //#endregion
10488
- //#region src/storage/domains/mcp-clients/index.ts
10500
+ // src/storage/domains/mcp-clients/index.ts
10489
10501
  const SNAPSHOT_FIELDS$5 = [
10490
10502
  "name",
10491
10503
  "description",
@@ -11046,8 +11058,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
11046
11058
  };
11047
11059
  }
11048
11060
  };
11049
- //#endregion
11050
- //#region src/storage/domains/mcp-servers/index.ts
11061
+ // src/storage/domains/mcp-servers/index.ts
11051
11062
  const SNAPSHOT_FIELDS$4 = [
11052
11063
  "name",
11053
11064
  "version",
@@ -11629,8 +11640,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
11629
11640
  };
11630
11641
  }
11631
11642
  };
11632
- //#endregion
11633
- //#region ../../packages/_internal-core/dist/memory/index.js
11643
+ // ../../packages/_internal-core/dist/memory/index.js
11634
11644
  /**
11635
11645
  * Shared rules for observational memory lifecycle writes. Every storage adapter applies
11636
11646
  * these inside its own atomic section (lock, transaction, or conditional update), so the
@@ -11715,8 +11725,7 @@ function isAppendOnlySince(storedObservations, snapshotObservations) {
11715
11725
  const snapshot = snapshotObservations ?? "";
11716
11726
  return stored === snapshot || stored.startsWith(snapshot);
11717
11727
  }
11718
- //#endregion
11719
- //#region src/storage/db/run-fencing.ts
11728
+ // src/storage/db/run-fencing.ts
11720
11729
  /**
11721
11730
  * Epoch milliseconds on the database clock. `clock_timestamp()` rather than
11722
11731
  * `now()`: a statement can wait on a row lock, and lease math must use the
@@ -11748,8 +11757,7 @@ function withRunFence(client, claimsTable, fence, operation, write) {
11748
11757
  return write(t);
11749
11758
  });
11750
11759
  }
11751
- //#endregion
11752
- //#region src/storage/domains/memory/index.ts
11760
+ // src/storage/domains/memory/index.ts
11753
11761
  /**
11754
11762
  * Local constant for the observational memory table name.
11755
11763
  * Defined locally to avoid a static import that crashes on older @mastra/core
@@ -14581,8 +14589,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
14581
14589
  }
14582
14590
  }
14583
14591
  };
14584
- //#endregion
14585
- //#region src/storage/domains/notifications/index.ts
14592
+ // src/storage/domains/notifications/index.ts
14586
14593
  const COMPOSITE_PRIMARY_KEY$1 = _mastra_core_storage.TABLE_CONFIGS[_mastra_core_storage.TABLE_NOTIFICATIONS].compositePrimaryKey;
14587
14594
  const statusTimestamp = (status, now) => {
14588
14595
  if (status === "delivered") return { deliveredAt: now };
@@ -15085,8 +15092,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
15085
15092
  return row ? rowToNotification(row) : void 0;
15086
15093
  }
15087
15094
  };
15088
- //#endregion
15089
- //#region src/storage/domains/observability/index.ts
15095
+ // src/storage/domains/observability/index.ts
15090
15096
  var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.ObservabilityStorage {
15091
15097
  /**
15092
15098
  * Retention-eligible tables. The observability domain has a single physical
@@ -15757,8 +15763,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
15757
15763
  }
15758
15764
  }
15759
15765
  };
15760
- //#endregion
15761
- //#region src/storage/domains/observability/v-next/signal-schema.ts
15766
+ // src/storage/domains/observability/v-next/signal-schema.ts
15762
15767
  const CURSOR_ID_COLUMN = {
15763
15768
  name: "cursorId",
15764
15769
  type: "bigserial"
@@ -16409,8 +16414,7 @@ const TEXT_ARRAY_COLUMNS = new Set(columnNamesByType(ALL_EVENT_COLUMNS, "text[]"
16409
16414
  const METRIC_TYPED_COLUMNS = typedColumnNames(METRIC_EVENT_COLUMNS);
16410
16415
  const SCORE_TYPED_COLUMNS = typedColumnNames(SCORE_EVENT_COLUMNS);
16411
16416
  const FEEDBACK_TYPED_COLUMNS = typedColumnNames(FEEDBACK_EVENT_COLUMNS);
16412
- //#endregion
16413
- //#region src/storage/domains/observability/v-next/ddl.ts
16417
+ // src/storage/domains/observability/v-next/ddl.ts
16414
16418
  /**
16415
16419
  * Raw DDL for Postgres v-next observability tables.
16416
16420
  *
@@ -16807,8 +16811,7 @@ function additiveColumns(schema) {
16807
16811
  function allIndexDDL(schema) {
16808
16812
  return tableIndexes().map((spec) => indexDDL(schema, spec));
16809
16813
  }
16810
- //#endregion
16811
- //#region src/storage/domains/observability/v-next/discovery.ts
16814
+ // src/storage/domains/observability/v-next/discovery.ts
16812
16815
  const DEFAULT_TTL_SECONDS = 300;
16813
16816
  const DEFAULT_LOOKBACK_SECONDS = 2592e3;
16814
16817
  /** All signal tables that contain a column. Used by cross-signal discovery. */
@@ -17043,8 +17046,7 @@ async function getMetricLabelValues(client, schema, args, config) {
17043
17046
  if (args.limit) filtered = filtered.slice(0, args.limit);
17044
17047
  return { values: filtered };
17045
17048
  }
17046
- //#endregion
17047
- //#region src/storage/domains/observability/v-next/filters.ts
17049
+ // src/storage/domains/observability/v-next/filters.ts
17048
17050
  function newFilterAccumulator(startIndex = 1) {
17049
17051
  return {
17050
17052
  conditions: [],
@@ -17119,8 +17121,7 @@ function applySingleOrArrayFilter(acc, column, value, prefix = "") {
17119
17121
  function whereOrEmpty(acc) {
17120
17122
  return acc.conditions.length ? `WHERE ${acc.conditions.join(" AND ")}` : "";
17121
17123
  }
17122
- //#endregion
17123
- //#region src/storage/domains/observability/v-next/preview-compat.ts
17124
+ // src/storage/domains/observability/v-next/preview-compat.ts
17124
17125
  const generator = _mastra_core_storage.buildStoredPreview;
17125
17126
  const canGeneratePreviews = typeof generator === "function";
17126
17127
  /** SQL detection only; preview formatting stays in TypeScript. Empty strings are intentional. */
@@ -17177,8 +17178,7 @@ function buildSpanQueryResponse(...args) {
17177
17178
  }
17178
17179
  return response;
17179
17180
  }
17180
- //#endregion
17181
- //#region src/storage/domains/observability/v-next/review-status.ts
17181
+ // src/storage/domains/observability/v-next/review-status.ts
17182
17182
  const FEEDBACK_REVIEW_STATUSES = ["needs-review", "reviewed"];
17183
17183
  function isFeedbackReviewStatus(value) {
17184
17184
  return FEEDBACK_REVIEW_STATUSES.some((status) => status === value);
@@ -17202,8 +17202,7 @@ function parseUpdateFeedbackReviewStatusArgs(args) {
17202
17202
  reviewStatus: args.reviewStatus
17203
17203
  };
17204
17204
  }
17205
- //#endregion
17206
- //#region src/storage/domains/observability/v-next/sql.ts
17205
+ // src/storage/domains/observability/v-next/sql.ts
17207
17206
  /**
17208
17207
  * SQL helpers for the v-next Postgres observability domain.
17209
17208
  *
@@ -17333,8 +17332,7 @@ const SCORE_SELECT_COLUMNS = `
17333
17332
  ${buildSelectColumns(SCORE_EVENT_COLUMNS)}`;
17334
17333
  const FEEDBACK_SELECT_COLUMNS = `
17335
17334
  ${buildSelectColumns(FEEDBACK_EVENT_COLUMNS)}`;
17336
- //#endregion
17337
- //#region src/storage/domains/observability/v-next/helpers.ts
17335
+ // src/storage/domains/observability/v-next/helpers.ts
17338
17336
  const PROMOTED_KEYS = /* @__PURE__ */ new Set([
17339
17337
  "experimentId",
17340
17338
  "entityType",
@@ -17771,8 +17769,7 @@ function rowToFeedbackRecord(row) {
17771
17769
  scope: parsedJson(row.scope) ?? void 0
17772
17770
  };
17773
17771
  }
17774
- //#endregion
17775
- //#region src/storage/domains/observability/v-next/polling.ts
17772
+ // src/storage/domains/observability/v-next/polling.ts
17776
17773
  /**
17777
17774
  * Delta-polling helpers for the v-next Postgres observability domain.
17778
17775
  *
@@ -17841,8 +17838,7 @@ function decodeDeltaCursor(cursor) {
17841
17838
  async function readSafeXactHorizon(client) {
17842
17839
  return validatePgInteger((await client.one(`SELECT pg_snapshot_xmin(pg_current_snapshot())::text AS "xactId"`)).xactId);
17843
17840
  }
17844
- //#endregion
17845
- //#region src/storage/domains/observability/v-next/listing.ts
17841
+ // src/storage/domains/observability/v-next/listing.ts
17846
17842
  function responseItems(key, items) {
17847
17843
  return { [key]: items };
17848
17844
  }
@@ -17929,8 +17925,7 @@ async function listSignalDelta(config) {
17929
17925
  deltaCursor
17930
17926
  };
17931
17927
  }
17932
- //#endregion
17933
- //#region src/storage/domains/observability/v-next/olap.ts
17928
+ // src/storage/domains/observability/v-next/olap.ts
17934
17929
  /**
17935
17930
  * Shared OLAP helpers for the v-next Postgres observability domain.
17936
17931
  *
@@ -18134,8 +18129,7 @@ const COMPLEX_GROUP_BY_EXCLUDED = /* @__PURE__ */ new Set([
18134
18129
  "tags",
18135
18130
  "requestContext"
18136
18131
  ]);
18137
- //#endregion
18138
- //#region src/storage/domains/observability/v-next/feedback.ts
18132
+ // src/storage/domains/observability/v-next/feedback.ts
18139
18133
  /**
18140
18134
  * Feedback operations for the v-next Postgres observability domain.
18141
18135
  *
@@ -18373,8 +18367,7 @@ async function getFeedbackPercentiles(client, schema, args) {
18373
18367
  `;
18374
18368
  return { series: percentileSeriesFromRows(await client.manyOrNone(sql, acc.params), args.percentiles) };
18375
18369
  }
18376
- //#endregion
18377
- //#region src/storage/domains/observability/v-next/logs.ts
18370
+ // src/storage/domains/observability/v-next/logs.ts
18378
18371
  /**
18379
18372
  * Log operations for the v-next Postgres observability domain.
18380
18373
  */
@@ -18426,8 +18419,7 @@ async function listLogsDelta(client, table, filters, after, limit) {
18426
18419
  mapRow: rowToLogRecord
18427
18420
  });
18428
18421
  }
18429
- //#endregion
18430
- //#region src/storage/domains/observability/v-next/metrics.ts
18422
+ // src/storage/domains/observability/v-next/metrics.ts
18431
18423
  /**
18432
18424
  * Metric operations for the v-next Postgres observability domain.
18433
18425
  *
@@ -18664,8 +18656,7 @@ async function getMetricPercentiles(client, schema, args) {
18664
18656
  `;
18665
18657
  return { series: percentileSeriesFromRows(await client.manyOrNone(sql, acc.params), args.percentiles) };
18666
18658
  }
18667
- //#endregion
18668
- //#region src/storage/domains/observability/v-next/partitioning.ts
18659
+ // src/storage/domains/observability/v-next/partitioning.ts
18669
18660
  const DEFAULT_FUTURE_DAYS = 14;
18670
18661
  async function detectTimescale(client) {
18671
18662
  const row = await client.oneOrNone(`SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'timescaledb') AS "exists"`);
@@ -18824,8 +18815,7 @@ async function setupPartitioning(client, schema, options = {}) {
18824
18815
  return "native";
18825
18816
  }
18826
18817
  }
18827
- //#endregion
18828
- //#region src/storage/domains/observability/v-next/retention.ts
18818
+ // src/storage/domains/observability/v-next/retention.ts
18829
18819
  /**
18830
18820
  * Age-based retention for the v-next Postgres observability domain.
18831
18821
  *
@@ -18945,8 +18935,7 @@ async function pruneTimescaleTable({ client, schema, table, cutoff, options }) {
18945
18935
  done: true
18946
18936
  };
18947
18937
  }
18948
- //#endregion
18949
- //#region src/storage/domains/observability/v-next/scores.ts
18938
+ // src/storage/domains/observability/v-next/scores.ts
18950
18939
  /**
18951
18940
  * Score operations for the v-next Postgres observability domain.
18952
18941
  *
@@ -19225,8 +19214,7 @@ async function getScorePercentiles(client, schema, args) {
19225
19214
  `;
19226
19215
  return { series: percentileSeriesFromRows(await client.manyOrNone(sql, acc.params), args.percentiles) };
19227
19216
  }
19228
- //#endregion
19229
- //#region src/storage/domains/observability/v-next/trace-query.ts
19217
+ // src/storage/domains/observability/v-next/trace-query.ts
19230
19218
  const TRACE_STATUS_SQL = `CASE WHEN r."error" IS NOT NULL THEN 'error' ELSE 'success' END`;
19231
19219
  /** Core versions without the field reject it in strict query results, so it is only returned when core knows it. */
19232
19220
  const timeToFirstChunkSupported = "timeToFirstChunkMs" in _mastra_core_storage.TRACE_QUERY_FIELD_REGISTRY.trace;
@@ -20218,8 +20206,7 @@ function compileSpanQueryPredicate(predicate, offset) {
20218
20206
  function compileThreadQueryPredicate(predicate, offset) {
20219
20207
  return compileScalarPredicate(predicate, Object.fromEntries(Object.keys(_mastra_core_storage.THREAD_QUERY_FIELD_REGISTRY).map((field) => [field, `s."${field}"`])), offset);
20220
20208
  }
20221
- //#endregion
20222
- //#region src/storage/domains/observability/v-next/span-query.ts
20209
+ // src/storage/domains/observability/v-next/span-query.ts
20223
20210
  const identityFields = [
20224
20211
  "organizationId",
20225
20212
  "resourceId",
@@ -20432,8 +20419,7 @@ async function querySpans(client, schema, plan, timeoutMs) {
20432
20419
  return buildSpanQueryResponse(plan, hydrated, payloads, metrics);
20433
20420
  }, { repeatableRead: true });
20434
20421
  }
20435
- //#endregion
20436
- //#region src/storage/domains/observability/v-next/thread-query.ts
20422
+ // src/storage/domains/observability/v-next/thread-query.ts
20437
20423
  const contextFields = [
20438
20424
  "resourceId",
20439
20425
  "userId",
@@ -20664,8 +20650,7 @@ async function queryThreadRows(client, schema, plan, timeoutMs, strategy = "auto
20664
20650
  }) : null }
20665
20651
  };
20666
20652
  }
20667
- //#endregion
20668
- //#region src/storage/domains/observability/v-next/trace-aggregate.ts
20653
+ // src/storage/domains/observability/v-next/trace-aggregate.ts
20669
20654
  /** Trace-root column expressions (alias `r`) for each groupable dimension; same values `where` sees. */
20670
20655
  const DIMENSION_SQL = {
20671
20656
  entityType: "r.\"entityType\"",
@@ -20991,8 +20976,7 @@ async function runAggregate(client, plan, compiled, timeoutMs) {
20991
20976
  truncated
20992
20977
  };
20993
20978
  }
20994
- //#endregion
20995
- //#region src/storage/domains/observability/v-next/traces.ts
20979
+ // src/storage/domains/observability/v-next/traces.ts
20996
20980
  /**
20997
20981
  * Trace / branch list reads for the v-next Postgres observability domain.
20998
20982
  *
@@ -21606,8 +21590,7 @@ async function listBranchesDelta(client, span, filters, after, limit) {
21606
21590
  async function readBranchesStreamHeadCursor(client, span, filters) {
21607
21591
  return encodeDeltaCursor(await readSafeXactHorizon(client), 0);
21608
21592
  }
21609
- //#endregion
21610
- //#region src/storage/domains/observability/v-next/tracing.ts
21593
+ // src/storage/domains/observability/v-next/tracing.ts
21611
21594
  async function writeSpanRows(client, schema, rows) {
21612
21595
  const deduped = dedupeSpanRows(rows);
21613
21596
  const insert = buildInsert(schema, TABLE_SPAN_EVENTS, deduped, spanConflictClause(Object.keys(deduped[0] ?? {})));
@@ -21736,8 +21719,7 @@ async function dangerouslyClearTracing(client, schema) {
21736
21719
  const span = qualifiedTable(schema, TABLE_SPAN_EVENTS);
21737
21720
  await client.none(`TRUNCATE TABLE ${span} RESTART IDENTITY`);
21738
21721
  }
21739
- //#endregion
21740
- //#region src/storage/domains/observability/v-next/index.ts
21722
+ // src/storage/domains/observability/v-next/index.ts
21741
21723
  /**
21742
21724
  * Postgres v-next observability storage domain.
21743
21725
  *
@@ -21825,7 +21807,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
21825
21807
  else if (await detectPartman(this.#client)) mode = "partman";
21826
21808
  else mode = "native";
21827
21809
  const ddlMode = mode === "timescale" ? "timescale" : "partitioned";
21828
- try {
21810
+ if (!await this.#client.oneOrNone("SELECT 1 FROM information_schema.schemata WHERE schema_name = $1", [this.#schema])) try {
21829
21811
  await this.#client.none(schemaDDL(this.#schema));
21830
21812
  } catch (error) {
21831
21813
  if (!isDuplicateSchemaError(error)) throw error;
@@ -22176,8 +22158,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
22176
22158
  }
22177
22159
  }
22178
22160
  };
22179
- //#endregion
22180
- //#region src/storage/domains/prompt-blocks/index.ts
22161
+ // src/storage/domains/prompt-blocks/index.ts
22181
22162
  const SNAPSHOT_FIELDS$3 = [
22182
22163
  "name",
22183
22164
  "description",
@@ -22754,8 +22735,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
22754
22735
  };
22755
22736
  }
22756
22737
  };
22757
- //#endregion
22758
- //#region src/storage/domains/schedules/index.ts
22738
+ // src/storage/domains/schedules/index.ts
22759
22739
  function getSchemaName$2(schema) {
22760
22740
  return schema ? `"${schema}"` : "\"public\"";
22761
22741
  }
@@ -23123,8 +23103,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
23123
23103
  ${limitClause}`, params)).map(rowToTrigger);
23124
23104
  }
23125
23105
  };
23126
- //#endregion
23127
- //#region src/storage/domains/scorer-definitions/index.ts
23106
+ // src/storage/domains/scorer-definitions/index.ts
23128
23107
  const SNAPSHOT_FIELDS$2 = [
23129
23108
  "name",
23130
23109
  "description",
@@ -23724,8 +23703,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
23724
23703
  };
23725
23704
  }
23726
23705
  };
23727
- //#endregion
23728
- //#region src/storage/domains/scores/index.ts
23706
+ // src/storage/domains/scores/index.ts
23729
23707
  /**
23730
23708
  * Appends multi-tenant scope conditions to a query. Mutates `conditions`/`queryParams`.
23731
23709
  * Returns the next positional parameter index.
@@ -24187,8 +24165,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
24187
24165
  }
24188
24166
  }
24189
24167
  };
24190
- //#endregion
24191
- //#region src/storage/domains/skills/index.ts
24168
+ // src/storage/domains/skills/index.ts
24192
24169
  const SNAPSHOT_FIELDS$1 = [
24193
24170
  "name",
24194
24171
  "description",
@@ -24884,8 +24861,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
24884
24861
  };
24885
24862
  }
24886
24863
  };
24887
- //#endregion
24888
- //#region src/storage/domains/thread-state/index.ts
24864
+ // src/storage/domains/thread-state/index.ts
24889
24865
  const COMPOSITE_PRIMARY_KEY = ["threadId", "type"];
24890
24866
  /**
24891
24867
  * PostgreSQL implementation of {@link ThreadStateStorage}.
@@ -25050,8 +25026,7 @@ var ThreadStatePG = class ThreadStatePG extends _mastra_core_storage.ThreadState
25050
25026
  }
25051
25027
  }
25052
25028
  };
25053
- //#endregion
25054
- //#region src/storage/domains/tool-provider-connections/index.ts
25029
+ // src/storage/domains/tool-provider-connections/index.ts
25055
25030
  function normaliseScope(raw) {
25056
25031
  const value = raw == null ? "per-author" : String(raw);
25057
25032
  if (value === "shared") return "shared";
@@ -25306,8 +25281,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
25306
25281
  }
25307
25282
  }
25308
25283
  };
25309
- //#endregion
25310
- //#region src/storage/domains/workflow-definitions/index.ts
25284
+ // src/storage/domains/workflow-definitions/index.ts
25311
25285
  function rowToDefinition(row) {
25312
25286
  const inputSchema = parseJsonResilient(row.inputSchema);
25313
25287
  const outputSchema = parseJsonResilient(row.outputSchema);
@@ -25507,8 +25481,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
25507
25481
  await this.#db.client.none(`DELETE FROM ${tableName} WHERE "id" = $1`, [id]);
25508
25482
  }
25509
25483
  };
25510
- //#endregion
25511
- //#region src/storage/domains/workflows/index.ts
25484
+ // src/storage/domains/workflows/index.ts
25512
25485
  function getSchemaName(schema) {
25513
25486
  return schema ? `"${schema}"` : "\"public\"";
25514
25487
  }
@@ -26237,8 +26210,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
26237
26210
  }
26238
26211
  }
26239
26212
  };
26240
- //#endregion
26241
- //#region src/storage/domains/workspaces/index.ts
26213
+ // src/storage/domains/workspaces/index.ts
26242
26214
  const SNAPSHOT_FIELDS = [
26243
26215
  "name",
26244
26216
  "description",
@@ -26859,8 +26831,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
26859
26831
  };
26860
26832
  }
26861
26833
  };
26862
- //#endregion
26863
- //#region src/storage/factory-storage.ts
26834
+ // src/storage/factory-storage.ts
26864
26835
  const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
26865
26836
  const PG_UNIQUE_VIOLATION = "23505";
26866
26837
  const COLUMN_DDL = {
@@ -27152,38 +27123,6 @@ var PgFactoryStorageOps = class {
27152
27123
  * Supports serializable app-table transactions for cross-replica invariant
27153
27124
  * enforcement and `authDatabase()` exposing the shared pool.
27154
27125
  */
27155
- /**
27156
- * A pool-level `error` listener only covers *idle* clients: pg hands ownership
27157
- * of a client to the borrower for the duration of a checkout and takes its own
27158
- * listener off. So a backend restart or network blip that lands on a client
27159
- * mid-transaction reaches an emitter with no listener, and Node escalates that
27160
- * to an uncaughtException that kills the process — the pool handler logs the
27161
- * idle siblings and the borrowed one still brings everything down.
27162
- *
27163
- * Attach a listener once per physical connection instead. `connect` fires when
27164
- * the pool establishes a client, so the client stays covered for its whole life
27165
- * and there is nothing to remove on release.
27166
- *
27167
- * That listener outlives the checkout, so it also sees the failures the pool is
27168
- * already reporting through its own idle listener. Follow `acquire`/`release`
27169
- * to tell the two apart and stay quiet while the client is idle — otherwise one
27170
- * dropped connection is announced twice, the second time as the wrong thing.
27171
- *
27172
- * The pool still discards the failed connection; this only keeps the failure
27173
- * reportable instead of fatal.
27174
- */
27175
- function guardCheckedOutClientErrors(pool, warn = console.warn) {
27176
- const borrowed = /* @__PURE__ */ new WeakSet();
27177
- pool.on("connect", (client) => {
27178
- borrowed.add(client);
27179
- client.on("error", (err) => {
27180
- if (!borrowed.has(client)) return;
27181
- warn(`PgFactoryStorage: client error while checked out (the pool discards this connection): ${err instanceof Error ? err.message : String(err)}`);
27182
- });
27183
- });
27184
- pool.on("acquire", (client) => borrowed.add(client));
27185
- pool.on("release", (_err, client) => borrowed.delete(client));
27186
- }
27187
27126
  var PgFactoryStorage = class extends _mastra_core_storage.FactoryStorage {
27188
27127
  ops;
27189
27128
  #pool;
@@ -27309,8 +27248,7 @@ var PgFactoryStorage = class extends _mastra_core_storage.FactoryStorage {
27309
27248
  }
27310
27249
  }
27311
27250
  };
27312
- //#endregion
27313
- //#region src/storage/index.ts
27251
+ // src/storage/index.ts
27314
27252
  /** Default maximum number of connections in the pool */
27315
27253
  const DEFAULT_MAX_CONNECTIONS = 20;
27316
27254
  /** Default idle timeout in milliseconds */
@@ -27482,6 +27420,7 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
27482
27420
  pool.on("error", (err) => {
27483
27421
  this.logger?.warn?.("PostgresStore: idle pool client error (pool discards the client and reconnects on next checkout)", { err: err instanceof Error ? err.message : err });
27484
27422
  });
27423
+ guardCheckedOutClientErrors(pool, (message) => this.logger?.warn?.(message));
27485
27424
  return pool;
27486
27425
  }
27487
27426
  #buildPool(config) {
@@ -27621,9 +27560,12 @@ var PostgresStoreVNext = class extends PostgresStore {
27621
27560
  const observabilityClient = built.client;
27622
27561
  this.#observabilityPool = built.pool;
27623
27562
  this.#ownsObservabilityPool = built.owned;
27624
- if (built.owned) built.pool.on("error", (err) => {
27625
- 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 });
27626
- });
27563
+ if (built.owned) {
27564
+ guardCheckedOutClientErrors(built.pool, (message) => this.logger?.warn?.(message));
27565
+ built.pool.on("error", (err) => {
27566
+ 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 });
27567
+ });
27568
+ }
27627
27569
  const observability = new ObservabilityStoragePostgresVNext({
27628
27570
  client: observabilityClient,
27629
27571
  schemaName: obsConfig.schemaName ?? config.schemaName,
@@ -27677,8 +27619,7 @@ var PostgresStoreVNext = class extends PostgresStore {
27677
27619
  }
27678
27620
  }
27679
27621
  };
27680
- //#endregion
27681
- //#region src/vector/prompt.ts
27622
+ // src/vector/prompt.ts
27682
27623
  /**
27683
27624
  * Vector store specific prompt that details supported operators and examples.
27684
27625
  * This prompt helps users construct valid filters for PG Vector.
@@ -27780,7 +27721,6 @@ Example Complex Query:
27780
27721
  ]}
27781
27722
  ]
27782
27723
  }`;
27783
- //#endregion
27784
27724
  exports.AgentsPG = AgentsPG;
27785
27725
  exports.BackgroundTasksPG = BackgroundTasksPG;
27786
27726
  exports.BlobsPG = BlobsPG;