@mastra/pg 1.23.0-alpha.0 → 1.23.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 (33) hide show
  1. package/dist/docs/SKILL.md +1 -1
  2. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  3. package/dist/index.cjs +492 -273
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.js +492 -273
  6. package/dist/index.js.map +1 -1
  7. package/dist/shared/config.d.ts +12 -2
  8. package/dist/shared/config.d.ts.map +1 -1
  9. package/dist/storage/db/index.d.ts +9 -2
  10. package/dist/storage/db/index.d.ts.map +1 -1
  11. package/dist/storage/domains/agents/index.d.ts.map +1 -1
  12. package/dist/storage/domains/datasets/index.d.ts +6 -1
  13. package/dist/storage/domains/datasets/index.d.ts.map +1 -1
  14. package/dist/storage/domains/experiments/index.d.ts +2 -2
  15. package/dist/storage/domains/experiments/index.d.ts.map +1 -1
  16. package/dist/storage/domains/knowledge/index.d.ts.map +1 -1
  17. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -1
  18. package/dist/storage/domains/mcp-servers/index.d.ts.map +1 -1
  19. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  20. package/dist/storage/domains/notifications/index.d.ts.map +1 -1
  21. package/dist/storage/domains/observability/index.d.ts.map +1 -1
  22. package/dist/storage/domains/observability/v-next/index.d.ts.map +1 -1
  23. package/dist/storage/domains/observability/v-next/tracing.d.ts +7 -0
  24. package/dist/storage/domains/observability/v-next/tracing.d.ts.map +1 -1
  25. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -1
  26. package/dist/storage/domains/schedules/index.d.ts.map +1 -1
  27. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -1
  28. package/dist/storage/domains/skills/index.d.ts.map +1 -1
  29. package/dist/storage/domains/workflow-definitions/index.d.ts.map +1 -1
  30. package/dist/storage/domains/workspaces/index.d.ts.map +1 -1
  31. package/dist/storage/index.d.ts +7 -5
  32. package/dist/storage/index.d.ts.map +1 -1
  33. package/package.json +3 -3
package/dist/index.cjs CHANGED
@@ -44,7 +44,11 @@ let _mastra_core_storage_domains_skills = require("@mastra/core/storage/domains/
44
44
  * Type guard for pre-configured pg.Pool config
45
45
  */
46
46
  const isPoolConfig = (cfg) => {
47
- return "pool" in cfg;
47
+ return "pool" in cfg && cfg.pool !== void 0;
48
+ };
49
+ /** Type guard for an explicitly named pre-configured writer pool. */
50
+ const isWritePoolConfig = (cfg) => {
51
+ return "writePool" in cfg && cfg.writePool !== void 0;
48
52
  };
49
53
  /**
50
54
  * Type guard for connection string config
@@ -69,10 +73,8 @@ const isCloudSqlConfig = (cfg) => {
69
73
  */
70
74
  const validateConfig = (name, config) => {
71
75
  if (!config.id || typeof config.id !== "string" || config.id.trim() === "") throw new Error(`${name}: id must be provided and cannot be empty.`);
72
- if (isPoolConfig(config)) {
73
- if (!config.pool) throw new Error(`${name}: pool must be provided when using pool config.`);
74
- return;
75
- }
76
+ if ("pool" in config && "writePool" in config) throw new Error(`${name}: provide either pool or writePool, not both.`);
77
+ if (isPoolConfig(config) || isWritePoolConfig(config)) return;
76
78
  if (isConnectionStringConfig(config)) {
77
79
  if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") throw new Error(`${name}: connectionString must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults.`);
78
80
  } else if (isCloudSqlConfig(config)) {} else if (isHostConfig(config)) {
@@ -2383,16 +2385,21 @@ async function loadSchemaSnapshot(client, schemaName) {
2383
2385
  function resolvePgConfig(config) {
2384
2386
  if ("client" in config) return {
2385
2387
  client: config.client,
2388
+ readClient: config.readClient ?? config.client,
2386
2389
  schemaName: config.schemaName,
2387
2390
  skipDefaultIndexes: config.skipDefaultIndexes,
2388
2391
  indexes: config.indexes
2389
2392
  };
2390
- if ("pool" in config) return {
2391
- client: new PoolAdapter(config.pool),
2392
- schemaName: config.schemaName,
2393
- skipDefaultIndexes: config.skipDefaultIndexes,
2394
- indexes: config.indexes
2395
- };
2393
+ if ("pool" in config) {
2394
+ const client = new PoolAdapter(config.pool);
2395
+ return {
2396
+ client,
2397
+ readClient: config.readPool && config.readPool !== config.pool ? new PoolAdapter(config.readPool) : client,
2398
+ schemaName: config.schemaName,
2399
+ skipDefaultIndexes: config.skipDefaultIndexes,
2400
+ indexes: config.indexes
2401
+ };
2402
+ }
2396
2403
  let pool;
2397
2404
  if ("connectionString" in config) pool = new pg.Pool({
2398
2405
  connectionString: config.connectionString,
@@ -2409,8 +2416,10 @@ function resolvePgConfig(config) {
2409
2416
  pool.on("error", (err) => {
2410
2417
  console.warn(`resolvePgConfig: idle pool client error (pool discards the client and reconnects on next checkout): ${err instanceof Error ? err.message : String(err)}`);
2411
2418
  });
2419
+ const client = new PoolAdapter(pool);
2412
2420
  return {
2413
- client: new PoolAdapter(pool),
2421
+ client,
2422
+ readClient: client,
2414
2423
  schemaName: config.schemaName,
2415
2424
  skipDefaultIndexes: config.skipDefaultIndexes,
2416
2425
  indexes: config.indexes
@@ -2618,6 +2627,7 @@ function assertPositiveLimit(limit) {
2618
2627
  }
2619
2628
  var PgDB = class extends _mastra_core_base.MastraBase {
2620
2629
  client;
2630
+ readClient;
2621
2631
  schemaName;
2622
2632
  skipDefaultIndexes;
2623
2633
  /** Cache of actual table columns: tableName -> Set<columnName> */
@@ -2630,6 +2640,7 @@ var PgDB = class extends _mastra_core_base.MastraBase {
2630
2640
  name: "PG_DB_LAYER"
2631
2641
  });
2632
2642
  this.client = config.client;
2643
+ this.readClient = config.readClient ?? config.client;
2633
2644
  this.schemaName = config.schemaName;
2634
2645
  this.skipDefaultIndexes = config.skipDefaultIndexes;
2635
2646
  }
@@ -3885,9 +3896,10 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
3885
3896
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_AGENTS, _mastra_core_storage.TABLE_AGENT_VERSIONS];
3886
3897
  constructor(config) {
3887
3898
  super();
3888
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
3899
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
3889
3900
  this.#db = new PgDB({
3890
3901
  client,
3902
+ readClient,
3891
3903
  schemaName,
3892
3904
  skipDefaultIndexes
3893
3905
  });
@@ -4146,12 +4158,19 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4146
4158
  };
4147
4159
  }
4148
4160
  async getById(id) {
4161
+ return this.#getById(this.#db.readClient, id);
4162
+ }
4163
+ /**
4164
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
4165
+ * lagging read replica cannot yield stale or missing rows mid-update.
4166
+ */
4167
+ async #getById(client, id) {
4149
4168
  try {
4150
4169
  const tableName = getTableName$5({
4151
4170
  indexName: _mastra_core_storage.TABLE_AGENTS,
4152
4171
  schemaName: getSchemaName$5(this.#schema)
4153
4172
  });
4154
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4173
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4155
4174
  if (!result) return null;
4156
4175
  return this.parseRow(result);
4157
4176
  } catch (error) {
@@ -4236,7 +4255,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4236
4255
  indexName: _mastra_core_storage.TABLE_AGENTS,
4237
4256
  schemaName: getSchemaName$5(this.#schema)
4238
4257
  });
4239
- if (!await this.getById(id)) throw new _mastra_core_error.MastraError({
4258
+ if (!await this.#getById(this.#db.client, id)) throw new _mastra_core_error.MastraError({
4240
4259
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_AGENT", "NOT_FOUND"),
4241
4260
  domain: _mastra_core_error.ErrorDomain.STORAGE,
4242
4261
  category: _mastra_core_error.ErrorCategory.USER,
@@ -4274,7 +4293,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4274
4293
  values.push(now);
4275
4294
  values.push(id);
4276
4295
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
4277
- const updatedAgent = await this.getById(id);
4296
+ const updatedAgent = await this.#getById(this.#db.client, id);
4278
4297
  if (!updatedAgent) throw new _mastra_core_error.MastraError({
4279
4298
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_AGENT", "NOT_FOUND_AFTER_UPDATE"),
4280
4299
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -4371,7 +4390,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4371
4390
  const joinClause = useJoin && joinSqlIdx !== null ? `LEFT JOIN ${favoritesTable} s ON s."entityType" = 'agent' AND s."entityId" = a.id AND s."userId" = $${joinSqlIdx}` : "";
4372
4391
  const joinParams = useJoin && joinUserId ? [joinUserId] : [];
4373
4392
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
4374
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} a ${joinClause} ${whereClause}`, [...joinParams, ...queryParams]);
4393
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} a ${joinClause} ${whereClause}`, [...joinParams, ...queryParams]);
4375
4394
  const total = parseInt(countResult.count, 10);
4376
4395
  if (total === 0) return {
4377
4396
  agents: [],
@@ -4389,7 +4408,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4389
4408
  const limitIdx = paramIdx++;
4390
4409
  const offsetIdx = paramIdx++;
4391
4410
  return {
4392
- agents: (await this.#db.client.manyOrNone(`SELECT a.* FROM ${tableName} a ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
4411
+ agents: (await this.#db.readClient.manyOrNone(`SELECT a.* FROM ${tableName} a ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
4393
4412
  ...joinParams,
4394
4413
  ...queryParams,
4395
4414
  limitValue,
@@ -4489,7 +4508,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4489
4508
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4490
4509
  schemaName: getSchemaName$5(this.#schema)
4491
4510
  });
4492
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4511
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4493
4512
  if (!result) return null;
4494
4513
  return this.parseVersionRow(result);
4495
4514
  } catch (error) {
@@ -4510,7 +4529,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4510
4529
  schemaName: getSchemaName$5(this.#schema)
4511
4530
  });
4512
4531
  const placeholders = ids.map((_, i) => `$${i + 1}`).join(", ");
4513
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE id IN (${placeholders})`, ids)).map((row) => this.parseVersionRow(row));
4532
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE id IN (${placeholders})`, ids)).map((row) => this.parseVersionRow(row));
4514
4533
  } catch (error) {
4515
4534
  if (error instanceof _mastra_core_error.MastraError) throw error;
4516
4535
  throw new _mastra_core_error.MastraError({
@@ -4527,7 +4546,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4527
4546
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4528
4547
  schemaName: getSchemaName$5(this.#schema)
4529
4548
  });
4530
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 AND "versionNumber" = $2`, [agentId, versionNumber]);
4549
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 AND "versionNumber" = $2`, [agentId, versionNumber]);
4531
4550
  if (!result) return null;
4532
4551
  return this.parseVersionRow(result);
4533
4552
  } catch (error) {
@@ -4549,7 +4568,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4549
4568
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4550
4569
  schemaName: getSchemaName$5(this.#schema)
4551
4570
  });
4552
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [agentId]);
4571
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [agentId]);
4553
4572
  if (!result) return null;
4554
4573
  return this.parseVersionRow(result);
4555
4574
  } catch (error) {
@@ -4578,7 +4597,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4578
4597
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4579
4598
  schemaName: getSchemaName$5(this.#schema)
4580
4599
  });
4581
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4600
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4582
4601
  const total = parseInt(countResult.count, 10);
4583
4602
  if (total === 0) return {
4584
4603
  versions: [],
@@ -4589,7 +4608,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4589
4608
  };
4590
4609
  const limitValue = perPageInput === false ? total : perPage;
4591
4610
  return {
4592
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
4611
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
4593
4612
  agentId,
4594
4613
  limitValue,
4595
4614
  offset
@@ -4659,7 +4678,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4659
4678
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4660
4679
  schemaName: getSchemaName$5(this.#schema)
4661
4680
  });
4662
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4681
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4663
4682
  return parseInt(result.count, 10);
4664
4683
  } catch (error) {
4665
4684
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -4916,9 +4935,10 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
4916
4935
  } };
4917
4936
  constructor(config) {
4918
4937
  super();
4919
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
4938
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
4920
4939
  this.#db = new PgDB({
4921
4940
  client,
4941
+ readClient,
4922
4942
  schemaName,
4923
4943
  skipDefaultIndexes
4924
4944
  });
@@ -5170,7 +5190,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5170
5190
  params.push(filter.toDate.toISOString());
5171
5191
  }
