@mastra/pg 1.23.0-alpha.1 → 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 (30) 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 +461 -271
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.js +461 -271
  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/v-next/index.d.ts.map +1 -1
  22. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -1
  23. package/dist/storage/domains/schedules/index.d.ts.map +1 -1
  24. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -1
  25. package/dist/storage/domains/skills/index.d.ts.map +1 -1
  26. package/dist/storage/domains/workflow-definitions/index.d.ts.map +1 -1
  27. package/dist/storage/domains/workspaces/index.d.ts.map +1 -1
  28. package/dist/storage/index.d.ts +7 -5
  29. package/dist/storage/index.d.ts.map +1 -1
  30. 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",
@@ -17771,6 +17876,8 @@ function wrapError(op, error, details) {
17771
17876
  }
17772
17877
  var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext extends _mastra_core_storage.ObservabilityStorage {
17773
17878
  #client;
17879
+ /** Reader-backed client for standalone reads; writes, DDL, and discovery-cache refresh stay on #client. */
17880
+ #readClient;
17774
17881
  #schema;
17775
17882
  #partitioning;
17776
17883
  #discoveryConfig;
@@ -17778,8 +17885,9 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
17778
17885
  #partitionMode;
17779
17886
  constructor(config) {
17780
17887
  super();
17781
- const { client, schemaName } = resolvePgConfig(config);
17888
+ const { client, readClient, schemaName } = resolvePgConfig(config);
17782
17889
  this.#client = client;
17890
+ this.#readClient = readClient;
17783
17891
  this.#schema = schemaName ?? "public";
17784
17892
  this.#partitioning = config.partitioning ?? {};
17785
17893
  this.#discoveryConfig = config.discovery ?? {};
@@ -17964,34 +18072,34 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
17964
18072
  await this.#run("BATCH_CREATE_SPANS", () => batchCreateSpans(this.#client, this.#schema, args), { count: args.records.length });
17965
18073
  }
17966
18074
  async getSpan(args) {
17967
- return this.#run("GET_SPAN", () => getSpan(this.#client, this.#schema, args), {
18075
+ return this.#run("GET_SPAN", () => getSpan(this.#readClient, this.#schema, args), {
17968
18076
  traceId: args.traceId,
17969
18077
  spanId: args.spanId
17970
18078
  });
17971
18079
  }
17972
18080
  async getSpans(args) {
17973
- return this.#run("GET_SPANS", () => getSpans(this.#client, this.#schema, args), {
18081
+ return this.#run("GET_SPANS", () => getSpans(this.#readClient, this.#schema, args), {
17974
18082
  traceId: args.traceId,
17975
18083
  count: args.spanIds.length
17976
18084
  });
17977
18085
  }
17978
18086
  async getRootSpan(args) {
17979
- 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 });
17980
18088
  }
17981
18089
  async getTrace(args) {
17982
- 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 });
17983
18091
  }
17984
18092
  async getTraceLight(args) {
17985
- 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 });
17986
18094
  }
17987
18095
  async listTraces(args) {
17988
- return this.#run("LIST_TRACES", () => listTraces(this.#client, this.#schema, args));
18096
+ return this.#run("LIST_TRACES", () => listTraces(this.#readClient, this.#schema, args));
17989
18097
  }
17990
18098
  async queryTraces(plan) {
17991
- 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));
17992
18100
  }
17993
18101
  async listBranches(args) {
17994
- return this.#run("LIST_BRANCHES", () => listBranches(this.#client, this.#schema, args));
18102
+ return this.#run("LIST_BRANCHES", () => listBranches(this.#readClient, this.#schema, args));
17995
18103
  }
17996
18104
  async batchCreateLogs(args) {
17997
18105
  await this.#run("BATCH_CREATE_LOGS", () => batchCreateLogs(this.#client, this.#schema, args), { count: args.logs.length });
@@ -18012,58 +18120,58 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
18012
18120
  await this.#run("BATCH_CREATE_FEEDBACK", () => batchCreateFeedback(this.#client, this.#schema, args), { count: args.feedbacks.length });
18013
18121
  }
18014
18122
  async listLogs(args) {
18015
- return this.#run("LIST_LOGS", () => listLogs(this.#client, this.#schema, args));
18123
+ return this.#run("LIST_LOGS", () => listLogs(this.#readClient, this.#schema, args));
18016
18124
  }
18017
18125
  async listMetrics(args) {
18018
- return this.#run("LIST_METRICS", () => listMetrics(this.#client, this.#schema, args));
18126
+ return this.#run("LIST_METRICS", () => listMetrics(this.#readClient, this.#schema, args));
18019
18127
  }
18020
18128
  async listScores(args) {
18021
- return this.#run("LIST_SCORES", () => listScores(this.#client, this.#schema, args));
18129
+ return this.#run("LIST_SCORES", () => listScores(this.#readClient, this.#schema, args));
18022
18130
  }
18023
18131
  async getScoreById(scoreId) {
18024
- 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 });
18025
18133
  }