5172
5192
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5173
- const countResult = await this.#db.client.oneOrNone(`SELECT COUNT(*) as count FROM ${table} ${where}`, params.slice(0, paramIdx - 1));
5193
+ const countResult = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) as count FROM ${table} ${where}`, params.slice(0, paramIdx - 1));
5174
5194
  const total = Number(countResult?.count ?? 0);
5175
5195
  let sql = `SELECT * FROM ${table} ${where} ORDER BY ${filter.orderBy === "startedAt" ? "\"startedAt\"" : filter.orderBy === "suspendedAt" ? "\"suspendedAt\"" : filter.orderBy === "completedAt" ? "\"completedAt\"" : "\"createdAt\""} ${filter.orderDirection === "desc" ? "DESC" : "ASC"}`;
5176
5196
  if (filter.perPage != null) {
@@ -5182,7 +5202,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5182
5202
  }
5183
5203
  }
5184
5204
  return {
5185
- tasks: (await this.#db.client.manyOrNone(sql, params)).map(rowToTask),
5205
+ tasks: (await this.#db.readClient.manyOrNone(sql, params)).map(rowToTask),
5186
5206
  total
5187
5207
  };
5188
5208
  }
@@ -5219,12 +5239,12 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5219
5239
  }
5220
5240
  async getRunningCount() {
5221
5241
  const table = getTableName$4(getSchemaName$4(this.#schema));
5222
- const result = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${table} WHERE "status" = 'running'`);
5242
+ const result = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${table} WHERE "status" = 'running'`);
5223
5243
  return Number(result?.count ?? 0);
5224
5244
  }
5225
5245
  async getRunningCountByAgent(agentId) {
5226
5246
  const table = getTableName$4(getSchemaName$4(this.#schema));
5227
- const result = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${table} WHERE "status" = 'running' AND "agent_id" = $1`, [agentId]);
5247
+ const result = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${table} WHERE "status" = 'running' AND "agent_id" = $1`, [agentId]);
5228
5248
  return Number(result?.count ?? 0);
5229
5249
  }
5230
5250
  };
@@ -5236,9 +5256,10 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5236
5256
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SKILL_BLOBS];
5237
5257
  constructor(config) {
5238
5258
  super();
5239
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
5259
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
5240
5260
  this.#db = new PgDB({
5241
5261
  client,
5262
+ readClient,
5242
5263
  schemaName,
5243
5264
  skipDefaultIndexes
5244
5265
  });
@@ -5280,7 +5301,7 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5280
5301
  indexName: _mastra_core_storage.TABLE_SKILL_BLOBS,
5281
5302
  schemaName: getSchemaName$5(this.#schema)
5282
5303
  });
5283
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "hash" = $1`, [hash]);
5304
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "hash" = $1`, [hash]);
5284
5305
  if (!row) return null;
5285
5306
  return this.#parseRow(row);
5286
5307
  }
@@ -5289,7 +5310,7 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5289
5310
  indexName: _mastra_core_storage.TABLE_SKILL_BLOBS,
5290
5311
  schemaName: getSchemaName$5(this.#schema)
5291
5312
  });
5292
- return await this.#db.client.oneOrNone(`SELECT 1 FROM ${tableName} WHERE "hash" = $1 LIMIT 1`, [hash]) !== null;
5313
+ return await this.#db.readClient.oneOrNone(`SELECT 1 FROM ${tableName} WHERE "hash" = $1 LIMIT 1`, [hash]) !== null;
5293
5314
  }
5294
5315
  async delete(hash) {
5295
5316
  const tableName = getTableName$5({
@@ -5310,7 +5331,7 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5310
5331
  schemaName: getSchemaName$5(this.#schema)
5311
5332
  });
5312
5333
  const placeholders = hashes.map((_, i) => `$${i + 1}`).join(", ");
5313
- const rows = await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "hash" IN (${placeholders})`, hashes);
5334
+ const rows = await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "hash" IN (${placeholders})`, hashes);
5314
5335
  for (const row of rows) {
5315
5336
  const entry = this.#parseRow(row);
5316
5337
  result.set(entry.hash, entry);
@@ -5340,9 +5361,10 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5340
5361
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS, _mastra_core_storage.TABLE_CHANNEL_CONFIG];
5341
5362
  constructor(config) {
5342
5363
  super();
5343
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5364
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5344
5365
  this.#db = new PgDB({
5345
5366
  client,
5367
+ readClient,
5346
5368
  schemaName,
5347
5369
  skipDefaultIndexes
5348
5370
  });
@@ -5449,7 +5471,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5449
5471
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5450
5472
  schemaName: getSchemaName$5(this.#schema)
5451
5473
  });
5452
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
5474
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
5453
5475
  return row ? this.#parseInstallationRow(row) : null;
5454
5476
  }
5455
5477
  async getInstallationByAgent(platform, agentId) {
@@ -5457,7 +5479,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5457
5479
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5458
5480
  schemaName: getSchemaName$5(this.#schema)
5459
5481
  });
5460
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1 AND "agentId" = $2 ORDER BY CASE "status" WHEN 'active' THEN 0 WHEN 'pending' THEN 1 ELSE 2 END, "updatedAt" DESC LIMIT 1`, [platform, agentId]);
5482
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1 AND "agentId" = $2 ORDER BY CASE "status" WHEN 'active' THEN 0 WHEN 'pending' THEN 1 ELSE 2 END, "updatedAt" DESC LIMIT 1`, [platform, agentId]);
5461
5483
  return row ? this.#parseInstallationRow(row) : null;
5462
5484
  }
5463
5485
  async getInstallationByWebhookId(webhookId) {
@@ -5465,7 +5487,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5465
5487
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5466
5488
  schemaName: getSchemaName$5(this.#schema)
5467
5489
  });
5468
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "webhookId" = $1`, [webhookId]);
5490
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "webhookId" = $1`, [webhookId]);
5469
5491
  return row ? this.#parseInstallationRow(row) : null;
5470
5492
  }
5471
5493
  async listInstallations(platform) {
@@ -5473,7 +5495,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5473
5495
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5474
5496
  schemaName: getSchemaName$5(this.#schema)
5475
5497
  });
5476
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1 ORDER BY "createdAt" DESC`, [platform])).map((row) => this.#parseInstallationRow(row));
5498
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1 ORDER BY "createdAt" DESC`, [platform])).map((row) => this.#parseInstallationRow(row));
5477
5499
  }
5478
5500
  async deleteInstallation(id) {
5479
5501
  const tableName = getTableName$5({
@@ -5505,7 +5527,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5505
5527
  indexName: _mastra_core_storage.TABLE_CHANNEL_CONFIG,
5506
5528
  schemaName: getSchemaName$5(this.#schema)
5507
5529
  });
5508
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1`, [platform]);
5530
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1`, [platform]);
5509
5531
  if (!row) return null;
5510
5532
  return {
5511
5533
  platform: row.platform,
@@ -5553,9 +5575,10 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5553
5575
  ];
5554
5576
  constructor(config) {
5555
5577
  super();
5556
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5578
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5557
5579
  this.#db = new PgDB({
5558
5580
  client,
5581
+ readClient,
5559
5582
  schemaName,
5560
5583
  skipDefaultIndexes
5561
5584
  });
@@ -5816,7 +5839,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5816
5839
  };
5817
5840
  } catch (error) {
5818
5841
  if (input.id !== void 0 && (0, _mastra_core_storage.hasErrorCode)(error, /* @__PURE__ */ new Set(["23505"]))) {
5819
- const existing = await this.getDatasetById({ id: input.id });
5842
+ const existing = await this.#getDatasetById(this.#db.client, { id: input.id });
5820
5843
  if (existing) return this.resolveExistingDataset(existing, {
5821
5844
  ...input,
5822
5845
  id: input.id
@@ -5830,7 +5853,20 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5830
5853
  }, error);
5831
5854
  }
5832
5855
  }
5833
- async getDatasetById({ id, filters }) {
5856
+ async getDatasetById(args) {
5857
+ return this.#getDatasetById(this.#db.readClient, args);
5858
+ }
5859
+ getDatasetForMutation(args) {
5860
+ return this.#getDatasetById(this.#db.client, args);
5861
+ }
5862
+ listItemsForMutation(args) {
5863
+ return this.#listItems(this.#db.client, args);
5864
+ }
5865
+ /**
5866
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
5867
+ * lagging read replica cannot yield stale or missing rows mid-update.
5868
+ */
5869
+ async #getDatasetById(client, { id, filters }) {
5834
5870
  try {
5835
5871
  const tableName = getTableName$5({
5836
5872
  indexName: _mastra_core_storage.TABLE_DATASETS,
@@ -5838,7 +5874,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5838
5874
  });
5839
5875
  const { conditions, params } = tenancyWhere(filters, 2);
5840
5876
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
5841
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
5877
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
5842
5878
  return result ? this.transformDatasetRow(result) : null;
5843
5879
  } catch (error) {
5844
5880
  throw new _mastra_core_error.MastraError({
@@ -5850,7 +5886,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5850
5886
  }
5851
5887
  async _doUpdateDataset(args) {
5852
5888
  try {
5853
- const existing = await this.getDatasetById({
5889
+ const existing = await this.#getDatasetById(this.#db.client, {
5854
5890
  id: args.id,
5855
5891
  filters: args.filters
5856
5892
  });
@@ -6022,7 +6058,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6022
6058
  }
6023
6059
  }
6024
6060
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
6025
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
6061
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
6026
6062
  const total = parseInt(countResult.count, 10);
6027
6063
  if (total === 0) return {
6028
6064
  datasets: [],
@@ -6037,7 +6073,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6037
6073
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6038
6074
  const limitValue = perPageInput === false ? total : perPage;
6039
6075
  return {
6040
- datasets: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6076
+ datasets: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6041
6077
  ...queryParams,
6042
6078
  limitValue,
6043
6079
  offset
@@ -6141,7 +6177,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6141
6177
  }
6142
6178
  async _doUpdateItem(args) {
6143
6179
  try {
6144
- const existing = await this.getItemById({ id: args.id });
6180
+ const existing = await this.#getItemById(this.#db.client, { id: args.id });
6145
6181
  if (!existing) throw new _mastra_core_error.MastraError({
6146
6182
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_ITEM", "NOT_FOUND"),
6147
6183
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -6247,7 +6283,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6247
6283
  }
6248
6284
  async _doDeleteItem({ id, datasetId }) {
6249
6285
  try {
6250
- const existing = await this.getItemById({ id });
6286
+ const existing = await this.#getItemById(this.#db.client, { id });
6251
6287
  if (!existing) return;
6252
6288
  if (existing.datasetId !== datasetId) throw new _mastra_core_error.MastraError({
6253
6289
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "DELETE_ITEM", "DATASET_MISMATCH"),
@@ -6414,7 +6450,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6414
6450
  }
6415
6451
  async _doBatchDeleteItems(input) {
6416
6452
  try {
6417
- const dataset = await this.getDatasetById({ id: input.datasetId });
6453
+ const dataset = await this.#getDatasetById(this.#db.client, { id: input.datasetId });
6418
6454
  if (!dataset) throw new _mastra_core_error.MastraError({
6419
6455
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "BULK_DELETE_ITEMS", "DATASET_NOT_FOUND"),
6420
6456
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -6423,7 +6459,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6423
6459
  });
6424
6460
  const currentItems = [];
6425
6461
  for (const itemId of input.itemIds) {
6426
- const item = await this.getItemById({ id: itemId });
6462
+ const item = await this.#getItemById(this.#db.client, { id: itemId });
6427
6463
  if (item && item.datasetId === input.datasetId) currentItems.push(item);
6428
6464
  }
6429
6465
  if (currentItems.length === 0) return;
@@ -6487,14 +6523,17 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6487
6523
  }
6488
6524
  }
6489
6525
  async getItemById(args) {
6526
+ return this.#getItemById(this.#db.readClient, args);
6527
+ }
6528
+ async #getItemById(client, args) {
6490
6529
  try {
6491
6530
  const tableName = getTableName$5({
6492
6531
  indexName: _mastra_core_storage.TABLE_DATASET_ITEMS,
6493
6532
  schemaName: getSchemaName$5(this.#schema)
6494
6533
  });
6495
6534
  let result;
6496
- if (args.datasetVersion !== void 0) result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 AND "datasetVersion" <= $2 AND ("validTo" IS NULL OR "validTo" > $2) AND "isDeleted" = false ORDER BY "datasetVersion" DESC LIMIT 1`, [args.id, args.datasetVersion]);
6497
- else result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 AND "validTo" IS NULL AND "isDeleted" = false`, [args.id]);
6535
+ if (args.datasetVersion !== void 0) result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 AND "datasetVersion" <= $2 AND ("validTo" IS NULL OR "validTo" > $2) AND "isDeleted" = false ORDER BY "datasetVersion" DESC LIMIT 1`, [args.id, args.datasetVersion]);
6536
+ else result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 AND "validTo" IS NULL AND "isDeleted" = false`, [args.id]);
6498
6537
  return result ? this.transformItemRow(result) : null;
6499
6538
  } catch (error) {
6500
6539
  throw new _mastra_core_error.MastraError({
@@ -6510,7 +6549,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6510
6549
  indexName: _mastra_core_storage.TABLE_DATASET_ITEMS,
6511
6550
  schemaName: getSchemaName$5(this.#schema)
6512
6551
  });
6513
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "datasetId" = $1 AND "datasetVersion" <= $2 AND ("validTo" IS NULL OR "validTo" > $3) AND "isDeleted" = false ORDER BY "createdAt" DESC, "id" ASC`, [
6552
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "datasetId" = $1 AND "datasetVersion" <= $2 AND ("validTo" IS NULL OR "validTo" > $3) AND "isDeleted" = false ORDER BY "createdAt" DESC, "id" ASC`, [
6514
6553
  datasetId,
6515
6554
  version,
6516
6555
  version
@@ -6529,7 +6568,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6529
6568
  indexName: _mastra_core_storage.TABLE_DATASET_ITEMS,
6530
6569
  schemaName: getSchemaName$5(this.#schema)
6531
6570
  });
6532
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 ORDER BY "datasetVersion" DESC`, [itemId]) || []).map((row) => this.transformItemRowFull(row));
6571
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 ORDER BY "datasetVersion" DESC`, [itemId]) || []).map((row) => this.transformItemRowFull(row));
6533
6572
  } catch (error) {
6534
6573
  throw new _mastra_core_error.MastraError({
6535
6574
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "GET_ITEM_HISTORY", "FAILED"),
@@ -6539,6 +6578,13 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6539
6578
  }
6540
6579
  }
6541
6580
  async listItems(args) {
6581
+ return this.#listItems(this.#db.readClient, args);
6582
+ }
6583
+ /**
6584
+ * Same listing against an explicit client. `updateDataset` validates existing
6585
+ * items on the writer so a lagging replica cannot hide freshly inserted rows.
6586
+ */
6587
+ async #listItems(client, args) {
6542
6588
  try {
6543
6589
  const { page, perPage: perPageInput } = args.pagination;
6544
6590
  const tableName = getTableName$5({
@@ -6575,7 +6621,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6575
6621
  }
6576
6622
  }
6577
6623
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
6578
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
6624
+ const countResult = await client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
6579
6625
  const total = parseInt(countResult.count, 10);
6580
6626
  if (total === 0) return {
6581
6627
  items: [],
@@ -6590,7 +6636,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6590
6636
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6591
6637
  const limitValue = perPageInput === false ? total : perPage;
6592
6638
  return {
6593
- items: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6639
+ items: (await client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6594
6640
  ...queryParams,
6595
6641
  limitValue,
6596
6642
  offset
@@ -6645,7 +6691,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6645
6691
  indexName: _mastra_core_storage.TABLE_DATASET_VERSIONS,
6646
6692
  schemaName: getSchemaName$5(this.#schema)
6647
6693
  });
6648
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "datasetId" = $1`, [input.datasetId]);
6694
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "datasetId" = $1`, [input.datasetId]);
6649
6695
  const total = parseInt(countResult.count, 10);
6650
6696
  if (total === 0) return {
6651
6697
  versions: [],
@@ -6660,7 +6706,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6660
6706
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6661
6707
  const limitValue = perPageInput === false ? total : perPage;
6662
6708
  return {
6663
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "datasetId" = $1 ORDER BY "version" DESC LIMIT $2 OFFSET $3`, [
6709
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "datasetId" = $1 ORDER BY "version" DESC LIMIT $2 OFFSET $3`, [
6664
6710
  input.datasetId,
6665
6711
  limitValue,
6666
6712
  offset
@@ -6710,9 +6756,10 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
6710
6756
  } };
6711
6757
  constructor(config) {
6712
6758
  super();
6713
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
6759
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
6714
6760
  this.#db = new PgDB({
6715
6761
  client,
6762
+ readClient,
6716
6763
  schemaName,
6717
6764
  skipDefaultIndexes
6718
6765
  });
@@ -7050,7 +7097,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7050
7097
  }
7051
7098
  async updateExperiment(input) {
7052
7099
  try {
7053
- if (!await this.getExperimentById({ id: input.id })) throw new _mastra_core_error.MastraError({
7100
+ if (!await this.#getExperimentById(this.#db.client, { id: input.id })) throw new _mastra_core_error.MastraError({
7054
7101
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_EXPERIMENT", "NOT_FOUND"),
7055
7102
  domain: _mastra_core_error.ErrorDomain.STORAGE,
7056
7103
  category: _mastra_core_error.ErrorCategory.USER,
@@ -7106,7 +7153,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7106
7153
  }
7107
7154
  values.push(input.id);
7108
7155
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE "id" = $${paramIndex}`, values);
7109
- return await this.getExperimentById({ id: input.id });
7156
+ return await this.#getExperimentById(this.#db.client, { id: input.id });
7110
7157
  } catch (error) {
7111
7158
  if (error instanceof _mastra_core_error.MastraError) throw error;
7112
7159
  throw new _mastra_core_error.MastraError({
@@ -7116,7 +7163,14 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7116
7163
  }, error);
7117
7164
  }
7118
7165
  }