18026
18134
  async listFeedback(args) {
18027
- return this.#run("LIST_FEEDBACK", () => listFeedback(this.#client, this.#schema, args));
18135
+ return this.#run("LIST_FEEDBACK", () => listFeedback(this.#readClient, this.#schema, args));
18028
18136
  }
18029
18137
  async updateFeedbackReviewStatus(args) {
18030
18138
  return this.#run("UPDATE_FEEDBACK_REVIEW_STATUS", () => updateFeedbackReviewStatus(this.#client, this.#schema, args), { feedbackId: args.feedbackId });
18031
18139
  }
18032
18140
  async getMetricAggregate(args) {
18033
- 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));
18034
18142
  }
18035
18143
  async getMetricBreakdown(args) {
18036
- 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));
18037
18145
  }
18038
18146
  async getMetricTimeSeries(args) {
18039
- 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));
18040
18148
  }
18041
18149
  async getMetricPercentiles(args) {
18042
- 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));
18043
18151
  }
18044
18152
  async getScoreAggregate(args) {
18045
- 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));
18046
18154
  }
18047
18155
  async getScoreBreakdown(args) {
18048
- 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));
18049
18157
  }
18050
18158
  async getScoreTimeSeries(args) {
18051
- 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));
18052
18160
  }
18053
18161
  async getScorePercentiles(args) {
18054
- 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));
18055
18163
  }
18056
18164
  async getFeedbackAggregate(args) {
18057
- 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));
18058
18166
  }
18059
18167
  async getFeedbackBreakdown(args) {
18060
- 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));
18061
18169
  }
18062
18170
  async getFeedbackTimeSeries(args) {
18063
- 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));
18064
18172
  }
18065
18173
  async getFeedbackPercentiles(args) {
18066
- 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));
18067
18175
  }
18068
18176
  async getEntityTypes(args) {
18069
18177
  return this.#run("GET_ENTITY_TYPES", () => getEntityTypes(this.#client, this.#schema, args, this.#discovery));
@@ -18122,9 +18230,10 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18122
18230
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_PROMPT_BLOCKS, _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS];
18123
18231
  constructor(config) {
18124
18232
  super();
18125
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18233
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18126
18234
  this.#db = new PgDB({
18127
18235
  client,
18236
+ readClient,
18128
18237
  schemaName,
18129
18238
  skipDefaultIndexes
18130
18239
  });
@@ -18201,12 +18310,19 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18201
18310
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_PROMPT_BLOCKS });
18202
18311
  }
18203
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) {
18204
18320
  try {
18205
18321
  const tableName = getTableName$5({
18206
18322
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCKS,
18207
18323
  schemaName: getSchemaName$5(this.#schema)
18208
18324
  });
18209
- 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]);
18210
18326
  if (!result) return null;
18211
18327
  return this.parseBlockRow(result);
18212
18328
  } catch (error) {
@@ -18285,7 +18401,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18285
18401
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCKS,
18286
18402
  schemaName: getSchemaName$5(this.#schema)
18287
18403
  });
18288
- const existingBlock = await this.getById(id);
18404
+ const existingBlock = await this.#getById(this.#db.client, id);
18289
18405
  if (!existingBlock) throw new _mastra_core_error.MastraError({
18290
18406
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND"),
18291
18407
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -18324,7 +18440,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18324
18440
  values.push(now);
18325
18441
  values.push(id);
18326
18442
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
18327
- const updatedBlock = await this.getById(id);
18443
+ const updatedBlock = await this.#getById(this.#db.client, id);
18328
18444
  if (!updatedBlock) throw new _mastra_core_error.MastraError({
18329
18445
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
18330
18446
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -18393,7 +18509,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18393
18509
  queryParams.push(JSON.stringify(metadata));
18394
18510
  }
18395
18511
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
18396
- 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);
18397
18513
  const total = parseInt(countResult.count, 10);
18398
18514
  if (total === 0) return {
18399
18515
  promptBlocks: [],
@@ -18404,7 +18520,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18404
18520
  };
18405
18521
  const limitValue = perPageInput === false ? total : perPage;
18406
18522
  return {
18407
- 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++}`, [
18408
18524
  ...queryParams,
18409
18525
  limitValue,
18410
18526
  offset
@@ -18483,7 +18599,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18483
18599
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18484
18600
  schemaName: getSchemaName$5(this.#schema)
18485
18601
  });
18486
- 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]);
18487
18603
  if (!result) return null;
18488
18604
  return this.parseVersionRow(result);
18489
18605
  } catch (error) {
@@ -18502,7 +18618,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18502
18618
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18503
18619
  schemaName: getSchemaName$5(this.#schema)
18504
18620
  });
18505
- 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]);
18506
18622
  if (!result) return null;
18507
18623
  return this.parseVersionRow(result);
18508
18624
  } catch (error) {
@@ -18524,7 +18640,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18524
18640
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18525
18641
  schemaName: getSchemaName$5(this.#schema)
18526
18642
  });
18527
- 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]);
18528
18644
  if (!result) return null;
18529
18645
  return this.parseVersionRow(result);
18530
18646
  } catch (error) {
@@ -18553,7 +18669,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18553
18669
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18554
18670
  schemaName: getSchemaName$5(this.#schema)
18555
18671
  });
18556
- 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]);
18557
18673
  const total = parseInt(countResult.count, 10);
18558
18674
  if (total === 0) return {
18559
18675
  versions: [],
@@ -18564,7 +18680,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18564
18680
  };
18565
18681
  const limitValue = perPageInput === false ? total : perPage;
18566
18682
  return {
18567
- 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`, [
18568
18684
  blockId,
18569
18685
  limitValue,
18570
18686
  offset
@@ -18634,7 +18750,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18634
18750
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18635
18751
  schemaName: getSchemaName$5(this.#schema)
18636
18752
  });
18637
- 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]);
18638
18754
  return parseInt(result.count, 10);