7119
- async getExperimentById({ id, filters }) {
7166
+ async getExperimentById(args) {
7167
+ return this.#getExperimentById(this.#db.readClient, args);
7168
+ }
7169
+ /**
7170
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
7171
+ * lagging read replica cannot yield stale or missing rows mid-update.
7172
+ */
7173
+ async #getExperimentById(client, { id, filters }) {
7120
7174
  try {
7121
7175
  const tableName = getTableName$5({
7122
7176
  indexName: _mastra_core_storage.TABLE_EXPERIMENTS,
@@ -7124,7 +7178,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7124
7178
  });
7125
7179
  const { conditions, params } = tenancyWhere(filters, 2);
7126
7180
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
7127
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7181
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7128
7182
  return result ? this.transformExperimentRow(result) : null;
7129
7183
  } catch (error) {
7130
7184
  throw new _mastra_core_error.MastraError({
@@ -7192,7 +7246,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7192
7246
  }
7193
7247
  }
7194
7248
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
7195
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
7249
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
7196
7250
  const total = parseInt(countResult.count, 10);
7197
7251
  if (total === 0) return {
7198
7252
  experiments: [],
@@ -7207,7 +7261,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7207
7261
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
7208
7262
  const limitValue = perPageInput === false ? total : perPage;
7209
7263
  return {
7210
- experiments: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7264
+ experiments: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7211
7265
  ...queryParams,
7212
7266
  limitValue,
7213
7267
  offset
@@ -7411,7 +7465,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7411
7465
  values.push(input.comment);
7412
7466
  }
7413
7467
  if (setClauses.length === 0) {
7414
- const existing = await this.getExperimentResultById({ id: input.id });
7468
+ const existing = await this.#getExperimentResultById(this.#db.client, { id: input.id });
7415
7469
  if (!existing) throw new _mastra_core_error.MastraError({
7416
7470
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_EXPERIMENT_RESULT", "NOT_FOUND"),
7417
7471
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -7444,7 +7498,14 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7444
7498
  }, error);
7445
7499
  }
7446
7500
  }
7447
- async getExperimentResultById({ id, filters }) {
7501
+ async getExperimentResultById(args) {
7502
+ return this.#getExperimentResultById(this.#db.readClient, args);
7503
+ }
7504
+ /**
7505
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
7506
+ * lagging read replica cannot yield stale or missing rows mid-update.
7507
+ */
7508
+ async #getExperimentResultById(client, { id, filters }) {
7448
7509
  try {
7449
7510
  const tableName = getTableName$5({
7450
7511
  indexName: _mastra_core_storage.TABLE_EXPERIMENT_RESULTS,
@@ -7452,7 +7513,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7452
7513
  });
7453
7514
  const { conditions, params } = tenancyWhere(filters, 2);
7454
7515
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
7455
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7516
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7456
7517
  return result ? this.transformExperimentResultRow(result) : null;
7457
7518
  } catch (error) {
7458
7519
  throw new _mastra_core_error.MastraError({
@@ -7492,7 +7553,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7492
7553
  }
7493
7554
  }
7494
7555
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
7495
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
7556
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
7496
7557
  const total = parseInt(countResult.count, 10);
7497
7558
  if (total === 0) return {
7498
7559
  results: [],
@@ -7507,7 +7568,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7507
7568
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
7508
7569
  const limitValue = perPageInput === false ? total : perPage;
7509
7570
  return {
7510
- results: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7571
+ results: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7511
7572
  ...queryParams,
7512
7573
  limitValue,
7513
7574
  offset
@@ -7561,7 +7622,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7561
7622
  indexName: _mastra_core_storage.TABLE_EXPERIMENT_RESULTS,
7562
7623
  schemaName: getSchemaName$5(this.#schema)
7563
7624
  });
7564
- return (await this.#db.client.manyOrNone(`SELECT
7625
+ return (await this.#db.readClient.manyOrNone(`SELECT
7565
7626
  "experimentId",
7566
7627
  COUNT(*)::int as total,
7567
7628
  SUM(CASE WHEN status = 'needs-review' THEN 1 ELSE 0 END)::int as "needsReview",
@@ -7603,9 +7664,10 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7603
7664
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_FAVORITES];
7604
7665
  constructor(config) {
7605
7666
  super();
7606
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
7667
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
7607
7668
  this.#db = new PgDB({
7608
7669
  client,
7670
+ readClient,
7609
7671
  schemaName,
7610
7672
  skipDefaultIndexes
7611
7673
  });
@@ -7771,7 +7833,7 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7771
7833
  schemaName: getSchemaName$5(this.#schema)
7772
7834
  });
7773
7835
  try {
7774
- return await this.#db.client.oneOrNone(`SELECT 1 FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 AND "entityId" = $3 LIMIT 1`, [
7836
+ return await this.#db.readClient.oneOrNone(`SELECT 1 FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 AND "entityId" = $3 LIMIT 1`, [
7775
7837
  input.userId,
7776
7838
  input.entityType,
7777
7839
  input.entityId
@@ -7794,7 +7856,7 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7794
7856
  });
7795
7857
  try {
7796
7858
  const placeholders = entityIds.map((_, i) => `$${i + 3}`).join(", ");
7797
- const rows = await this.#db.client.manyOrNone(`SELECT "entityId" FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 AND "entityId" IN (${placeholders})`, [
7859
+ const rows = await this.#db.readClient.manyOrNone(`SELECT "entityId" FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 AND "entityId" IN (${placeholders})`, [
7798
7860
  userId,
7799
7861
  entityType,
7800
7862
  ...entityIds
@@ -7817,7 +7879,7 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7817
7879
  schemaName: getSchemaName$5(this.#schema)
7818
7880
  });
7819
7881
  try {
7820
- return (await this.#db.client.manyOrNone(`SELECT "entityId" FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 ORDER BY "createdAt" DESC, "entityId" ASC`, [input.userId, input.entityType]) ?? []).map((row) => row.entityId);
7882
+ return (await this.#db.readClient.manyOrNone(`SELECT "entityId" FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 ORDER BY "createdAt" DESC, "entityId" ASC`, [input.userId, input.entityType]) ?? []).map((row) => row.entityId);
7821
7883
  } catch (error) {
7822
7884
  if (error instanceof _mastra_core_error.MastraError) throw error;
7823
7885
  throw new _mastra_core_error.MastraError({
@@ -8120,16 +8182,20 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8120
8182
  }
8121
8183
  #client;
8122
8184
  #executor;
8185
+ /** Reader-backed executor for standalone reads; mutations and read-modify-write stay on #executor. */
8186
+ #readExecutor;
8123
8187
  #db;
8124
8188
  #schemaName;
8125
8189
  constructor(config) {
8126
8190
  super();
8127
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
8191
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
8128
8192
  this.#client = client;
8129
8193
  this.#schemaName = schemaName;
8130
8194
  this.#executor = createExecutor(client, schemaName);
8195
+ this.#readExecutor = createExecutor(readClient, schemaName);
8131
8196
  this.#db = new PgDB({
8132
8197
  client,
8198
+ readClient,
8133
8199
  schemaName,
8134
8200
  skipDefaultIndexes
8135
8201
  });
@@ -8231,13 +8297,13 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8231
8297
  });
8232
8298
  }
8233
8299
  async getNode(id) {
8234
- return this.#getNode(this.#executor, id);
8300
+ return this.#getNode(this.#readExecutor, id);
8235
8301
  }
8236
8302
  async getNodeByName(input) {
8237
- return this.#getNodeByName(this.#executor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8303
+ return this.#getNodeByName(this.#readExecutor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8238
8304
  }
8239
8305
  async resolveNode(input) {
8240
- return this.#resolveNode(this.#executor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8306
+ return this.#resolveNode(this.#readExecutor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8241
8307
  }
8242
8308
  async listNodes(input) {
8243
8309
  const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
@@ -8267,7 +8333,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8267
8333
  args.push(updatedAt, updatedAt, cursor.name, cursor.name, cursor.id);
8268
8334
  }
8269
8335
  args.push(input.limit ?? 100);
8270
- return (await this.#executor.execute({
8336
+ return (await this.#readExecutor.execute({
8271
8337
  sql: `SELECT *, scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" WHERE ${clauses.join(" AND ")} ORDER BY updatedAt DESC, name ASC, id ASC LIMIT ?`,
8272
8338
  args
8273
8339
  })).rows.map(parseNode);
@@ -8433,7 +8499,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8433
8499
  });
8434
8500
  }
8435
8501
  async getKnowledge(input) {
8436
- const result = await this.#executor.execute({
8502
+ const result = await this.#readExecutor.execute({
8437
8503
  sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${input.includeDeleted ? "" : " AND deletedAt IS NULL"}`,
8438
8504
  args: [input.id]
8439
8505
  });
@@ -8458,7 +8524,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8458
8524
  if (input.after) args.push(input.after);
8459
8525
  const limit = input.limit ?? 100;
8460
8526
  args.push(limit + 1);
8461
- const records = (await this.#executor.execute({
8527
+ const records = (await this.#readExecutor.execute({
8462
8528
  sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE sourceThreadId=? AND ${visibleSql}${input.includeDeleted ? "" : " AND deletedAt IS NULL"}${input.after ? " AND id > ?" : ""} ORDER BY id ASC LIMIT ?`,
8463
8529
  args
8464
8530
  })).rows.map(parseKnowledge);
@@ -8553,7 +8619,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8553
8619
  const normalizedQuery = input.query.trim().toLocaleLowerCase();
8554
8620
  if (!normalizedQuery) return [];
8555
8621
  const query = `%${escapeLikePattern(normalizedQuery)}%`;
8556
- const results = (await this.#executor.execute({
8622
+ const results = (await this.#readExecutor.execute({
8557
8623
  sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" WHERE mergedInto IS NULL AND ${visibleSql} AND (canonicalName LIKE ? ESCAPE '=' OR lower(COALESCE(kind,'')) LIKE ? ESCAPE '=' OR lower(COALESCE(content,'')) LIKE ? ESCAPE '=' OR lower(COALESCE(description,'')) LIKE ? ESCAPE '=') ORDER BY updatedAt DESC LIMIT ?`,
8558
8624
  args: [
8559
8625
  key,
@@ -8577,7 +8643,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8577
8643
  scope: parseJson$1(row.scopeJson)
8578
8644
  }));
8579
8645
  if (results.length < (input.limit ?? 20)) {
8580
- const records = await this.#executor.execute({
8646
+ const records = await this.#readExecutor.execute({
8581
8647
  sql: `SELECT f.*,f.scope AS "scopeJson",r.name,r.scope AS "parentScopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" f JOIN "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" r ON r.id=f.node AND r.type='node' AND r.mergedInto IS NULL WHERE f.deletedAt IS NULL AND ${visibleSql.replaceAll("scopeKey", "f.scopeKey")} AND lower(f.text) LIKE ? ESCAPE '=' ORDER BY f.id DESC LIMIT ?`,
8582
8648
  args: [
8583
8649
  key,
@@ -8630,7 +8696,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8630
8696
  }
8631
8697
  async listActivity(input) {
8632
8698
  const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8633
- return (await this.#executor.execute({
8699
+ return (await this.#readExecutor.execute({
8634
8700
  sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY}" WHERE ${visibleSql}${input.after ? " AND id < ?" : ""} ORDER BY id DESC LIMIT ?`,
8635
8701
  args: [
8636
8702
  key,
@@ -8774,7 +8840,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8774
8840
  }
8775
8841
  async #queryKnowledge(input, relationship) {
8776
8842
  const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
8777
- const node = await this.#resolveTerminalNode(this.#executor, nodeReferenceId(input.node));
8843
+ const node = await this.#resolveTerminalNode(this.#readExecutor, nodeReferenceId(input.node));
8778
8844
  if (!node) return { records: [] };
8779
8845
  const key = (0, _mastra_core_storage.knowledgeScopeKey)(scope);
8780
8846
  const args = [
@@ -8785,7 +8851,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8785
8851
  ];
8786
8852
  if (input.after) args.push(input.after);
8787
8853
  args.push((input.limit ?? 100) + 1);
8788
- const records = (await this.#executor.execute({
8854
+ const records = (await this.#readExecutor.execute({
8789
8855
  sql: `SELECT DISTINCT f.*,f.scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" f${relationship === "about" ? "" : ` LEFT JOIN "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" m ON m.sourceType='record' AND m.sourceId=f.id`} WHERE ${relationship === "about" ? "f.node=?" : relationship === "mentioning" ? "m.recordId=?" : "(f.node=? OR m.recordId=?)"} AND ${visibleSql.replaceAll("scopeKey", "f.scopeKey")}${input.includeDeleted ? "" : " AND f.deletedAt IS NULL"}${input.after ? " AND f.id < ?" : ""} ORDER BY f.id DESC LIMIT ?`,
8790
8856
  args
8791
8857
  })).rows.map(parseKnowledge);
@@ -8897,9 +8963,10 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
8897
8963
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_MCP_CLIENTS, _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS];
8898
8964
  constructor(config) {
8899
8965
  super();
8900
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
8966
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
8901
8967
  this.#db = new PgDB({
8902
8968
  client,
8969
+ readClient,
8903
8970
  schemaName,
8904
8971
  skipDefaultIndexes
8905
8972
  });
@@ -8963,12 +9030,19 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
8963
9030
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_MCP_CLIENTS });
8964
9031
  }
8965
9032
  async getById(id) {
9033
+ return this.#getById(this.#db.readClient, id);
9034
+ }
9035
+ /**
9036
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
9037
+ * lagging read replica cannot yield stale or missing rows mid-update.
9038
+ */
9039
+ async #getById(client, id) {
8966
9040
  try {
8967
9041
  const tableName = getTableName$5({
8968
9042
  indexName: _mastra_core_storage.TABLE_MCP_CLIENTS,
8969
9043
  schemaName: getSchemaName$5(this.#schema)
8970
9044
  });
8971
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9045
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
8972
9046
  if (!result) return null;
8973
9047
  return this.parseMCPClientRow(result);
8974
9048
  } catch (error) {
@@ -9047,7 +9121,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9047
9121
  indexName: _mastra_core_storage.TABLE_MCP_CLIENTS,
9048
9122
  schemaName: getSchemaName$5(this.#schema)
9049
9123
  });
9050
- const existingClient = await this.getById(id);
9124
+ const existingClient = await this.#getById(this.#db.client, id);
9051
9125
  if (!existingClient) throw new _mastra_core_error.MastraError({
9052
9126
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_CLIENT", "NOT_FOUND"),
9053
9127
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9086,7 +9160,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9086
9160
  values.push(now);
9087
9161
  values.push(id);
9088
9162
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
9089
- const updatedClient = await this.getById(id);
9163
+ const updatedClient = await this.#getById(this.#db.client, id);
9090
9164
  if (!updatedClient) throw new _mastra_core_error.MastraError({
9091
9165
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_CLIENT", "NOT_FOUND_AFTER_UPDATE"),
9092
9166
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9153,7 +9227,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9153
9227
  queryParams.push(JSON.stringify(metadata));
9154
9228
  }
9155
9229
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
9156
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9230
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9157
9231
  const total = parseInt(countResult.count, 10);
9158
9232
  if (total === 0) return {
9159
9233
  mcpClients: [],
@@ -9164,7 +9238,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9164
9238
  };
9165
9239
  const limitValue = perPageInput === false ? total : perPage;
9166
9240
  return {
9167
- mcpClients: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9241
+ mcpClients: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9168
9242
  ...queryParams,
9169
9243
  limitValue,
9170
9244
  offset
@@ -9241,7 +9315,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9241
9315
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9242
9316
  schemaName: getSchemaName$5(this.#schema)
9243
9317
  });
9244
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9318
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9245
9319
  if (!result) return null;
9246
9320
  return this.parseVersionRow(result);
9247
9321
  } catch (error) {
@@ -9260,7 +9334,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9260
9334
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9261
9335
  schemaName: getSchemaName$5(this.#schema)
9262
9336
  });
9263
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 AND "versionNumber" = $2`, [mcpClientId, versionNumber]);
9337
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 AND "versionNumber" = $2`, [mcpClientId, versionNumber]);
9264
9338
  if (!result) return null;
9265
9339
  return this.parseVersionRow(result);
9266
9340
  } catch (error) {
@@ -9282,7 +9356,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9282
9356
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9283
9357
  schemaName: getSchemaName$5(this.#schema)
9284
9358
  });
9285
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpClientId]);
9359
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpClientId]);
9286
9360
  if (!result) return null;
9287
9361
  return this.parseVersionRow(result);
9288
9362
  } catch (error) {
@@ -9311,7 +9385,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9311
9385
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9312
9386
  schemaName: getSchemaName$5(this.#schema)
9313
9387
  });
9314
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9388
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9315
9389
  const total = parseInt(countResult.count, 10);
9316
9390
  if (total === 0) return {
9317
9391
  versions: [],
@@ -9322,7 +9396,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9322
9396
  };
9323
9397
  const limitValue = perPageInput === false ? total : perPage;
9324
9398
  return {
9325
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9399
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9326
9400
  mcpClientId,
9327
9401
  limitValue,
9328
9402
  offset
@@ -9392,7 +9466,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9392
9466
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9393
9467
  schemaName: getSchemaName$5(this.#schema)
9394
9468
  });
9395
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9469
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9396
9470
  return parseInt(result.count, 10);
9397
9471
  } catch (error) {
9398
9472
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -9452,9 +9526,10 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9452
9526
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_MCP_SERVERS, _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS];
9453
9527
  constructor(config) {
9454
9528
  super();
9455
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
9529
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
9456
9530
  this.#db = new PgDB({
9457
9531
  client,
9532
+ readClient,
9458
9533
  schemaName,
9459
9534
  skipDefaultIndexes
9460
9535
  });
@@ -9518,12 +9593,19 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9518
9593
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_MCP_SERVERS });
9519
9594
  }
9520
9595
  async getById(id) {
9596
+ return this.#getById(this.#db.readClient, id);
9597
+ }
9598
+ /**
9599
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
9600
+ * lagging read replica cannot yield stale or missing rows mid-update.
9601
+ */
9602
+ async #getById(client, id) {
9521
9603
  try {
9522
9604
  const tableName = getTableName$5({
9523
9605
  indexName: _mastra_core_storage.TABLE_MCP_SERVERS,
9524
9606
  schemaName: getSchemaName$5(this.#schema)
9525
9607
  });
9526
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9608
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9527
9609
  if (!result) return null;
9528
9610
  return this.parseMCPServerRow(result);
9529
9611
  } catch (error) {
@@ -9602,7 +9684,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9602
9684
  indexName: _mastra_core_storage.TABLE_MCP_SERVERS,
9603
9685
  schemaName: getSchemaName$5(this.#schema)
9604
9686
  });
9605
- const existingServer = await this.getById(id);
9687
+ const existingServer = await this.#getById(this.#db.client, id);
9606
9688
  if (!existingServer) throw new _mastra_core_error.MastraError({
9607
9689
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_SERVER", "NOT_FOUND"),
9608
9690
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9641,7 +9723,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9641
9723
  values.push(now);
9642
9724
  values.push(id);
9643
9725
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
9644
- const updatedServer = await this.getById(id);
9726
+ const updatedServer = await this.#getById(this.#db.client, id);
9645
9727
  if (!updatedServer) throw new _mastra_core_error.MastraError({
9646
9728
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_SERVER", "NOT_FOUND_AFTER_UPDATE"),
9647
9729
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9708,7 +9790,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9708
9790
  queryParams.push(JSON.stringify(metadata));
9709
9791
  }
9710
9792
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
9711
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9793
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9712
9794
  const total = parseInt(countResult.count, 10);
9713
9795
  if (total === 0) return {
9714
9796
  mcpServers: [],
@@ -9719,7 +9801,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9719
9801
  };
9720
9802
  const limitValue = perPageInput === false ? total : perPage;
9721
9803
  return {
9722
- mcpServers: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9804
+ mcpServers: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9723
9805
  ...queryParams,
9724
9806
  limitValue,
9725
9807
  offset
@@ -9806,7 +9888,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9806
9888
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9807
9889
  schemaName: getSchemaName$5(this.#schema)
9808
9890
  });
9809
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9891
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9810
9892
  if (!result) return null;
9811
9893
  return this.parseVersionRow(result);
9812
9894
  } catch (error) {
@@ -9825,7 +9907,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9825
9907
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9826
9908
  schemaName: getSchemaName$5(this.#schema)
9827
9909
  });
9828
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 AND "versionNumber" = $2`, [mcpServerId, versionNumber]);
9910
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 AND "versionNumber" = $2`, [mcpServerId, versionNumber]);
9829
9911
  if (!result) return null;
9830
9912
  return this.parseVersionRow(result);
9831
9913
  } catch (error) {
@@ -9847,7 +9929,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9847
9929
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9848
9930
  schemaName: getSchemaName$5(this.#schema)
9849
9931
  });
9850
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpServerId]);
9932
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpServerId]);
9851
9933
  if (!result) return null;
9852
9934
  return this.parseVersionRow(result);
9853
9935
  } catch (error) {
@@ -9876,7 +9958,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9876
9958
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9877
9959
  schemaName: getSchemaName$5(this.#schema)
9878
9960
  });
9879
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
9961
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
9880
9962
  const total = parseInt(countResult.count, 10);
9881
9963
  if (total === 0) return {
9882
9964
  versions: [],
@@ -9887,7 +9969,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9887
9969
  };
9888
9970
  const limitValue = perPageInput === false ? total : perPage;
9889
9971
  return {
9890
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9972
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9891
9973
  mcpServerId,
9892
9974
  limitValue,
9893
9975
  offset
@@ -9957,7 +10039,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9957
10039
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9958
10040
  schemaName: getSchemaName$5(this.#schema)
9959
10041
  });
9960
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
10042
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
9961
10043
  return parseInt(result.count, 10);
9962
10044
  } catch (error) {
9963
10045
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -10126,9 +10208,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10126
10208
  ];
10127
10209
  constructor(config) {
10128
10210
  super();
10129
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
10211
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
10130
10212
  this.#db = new PgDB({
10131
10213
  client,
10214
+ readClient,
10132
10215
  schemaName,
10133
10216
  skipDefaultIndexes
10134
10217
  });
@@ -10377,6 +10460,16 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10377
10460
  };
10378
10461
  }
10379
10462
  async getThreadById({ threadId, resourceId }) {
10463
+ return this.#getThreadById(this.#db.readClient, {
10464
+ threadId,
10465
+ resourceId
10466
+ });
10467
+ }
10468
+ /**
10469
+ * Thread lookup against an explicit client. Mutation paths pass the writer so
10470
+ * a lagging read replica cannot produce false not-found or stale metadata.
10471
+ */
10472
+ async #getThreadById(client, { threadId, resourceId }) {
10380
10473
  try {
10381
10474
  let query = `SELECT * FROM ${getTableName$3({
10382
10475
  indexName: _mastra_core_storage.TABLE_THREADS,
@@ -10387,7 +10480,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10387
10480
  query += ` AND "resourceId" = $2`;
10388
10481
  params.push(resourceId);
10389
10482
  }
10390
- const thread = await this.#db.client.oneOrNone(query, params);
10483
+ const thread = await client.oneOrNone(query, params);
10391
10484
  if (!thread) return null;
10392
10485
  return {
10393
10486
  id: thread.id,
@@ -10456,7 +10549,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10456
10549
  }
10457
10550
  const baseQuery = `FROM ${tableName} ${whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : ""}`;
10458
10551
  const countQuery = `SELECT COUNT(*) ${baseQuery}`;
10459
- const countResult = await this.#db.client.one(countQuery, queryParams);
10552
+ const countResult = await this.#db.readClient.one(countQuery, queryParams);
10460
10553
  const total = parseInt(countResult.count, 10);
10461
10554
  if (total === 0) return {
10462
10555
  threads: [],
@@ -10468,7 +10561,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10468
10561
  const limitValue = perPageInput === false ? total : perPage;
10469
10562
  const dataQuery = `SELECT id, "resourceId", title, metadata, "createdAt", "createdAtZ", "updatedAt", "updatedAtZ" ${baseQuery} ORDER BY COALESCE("${field}Z", "${field}") ${direction} LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`;
10470
10563
  return {
10471
- threads: (await this.#db.client.manyOrNone(dataQuery, [
10564
+ threads: (await this.#db.readClient.manyOrNone(dataQuery, [
10472
10565
  ...queryParams,
10473
10566
  limitValue,
10474
10567
  offset
@@ -10552,7 +10645,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10552
10645
  indexName: _mastra_core_storage.TABLE_THREADS,
10553
10646
  schemaName: getSchemaName$3(this.#schema)
10554
10647
  });
10555
- const existingThread = await this.getThreadById({ threadId: id });
10648
+ const existingThread = await this.#getThreadById(this.#db.client, { threadId: id });
10556
10649
  if (!existingThread) throw new _mastra_core_error.MastraError({
10557
10650
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_THREAD", "FAILED"),
10558
10651
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -10684,7 +10777,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10684
10777
  if (targetIds.length === 0) return null;
10685
10778
  const idPlaceholders = targetIds.map((_, i) => "$" + (i + 1)).join(", ");
10686
10779
  const targetResourceCondition = resourceId ? ` AND "resourceId" = $${targetIds.length + 1}` : "";
10687
- const targetRows = await this.#db.client.manyOrNone(`SELECT id, thread_id, "createdAt" FROM ${tableName} WHERE id IN (${idPlaceholders})${targetResourceCondition}`, resourceId ? [...targetIds, resourceId] : targetIds);
10780
+ const targetRows = await this.#db.readClient.manyOrNone(`SELECT id, thread_id, "createdAt" FROM ${tableName} WHERE id IN (${idPlaceholders})${targetResourceCondition}`, resourceId ? [...targetIds, resourceId] : targetIds);
10688
10781
  if (targetRows.length === 0) return null;
10689
10782
  const targetMap = new Map(targetRows.map((r) => [r.id, {
10690
10783
  threadId: r.thread_id,
@@ -10735,7 +10828,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10735
10828
  let finalQuery;
10736
10829
  if (unionQueries.length === 1) finalQuery = unionQueries[0].slice(1, -1);
10737
10830
  else finalQuery = `SELECT * FROM (${unionQueries.join(" UNION ALL ")}) AS combined ORDER BY "createdAt" ASC, id ASC`;
10738
- const includedRows = await this.#db.client.manyOrNone(finalQuery, params);
10831
+ const includedRows = await this.#db.readClient.manyOrNone(finalQuery, params);
10739
10832
  const seen = /* @__PURE__ */ new Set();
10740
10833
  return includedRows.filter((row) => {
10741
10834
  if (seen.has(row.id)) return false;
@@ -10771,7 +10864,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10771
10864
  WHERE id IN (${inPlaceholders(messageIds.length)})
10772
10865
  ORDER BY "createdAt" DESC
10773
10866
  `;
10774
- const resultRows = await this.#db.client.manyOrNone(query, messageIds);
10867
+ const resultRows = await this.#db.readClient.manyOrNone(query, messageIds);
10775
10868
  return { messages: new _mastra_core_agent.MessageList().add(resultRows.map((row) => this.parseRow(row)), "memory").get.all.db() };
10776
10869
  } catch (error) {
10777
10870
  const mastraError = new _mastra_core_error.MastraError({
@@ -10802,7 +10895,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10802
10895
  perPage,
10803
10896
  offset
10804
10897
  ];
10805
- const rows = await this.#db.client.manyOrNone(`${selectStatement}, COUNT(*) OVER () AS "__total" FROM ${tableName} ${whereClause} ${orderByStatement}${limitClause}`, dataParams) || [];
10898
+ const rows = await this.#db.readClient.manyOrNone(`${selectStatement}, COUNT(*) OVER () AS "__total" FROM ${tableName} ${whereClause} ${orderByStatement}${limitClause}`, dataParams) || [];
10806
10899
  if (rows.length > 0) return {
10807
10900
  total: Number(rows[0].__total),
10808
10901
  messages: rows
@@ -10811,7 +10904,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10811
10904
  total: 0,
10812
10905
  messages: []
10813
10906
  };
10814
- const countResult = await this.#db.client.one(`SELECT COUNT(*) FROM ${tableName} ${whereClause}`, queryParams);
10907
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) FROM ${tableName} ${whereClause}`, queryParams);
10815
10908
  return {
10816
10909
  total: parseInt(countResult.count, 10),
10817
10910
  messages: []
@@ -10905,7 +10998,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10905
10998
  let total;
10906
10999
  let messages;
10907
11000
  if (metadataFilter) {
10908
- const filteredRows = (await this.#db.client.manyOrNone(`${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement}`, queryParams) || []).filter((row) => (0, _mastra_core_storage.storageMessageMatchesMetadataFilter)(row.content, metadataFilter));
11001
+ const filteredRows = (await this.#db.readClient.manyOrNone(`${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement}`, queryParams) || []).filter((row) => (0, _mastra_core_storage.storageMessageMatchesMetadataFilter)(row.content, metadataFilter));
10909
11002
  total = filteredRows.length;
10910
11003
  messages = perPageInput === false ? filteredRows : filteredRows.slice(offset, offset + perPage);
10911
11004
  } else ({total, messages} = await this.#fetchMessagePage({
@@ -11051,7 +11144,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11051
11144
  let total;
11052
11145
  let messages;
11053
11146
  if (metadataFilter) {
11054
- const filteredRows = (await this.#db.client.manyOrNone(`${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement}`, queryParams) || []).filter((row) => (0, _mastra_core_storage.storageMessageMatchesMetadataFilter)(row.content, metadataFilter));
11147
+ const filteredRows = (await this.#db.readClient.manyOrNone(`${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement}`, queryParams) || []).filter((row) => (0, _mastra_core_storage.storageMessageMatchesMetadataFilter)(row.content, metadataFilter));
11055
11148
  total = filteredRows.length;
11056
11149
  messages = perPageInput === false ? filteredRows : filteredRows.slice(offset, offset + perPage);
11057
11150
  } else ({total, messages} = await this.#fetchMessagePage({
@@ -11126,7 +11219,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11126
11219
  if (!message.resourceId) throw new Error(`Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`);
11127
11220
  threadIds.add(message.threadId);
11128
11221
  }
11129
- for (const threadIdToCheck of threadIds) if (!await this.getThreadById({ threadId: threadIdToCheck })) throw new _mastra_core_error.MastraError({
11222
+ for (const threadIdToCheck of threadIds) if (!await this.#getThreadById(this.#db.client, { threadId: threadIdToCheck })) throw new _mastra_core_error.MastraError({
11130
11223
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "SAVE_MESSAGES", "FAILED"),
11131
11224
  domain: _mastra_core_error.ErrorDomain.STORAGE,
11132
11225
  category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
@@ -11294,11 +11387,14 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11294
11387
  }
11295
11388
  }
11296
11389
  async getResourceById({ resourceId }) {
11390
+ return this.#getResourceById(this.#db.readClient, resourceId);
11391
+ }
11392
+ async #getResourceById(client, resourceId) {
11297
11393
  const tableName = getTableName$3({
11298
11394
  indexName: _mastra_core_storage.TABLE_RESOURCES,
11299
11395
  schemaName: getSchemaName$3(this.#schema)
11300
11396
  });
11301
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [resourceId]);
11397
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [resourceId]);
11302
11398
  if (!result) return null;
11303
11399
  return {
11304
11400
  id: result.id,
@@ -11323,7 +11419,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11323
11419
  return resource;
11324
11420
  }
11325
11421
  async updateResource({ resourceId, workingMemory, metadata }) {
11326
- const existingResource = await this.getResourceById({ resourceId });
11422
+ const existingResource = await this.#getResourceById(this.#db.client, resourceId);
11327
11423
  if (!existingResource) {
11328
11424
  const newResource = {
11329
11425
  id: resourceId,
@@ -11371,7 +11467,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11371
11467
  }
11372
11468
  async cloneThread(args) {
11373
11469
  const { sourceThreadId, newThreadId: providedThreadId, resourceId, title, metadata, options } = args;
11374
- const sourceThread = await this.getThreadById({ threadId: sourceThreadId });
11470
+ const sourceThread = await this.#getThreadById(this.#db.client, { threadId: sourceThreadId });
11375
11471
  if (!sourceThread) throw new _mastra_core_error.MastraError({
11376
11472
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "CLONE_THREAD", "SOURCE_NOT_FOUND"),
11377
11473
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -11380,7 +11476,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11380
11476
  details: { sourceThreadId }
11381
11477
  });
11382
11478
  const newThreadId = providedThreadId || crypto.randomUUID();
11383
- if (await this.getThreadById({ threadId: newThreadId })) throw new _mastra_core_error.MastraError({
11479
+ if (await this.#getThreadById(this.#db.client, { threadId: newThreadId })) throw new _mastra_core_error.MastraError({
11384
11480
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "CLONE_THREAD", "THREAD_EXISTS"),
11385
11481
  domain: _mastra_core_error.ErrorDomain.STORAGE,
11386
11482
  category: _mastra_core_error.ErrorCategory.USER,
@@ -11555,7 +11651,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11555
11651
  indexName: OM_TABLE,
11556
11652
  schemaName: getSchemaName$3(this.#schema)
11557
11653
  });
11558
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`, [lookupKey]);
11654
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`, [lookupKey]);
11559
11655
  if (!result) return null;
11560
11656
  return this.parseOMRow(result);
11561
11657
  } catch (error) {
@@ -11597,7 +11693,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11597
11693
  params.push(options.offset);
11598
11694
  sql += ` OFFSET $${paramIndex}`;
11599
11695
  }
11600
- const result = await this.#db.client.manyOrNone(sql, params);
11696
+ const result = await this.#db.readClient.manyOrNone(sql, params);
11601
11697
  if (!result) return [];
11602
11698
  return result.map((row) => this.parseOMRow(row));
11603
11699
  } catch (error) {
@@ -12538,9 +12634,10 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12538
12634
  } };
12539
12635
  constructor(config) {
12540
12636
  super();
12541
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12637
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12542
12638
  this.#db = new PgDB({
12543
12639
  client,
12640
+ readClient,
12544
12641
  schemaName,
12545
12642
  skipDefaultIndexes
12546
12643
  });
@@ -12709,7 +12806,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12709
12806
  coalescedCount: (existing.coalescedCount ?? 1) + 1,
12710
12807
  metadata: metadata ?? null
12711
12808
  });
12712
- const updated = await this.getNotification({
12809
+ const updated = await this.#getNotification(this.#db.client, {
12713
12810
  threadId: existing.threadId,
12714
12811
  id: existing.id
12715
12812
  });
@@ -12775,7 +12872,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12775
12872
  indexName: _mastra_core_storage.TABLE_NOTIFICATIONS,
12776
12873
  schemaName: getSchemaName$5(this.#schema)
12777
12874
  });
12778
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY "updatedAt" DESC${limit}`, args)).map((row) => rowToNotification(row));
12875
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY "updatedAt" DESC${limit}`, args)).map((row) => rowToNotification(row));
12779
12876
  }
12780
12877
  async listDueNotifications(input) {
12781
12878
  const conditions = ["\"status\" = $1", "((\"deliverAt\" IS NOT NULL AND \"deliverAt\" <= $2) OR (\"summaryAt\" IS NOT NULL AND \"summaryAt\" <= $3))"];
@@ -12798,18 +12895,25 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12798
12895
  indexName: _mastra_core_storage.TABLE_NOTIFICATIONS,
12799
12896
  schemaName: getSchemaName$5(this.#schema)
12800
12897
  });
12801
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY CASE WHEN "deliverAt" IS NULL THEN "summaryAt" WHEN "summaryAt" IS NULL THEN "deliverAt" WHEN "deliverAt" <= "summaryAt" THEN "deliverAt" ELSE "summaryAt" END ASC, "updatedAt" ASC${limit}`, args)).map((row) => rowToNotification(row));
12898
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY CASE WHEN "deliverAt" IS NULL THEN "summaryAt" WHEN "summaryAt" IS NULL THEN "deliverAt" WHEN "deliverAt" <= "summaryAt" THEN "deliverAt" ELSE "summaryAt" END ASC, "updatedAt" ASC${limit}`, args)).map((row) => rowToNotification(row));
12802
12899
  }
12803
12900
  async getNotification(input) {
12901
+ return this.#getNotification(this.#db.readClient, input);
12902
+ }
12903
+ /**
12904
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
12905
+ * lagging read replica cannot yield stale or missing rows mid-update.
12906
+ */
12907
+ async #getNotification(client, input) {
12804
12908
  const tableName = getTableName$5({
12805
12909
  indexName: _mastra_core_storage.TABLE_NOTIFICATIONS,
12806
12910
  schemaName: getSchemaName$5(this.#schema)
12807
12911
  });
12808
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "threadId" = $1 AND "id" = $2 LIMIT 1`, [input.threadId, input.id]);
12912
+ const row = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "threadId" = $1 AND "id" = $2 LIMIT 1`, [input.threadId, input.id]);
12809
12913
  return row ? rowToNotification(row) : null;
12810
12914
  }
12811
12915
  async updateNotification(input) {
12812
- if (!await this.getNotification({
12916
+ if (!await this.#getNotification(this.#db.client, {
12813
12917
  threadId: input.threadId,
12814
12918
  id: input.id
12815
12919
  })) throw new Error(`Notification ${input.id} was not found for thread ${input.threadId}`);
@@ -12833,7 +12937,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12833
12937
  ...input.summarySignalId !== void 0 ? { summarySignalId: input.summarySignalId } : {},
12834
12938
  updatedAt: now
12835
12939
  });
12836
- const updated = await this.getNotification({
12940
+ const updated = await this.#getNotification(this.#db.client, {
12837
12941
  threadId: input.threadId,
12838
12942
  id: input.id
12839
12943
  });
@@ -12880,9 +12984,10 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
12880
12984
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SPANS];
12881
12985
  constructor(config) {
12882
12986
  super();
12883
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12987
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12884
12988
  this.#db = new PgDB({
12885
12989
  client,
12990
+ readClient,
12886
12991
  schemaName,
12887
12992
  skipDefaultIndexes
12888
12993
  });
@@ -13115,7 +13220,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13115
13220
  indexName: _mastra_core_storage.TABLE_SPANS,
13116
13221
  schemaName: getSchemaName$5(this.#schema)
13117
13222
  });
13118
- const row = await this.#db.client.oneOrNone(`SELECT
13223
+ const row = await this.#db.readClient.oneOrNone(`SELECT
13119
13224
  "traceId", "spanId", "parentSpanId", "name",