18639
18755
  } catch (error) {
18640
18756
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -18735,6 +18851,7 @@ function rowToTrigger(row) {
18735
18851
  var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorage {
18736
18852
  #db;
18737
18853
  #client;
18854
+ #readClient;
18738
18855
  #schema;
18739
18856
  #skipDefaultIndexes;
18740
18857
  #indexes;
@@ -18754,10 +18871,12 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18754
18871
  } };
18755
18872
  constructor(config) {
18756
18873
  super();
18757
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18874
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18758
18875
  this.#client = client;
18876
+ this.#readClient = readClient;
18759
18877
  this.#db = new PgDB({
18760
18878
  client,
18879
+ readClient,
18761
18880
  schemaName,
18762
18881
  skipDefaultIndexes
18763
18882
  });
@@ -18881,7 +19000,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18881
19000
  return getTableName$2(tableName, getSchemaName$2((0, _mastra_core_utils.parseSqlIdentifier)(this.#schema, "schema name")));
18882
19001
  }
18883
19002
  async createSchedule(schedule) {
18884
- 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`);
18885
19004
  await this.#db.insert({
18886
19005
  tableName: _mastra_core_storage.TABLE_SCHEDULES,
18887
19006
  record: {
@@ -18903,7 +19022,14 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18903
19022
  return schedule;
18904
19023
  }
18905
19024
  async getSchedule(id) {
18906
- 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]);
18907
19033
  return row ? rowToSchedule(row) : null;
18908
19034
  }
18909
19035
  async listSchedules(filter) {
@@ -18928,7 +19054,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18928
19054
  conditions.push(`owner_id = $${params.length}`);
18929
19055
  }
18930
19056
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
18931
- 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);
18932
19058
  }
18933
19059
  async listDueSchedules(now, limit) {
18934
19060
  const cap = limit ?? 100;
@@ -18958,13 +19084,13 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18958
19084
  if ("ownerId" in patch) push("owner_id = ?", patch.ownerId ?? null);
18959
19085
  push("updated_at = ?", Date.now());
18960
19086
  if (setClauses.length === 1) {
18961
- const existing = await this.getSchedule(id);
19087
+ const existing = await this.#getSchedule(this.#client, id);
18962
19088
  if (!existing) throw new Error(`Schedule ${id} not found`);
18963
19089
  return existing;
18964
19090
  }
18965
19091
  params.push(id);
18966
19092
  await this.#client.none(`UPDATE ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} SET ${setClauses.join(", ")} WHERE id = $${params.length}`, params);
18967
- const updated = await this.getSchedule(id);
19093
+ const updated = await this.#getSchedule(this.#client, id);
18968
19094
  if (!updated) throw new Error(`Schedule ${id} not found`);
18969
19095
  return updated;
18970
19096
  }
@@ -19021,7 +19147,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
19021
19147
  params.push(Math.floor(opts.limit));
19022
19148
  limitClause = `LIMIT $${params.length}`;
19023
19149
  }
19024
- 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)}
19025
19151
  WHERE ${conditions.join(" AND ")}
19026
19152
  ORDER BY actual_fire_at DESC
19027
19153
  ${limitClause}`, params)).map(rowToTrigger);
@@ -19047,9 +19173,10 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19047
19173
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SCORER_DEFINITIONS, _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS];
19048
19174
  constructor(config) {
19049
19175
  super();
19050
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19176
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19051
19177
  this.#db = new PgDB({
19052
19178
  client,
19179
+ readClient,
19053
19180
  schemaName,
19054
19181
  skipDefaultIndexes
19055
19182
  });
@@ -19126,12 +19253,19 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19126
19253
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS });
19127
19254
  }
19128
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) {
19129
19263
  try {
19130
19264
  const tableName = getTableName$5({
19131
19265
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS,
19132
19266
  schemaName: getSchemaName$5(this.#schema)
19133
19267
  });
19134
- 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]);
19135
19269
  if (!result) return null;
19136
19270
  return this.parseScorerRow(result);
19137
19271
  } catch (error) {
@@ -19214,7 +19348,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19214
19348
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS,
19215
19349
  schemaName: getSchemaName$5(this.#schema)
19216
19350
  });