13120
13225
  "entityType", "entityId", "entityName",
13121
13226
  "userId", "organizationId", "resourceId",
@@ -13151,7 +13256,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13151
13256
  indexName: _mastra_core_storage.TABLE_SPANS,
13152
13257
  schemaName: getSchemaName$5(this.#schema)
13153
13258
  });
13154
- const row = await this.#db.client.oneOrNone(`SELECT
13259
+ const row = await this.#db.readClient.oneOrNone(`SELECT
13155
13260
  "traceId", "spanId", "parentSpanId", "name",
13156
13261
  "entityType", "entityId", "entityName",
13157
13262
  "userId", "organizationId", "resourceId",
@@ -13184,7 +13289,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13184
13289
  indexName: _mastra_core_storage.TABLE_SPANS,
13185
13290
  schemaName: getSchemaName$5(this.#schema)
13186
13291
  });
13187
- const spans = await this.#db.client.manyOrNone(`SELECT
13292
+ const spans = await this.#db.readClient.manyOrNone(`SELECT
13188
13293
  "traceId", "spanId", "parentSpanId", "name",
13189
13294
  "entityType", "entityId", "entityName",
13190
13295
  "userId", "organizationId", "resourceId",
@@ -13221,7 +13326,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13221
13326
  indexName: _mastra_core_storage.TABLE_SPANS,
13222
13327
  schemaName: getSchemaName$5(this.#schema)
13223
13328
  });
13224
- const spans = await this.#db.client.manyOrNone(`SELECT
13329
+ const spans = await this.#db.readClient.manyOrNone(`SELECT
13225
13330
  "traceId", "spanId", "parentSpanId", "name",
13226
13331
  "entityType", "entityId", "entityName",
13227
13332
  "spanType", "error", "isEvent",
@@ -13405,7 +13510,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13405
13510
  let orderClause;
13406
13511
  if (orderField === "endedAt") orderClause = `ORDER BY r."${sortField}" ${sortDirection} ${sortDirection === "DESC" ? "NULLS FIRST" : "NULLS LAST"}`;
13407
13512
  else orderClause = `ORDER BY r."${sortField}" ${sortDirection}`;
13408
- const countResult = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${tableName} r ${whereClause}`, params);
13513
+ const countResult = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${tableName} r ${whereClause}`, params);
13409
13514
  const count = Number(countResult?.count ?? 0);
13410
13515
  if (count === 0) return {
13411
13516
  pagination: {
@@ -13416,7 +13521,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13416
13521
  },
13417
13522
  spans: []
13418
13523
  };
13419
- const spans = await this.#db.client.manyOrNone(`SELECT
13524
+ const spans = await this.#db.readClient.manyOrNone(`SELECT
13420
13525
  r."traceId", r."spanId", r."parentSpanId", r."name",
13421
13526
  r."entityType", r."entityId", r."entityName",
13422
13527
  r."userId", r."organizationId", r."resourceId",
@@ -13513,6 +13618,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13513
13618
  }
13514
13619
  }