19217
- const existingScorer = await this.getById(id);
19351
+ const existingScorer = await this.#getById(this.#db.client, id);
19218
19352
  if (!existingScorer) throw new _mastra_core_error.MastraError({
19219
19353
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND"),
19220
19354
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -19253,7 +19387,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19253
19387
  values.push(now);
19254
19388
  values.push(id);
19255
19389
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
19256
- const updatedScorer = await this.getById(id);
19390
+ const updatedScorer = await this.#getById(this.#db.client, id);
19257
19391
  if (!updatedScorer) throw new _mastra_core_error.MastraError({
19258
19392
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
19259
19393
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -19330,7 +19464,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19330
19464
  queryParams.push(JSON.stringify(metadata));
19331
19465
  }
19332
19466
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
19333
- 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);
19334
19468
  const total = parseInt(countResult.count, 10);
19335
19469
  if (total === 0) return {
19336
19470
  scorerDefinitions: [],
@@ -19341,7 +19475,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19341
19475
  };
19342
19476
  const limitValue = perPageInput === false ? total : perPage;
19343
19477
  return {
19344
- 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++}`, [
19345
19479
  ...queryParams,
19346
19480
  limitValue,
19347
19481
  offset
@@ -19423,7 +19557,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19423
19557
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19424
19558
  schemaName: getSchemaName$5(this.#schema)
19425
19559
  });
19426
- 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]);
19427
19561
  if (!result) return null;
19428
19562
  return this.parseVersionRow(result);
19429
19563
  } catch (error) {
@@ -19442,7 +19576,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19442
19576
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19443
19577
  schemaName: getSchemaName$5(this.#schema)
19444
19578
  });
19445
- 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]);
19446
19580
  if (!result) return null;
19447
19581
  return this.parseVersionRow(result);
19448
19582
  } catch (error) {
@@ -19464,7 +19598,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19464
19598
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19465
19599
  schemaName: getSchemaName$5(this.#schema)
19466
19600
  });
19467
- 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]);
19468
19602
  if (!result) return null;
19469
19603
  return this.parseVersionRow(result);
19470
19604
  } catch (error) {
@@ -19493,7 +19627,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19493
19627
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19494
19628
  schemaName: getSchemaName$5(this.#schema)
19495
19629
  });
19496
- 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]);
19497
19631
  const total = parseInt(countResult.count, 10);
19498
19632
  if (total === 0) return {
19499
19633
  versions: [],
@@ -19504,7 +19638,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19504
19638
  };
19505
19639
  const limitValue = perPageInput === false ? total : perPage;
19506
19640
  return {
19507
- 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`, [
19508
19642
  scorerDefinitionId,
19509
19643
  limitValue,
19510
19644
  offset
@@ -19574,7 +19708,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19574
19708
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19575
19709
  schemaName: getSchemaName$5(this.#schema)
19576
19710
  });
19577
- 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]);
19578
19712
  return parseInt(result.count, 10);
19579
19713
  } catch (error) {
19580
19714
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -19671,9 +19805,10 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19671
19805
  } };
19672
19806
  constructor(config) {
19673
19807
  super();
19674
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19808
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19675
19809
  this.#db = new PgDB({
19676
19810
  client,
19811
+ readClient,
19677
19812
  schemaName,
19678
19813
  skipDefaultIndexes
19679
19814
  });
@@ -19807,7 +19942,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19807
19942
  }