13515
13620
  async batchDeleteTraces(args) {
13621
+ this.assertUnscopedBatchDeleteTraces(args);
13516
13622
  try {
13517
13623
  const tableName = getTableName$5({
13518
13624
  indexName: _mastra_core_storage.TABLE_SPANS,
@@ -17695,11 +17801,39 @@ async function getTraceLight(client, schema, args) {
17695
17801
  spans: rows.map(rowToLightSpanRecord)
17696
17802
  };
17697
17803
  }
17804
+ /**
17805
+ * Delete traces by traceId, cascading to trace-linked signal events
17806
+ * (metrics, logs, scores, feedback). Signal rows with a NULL traceId are
17807
+ * never affected. When the optional tenant scope (`organizationId` /
17808
+ * `resourceId`) is set, every DELETE additionally requires the row's tenant
17809
+ * columns to match.
17810
+ */
17698
17811
  async function batchDeleteTraces(client, schema, args) {
17699
17812
  if (args.traceIds.length === 0) return;
17700
- const span = qualifiedTable(schema, TABLE_SPAN_EVENTS);
17813
+ const params = [...args.traceIds];
17701
17814
  const placeholders = args.traceIds.map((_, i) => `$${i + 1}`).join(", ");
17702
- await client.query(`DELETE FROM ${span} WHERE "traceId" IN (${placeholders})`, args.traceIds);
17815
+ let scopeCondition = "";
17816
+ if (args.organizationId !== void 0) {
17817
+ params.push(args.organizationId);
17818
+ scopeCondition += ` AND "organizationId" = $${params.length}`;
17819
+ }
17820
+ if (args.resourceId !== void 0) {
17821
+ params.push(args.resourceId);
17822
+ scopeCondition += ` AND "resourceId" = $${params.length}`;
17823
+ }
17824
+ const tables = [
17825
+ TABLE_SPAN_EVENTS,
17826
+ TABLE_METRIC_EVENTS,
17827
+ TABLE_LOG_EVENTS,
17828
+ TABLE_SCORE_EVENTS,
17829
+ TABLE_FEEDBACK_EVENTS
17830
+ ];
17831
+ await client.tx(async (t) => {
17832
+ for (const tableName of tables) {
17833
+ const table = qualifiedTable(schema, tableName);
17834
+ await t.query(`DELETE FROM ${table} WHERE "traceId" IN (${placeholders})${scopeCondition}`, params);
17835
+ }
17836
+ });
17703
17837
  }
17704
17838
  /** Truncate the span_events table. */
17705
17839
  async function dangerouslyClearTracing(client, schema) {
@@ -17742,6 +17876,8 @@ function wrapError(op, error, details) {
17742
17876
  }
17743
17877
  var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext extends _mastra_core_storage.ObservabilityStorage {
17744
17878
  #client;
17879
+ /** Reader-backed client for standalone reads; writes, DDL, and discovery-cache refresh stay on #client. */
17880
+ #readClient;
17745
17881
  #schema;
17746
17882
  #partitioning;
17747
17883
  #discoveryConfig;
@@ -17749,8 +17885,9 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
17749
17885
  #partitionMode;
17750
17886
  constructor(config) {
17751
17887
  super();
17752
- const { client, schemaName } = resolvePgConfig(config);
17888
+ const { client, readClient, schemaName } = resolvePgConfig(config);
17753
17889
  this.#client = client;
17890
+ this.#readClient = readClient;
17754
17891
  this.#schema = schemaName ?? "public";
17755
17892
  this.#partitioning = config.partitioning ?? {};
17756
17893
  this.#discoveryConfig = config.discovery ?? {};
@@ -17935,34 +18072,34 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
17935
18072
  await this.#run("BATCH_CREATE_SPANS", () => batchCreateSpans(this.#client, this.#schema, args), { count: args.records.length });
17936
18073
  }
17937
18074
  async getSpan(args) {
17938
- return this.#run("GET_SPAN", () => getSpan(this.#client, this.#schema, args), {
18075
+ return this.#run("GET_SPAN", () => getSpan(this.#readClient, this.#schema, args), {
17939
18076
  traceId: args.traceId,
17940
18077
  spanId: args.spanId
17941
18078
  });
17942
18079
  }
17943
18080
  async getSpans(args) {
17944
- return this.#run("GET_SPANS", () => getSpans(this.#client, this.#schema, args), {
18081
+ return this.#run("GET_SPANS", () => getSpans(this.#readClient, this.#schema, args), {
17945
18082
  traceId: args.traceId,
17946
18083
  count: args.spanIds.length
17947
18084
  });
17948
18085
  }
17949
18086
  async getRootSpan(args) {
17950
- return this.#run("GET_ROOT_SPAN", () => getRootSpan(this.#client, this.#schema, args), { traceId: args.traceId });
18087
+ return this.#run("GET_ROOT_SPAN", () => getRootSpan(this.#readClient, this.#schema, args), { traceId: args.traceId });
17951
18088
  }
17952
18089
  async getTrace(args) {
17953
- return this.#run("GET_TRACE", () => getTrace(this.#client, this.#schema, args), { traceId: args.traceId });
18090
+ return this.#run("GET_TRACE", () => getTrace(this.#readClient, this.#schema, args), { traceId: args.traceId });
17954
18091
  }
17955
18092
  async getTraceLight(args) {
17956
- return this.#run("GET_TRACE_LIGHT", () => getTraceLight(this.#client, this.#schema, args), { traceId: args.traceId });
18093
+ return this.#run("GET_TRACE_LIGHT", () => getTraceLight(this.#readClient, this.#schema, args), { traceId: args.traceId });
17957
18094
  }
17958
18095
  async listTraces(args) {
17959
- return this.#run("LIST_TRACES", () => listTraces(this.#client, this.#schema, args));
18096
+ return this.#run("LIST_TRACES", () => listTraces(this.#readClient, this.#schema, args));
17960
18097
  }
17961
18098
  async queryTraces(plan) {
17962
- return this.#run("QUERY_TRACES", () => queryTraces(this.#client, this.#schema, plan, this.#traceQueryTimeoutMs));
18099
+ return this.#run("QUERY_TRACES", () => queryTraces(this.#readClient, this.#schema, plan, this.#traceQueryTimeoutMs));
17963
18100
  }
17964
18101
  async listBranches(args) {
17965
- return this.#run("LIST_BRANCHES", () => listBranches(this.#client, this.#schema, args));
18102
+ return this.#run("LIST_BRANCHES", () => listBranches(this.#readClient, this.#schema, args));
17966
18103
  }
17967
18104
  async batchCreateLogs(args) {
17968
18105
  await this.#run("BATCH_CREATE_LOGS", () => batchCreateLogs(this.#client, this.#schema, args), { count: args.logs.length });
@@ -17983,58 +18120,58 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
17983
18120
  await this.#run("BATCH_CREATE_FEEDBACK", () => batchCreateFeedback(this.#client, this.#schema, args), { count: args.feedbacks.length });
17984
18121
  }
17985
18122
  async listLogs(args) {
17986
- return this.#run("LIST_LOGS", () => listLogs(this.#client, this.#schema, args));
18123
+ return this.#run("LIST_LOGS", () => listLogs(this.#readClient, this.#schema, args));
17987
18124
  }
17988
18125
  async listMetrics(args) {
17989
- return this.#run("LIST_METRICS", () => listMetrics(this.#client, this.#schema, args));
18126
+ return this.#run("LIST_METRICS", () => listMetrics(this.#readClient, this.#schema, args));
17990
18127
  }
17991
18128
  async listScores(args) {
17992
- return this.#run("LIST_SCORES", () => listScores(this.#client, this.#schema, args));
18129
+ return this.#run("LIST_SCORES", () => listScores(this.#readClient, this.#schema, args));
17993
18130
  }
17994
18131
  async getScoreById(scoreId) {
17995
- return this.#run("GET_SCORE_BY_ID", () => getScoreById(this.#client, this.#schema, scoreId), { scoreId });
18132
+ return this.#run("GET_SCORE_BY_ID", () => getScoreById(this.#readClient, this.#schema, scoreId), { scoreId });
17996
18133
  }
17997
18134
  async listFeedback(args) {
17998
- return this.#run("LIST_FEEDBACK", () => listFeedback(this.#client, this.#schema, args));
18135
+ return this.#run("LIST_FEEDBACK", () => listFeedback(this.#readClient, this.#schema, args));
17999
18136
  }
18000
18137
  async updateFeedbackReviewStatus(args) {
18001
18138
  return this.#run("UPDATE_FEEDBACK_REVIEW_STATUS", () => updateFeedbackReviewStatus(this.#client, this.#schema, args), { feedbackId: args.feedbackId });
18002
18139
  }
18003
18140
  async getMetricAggregate(args) {
18004
- return this.#run("GET_METRIC_AGGREGATE", () => getMetricAggregate(this.#client, this.#schema, args));
18141
+ return this.#run("GET_METRIC_AGGREGATE", () => getMetricAggregate(this.#readClient, this.#schema, args));
18005
18142
  }
18006
18143
  async getMetricBreakdown(args) {
18007
- return this.#run("GET_METRIC_BREAKDOWN", () => getMetricBreakdown(this.#client, this.#schema, args));
18144
+ return this.#run("GET_METRIC_BREAKDOWN", () => getMetricBreakdown(this.#readClient, this.#schema, args));
18008
18145
  }
18009
18146
  async getMetricTimeSeries(args) {
18010
- return this.#run("GET_METRIC_TIME_SERIES", () => getMetricTimeSeries(this.#client, this.#schema, args));
18147
+ return this.#run("GET_METRIC_TIME_SERIES", () => getMetricTimeSeries(this.#readClient, this.#schema, args));
18011
18148
  }
18012
18149
  async getMetricPercentiles(args) {
18013
- return this.#run("GET_METRIC_PERCENTILES", () => getMetricPercentiles(this.#client, this.#schema, args));
18150
+ return this.#run("GET_METRIC_PERCENTILES", () => getMetricPercentiles(this.#readClient, this.#schema, args));
18014
18151
  }
18015
18152
  async getScoreAggregate(args) {
18016
- return this.#run("GET_SCORE_AGGREGATE", () => getScoreAggregate(this.#client, this.#schema, args));
18153
+ return this.#run("GET_SCORE_AGGREGATE", () => getScoreAggregate(this.#readClient, this.#schema, args));
18017
18154
  }
18018
18155
  async getScoreBreakdown(args) {
18019
- return this.#run("GET_SCORE_BREAKDOWN", () => getScoreBreakdown(this.#client, this.#schema, args));
18156
+ return this.#run("GET_SCORE_BREAKDOWN", () => getScoreBreakdown(this.#readClient, this.#schema, args));
18020
18157
  }
18021
18158
  async getScoreTimeSeries(args) {
18022
- return this.#run("GET_SCORE_TIME_SERIES", () => getScoreTimeSeries(this.#client, this.#schema, args));
18159
+ return this.#run("GET_SCORE_TIME_SERIES", () => getScoreTimeSeries(this.#readClient, this.#schema, args));
18023
18160
  }
18024
18161
  async getScorePercentiles(args) {
18025
- return this.#run("GET_SCORE_PERCENTILES", () => getScorePercentiles(this.#client, this.#schema, args));
18162
+ return this.#run("GET_SCORE_PERCENTILES", () => getScorePercentiles(this.#readClient, this.#schema, args));
18026
18163
  }
18027
18164
  async getFeedbackAggregate(args) {
18028
- return this.#run("GET_FEEDBACK_AGGREGATE", () => getFeedbackAggregate(this.#client, this.#schema, args));
18165
+ return this.#run("GET_FEEDBACK_AGGREGATE", () => getFeedbackAggregate(this.#readClient, this.#schema, args));
18029
18166
  }
18030
18167
  async getFeedbackBreakdown(args) {
18031
- return this.#run("GET_FEEDBACK_BREAKDOWN", () => getFeedbackBreakdown(this.#client, this.#schema, args));
18168
+ return this.#run("GET_FEEDBACK_BREAKDOWN", () => getFeedbackBreakdown(this.#readClient, this.#schema, args));
18032
18169
  }
18033
18170
  async getFeedbackTimeSeries(args) {
18034
- return this.#run("GET_FEEDBACK_TIME_SERIES", () => getFeedbackTimeSeries(this.#client, this.#schema, args));
18171
+ return this.#run("GET_FEEDBACK_TIME_SERIES", () => getFeedbackTimeSeries(this.#readClient, this.#schema, args));
18035
18172
  }
18036
18173
  async getFeedbackPercentiles(args) {
18037
- return this.#run("GET_FEEDBACK_PERCENTILES", () => getFeedbackPercentiles(this.#client, this.#schema, args));
18174
+ return this.#run("GET_FEEDBACK_PERCENTILES", () => getFeedbackPercentiles(this.#readClient, this.#schema, args));
18038
18175
  }
18039
18176
  async getEntityTypes(args) {
18040
18177
  return this.#run("GET_ENTITY_TYPES", () => getEntityTypes(this.#client, this.#schema, args, this.#discovery));
@@ -18093,9 +18230,10 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18093
18230
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_PROMPT_BLOCKS, _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS];
18094
18231
  constructor(config) {
18095
18232
  super();
18096
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18233
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18097
18234
  this.#db = new PgDB({
18098
18235
  client,
18236
+ readClient,
18099
18237
  schemaName,
18100
18238
  skipDefaultIndexes
18101
18239
  });
@@ -18172,12 +18310,19 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18172
18310
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_PROMPT_BLOCKS });
18173
18311
  }
18174
18312
  async getById(id) {
18313
+ return this.#getById(this.#db.readClient, id);
18314
+ }
18315
+ /**
18316
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
18317
+ * lagging read replica cannot yield stale or missing rows mid-update.
18318
+ */
18319
+ async #getById(client, id) {
18175
18320
  try {
18176
18321
  const tableName = getTableName$5({
18177
18322
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCKS,
18178
18323
  schemaName: getSchemaName$5(this.#schema)
18179
18324
  });
18180
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18325
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18181
18326
  if (!result) return null;
18182
18327
  return this.parseBlockRow(result);
18183
18328
  } catch (error) {
@@ -18256,7 +18401,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18256
18401
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCKS,
18257
18402
  schemaName: getSchemaName$5(this.#schema)
18258
18403
  });
18259
- const existingBlock = await this.getById(id);
18404
+ const existingBlock = await this.#getById(this.#db.client, id);
18260
18405
  if (!existingBlock) throw new _mastra_core_error.MastraError({
18261
18406
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND"),
18262
18407
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -18295,7 +18440,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18295
18440
  values.push(now);
18296
18441
  values.push(id);
18297
18442
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
18298
- const updatedBlock = await this.getById(id);
18443
+ const updatedBlock = await this.#getById(this.#db.client, id);
18299
18444
  if (!updatedBlock) throw new _mastra_core_error.MastraError({
18300
18445
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
18301
18446
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -18364,7 +18509,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18364
18509
  queryParams.push(JSON.stringify(metadata));
18365
18510
  }
18366
18511
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
18367
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
18512
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
18368
18513
  const total = parseInt(countResult.count, 10);
18369
18514
  if (total === 0) return {
18370
18515
  promptBlocks: [],
@@ -18375,7 +18520,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18375
18520
  };
18376
18521
  const limitValue = perPageInput === false ? total : perPage;
18377
18522
  return {
18378
- promptBlocks: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
18523
+ promptBlocks: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
18379
18524
  ...queryParams,
18380
18525
  limitValue,
18381
18526
  offset
@@ -18454,7 +18599,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18454
18599
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18455
18600
  schemaName: getSchemaName$5(this.#schema)
18456
18601
  });
18457
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18602
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18458
18603
  if (!result) return null;
18459
18604
  return this.parseVersionRow(result);
18460
18605
  } catch (error) {
@@ -18473,7 +18618,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18473
18618
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18474
18619
  schemaName: getSchemaName$5(this.#schema)
18475
18620
  });
18476
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 AND "versionNumber" = $2`, [blockId, versionNumber]);
18621
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 AND "versionNumber" = $2`, [blockId, versionNumber]);
18477
18622
  if (!result) return null;
18478
18623
  return this.parseVersionRow(result);
18479
18624
  } catch (error) {
@@ -18495,7 +18640,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18495
18640
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18496
18641
  schemaName: getSchemaName$5(this.#schema)
18497
18642
  });
18498
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [blockId]);
18643
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [blockId]);
18499
18644
  if (!result) return null;
18500
18645
  return this.parseVersionRow(result);
18501
18646
  } catch (error) {
@@ -18524,7 +18669,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18524
18669
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18525
18670
  schemaName: getSchemaName$5(this.#schema)
18526
18671
  });
18527
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18672
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18528
18673
  const total = parseInt(countResult.count, 10);
18529
18674
  if (total === 0) return {
18530
18675
  versions: [],
@@ -18535,7 +18680,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18535
18680
  };
18536
18681
  const limitValue = perPageInput === false ? total : perPage;
18537
18682
  return {
18538
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
18683
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
18539
18684
  blockId,
18540
18685
  limitValue,
18541
18686
  offset
@@ -18605,7 +18750,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18605
18750
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18606
18751
  schemaName: getSchemaName$5(this.#schema)
18607
18752
  });
18608
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18753
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18609
18754
  return parseInt(result.count, 10);
18610
18755
  } catch (error) {
18611
18756
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -18706,6 +18851,7 @@ function rowToTrigger(row) {
18706
18851
  var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorage {
18707
18852
  #db;
18708
18853
  #client;
18854
+ #readClient;
18709
18855
  #schema;
18710
18856
  #skipDefaultIndexes;
18711
18857
  #indexes;
@@ -18725,10 +18871,12 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18725
18871
  } };
18726
18872
  constructor(config) {
18727
18873
  super();
18728
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18874
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18729
18875
  this.#client = client;
18876
+ this.#readClient = readClient;
18730
18877
  this.#db = new PgDB({
18731
18878
  client,
18879
+ readClient,
18732
18880
  schemaName,
18733
18881
  skipDefaultIndexes
18734
18882
  });
@@ -18852,7 +19000,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18852
19000
  return getTableName$2(tableName, getSchemaName$2((0, _mastra_core_utils.parseSqlIdentifier)(this.#schema, "schema name")));
18853
19001
  }
18854
19002
  async createSchedule(schedule) {
18855
- if (await this.getSchedule(schedule.id)) throw new Error(`Schedule with id "${schedule.id}" already exists`);
19003
+ if (await this.#getSchedule(this.#client, schedule.id)) throw new Error(`Schedule with id "${schedule.id}" already exists`);
18856
19004
  await this.#db.insert({
18857
19005
  tableName: _mastra_core_storage.TABLE_SCHEDULES,
18858
19006
  record: {
@@ -18874,7 +19022,14 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18874
19022
  return schedule;
18875
19023
  }
18876
19024
  async getSchedule(id) {
18877
- const row = await this.#client.oneOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} WHERE id = $1`, [id]);
19025
+ return this.#getSchedule(this.#readClient, id);
19026
+ }
19027
+ /**
19028
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
19029
+ * lagging read replica cannot yield stale or missing rows mid-update.
19030
+ */
19031
+ async #getSchedule(client, id) {
19032
+ const row = await client.oneOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} WHERE id = $1`, [id]);
18878
19033
  return row ? rowToSchedule(row) : null;
18879
19034
  }
18880
19035
  async listSchedules(filter) {
@@ -18899,7 +19054,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18899
19054
  conditions.push(`owner_id = $${params.length}`);
18900
19055
  }
18901
19056
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
18902
- return (await this.#client.manyOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} ${where} ORDER BY created_at ASC`, params)).map(rowToSchedule);
19057
+ return (await this.#readClient.manyOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} ${where} ORDER BY created_at ASC`, params)).map(rowToSchedule);
18903
19058
  }
18904
19059
  async listDueSchedules(now, limit) {
18905
19060
  const cap = limit ?? 100;
@@ -18929,13 +19084,13 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18929
19084
  if ("ownerId" in patch) push("owner_id = ?", patch.ownerId ?? null);
18930
19085
  push("updated_at = ?", Date.now());
18931
19086
  if (setClauses.length === 1) {
18932
- const existing = await this.getSchedule(id);
19087
+ const existing = await this.#getSchedule(this.#client, id);
18933
19088
  if (!existing) throw new Error(`Schedule ${id} not found`);
18934
19089
  return existing;
18935
19090
  }
18936
19091
  params.push(id);
18937
19092
  await this.#client.none(`UPDATE ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} SET ${setClauses.join(", ")} WHERE id = $${params.length}`, params);
18938
- const updated = await this.getSchedule(id);
19093
+ const updated = await this.#getSchedule(this.#client, id);
18939
19094
  if (!updated) throw new Error(`Schedule ${id} not found`);
18940
19095
  return updated;
18941
19096
  }
@@ -18992,7 +19147,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18992
19147
  params.push(Math.floor(opts.limit));
18993
19148
  limitClause = `LIMIT $${params.length}`;
18994
19149
  }