19808
19943
  async getScoreById({ id }) {
19809
19944
  try {
19810
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${getTableName$1({
19945
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${getTableName$1({
19811
19946
  indexName: _mastra_core_storage.TABLE_SCORERS,
19812
19947
  schemaName: getSchemaName$1(this.#schema)
19813
19948
  })} WHERE id = $1`, [id]);
@@ -19839,7 +19974,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19839
19974
  }
19840
19975
  paramIndex = applyTenancyFilters(conditions, queryParams, paramIndex, filters);
19841
19976
  const whereClause = conditions.join(" AND ");
19842
- 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({
19843
19978
  indexName: _mastra_core_storage.TABLE_SCORERS,
19844
19979
  schemaName: getSchemaName$1(this.#schema)
19845
19980
  })} WHERE ${whereClause}`, queryParams);
@@ -19857,7 +19992,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19857
19992
  };
19858
19993
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
19859
19994
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
19860
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
19995
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
19861
19996
  indexName: _mastra_core_storage.TABLE_SCORERS,
19862
19997
  schemaName: getSchemaName$1(this.#schema)
19863
19998
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -19947,7 +20082,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19947
20082
  const queryParams = [runId];
19948
20083
  let paramIndex = applyTenancyFilters(conditions, queryParams, 2, filters);
19949
20084
  const whereClause = conditions.join(" AND ");
19950
- 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({
19951
20086
  indexName: _mastra_core_storage.TABLE_SCORERS,
19952
20087
  schemaName: getSchemaName$1(this.#schema)
19953
20088
  })} WHERE ${whereClause}`, queryParams);
@@ -19965,7 +20100,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19965
20100
  };
19966
20101
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
19967
20102
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
19968
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
20103
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
19969
20104
  indexName: _mastra_core_storage.TABLE_SCORERS,
19970
20105
  schemaName: getSchemaName$1(this.#schema)
19971
20106
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -19996,7 +20131,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19996
20131
  const queryParams = [entityId, entityType];
19997
20132
  let paramIndex = applyTenancyFilters(conditions, queryParams, 3, filters);
19998
20133
  const whereClause = conditions.join(" AND ");
19999
- 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({
20000
20135
  indexName: _mastra_core_storage.TABLE_SCORERS,
20001
20136
  schemaName: getSchemaName$1(this.#schema)
20002
20137
  })} WHERE ${whereClause}`, queryParams);
@@ -20014,7 +20149,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20014
20149
  };
20015
20150
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
20016
20151
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
20017
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
20152
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
20018
20153
  indexName: _mastra_core_storage.TABLE_SCORERS,
20019
20154
  schemaName: getSchemaName$1(this.#schema)
20020
20155
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -20049,14 +20184,14 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20049
20184
  const queryParams = [traceId, spanId];
20050
20185
  let paramIndex = applyTenancyFilters(conditions, queryParams, 3, filters);
20051
20186
  const whereClause = conditions.join(" AND ");
20052
- 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);
20053
20188
  const total = Number(countSQLResult?.count ?? 0);
20054
20189
  const { page, perPage: perPageInput } = pagination;
20055
20190
  const perPage = (0, _mastra_core_storage.normalizePerPage)(perPageInput, 100);
20056
20191
  const { offset: start, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
20057
20192
  const limitValue = perPageInput === false ? total : perPage;
20058
20193
  const end = perPageInput === false ? total : start + perPage;
20059
- 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++}`, [
20060
20195
  ...queryParams,
20061
20196
  limitValue,
20062
20197
  start
@@ -20104,9 +20239,10 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20104
20239
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SKILLS, _mastra_core_storage.TABLE_SKILL_VERSIONS];
20105
20240
  constructor(config) {
20106
20241
  super();
20107
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20242
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20108
20243
  this.#db = new PgDB({
20109
20244
  client,
20245
+ readClient,
20110
20246
  schemaName,
20111
20247
  skipDefaultIndexes
20112
20248
  });
@@ -20180,12 +20316,19 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20180
20316
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_SKILLS });
20181
20317
  }
20182
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) {
20183
20326
  try {
20184
20327
  const tableName = getTableName$5({
20185
20328
  indexName: _mastra_core_storage.TABLE_SKILLS,
20186
20329
  schemaName: getSchemaName$5(this.#schema)
20187
20330
  });
20188
- 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]);
20189
20332
  if (!result) return null;
20190
20333
  return this.parseSkillRow(result);
20191
20334
  } catch (error) {
@@ -20267,7 +20410,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20267
20410
  indexName: _mastra_core_storage.TABLE_SKILLS,
20268
20411
  schemaName: getSchemaName$5(this.#schema)
20269
20412
  });
20270
- 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({
20271
20414
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NOT_FOUND"),
20272
20415
  domain: _mastra_core_error.ErrorDomain.STORAGE,
20273
20416
  category: _mastra_core_error.ErrorCategory.USER,
@@ -20279,7 +20422,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20279
20422
  const configFields = {};
20280
20423
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
20281
20424
  if (SNAPSHOT_FIELDS$1.some((field) => field in configFields)) {
20282
- const latestVersion = await this.getLatestVersion(id);
20425
+ const latestVersion = await this.#getLatestVersion(this.#db.client, id);
20283
20426
  if (!latestVersion) throw new _mastra_core_error.MastraError({
20284
20427
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NO_VERSIONS"),
20285
20428
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -20336,7 +20479,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20336
20479
  values.push(now);
20337
20480
  values.push(id);
20338
20481
  if (setClauses.length > 2 || versionCreated) await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
20339
- const updatedSkill = await this.getById(id);
20482
+ const updatedSkill = await this.#getById(this.#db.client, id);
20340
20483
  if (!updatedSkill) throw new _mastra_core_error.MastraError({
20341
20484
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NOT_FOUND_AFTER_UPDATE"),
20342
20485
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -20429,7 +20572,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20429
20572
  const joinClause = useJoin && joinSqlIdx !== null ? `LEFT JOIN ${favoritesTable} sr ON sr."entityType" = 'skill' AND sr."entityId" = s.id AND sr."userId" = $${joinSqlIdx}` : "";
20430
20573
  const joinParams = useJoin && joinUserId ? [joinUserId] : [];
20431
20574
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
20432
- 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]);
20433
20576
  const total = parseInt(countResult.count, 10);
20434
20577
  if (total === 0) return {
20435
20578
  skills: [],
@@ -20447,7 +20590,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20447
20590
  const limitIdx = paramIdx++;
20448
20591
  const offsetIdx = paramIdx++;
20449
20592
  return {
20450
- 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}`, [
20451
20594
  ...joinParams,
20452
20595
  ...queryParams,
20453
20596
  limitValue,
@@ -20535,7 +20678,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20535
20678
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20536
20679
  schemaName: getSchemaName$5(this.#schema)
20537
20680
  });
20538
- 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]);
20539
20682
  if (!result) return null;
20540
20683
  return this.parseVersionRow(result);
20541
20684
  } catch (error) {
@@ -20556,7 +20699,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20556
20699
  schemaName: getSchemaName$5(this.#schema)
20557
20700
  });