18995
- return (await this.#client.manyOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULE_TRIGGERS)}
19150
+ return (await this.#readClient.manyOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULE_TRIGGERS)}
18996
19151
  WHERE ${conditions.join(" AND ")}
18997
19152
  ORDER BY actual_fire_at DESC
18998
19153
  ${limitClause}`, params)).map(rowToTrigger);
@@ -19018,9 +19173,10 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19018
19173
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SCORER_DEFINITIONS, _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS];
19019
19174
  constructor(config) {
19020
19175
  super();
19021
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19176
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19022
19177
  this.#db = new PgDB({
19023
19178
  client,
19179
+ readClient,
19024
19180
  schemaName,
19025
19181
  skipDefaultIndexes
19026
19182
  });
@@ -19097,12 +19253,19 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19097
19253
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS });
19098
19254
  }
19099
19255
  async getById(id) {
19256
+ return this.#getById(this.#db.readClient, id);
19257
+ }
19258
+ /**
19259
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
19260
+ * lagging read replica cannot yield stale or missing rows mid-update.
19261
+ */
19262
+ async #getById(client, id) {
19100
19263
  try {
19101
19264
  const tableName = getTableName$5({
19102
19265
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS,
19103
19266
  schemaName: getSchemaName$5(this.#schema)
19104
19267
  });
19105
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19268
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19106
19269
  if (!result) return null;
19107
19270
  return this.parseScorerRow(result);
19108
19271
  } catch (error) {
@@ -19185,7 +19348,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19185
19348
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS,
19186
19349
  schemaName: getSchemaName$5(this.#schema)
19187
19350
  });
19188
- const existingScorer = await this.getById(id);
19351
+ const existingScorer = await this.#getById(this.#db.client, id);
19189
19352
  if (!existingScorer) throw new _mastra_core_error.MastraError({
19190
19353
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND"),
19191
19354
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -19224,7 +19387,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19224
19387
  values.push(now);
19225
19388
  values.push(id);
19226
19389
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
19227
- const updatedScorer = await this.getById(id);
19390
+ const updatedScorer = await this.#getById(this.#db.client, id);
19228
19391
  if (!updatedScorer) throw new _mastra_core_error.MastraError({
19229
19392
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
19230
19393
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -19301,7 +19464,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19301
19464
  queryParams.push(JSON.stringify(metadata));
19302
19465
  }
19303
19466
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
19304
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
19467
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
19305
19468
  const total = parseInt(countResult.count, 10);
19306
19469
  if (total === 0) return {
19307
19470
  scorerDefinitions: [],
@@ -19312,7 +19475,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19312
19475
  };
19313
19476
  const limitValue = perPageInput === false ? total : perPage;
19314
19477
  return {
19315
- scorerDefinitions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
19478
+ scorerDefinitions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
19316
19479
  ...queryParams,
19317
19480
  limitValue,
19318
19481
  offset
@@ -19394,7 +19557,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19394
19557
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19395
19558
  schemaName: getSchemaName$5(this.#schema)
19396
19559
  });
19397
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19560
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19398
19561
  if (!result) return null;
19399
19562
  return this.parseVersionRow(result);
19400
19563
  } catch (error) {
@@ -19413,7 +19576,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19413
19576
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19414
19577
  schemaName: getSchemaName$5(this.#schema)
19415
19578
  });
19416
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 AND "versionNumber" = $2`, [scorerDefinitionId, versionNumber]);
19579
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 AND "versionNumber" = $2`, [scorerDefinitionId, versionNumber]);
19417
19580
  if (!result) return null;
19418
19581
  return this.parseVersionRow(result);
19419
19582
  } catch (error) {
@@ -19435,7 +19598,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19435
19598
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19436
19599
  schemaName: getSchemaName$5(this.#schema)
19437
19600
  });
19438
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [scorerDefinitionId]);
19601
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [scorerDefinitionId]);
19439
19602
  if (!result) return null;
19440
19603
  return this.parseVersionRow(result);
19441
19604
  } catch (error) {
@@ -19464,7 +19627,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19464
19627
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19465
19628
  schemaName: getSchemaName$5(this.#schema)
19466
19629
  });
19467
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19630
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19468
19631
  const total = parseInt(countResult.count, 10);
19469
19632
  if (total === 0) return {
19470
19633
  versions: [],
@@ -19475,7 +19638,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19475
19638
  };
19476
19639
  const limitValue = perPageInput === false ? total : perPage;
19477
19640
  return {
19478
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
19641
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
19479
19642
  scorerDefinitionId,
19480
19643
  limitValue,
19481
19644
  offset
@@ -19545,7 +19708,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19545
19708
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19546
19709
  schemaName: getSchemaName$5(this.#schema)
19547
19710
  });
19548
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19711
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19549
19712
  return parseInt(result.count, 10);
19550
19713
  } catch (error) {
19551
19714
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -19642,9 +19805,10 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19642
19805
  } };
19643
19806
  constructor(config) {
19644
19807
  super();
19645
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19808
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19646
19809
  this.#db = new PgDB({
19647
19810
  client,
19811
+ readClient,
19648
19812
  schemaName,
19649
19813
  skipDefaultIndexes
19650
19814
  });
@@ -19778,7 +19942,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19778
19942
  }
19779
19943
  async getScoreById({ id }) {
19780
19944
  try {
19781
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${getTableName$1({
19945
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${getTableName$1({
19782
19946
  indexName: _mastra_core_storage.TABLE_SCORERS,
19783
19947
  schemaName: getSchemaName$1(this.#schema)
19784
19948
  })} WHERE id = $1`, [id]);
@@ -19810,7 +19974,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19810
19974
  }
19811
19975
  paramIndex = applyTenancyFilters(conditions, queryParams, paramIndex, filters);
19812
19976
  const whereClause = conditions.join(" AND ");
19813
- const total = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
19977
+ const total = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
19814
19978
  indexName: _mastra_core_storage.TABLE_SCORERS,
19815
19979
  schemaName: getSchemaName$1(this.#schema)
19816
19980
  })} WHERE ${whereClause}`, queryParams);
@@ -19828,7 +19992,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19828
19992
  };
19829
19993
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
19830
19994
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
19831
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
19995
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
19832
19996
  indexName: _mastra_core_storage.TABLE_SCORERS,
19833
19997
  schemaName: getSchemaName$1(this.#schema)
19834
19998
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -19918,7 +20082,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19918
20082
  const queryParams = [runId];
19919
20083
  let paramIndex = applyTenancyFilters(conditions, queryParams, 2, filters);
19920
20084
  const whereClause = conditions.join(" AND ");
19921
- const total = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
20085
+ const total = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
19922
20086
  indexName: _mastra_core_storage.TABLE_SCORERS,
19923
20087
  schemaName: getSchemaName$1(this.#schema)
19924
20088
  })} WHERE ${whereClause}`, queryParams);
@@ -19936,7 +20100,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19936
20100
  };
19937
20101
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
19938
20102
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
19939
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
20103
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
19940
20104
  indexName: _mastra_core_storage.TABLE_SCORERS,
19941
20105
  schemaName: getSchemaName$1(this.#schema)
19942
20106
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -19967,7 +20131,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19967
20131
  const queryParams = [entityId, entityType];
19968
20132
  let paramIndex = applyTenancyFilters(conditions, queryParams, 3, filters);
19969
20133
  const whereClause = conditions.join(" AND ");
19970
- const total = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
20134
+ const total = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
19971
20135
  indexName: _mastra_core_storage.TABLE_SCORERS,
19972
20136
  schemaName: getSchemaName$1(this.#schema)
19973
20137
  })} WHERE ${whereClause}`, queryParams);
@@ -19985,7 +20149,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19985
20149
  };
19986
20150
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
19987
20151
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
19988
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
20152
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
19989
20153
  indexName: _mastra_core_storage.TABLE_SCORERS,
19990
20154
  schemaName: getSchemaName$1(this.#schema)
19991
20155
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -20020,14 +20184,14 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20020
20184
  const queryParams = [traceId, spanId];
20021
20185
  let paramIndex = applyTenancyFilters(conditions, queryParams, 3, filters);
20022
20186
  const whereClause = conditions.join(" AND ");
20023
- const countSQLResult = await this.#db.client.oneOrNone(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`, queryParams);
20187
+ const countSQLResult = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`, queryParams);
20024
20188
  const total = Number(countSQLResult?.count ?? 0);
20025
20189
  const { page, perPage: perPageInput } = pagination;
20026
20190
  const perPage = (0, _mastra_core_storage.normalizePerPage)(perPageInput, 100);
20027
20191
  const { offset: start, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
20028
20192
  const limitValue = perPageInput === false ? total : perPage;
20029
20193
  const end = perPageInput === false ? total : start + perPage;
20030
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
20194
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
20031
20195
  ...queryParams,
20032
20196
  limitValue,
20033
20197
  start
@@ -20075,9 +20239,10 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20075
20239
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SKILLS, _mastra_core_storage.TABLE_SKILL_VERSIONS];
20076
20240
  constructor(config) {
20077
20241
  super();
20078
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20242
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20079
20243
  this.#db = new PgDB({
20080
20244
  client,
20245
+ readClient,
20081
20246
  schemaName,
20082
20247
  skipDefaultIndexes
20083
20248
  });
@@ -20151,12 +20316,19 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20151
20316
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_SKILLS });
20152
20317
  }
20153
20318
  async getById(id) {
20319
+ return this.#getById(this.#db.readClient, id);
20320
+ }
20321
+ /**
20322
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
20323
+ * lagging read replica cannot yield stale or missing rows mid-update.
20324
+ */
20325
+ async #getById(client, id) {
20154
20326
  try {
20155
20327
  const tableName = getTableName$5({
20156
20328
  indexName: _mastra_core_storage.TABLE_SKILLS,
20157
20329
  schemaName: getSchemaName$5(this.#schema)
20158
20330
  });
20159
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20331
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20160
20332
  if (!result) return null;
20161
20333
  return this.parseSkillRow(result);
20162
20334
  } catch (error) {
@@ -20238,7 +20410,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20238
20410
  indexName: _mastra_core_storage.TABLE_SKILLS,
20239
20411
  schemaName: getSchemaName$5(this.#schema)
20240
20412
  });
20241
- if (!await this.getById(id)) throw new _mastra_core_error.MastraError({
20413
+ if (!await this.#getById(this.#db.client, id)) throw new _mastra_core_error.MastraError({
20242
20414
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NOT_FOUND"),
20243
20415
  domain: _mastra_core_error.ErrorDomain.STORAGE,
20244
20416
  category: _mastra_core_error.ErrorCategory.USER,
@@ -20250,7 +20422,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20250
20422
  const configFields = {};
20251
20423
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
20252
20424
  if (SNAPSHOT_FIELDS$1.some((field) => field in configFields)) {
20253
- const latestVersion = await this.getLatestVersion(id);
20425
+ const latestVersion = await this.#getLatestVersion(this.#db.client, id);
20254
20426
  if (!latestVersion) throw new _mastra_core_error.MastraError({
20255
20427
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NO_VERSIONS"),
20256
20428
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -20307,7 +20479,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20307
20479
  values.push(now);
20308
20480
  values.push(id);
20309
20481
  if (setClauses.length > 2 || versionCreated) await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
20310
- const updatedSkill = await this.getById(id);
20482
+ const updatedSkill = await this.#getById(this.#db.client, id);
20311
20483
  if (!updatedSkill) throw new _mastra_core_error.MastraError({
20312
20484
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NOT_FOUND_AFTER_UPDATE"),
20313
20485
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -20400,7 +20572,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20400
20572
  const joinClause = useJoin && joinSqlIdx !== null ? `LEFT JOIN ${favoritesTable} sr ON sr."entityType" = 'skill' AND sr."entityId" = s.id AND sr."userId" = $${joinSqlIdx}` : "";
20401
20573
  const joinParams = useJoin && joinUserId ? [joinUserId] : [];
20402
20574
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
20403
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} s ${joinClause} ${whereClause}`, [...joinParams, ...queryParams]);
20575
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} s ${joinClause} ${whereClause}`, [...joinParams, ...queryParams]);
20404
20576
  const total = parseInt(countResult.count, 10);
20405
20577
  if (total === 0) return {
20406
20578
  skills: [],
@@ -20418,7 +20590,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20418
20590
  const limitIdx = paramIdx++;
20419
20591
  const offsetIdx = paramIdx++;
20420
20592
  return {
20421
- skills: (await this.#db.client.manyOrNone(`SELECT s.* FROM ${tableName} s ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
20593
+ skills: (await this.#db.readClient.manyOrNone(`SELECT s.* FROM ${tableName} s ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
20422
20594
  ...joinParams,
20423
20595
  ...queryParams,
20424
20596
  limitValue,
@@ -20506,7 +20678,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20506
20678
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20507
20679
  schemaName: getSchemaName$5(this.#schema)
20508
20680
  });
20509
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20681
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20510
20682
  if (!result) return null;
20511
20683
  return this.parseVersionRow(result);
20512
20684
  } catch (error) {
@@ -20527,7 +20699,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20527
20699
  schemaName: getSchemaName$5(this.#schema)
20528
20700
  });
20529
20701
  const placeholders = ids.map((_, i) => `$${i + 1}`).join(", ");
20530
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE id IN (${placeholders})`, ids)).map((row) => this.parseVersionRow(row));
20702
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE id IN (${placeholders})`, ids)).map((row) => this.parseVersionRow(row));
20531
20703
  } catch (error) {
20532
20704
  if (error instanceof _mastra_core_error.MastraError) throw error;
20533
20705
  throw new _mastra_core_error.MastraError({
@@ -20544,7 +20716,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20544
20716
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20545
20717
  schemaName: getSchemaName$5(this.#schema)
20546
20718
  });
20547
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 AND "versionNumber" = $2`, [skillId, versionNumber]);
20719
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 AND "versionNumber" = $2`, [skillId, versionNumber]);
20548
20720
  if (!result) return null;
20549
20721
  return this.parseVersionRow(result);
20550
20722
  } catch (error) {
@@ -20561,12 +20733,19 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20561
20733
  }
20562
20734
  }
20563
20735
  async getLatestVersion(skillId) {
20736
+ return this.#getLatestVersion(this.#db.readClient, skillId);
20737
+ }
20738
+ /**
20739
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
20740
+ * lagging read replica cannot yield stale or missing rows mid-update.
20741
+ */
20742
+ async #getLatestVersion(client, skillId) {
20564
20743
  try {
20565
20744
  const tableName = getTableName$5({
20566
20745
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20567
20746
  schemaName: getSchemaName$5(this.#schema)
20568
20747
  });
20569
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [skillId]);
20748
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [skillId]);
20570
20749
  if (!result) return null;
20571
20750
  return this.parseVersionRow(result);
20572
20751
  } catch (error) {
@@ -20595,7 +20774,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20595
20774
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20596
20775
  schemaName: getSchemaName$5(this.#schema)
20597
20776
  });
20598
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20777
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20599
20778
  const total = parseInt(countResult.count, 10);
20600
20779
  if (total === 0) return {
20601
20780
  versions: [],
@@ -20606,7 +20785,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20606
20785
  };
20607
20786
  const limitValue = perPageInput === false ? total : perPage;
20608
20787
  return {
20609
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
20788
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
20610
20789
  skillId,
20611
20790
  limitValue,
20612
20791
  offset
@@ -20676,7 +20855,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20676
20855
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20677
20856
  schemaName: getSchemaName$5(this.#schema)
20678
20857
  });