20558
20701
  const placeholders = ids.map((_, i) => `$${i + 1}`).join(", ");
20559
- 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));
20560
20703
  } catch (error) {
20561
20704
  if (error instanceof _mastra_core_error.MastraError) throw error;
20562
20705
  throw new _mastra_core_error.MastraError({
@@ -20573,7 +20716,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20573
20716
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20574
20717
  schemaName: getSchemaName$5(this.#schema)
20575
20718
  });
20576
- 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]);
20577
20720
  if (!result) return null;
20578
20721
  return this.parseVersionRow(result);
20579
20722
  } catch (error) {
@@ -20590,12 +20733,19 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20590
20733
  }
20591
20734
  }
20592
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) {
20593
20743
  try {
20594
20744
  const tableName = getTableName$5({
20595
20745
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20596
20746
  schemaName: getSchemaName$5(this.#schema)
20597
20747
  });
20598
- 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]);
20599
20749
  if (!result) return null;
20600
20750
  return this.parseVersionRow(result);
20601
20751
  } catch (error) {
@@ -20624,7 +20774,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20624
20774
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20625
20775
  schemaName: getSchemaName$5(this.#schema)
20626
20776
  });
20627
- 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]);
20628
20778
  const total = parseInt(countResult.count, 10);
20629
20779
  if (total === 0) return {
20630
20780
  versions: [],
@@ -20635,7 +20785,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20635
20785
  };
20636
20786
  const limitValue = perPageInput === false ? total : perPage;
20637
20787
  return {
20638
- 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`, [
20639
20789
  skillId,
20640
20790
  limitValue,
20641
20791
  offset
@@ -20705,7 +20855,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20705
20855
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20706
20856
  schemaName: getSchemaName$5(this.#schema)
20707
20857
  });
20708
- 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]);
20709
20859
  return parseInt(result.count, 10);
20710
20860
  } catch (error) {
20711
20861
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -20780,9 +20930,10 @@ var ThreadStatePG = class ThreadStatePG extends _mastra_core_storage.ThreadState
20780
20930
  } };
20781
20931
  constructor(config) {
20782
20932
  super();
20783
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
20933
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
20784
20934
  this.#db = new PgDB({
20785
20935
  client,
20936
+ readClient,
20786
20937
  schemaName,
20787
20938
  skipDefaultIndexes
20788
20939
  });
@@ -20945,9 +21096,10 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
20945
21096
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_TOOL_PROVIDER_CONNECTIONS];
20946
21097
  constructor(config) {
20947
21098
  super();
20948
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21099
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20949
21100
  this.#db = new PgDB({
20950
21101
  client,
21102
+ readClient,
20951
21103
  schemaName,
20952
21104
  skipDefaultIndexes
20953
21105
  });
@@ -21026,7 +21178,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
21026
21178
  schemaName: getSchemaName$5(this.#schema)
21027
21179
  });
21028
21180
  try {
21029
- 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`, [
21030
21182
  authorId,
21031
21183
  providerId,
21032
21184
  connectionId
@@ -21133,7 +21285,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
21133
21285
  clauses.push(`scope = $${args.length}`);
21134
21286
  }
21135
21287
  const whereClause = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
21136
- 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));
21137
21289
  } catch (error) {
21138
21290
  throw new _mastra_core_error.MastraError({
21139
21291
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "TOOL_PROVIDER_CONNECTION_LIST", "FAILED"),
@@ -21209,9 +21361,10 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21209
21361
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS];
21210
21362
  constructor(config) {
21211
21363
  super();
21212
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21364
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21213
21365
  this.#db = new PgDB({
21214
21366
  client,
21367
+ readClient,
21215
21368
  schemaName,
21216
21369
  skipDefaultIndexes
21217
21370
  });
@@ -21268,7 +21421,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21268
21421
  }
21269
21422
  async upsert(input) {
21270
21423
  const now = /* @__PURE__ */ new Date();
21271
- if (!await this.get(input.id)) {
21424
+ if (!await this.#get(this.#db.client, input.id)) {
21272
21425
  if (!("inputSchema" in input) || !input.inputSchema) throw new Error(`Cannot create workflow definition "${input.id}": inputSchema is required.`);
21273
21426
  if (!("outputSchema" in input) || !input.outputSchema) throw new Error(`Cannot create workflow definition "${input.id}": outputSchema is required.`);
21274
21427
  if (!("graph" in input) || !input.graph) throw new Error(`Cannot create workflow definition "${input.id}": graph is required.`);
@@ -21294,10 +21447,10 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21294
21447
  record
21295
21448
  });
21296
21449
  } catch (error) {
21297
- if (!await this.get(input.id)) throw error;
21450
+ if (!await this.#get(this.#db.client, input.id)) throw error;
21298
21451
  return this.applyUpdate(input, now);
21299
21452
  }
21300
- const created = await this.get(input.id);
21453
+ const created = await this.#get(this.#db.client, input.id);
21301
21454
  if (!created) throw new Error(`Failed to persist workflow definition "${input.id}".`);
21302
21455
  return created;
21303
21456
  }