20679
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20858
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20680
20859
  return parseInt(result.count, 10);
20681
20860
  } catch (error) {
20682
20861
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -20751,9 +20930,10 @@ var ThreadStatePG = class ThreadStatePG extends _mastra_core_storage.ThreadState
20751
20930
  } };
20752
20931
  constructor(config) {
20753
20932
  super();
20754
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
20933
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
20755
20934
  this.#db = new PgDB({
20756
20935
  client,
20936
+ readClient,
20757
20937
  schemaName,
20758
20938
  skipDefaultIndexes
20759
20939
  });
@@ -20916,9 +21096,10 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
20916
21096
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_TOOL_PROVIDER_CONNECTIONS];
20917
21097
  constructor(config) {
20918
21098
  super();
20919
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21099
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20920
21100
  this.#db = new PgDB({
20921
21101
  client,
21102
+ readClient,
20922
21103
  schemaName,
20923
21104
  skipDefaultIndexes
20924
21105
  });
@@ -20997,7 +21178,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
20997
21178
  schemaName: getSchemaName$5(this.#schema)
20998
21179
  });
20999
21180
  try {
21000
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "authorId" = $1 AND "providerId" = $2 AND "connectionId" = $3 LIMIT 1`, [
21181
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "authorId" = $1 AND "providerId" = $2 AND "connectionId" = $3 LIMIT 1`, [
21001
21182
  authorId,
21002
21183
  providerId,
21003
21184
  connectionId
@@ -21104,7 +21285,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
21104
21285
  clauses.push(`scope = $${args.length}`);
21105
21286
  }
21106
21287
  const whereClause = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
21107
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName}${whereClause}`, args)).map((row) => rowToToolProviderConnection(row));
21288
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName}${whereClause}`, args)).map((row) => rowToToolProviderConnection(row));
21108
21289
  } catch (error) {
21109
21290
  throw new _mastra_core_error.MastraError({
21110
21291
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "TOOL_PROVIDER_CONNECTION_LIST", "FAILED"),
@@ -21180,9 +21361,10 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21180
21361
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS];
21181
21362
  constructor(config) {
21182
21363
  super();
21183
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21364
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21184
21365
  this.#db = new PgDB({
21185
21366
  client,
21367
+ readClient,
21186
21368
  schemaName,
21187
21369
  skipDefaultIndexes
21188
21370
  });
@@ -21239,7 +21421,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21239
21421
  }
21240
21422
  async upsert(input) {
21241
21423
  const now = /* @__PURE__ */ new Date();
21242
- if (!await this.get(input.id)) {
21424
+ if (!await this.#get(this.#db.client, input.id)) {
21243
21425
  if (!("inputSchema" in input) || !input.inputSchema) throw new Error(`Cannot create workflow definition "${input.id}": inputSchema is required.`);
21244
21426
  if (!("outputSchema" in input) || !input.outputSchema) throw new Error(`Cannot create workflow definition "${input.id}": outputSchema is required.`);
21245
21427
  if (!("graph" in input) || !input.graph) throw new Error(`Cannot create workflow definition "${input.id}": graph is required.`);
@@ -21265,10 +21447,10 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21265
21447
  record
21266
21448
  });
21267
21449
  } catch (error) {
21268
- if (!await this.get(input.id)) throw error;
21450
+ if (!await this.#get(this.#db.client, input.id)) throw error;
21269
21451
  return this.applyUpdate(input, now);
21270
21452
  }
21271
- const created = await this.get(input.id);
21453
+ const created = await this.#get(this.#db.client, input.id);
21272
21454
  if (!created) throw new Error(`Failed to persist workflow definition "${input.id}".`);
21273
21455
  return created;
21274
21456
  }
@@ -21291,16 +21473,23 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21291
21473
  keys: { id: input.id },
21292
21474
  data
21293
21475
  });
21294
- const updated = await this.get(input.id);
21476
+ const updated = await this.#get(this.#db.client, input.id);
21295
21477
  if (!updated) throw new Error(`Failed to update workflow definition "${input.id}".`);
21296
21478
  return updated;
21297
21479
  }
21298
21480
  async get(id) {
21481
+ return this.#get(this.#db.readClient, id);
21482
+ }
21483
+ /**
21484
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
21485
+ * lagging read replica cannot yield stale or missing rows mid-update.
21486
+ */
21487
+ async #get(client, id) {
21299
21488
  const tableName = getTableName$5({
21300
21489
  indexName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
21301
21490
  schemaName: getSchemaName$5(this.#schema)
21302
21491
  });
21303
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
21492
+ const row = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
21304
21493
  return row ? rowToDefinition(row) : null;
21305
21494
  }
21306
21495
  async list(args) {
@@ -21319,7 +21508,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21319
21508
  conditions.push(`"authorId" = $${params.length}`);
21320
21509
  }
21321
21510
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
21322
- const definitions = (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${where} ORDER BY "updatedAt" DESC`, params)).map((row) => rowToDefinition(row));
21511
+ const definitions = (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${where} ORDER BY "updatedAt" DESC`, params)).map((row) => rowToDefinition(row));
21323
21512
  return {
21324
21513
  definitions,
21325
21514
  total: definitions.length
@@ -21384,9 +21573,10 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
21384
21573
  } };
21385
21574
  constructor(config) {
21386
21575
  super();
21387
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21576
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21388
21577
  this.#db = new PgDB({
21389
21578
  client,
21579
+ readClient,
21390
21580
  schemaName,
21391
21581
  skipDefaultIndexes
21392
21582
  });
@@ -21709,7 +21899,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
21709
21899
  ORDER BY "createdAt" DESC LIMIT 1
21710
21900
  `;
21711
21901
  const queryValues = values;
21712
- const result = await this.#db.client.oneOrNone(query, queryValues);
21902
+ const result = await this.#db.readClient.oneOrNone(query, queryValues);
21713
21903
  if (!result) return null;
21714
21904
  return this.parseWorkflowRun(result);
21715
21905
  } catch (error) {
@@ -21838,9 +22028,10 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
21838
22028
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_WORKSPACES, _mastra_core_storage.TABLE_WORKSPACE_VERSIONS];
21839
22029
  constructor(config) {
21840
22030
  super();
21841
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
22031
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21842
22032
  this.#db = new PgDB({
21843
22033
  client,
22034
+ readClient,
21844
22035
  schemaName,
21845
22036
  skipDefaultIndexes
21846
22037
  });
@@ -21904,12 +22095,19 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
21904
22095
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_WORKSPACES });
21905
22096
  }
21906
22097
  async getById(id) {
22098
+ return this.#getById(this.#db.readClient, id);
22099
+ }
22100
+ /**
22101
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
22102
+ * lagging read replica cannot yield stale or missing rows mid-update.
22103
+ */
22104
+ async #getById(client, id) {
21907
22105
  try {
21908
22106
  const tableName = getTableName$5({
21909
22107
  indexName: _mastra_core_storage.TABLE_WORKSPACES,
21910
22108
  schemaName: getSchemaName$5(this.#schema)
21911
22109
  });
21912
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
22110
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
21913
22111
  if (!result) return null;
21914
22112
  return this.parseWorkspaceRow(result);
21915
22113
  } catch (error) {
@@ -21988,7 +22186,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
21988
22186
  indexName: _mastra_core_storage.TABLE_WORKSPACES,
21989
22187
  schemaName: getSchemaName$5(this.#schema)
21990
22188
  });
21991
- const existingWorkspace = await this.getById(id);
22189
+ const existingWorkspace = await this.#getById(this.#db.client, id);
21992
22190
  if (!existingWorkspace) throw new _mastra_core_error.MastraError({
21993
22191
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NOT_FOUND"),
21994
22192
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22001,7 +22199,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22001
22199
  const configFields = {};
22002
22200
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
22003
22201
  if (SNAPSHOT_FIELDS.some((field) => field in configFields)) {
22004
- const latestVersion = await this.getLatestVersion(id);
22202
+ const latestVersion = await this.#getLatestVersion(this.#db.client, id);
22005
22203
  if (!latestVersion) throw new _mastra_core_error.MastraError({
22006
22204
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NO_VERSIONS"),
22007
22205
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22062,7 +22260,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22062
22260
  values.push(now);
22063
22261
  values.push(id);
22064
22262
  if (setClauses.length > 2 || versionCreated) await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
22065
- const updatedWorkspace = await this.getById(id);
22263
+ const updatedWorkspace = await this.#getById(this.#db.client, id);
22066
22264
  if (!updatedWorkspace) throw new _mastra_core_error.MastraError({
22067
22265
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NOT_FOUND_AFTER_UPDATE"),
22068
22266
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22127,7 +22325,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22127
22325
  queryParams.push(JSON.stringify(metadata));
22128
22326
  }
22129
22327
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
22130
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
22328
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
22131
22329
  const total = parseInt(countResult.count, 10);
22132
22330
  if (total === 0) return {
22133
22331
  workspaces: [],
@@ -22138,7 +22336,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22138
22336
  };
22139
22337
  const limitValue = perPageInput === false ? total : perPage;
22140
22338
  return {
22141
- workspaces: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
22339
+ workspaces: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
22142
22340
  ...queryParams,
22143
22341
  limitValue,
22144
22342
  offset
@@ -22223,7 +22421,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22223
22421
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22224
22422
  schemaName: getSchemaName$5(this.#schema)
22225
22423
  });
22226
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
22424
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
22227
22425
  if (!result) return null;
22228
22426
  return this.parseVersionRow(result);
22229
22427
  } catch (error) {
@@ -22242,7 +22440,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22242
22440
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22243
22441
  schemaName: getSchemaName$5(this.#schema)
22244
22442
  });
22245
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 AND "versionNumber" = $2`, [workspaceId, versionNumber]);
22443
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 AND "versionNumber" = $2`, [workspaceId, versionNumber]);
22246
22444
  if (!result) return null;
22247
22445
  return this.parseVersionRow(result);
22248
22446
  } catch (error) {
@@ -22259,12 +22457,19 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22259
22457
  }
22260
22458
  }
22261
22459
  async getLatestVersion(workspaceId) {
22460
+ return this.#getLatestVersion(this.#db.readClient, workspaceId);
22461
+ }
22462
+ /**
22463
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
22464
+ * lagging read replica cannot yield stale or missing rows mid-update.
22465
+ */
22466
+ async #getLatestVersion(client, workspaceId) {
22262
22467
  try {
22263
22468
  const tableName = getTableName$5({
22264
22469
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22265
22470
  schemaName: getSchemaName$5(this.#schema)
22266
22471
  });
22267
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [workspaceId]);
22472
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [workspaceId]);
22268
22473
  if (!result) return null;
22269
22474
  return this.parseVersionRow(result);
22270
22475
  } catch (error) {
@@ -22293,7 +22498,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22293
22498
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22294
22499
  schemaName: getSchemaName$5(this.#schema)
22295
22500
  });
22296
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22501
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22297
22502
  const total = parseInt(countResult.count, 10);
22298
22503
  if (total === 0) return {
22299
22504
  versions: [],
@@ -22304,7 +22509,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22304
22509
  };
22305
22510
  const limitValue = perPageInput === false ? total : perPage;
22306
22511
  return {
22307
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
22512
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
22308
22513
  workspaceId,
22309
22514
  limitValue,
22310
22515
  offset
@@ -22374,7 +22579,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22374
22579
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22375
22580
  schemaName: getSchemaName$5(this.#schema)
22376
22581
  });
22377
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22582
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22378
22583
  return parseInt(result.count, 10);
22379
22584
  } catch (error) {
22380
22585
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -22950,10 +23155,12 @@ function exportSchemas(schemaName) {
22950
23155
  * ```
22951
23156
  */
22952
23157
  var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
22953
- #pool;
23158
+ #writePool;
23159
+ #readPool;
22954
23160
  #db;
22955
- #ownsPool;
22956
- #poolClosed = false;
23161
+ #readDb;
23162
+ #ownsWritePool;
23163
+ #writePoolClosed = false;
22957
23164
  schema;
22958
23165
  isInitialized = false;
22959
23166
  #initPromise = null;
@@ -22969,15 +23176,21 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
22969
23176
  });
22970
23177
  this.schema = (0, _mastra_core_utils.parseSqlIdentifier)(config.schemaName || "public", "schema name");
22971
23178
  if (isPoolConfig(config)) {
22972
- this.#pool = config.pool;
22973
- this.#ownsPool = false;
23179
+ this.#writePool = config.pool;
23180
+ this.#ownsWritePool = false;
23181
+ } else if (isWritePoolConfig(config)) {
23182
+ this.#writePool = config.writePool;
23183
+ this.#ownsWritePool = false;
22974
23184
  } else {
22975
- this.#pool = this.createPool(config);
22976
- this.#ownsPool = true;
23185
+ this.#writePool = this.createPool(config);
23186
+ this.#ownsWritePool = true;
22977
23187
  }
22978
- this.#db = new RoutingDbClient(new PoolAdapter(this.#pool));
23188
+ this.#readPool = config.readPool ?? this.#writePool;
23189
+ this.#db = new RoutingDbClient(new PoolAdapter(this.#writePool));
23190
+ this.#readDb = this.#readPool === this.#writePool ? this.#db : new PoolAdapter(this.#readPool);
22979
23191
  const domainConfig = {
22980
23192
  client: this.#db,
23193
+ readClient: this.#readDb,
22981
23194
  schemaName: this.schema,
22982
23195
  skipDefaultIndexes: config.skipDefaultIndexes,
22983
23196
  indexes: config.indexes
@@ -23037,8 +23250,8 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
23037
23250
  async #runPinnedInit() {
23038
23251
  let pinnedClient;
23039
23252
  try {
23040
- pinnedClient = await this.#pool.connect();
23041
- const pinned = new PinnedClientAdapter(this.#pool, pinnedClient);
23253
+ pinnedClient = await this.#writePool.connect();
23254
+ const pinned = new PinnedClientAdapter(this.#writePool, pinnedClient);
23042
23255
  this.#db.pin(pinned);
23043
23256
  this.#db.setSchemaSnapshot(await loadSchemaSnapshot(pinned, this.schema));
23044
23257
  await super.init();
@@ -23071,21 +23284,27 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
23071
23284
  get db() {
23072
23285
  return this.#db;
23073
23286
  }
23074
- /**
23075
- * The underlying pg.Pool for direct database access or ORM integration.
23076
- */
23287
+ /** Database client for queries that may run against the configured read replica. */
23288
+ get readDb() {
23289
+ return this.#readDb;
23290
+ }
23291
+ /** The underlying writer pg.Pool for direct database access or ORM integration. */
23077
23292
  get pool() {
23078
- return this.#pool;
23293
+ return this.#writePool;
23294
+ }
23295
+ /** The underlying reader pg.Pool, falling back to the writer pool when unset. */
23296
+ get readPool() {
23297
+ return this.#readPool;
23079
23298
  }
23080
23299
  /**
23081
- * Closes the connection pool if it was created by this store.
23082
- * If a pool was passed in via config, it will not be closed.
23300
+ * Closes the writer connection pool if it was created by this store.
23301
+ * Caller-provided writer and reader pools are not closed.
23083
23302
  * Safe to call multiple times — subsequent calls are no-ops.
23084
23303
  */
23085
23304
  async close() {
23086
- if (this.#ownsPool && !this.#poolClosed) {
23087
- this.#poolClosed = true;
23088
- await this.#pool.end();
23305
+ if (this.#ownsWritePool && !this.#writePoolClosed) {
23306
+ this.#writePoolClosed = true;
23307
+ await this.#writePool.end();
23089
23308
  }
23090
23309
  }
23091
23310
  };