@@ -21320,16 +21473,23 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21320
21473
  keys: { id: input.id },
21321
21474
  data
21322
21475
  });
21323
- const updated = await this.get(input.id);
21476
+ const updated = await this.#get(this.#db.client, input.id);
21324
21477
  if (!updated) throw new Error(`Failed to update workflow definition "${input.id}".`);
21325
21478
  return updated;
21326
21479
  }
21327
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) {
21328
21488
  const tableName = getTableName$5({
21329
21489
  indexName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
21330
21490
  schemaName: getSchemaName$5(this.#schema)
21331
21491
  });
21332
- 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]);
21333
21493
  return row ? rowToDefinition(row) : null;
21334
21494
  }
21335
21495
  async list(args) {
@@ -21348,7 +21508,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21348
21508
  conditions.push(`"authorId" = $${params.length}`);
21349
21509
  }
21350
21510
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
21351
- 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));
21352
21512
  return {
21353
21513
  definitions,
21354
21514
  total: definitions.length
@@ -21413,9 +21573,10 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
21413
21573
  } };
21414
21574
  constructor(config) {
21415
21575
  super();
21416
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21576
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21417
21577
  this.#db = new PgDB({
21418
21578
  client,
21579
+ readClient,
21419
21580
  schemaName,
21420
21581
  skipDefaultIndexes
21421
21582
  });
@@ -21738,7 +21899,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
21738
21899
  ORDER BY "createdAt" DESC LIMIT 1
21739
21900
  `;
21740
21901
  const queryValues = values;
21741
- const result = await this.#db.client.oneOrNone(query, queryValues);
21902
+ const result = await this.#db.readClient.oneOrNone(query, queryValues);
21742
21903
  if (!result) return null;
21743
21904
  return this.parseWorkflowRun(result);
21744
21905
  } catch (error) {
@@ -21867,9 +22028,10 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
21867
22028
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_WORKSPACES, _mastra_core_storage.TABLE_WORKSPACE_VERSIONS];
21868
22029
  constructor(config) {
21869
22030
  super();
21870
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
22031
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21871
22032
  this.#db = new PgDB({
21872
22033
  client,
22034
+ readClient,
21873
22035
  schemaName,
21874
22036
  skipDefaultIndexes
21875
22037
  });
@@ -21933,12 +22095,19 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
21933
22095
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_WORKSPACES });
21934
22096
  }
21935
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) {
21936
22105
  try {
21937
22106
  const tableName = getTableName$5({
21938
22107
  indexName: _mastra_core_storage.TABLE_WORKSPACES,
21939
22108
  schemaName: getSchemaName$5(this.#schema)
21940
22109
  });
21941
- 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]);
21942
22111
  if (!result) return null;
21943
22112
  return this.parseWorkspaceRow(result);
21944
22113
  } catch (error) {
@@ -22017,7 +22186,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22017
22186
  indexName: _mastra_core_storage.TABLE_WORKSPACES,
22018
22187
  schemaName: getSchemaName$5(this.#schema)
22019
22188
  });
22020
- const existingWorkspace = await this.getById(id);
22189
+ const existingWorkspace = await this.#getById(this.#db.client, id);
22021
22190
  if (!existingWorkspace) throw new _mastra_core_error.MastraError({
22022
22191
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NOT_FOUND"),
22023
22192
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22030,7 +22199,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22030
22199
  const configFields = {};
22031
22200
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
22032
22201
  if (SNAPSHOT_FIELDS.some((field) => field in configFields)) {
22033
- const latestVersion = await this.getLatestVersion(id);
22202
+ const latestVersion = await this.#getLatestVersion(this.#db.client, id);
22034
22203
  if (!latestVersion) throw new _mastra_core_error.MastraError({
22035
22204
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NO_VERSIONS"),
22036
22205
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22091,7 +22260,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22091
22260
  values.push(now);
22092
22261
  values.push(id);
22093
22262
  if (setClauses.length > 2 || versionCreated) await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
22094
- const updatedWorkspace = await this.getById(id);
22263
+ const updatedWorkspace = await this.#getById(this.#db.client, id);
22095
22264
  if (!updatedWorkspace) throw new _mastra_core_error.MastraError({
22096
22265
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NOT_FOUND_AFTER_UPDATE"),
22097
22266
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22156,7 +22325,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22156
22325
  queryParams.push(JSON.stringify(metadata));
22157
22326
  }
22158
22327
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
22159
- 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);
22160
22329
  const total = parseInt(countResult.count, 10);
22161
22330
  if (total === 0) return {
22162
22331
  workspaces: [],
@@ -22167,7 +22336,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22167
22336
  };
22168
22337
  const limitValue = perPageInput === false ? total : perPage;
22169
22338
  return {
22170
- 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++}`, [
22171
22340
  ...queryParams,
22172
22341
  limitValue,
22173
22342
  offset
@@ -22252,7 +22421,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22252
22421
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22253
22422
  schemaName: getSchemaName$5(this.#schema)
22254
22423
  });
22255
- 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]);
22256
22425
  if (!result) return null;
22257
22426
  return this.parseVersionRow(result);
22258
22427
  } catch (error) {
@@ -22271,7 +22440,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22271
22440
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22272
22441
  schemaName: getSchemaName$5(this.#schema)
22273
22442
  });
22274
- 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]);
22275
22444
  if (!result) return null;
22276
22445
  return this.parseVersionRow(result);
22277
22446
  } catch (error) {
@@ -22288,12 +22457,19 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22288
22457
  }
22289
22458
  }
22290
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) {
22291
22467
  try {
22292
22468
  const tableName = getTableName$5({
22293
22469
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22294
22470
  schemaName: getSchemaName$5(this.#schema)
22295
22471
  });
22296
- 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]);
22297
22473
  if (!result) return null;
22298
22474
  return this.parseVersionRow(result);
22299
22475
  } catch (error) {
@@ -22322,7 +22498,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22322
22498
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22323
22499
  schemaName: getSchemaName$5(this.#schema)
22324
22500
  });
22325
- 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]);
22326
22502
  const total = parseInt(countResult.count, 10);
22327
22503
  if (total === 0) return {
22328
22504
  versions: [],
@@ -22333,7 +22509,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22333
22509
  };
22334
22510
  const limitValue = perPageInput === false ? total : perPage;
22335
22511
  return {
22336
- 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`, [
22337
22513
  workspaceId,
22338
22514
  limitValue,
22339
22515
  offset
@@ -22403,7 +22579,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22403
22579
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22404
22580
  schemaName: getSchemaName$5(this.#schema)
22405
22581
  });
22406
- 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]);
22407
22583
  return parseInt(result.count, 10);
22408
22584
  } catch (error) {
22409
22585
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -22979,10 +23155,12 @@ function exportSchemas(schemaName) {
22979
23155
  * ```
22980
23156
  */
22981
23157
  var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
22982
- #pool;
23158
+ #writePool;
23159
+ #readPool;
22983
23160
  #db;
22984
- #ownsPool;
22985
- #poolClosed = false;
23161
+ #readDb;
23162
+ #ownsWritePool;
23163
+ #writePoolClosed = false;
22986
23164
  schema;
22987
23165
  isInitialized = false;
22988
23166
  #initPromise = null;
@@ -22998,15 +23176,21 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
22998
23176
  });
22999
23177
  this.schema = (0, _mastra_core_utils.parseSqlIdentifier)(config.schemaName || "public", "schema name");
23000
23178
  if (isPoolConfig(config)) {
23001
- this.#pool = config.pool;
23002
- 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;
23003
23184
  } else {
23004
- this.#pool = this.createPool(config);
23005
- this.#ownsPool = true;
23185
+ this.#writePool = this.createPool(config);
23186
+ this.#ownsWritePool = true;
23006
23187
  }
23007
- 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);
23008
23191
  const domainConfig = {
23009
23192
  client: this.#db,
23193
+ readClient: this.#readDb,
23010
23194
  schemaName: this.schema,
23011
23195
  skipDefaultIndexes: config.skipDefaultIndexes,
23012
23196
  indexes: config.indexes
@@ -23066,8 +23250,8 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
23066
23250
  async #runPinnedInit() {
23067
23251
  let pinnedClient;
23068
23252
  try {
23069
- pinnedClient = await this.#pool.connect();
23070
- const pinned = new PinnedClientAdapter(this.#pool, pinnedClient);
23253
+ pinnedClient = await this.#writePool.connect();
23254
+ const pinned = new PinnedClientAdapter(this.#writePool, pinnedClient);
23071
23255
  this.#db.pin(pinned);
23072
23256
  this.#db.setSchemaSnapshot(await loadSchemaSnapshot(pinned, this.schema));
23073
23257
  await super.init();
@@ -23100,21 +23284,27 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
23100
23284
  get db() {
23101
23285
  return this.#db;
23102
23286
  }
23103
- /**
23104
- * The underlying pg.Pool for direct database access or ORM integration.
23105
- */
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. */
23106
23292
  get pool() {
23107
- 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;
23108
23298
  }
23109
23299
  /**
23110
- * Closes the connection pool if it was created by this store.
23111
- * 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.
23112
23302
  * Safe to call multiple times — subsequent calls are no-ops.
23113
23303
  */
23114
23304
  async close() {
23115
- if (this.#ownsPool && !this.#poolClosed) {
23116
- this.#poolClosed = true;
23117
- await this.#pool.end();
23305
+ if (this.#ownsWritePool && !this.#writePoolClosed) {
23306
+ this.#writePoolClosed = true;
23307
+ await this.#writePool.end();
23118
23308
  }
23119
23309
  }
23120
23310
  };