@mastra/pg 1.23.0-alpha.1 → 1.23.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/docs/SKILL.md +1 -1
  2. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  3. package/dist/index.cjs +468 -279
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.js +468 -279
  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/dist/vector/index.d.ts.map +1 -1
  31. 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)) {
@@ -934,12 +936,12 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
934
936
  client.release();
935
937
  }
936
938
  }
939
+ const indexInfo = await this.getIndexMetadata({ indexName });
937
940
  const client = await this.pool.connect();
938
941
  try {
939
942
  await this.ensureSearchPath(client);
940
943
  await client.query("BEGIN");
941
944
  const { sql: filterQuery, values: filterValues } = buildFilterQuery(this.transformFilter(filter), minScore, topK);
942
- const indexInfo = await this.getIndexMetadata({ indexName });
943
945
  const metric = indexInfo.metric ?? "cosine";
944
946
  const ops = this.getVectorOps(indexInfo.vectorType, metric);
945
947
  const vectorStr = ops.formatVector(queryVector, indexInfo.dimension);
@@ -1014,6 +1016,7 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
1014
1016
  async upsert({ indexName, vectors, metadata, ids, deleteFilter, namespace = DEFAULT_NAMESPACE }) {
1015
1017
  (0, _mastra_core_vector.validateUpsertInput)("PG", vectors, metadata, ids);
1016
1018
  const { tableName } = this.getTableName(indexName);
1019
+ const indexInfo = await this.getIndexMetadata({ indexName });
1017
1020
  const client = await this.pool.connect();
1018
1021
  try {
1019
1022
  await this.ensureSearchPath(client);
@@ -1035,7 +1038,6 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
1035
1038
  }
1036
1039
  }
1037
1040
  const vectorIds = ids || vectors.map(() => crypto.randomUUID());
1038
- const indexInfo = await this.getIndexMetadata({ indexName });
1039
1041
  const qualifiedVectorType = this.getVectorTypeName(indexInfo.vectorType, indexInfo.dimension);
1040
1042
  const ops = this.getVectorOps(indexInfo.vectorType, indexInfo.metric ?? "cosine");
1041
1043
  if (new Set(vectorIds).size !== vectorIds.length) for (let i = 0; i < vectors.length; i++) {
@@ -1323,7 +1325,7 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
1323
1325
  let existingIndexInfo = null;
1324
1326
  let dimension = 0;
1325
1327
  try {
1326
- existingIndexInfo = await this.getIndexMetadata({ indexName });
1328
+ existingIndexInfo = await this.describeIndexMetadata({ indexName }, client);
1327
1329
  dimension = existingIndexInfo.dimension;
1328
1330
  if (isConfigEmpty && existingIndexInfo.metric === metric) if (existingIndexInfo.type === "flat") this.logger?.debug(`No index exists for ${vectorIndexName}, will create default ivfflat index`);
1329
1331
  else {
@@ -1527,8 +1529,8 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
1527
1529
  * {@link describeIndex} it issues no `COUNT(*)`, so its cost does not grow with the
1528
1530
  * number of rows in the table.
1529
1531
  */
1530
- async describeIndexMetadata({ indexName }) {
1531
- const client = await this.pool.connect();
1532
+ async describeIndexMetadata({ indexName }, existingClient) {
1533
+ const client = existingClient ?? await this.pool.connect();
1532
1534
  try {
1533
1535
  const { tableName, parsedIndexName } = this.getTableName(indexName);
1534
1536
  const tableExists = await client.query(`
@@ -1588,7 +1590,6 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
1588
1590
  config
1589
1591
  };
1590
1592
  } catch (e) {
1591
- await client.query("ROLLBACK");
1592
1593
  const mastraError = new _mastra_core_error.MastraError({
1593
1594
  id: (0, _mastra_core_storage.createVectorErrorId)("PG", "DESCRIBE_INDEX", "FAILED"),
1594
1595
  domain: _mastra_core_error.ErrorDomain.MASTRA_VECTOR,
@@ -1598,7 +1599,7 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
1598
1599
  this.logger?.trackException(mastraError);
1599
1600
  throw mastraError;
1600
1601
  } finally {
1601
- client.release();
1602
+ if (!existingClient) client.release();
1602
1603
  }
1603
1604
  }
1604
1605
  /**
@@ -1703,10 +1704,10 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
1703
1704
  category: _mastra_core_error.ErrorCategory.USER,
1704
1705
  details: { indexName }
1705
1706
  });
1707
+ const indexInfo = await this.getIndexMetadata({ indexName });
1706
1708
  client = await this.pool.connect();
1707
1709
  await this.ensureSearchPath(client);
1708
1710
  const { tableName } = this.getTableName(indexName);
1709
- const indexInfo = await this.getIndexMetadata({ indexName });
1710
1711
  const qualifiedVectorType = this.getVectorTypeName(indexInfo.vectorType, indexInfo.dimension);
1711
1712
  const ops = this.getVectorOps(indexInfo.vectorType, indexInfo.metric ?? "cosine");
1712
1713
  let updateParts = [];
@@ -2383,16 +2384,21 @@ async function loadSchemaSnapshot(client, schemaName) {
2383
2384
  function resolvePgConfig(config) {
2384
2385
  if ("client" in config) return {
2385
2386
  client: config.client,
2387
+ readClient: config.readClient ?? config.client,
2386
2388
  schemaName: config.schemaName,
2387
2389
  skipDefaultIndexes: config.skipDefaultIndexes,
2388
2390
  indexes: config.indexes
2389
2391
  };
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
- };
2392
+ if ("pool" in config) {
2393
+ const client = new PoolAdapter(config.pool);
2394
+ return {
2395
+ client,
2396
+ readClient: config.readPool && config.readPool !== config.pool ? new PoolAdapter(config.readPool) : client,
2397
+ schemaName: config.schemaName,
2398
+ skipDefaultIndexes: config.skipDefaultIndexes,
2399
+ indexes: config.indexes
2400
+ };
2401
+ }
2396
2402
  let pool;
2397
2403
  if ("connectionString" in config) pool = new pg.Pool({
2398
2404
  connectionString: config.connectionString,
@@ -2409,8 +2415,10 @@ function resolvePgConfig(config) {
2409
2415
  pool.on("error", (err) => {
2410
2416
  console.warn(`resolvePgConfig: idle pool client error (pool discards the client and reconnects on next checkout): ${err instanceof Error ? err.message : String(err)}`);
2411
2417
  });
2418
+ const client = new PoolAdapter(pool);
2412
2419
  return {
2413
- client: new PoolAdapter(pool),
2420
+ client,
2421
+ readClient: client,
2414
2422
  schemaName: config.schemaName,
2415
2423
  skipDefaultIndexes: config.skipDefaultIndexes,
2416
2424
  indexes: config.indexes
@@ -2618,6 +2626,7 @@ function assertPositiveLimit(limit) {
2618
2626
  }
2619
2627
  var PgDB = class extends _mastra_core_base.MastraBase {
2620
2628
  client;
2629
+ readClient;
2621
2630
  schemaName;
2622
2631
  skipDefaultIndexes;
2623
2632
  /** Cache of actual table columns: tableName -> Set<columnName> */
@@ -2630,6 +2639,7 @@ var PgDB = class extends _mastra_core_base.MastraBase {
2630
2639
  name: "PG_DB_LAYER"
2631
2640
  });
2632
2641
  this.client = config.client;
2642
+ this.readClient = config.readClient ?? config.client;
2633
2643
  this.schemaName = config.schemaName;
2634
2644
  this.skipDefaultIndexes = config.skipDefaultIndexes;
2635
2645
  }
@@ -3885,9 +3895,10 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
3885
3895
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_AGENTS, _mastra_core_storage.TABLE_AGENT_VERSIONS];
3886
3896
  constructor(config) {
3887
3897
  super();
3888
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
3898
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
3889
3899
  this.#db = new PgDB({
3890
3900
  client,
3901
+ readClient,
3891
3902
  schemaName,
3892
3903
  skipDefaultIndexes
3893
3904
  });
@@ -4146,12 +4157,19 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4146
4157
  };
4147
4158
  }
4148
4159
  async getById(id) {
4160
+ return this.#getById(this.#db.readClient, id);
4161
+ }
4162
+ /**
4163
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
4164
+ * lagging read replica cannot yield stale or missing rows mid-update.
4165
+ */
4166
+ async #getById(client, id) {
4149
4167
  try {
4150
4168
  const tableName = getTableName$5({
4151
4169
  indexName: _mastra_core_storage.TABLE_AGENTS,
4152
4170
  schemaName: getSchemaName$5(this.#schema)
4153
4171
  });
4154
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4172
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4155
4173
  if (!result) return null;
4156
4174
  return this.parseRow(result);
4157
4175
  } catch (error) {
@@ -4236,7 +4254,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4236
4254
  indexName: _mastra_core_storage.TABLE_AGENTS,
4237
4255
  schemaName: getSchemaName$5(this.#schema)
4238
4256
  });
4239
- if (!await this.getById(id)) throw new _mastra_core_error.MastraError({
4257
+ if (!await this.#getById(this.#db.client, id)) throw new _mastra_core_error.MastraError({
4240
4258
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_AGENT", "NOT_FOUND"),
4241
4259
  domain: _mastra_core_error.ErrorDomain.STORAGE,
4242
4260
  category: _mastra_core_error.ErrorCategory.USER,
@@ -4274,7 +4292,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4274
4292
  values.push(now);
4275
4293
  values.push(id);
4276
4294
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
4277
- const updatedAgent = await this.getById(id);
4295
+ const updatedAgent = await this.#getById(this.#db.client, id);
4278
4296
  if (!updatedAgent) throw new _mastra_core_error.MastraError({
4279
4297
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_AGENT", "NOT_FOUND_AFTER_UPDATE"),
4280
4298
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -4371,7 +4389,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4371
4389
  const joinClause = useJoin && joinSqlIdx !== null ? `LEFT JOIN ${favoritesTable} s ON s."entityType" = 'agent' AND s."entityId" = a.id AND s."userId" = $${joinSqlIdx}` : "";
4372
4390
  const joinParams = useJoin && joinUserId ? [joinUserId] : [];
4373
4391
  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]);
4392
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} a ${joinClause} ${whereClause}`, [...joinParams, ...queryParams]);
4375
4393
  const total = parseInt(countResult.count, 10);
4376
4394
  if (total === 0) return {
4377
4395
  agents: [],
@@ -4389,7 +4407,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4389
4407
  const limitIdx = paramIdx++;
4390
4408
  const offsetIdx = paramIdx++;
4391
4409
  return {
4392
- agents: (await this.#db.client.manyOrNone(`SELECT a.* FROM ${tableName} a ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
4410
+ agents: (await this.#db.readClient.manyOrNone(`SELECT a.* FROM ${tableName} a ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
4393
4411
  ...joinParams,
4394
4412
  ...queryParams,
4395
4413
  limitValue,
@@ -4489,7 +4507,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4489
4507
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4490
4508
  schemaName: getSchemaName$5(this.#schema)
4491
4509
  });
4492
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4510
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
4493
4511
  if (!result) return null;
4494
4512
  return this.parseVersionRow(result);
4495
4513
  } catch (error) {
@@ -4510,7 +4528,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4510
4528
  schemaName: getSchemaName$5(this.#schema)
4511
4529
  });
4512
4530
  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));
4531
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE id IN (${placeholders})`, ids)).map((row) => this.parseVersionRow(row));
4514
4532
  } catch (error) {
4515
4533
  if (error instanceof _mastra_core_error.MastraError) throw error;
4516
4534
  throw new _mastra_core_error.MastraError({
@@ -4527,7 +4545,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4527
4545
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4528
4546
  schemaName: getSchemaName$5(this.#schema)
4529
4547
  });
4530
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 AND "versionNumber" = $2`, [agentId, versionNumber]);
4548
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 AND "versionNumber" = $2`, [agentId, versionNumber]);
4531
4549
  if (!result) return null;
4532
4550
  return this.parseVersionRow(result);
4533
4551
  } catch (error) {
@@ -4549,7 +4567,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4549
4567
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4550
4568
  schemaName: getSchemaName$5(this.#schema)
4551
4569
  });
4552
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [agentId]);
4570
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [agentId]);
4553
4571
  if (!result) return null;
4554
4572
  return this.parseVersionRow(result);
4555
4573
  } catch (error) {
@@ -4578,7 +4596,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4578
4596
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4579
4597
  schemaName: getSchemaName$5(this.#schema)
4580
4598
  });
4581
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4599
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4582
4600
  const total = parseInt(countResult.count, 10);
4583
4601
  if (total === 0) return {
4584
4602
  versions: [],
@@ -4589,7 +4607,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4589
4607
  };
4590
4608
  const limitValue = perPageInput === false ? total : perPage;
4591
4609
  return {
4592
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
4610
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
4593
4611
  agentId,
4594
4612
  limitValue,
4595
4613
  offset
@@ -4659,7 +4677,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4659
4677
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4660
4678
  schemaName: getSchemaName$5(this.#schema)
4661
4679
  });
4662
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4680
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
4663
4681
  return parseInt(result.count, 10);
4664
4682
  } catch (error) {
4665
4683
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -4916,9 +4934,10 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
4916
4934
  } };
4917
4935
  constructor(config) {
4918
4936
  super();
4919
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
4937
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
4920
4938
  this.#db = new PgDB({
4921
4939
  client,
4940
+ readClient,
4922
4941
  schemaName,
4923
4942
  skipDefaultIndexes
4924
4943
  });
@@ -5170,7 +5189,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5170
5189
  params.push(filter.toDate.toISOString());
5171
5190
  }
5172
5191
  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));
5192
+ const countResult = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) as count FROM ${table} ${where}`, params.slice(0, paramIdx - 1));
5174
5193
  const total = Number(countResult?.count ?? 0);
5175
5194
  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
5195
  if (filter.perPage != null) {
@@ -5182,7 +5201,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5182
5201
  }
5183
5202
  }
5184
5203
  return {
5185
- tasks: (await this.#db.client.manyOrNone(sql, params)).map(rowToTask),
5204
+ tasks: (await this.#db.readClient.manyOrNone(sql, params)).map(rowToTask),
5186
5205
  total
5187
5206
  };
5188
5207
  }
@@ -5219,12 +5238,12 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5219
5238
  }
5220
5239
  async getRunningCount() {
5221
5240
  const table = getTableName$4(getSchemaName$4(this.#schema));
5222
- const result = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${table} WHERE "status" = 'running'`);
5241
+ const result = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${table} WHERE "status" = 'running'`);
5223
5242
  return Number(result?.count ?? 0);
5224
5243
  }
5225
5244
  async getRunningCountByAgent(agentId) {
5226
5245
  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]);
5246
+ const result = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${table} WHERE "status" = 'running' AND "agent_id" = $1`, [agentId]);
5228
5247
  return Number(result?.count ?? 0);
5229
5248
  }
5230
5249
  };
@@ -5236,9 +5255,10 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5236
5255
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SKILL_BLOBS];
5237
5256
  constructor(config) {
5238
5257
  super();
5239
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
5258
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
5240
5259
  this.#db = new PgDB({
5241
5260
  client,
5261
+ readClient,
5242
5262
  schemaName,
5243
5263
  skipDefaultIndexes
5244
5264
  });
@@ -5280,7 +5300,7 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5280
5300
  indexName: _mastra_core_storage.TABLE_SKILL_BLOBS,
5281
5301
  schemaName: getSchemaName$5(this.#schema)
5282
5302
  });
5283
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "hash" = $1`, [hash]);
5303
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "hash" = $1`, [hash]);
5284
5304
  if (!row) return null;
5285
5305
  return this.#parseRow(row);
5286
5306
  }
@@ -5289,7 +5309,7 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5289
5309
  indexName: _mastra_core_storage.TABLE_SKILL_BLOBS,
5290
5310
  schemaName: getSchemaName$5(this.#schema)
5291
5311
  });
5292
- return await this.#db.client.oneOrNone(`SELECT 1 FROM ${tableName} WHERE "hash" = $1 LIMIT 1`, [hash]) !== null;
5312
+ return await this.#db.readClient.oneOrNone(`SELECT 1 FROM ${tableName} WHERE "hash" = $1 LIMIT 1`, [hash]) !== null;
5293
5313
  }
5294
5314
  async delete(hash) {
5295
5315
  const tableName = getTableName$5({
@@ -5310,7 +5330,7 @@ var BlobsPG = class extends _mastra_core_storage.BlobStore {
5310
5330
  schemaName: getSchemaName$5(this.#schema)
5311
5331
  });
5312
5332
  const placeholders = hashes.map((_, i) => `$${i + 1}`).join(", ");
5313
- const rows = await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "hash" IN (${placeholders})`, hashes);
5333
+ const rows = await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "hash" IN (${placeholders})`, hashes);
5314
5334
  for (const row of rows) {
5315
5335
  const entry = this.#parseRow(row);
5316
5336
  result.set(entry.hash, entry);
@@ -5340,9 +5360,10 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5340
5360
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS, _mastra_core_storage.TABLE_CHANNEL_CONFIG];
5341
5361
  constructor(config) {
5342
5362
  super();
5343
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5363
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5344
5364
  this.#db = new PgDB({
5345
5365
  client,
5366
+ readClient,
5346
5367
  schemaName,
5347
5368
  skipDefaultIndexes
5348
5369
  });
@@ -5449,7 +5470,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5449
5470
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5450
5471
  schemaName: getSchemaName$5(this.#schema)
5451
5472
  });
5452
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
5473
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
5453
5474
  return row ? this.#parseInstallationRow(row) : null;
5454
5475
  }
5455
5476
  async getInstallationByAgent(platform, agentId) {
@@ -5457,7 +5478,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5457
5478
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5458
5479
  schemaName: getSchemaName$5(this.#schema)
5459
5480
  });
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]);
5481
+ 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
5482
  return row ? this.#parseInstallationRow(row) : null;
5462
5483
  }
5463
5484
  async getInstallationByWebhookId(webhookId) {
@@ -5465,7 +5486,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5465
5486
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5466
5487
  schemaName: getSchemaName$5(this.#schema)
5467
5488
  });
5468
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "webhookId" = $1`, [webhookId]);
5489
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "webhookId" = $1`, [webhookId]);
5469
5490
  return row ? this.#parseInstallationRow(row) : null;
5470
5491
  }
5471
5492
  async listInstallations(platform) {
@@ -5473,7 +5494,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5473
5494
  indexName: _mastra_core_storage.TABLE_CHANNEL_INSTALLATIONS,
5474
5495
  schemaName: getSchemaName$5(this.#schema)
5475
5496
  });
5476
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1 ORDER BY "createdAt" DESC`, [platform])).map((row) => this.#parseInstallationRow(row));
5497
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1 ORDER BY "createdAt" DESC`, [platform])).map((row) => this.#parseInstallationRow(row));
5477
5498
  }
5478
5499
  async deleteInstallation(id) {
5479
5500
  const tableName = getTableName$5({
@@ -5505,7 +5526,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5505
5526
  indexName: _mastra_core_storage.TABLE_CHANNEL_CONFIG,
5506
5527
  schemaName: getSchemaName$5(this.#schema)
5507
5528
  });
5508
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1`, [platform]);
5529
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1`, [platform]);
5509
5530
  if (!row) return null;
5510
5531
  return {
5511
5532
  platform: row.platform,
@@ -5553,9 +5574,10 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5553
5574
  ];
5554
5575
  constructor(config) {
5555
5576
  super();
5556
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5577
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5557
5578
  this.#db = new PgDB({
5558
5579
  client,
5580
+ readClient,
5559
5581
  schemaName,
5560
5582
  skipDefaultIndexes
5561
5583
  });
@@ -5816,7 +5838,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5816
5838
  };
5817
5839
  } catch (error) {
5818
5840
  if (input.id !== void 0 && (0, _mastra_core_storage.hasErrorCode)(error, /* @__PURE__ */ new Set(["23505"]))) {
5819
- const existing = await this.getDatasetById({ id: input.id });
5841
+ const existing = await this.#getDatasetById(this.#db.client, { id: input.id });
5820
5842
  if (existing) return this.resolveExistingDataset(existing, {
5821
5843
  ...input,
5822
5844
  id: input.id
@@ -5830,7 +5852,20 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5830
5852
  }, error);
5831
5853
  }
5832
5854
  }
5833
- async getDatasetById({ id, filters }) {
5855
+ async getDatasetById(args) {
5856
+ return this.#getDatasetById(this.#db.readClient, args);
5857
+ }
5858
+ getDatasetForMutation(args) {
5859
+ return this.#getDatasetById(this.#db.client, args);
5860
+ }
5861
+ listItemsForMutation(args) {
5862
+ return this.#listItems(this.#db.client, args);
5863
+ }
5864
+ /**
5865
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
5866
+ * lagging read replica cannot yield stale or missing rows mid-update.
5867
+ */
5868
+ async #getDatasetById(client, { id, filters }) {
5834
5869
  try {
5835
5870
  const tableName = getTableName$5({
5836
5871
  indexName: _mastra_core_storage.TABLE_DATASETS,
@@ -5838,7 +5873,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5838
5873
  });
5839
5874
  const { conditions, params } = tenancyWhere(filters, 2);
5840
5875
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
5841
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
5876
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
5842
5877
  return result ? this.transformDatasetRow(result) : null;
5843
5878
  } catch (error) {
5844
5879
  throw new _mastra_core_error.MastraError({
@@ -5850,7 +5885,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5850
5885
  }
5851
5886
  async _doUpdateDataset(args) {
5852
5887
  try {
5853
- const existing = await this.getDatasetById({
5888
+ const existing = await this.#getDatasetById(this.#db.client, {
5854
5889
  id: args.id,
5855
5890
  filters: args.filters
5856
5891
  });
@@ -6022,7 +6057,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6022
6057
  }
6023
6058
  }
6024
6059
  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);
6060
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
6026
6061
  const total = parseInt(countResult.count, 10);
6027
6062
  if (total === 0) return {
6028
6063
  datasets: [],
@@ -6037,7 +6072,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6037
6072
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6038
6073
  const limitValue = perPageInput === false ? total : perPage;
6039
6074
  return {
6040
- datasets: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6075
+ datasets: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6041
6076
  ...queryParams,
6042
6077
  limitValue,
6043
6078
  offset
@@ -6141,7 +6176,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6141
6176
  }
6142
6177
  async _doUpdateItem(args) {
6143
6178
  try {
6144
- const existing = await this.getItemById({ id: args.id });
6179
+ const existing = await this.#getItemById(this.#db.client, { id: args.id });
6145
6180
  if (!existing) throw new _mastra_core_error.MastraError({
6146
6181
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_ITEM", "NOT_FOUND"),
6147
6182
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -6247,7 +6282,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6247
6282
  }
6248
6283
  async _doDeleteItem({ id, datasetId }) {
6249
6284
  try {
6250
- const existing = await this.getItemById({ id });
6285
+ const existing = await this.#getItemById(this.#db.client, { id });
6251
6286
  if (!existing) return;
6252
6287
  if (existing.datasetId !== datasetId) throw new _mastra_core_error.MastraError({
6253
6288
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "DELETE_ITEM", "DATASET_MISMATCH"),
@@ -6414,7 +6449,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6414
6449
  }
6415
6450
  async _doBatchDeleteItems(input) {
6416
6451
  try {
6417
- const dataset = await this.getDatasetById({ id: input.datasetId });
6452
+ const dataset = await this.#getDatasetById(this.#db.client, { id: input.datasetId });
6418
6453
  if (!dataset) throw new _mastra_core_error.MastraError({
6419
6454
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "BULK_DELETE_ITEMS", "DATASET_NOT_FOUND"),
6420
6455
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -6423,7 +6458,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6423
6458
  });
6424
6459
  const currentItems = [];
6425
6460
  for (const itemId of input.itemIds) {
6426
- const item = await this.getItemById({ id: itemId });
6461
+ const item = await this.#getItemById(this.#db.client, { id: itemId });
6427
6462
  if (item && item.datasetId === input.datasetId) currentItems.push(item);
6428
6463
  }
6429
6464
  if (currentItems.length === 0) return;
@@ -6487,14 +6522,17 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6487
6522
  }
6488
6523
  }
6489
6524
  async getItemById(args) {
6525
+ return this.#getItemById(this.#db.readClient, args);
6526
+ }
6527
+ async #getItemById(client, args) {
6490
6528
  try {
6491
6529
  const tableName = getTableName$5({
6492
6530
  indexName: _mastra_core_storage.TABLE_DATASET_ITEMS,
6493
6531
  schemaName: getSchemaName$5(this.#schema)
6494
6532
  });
6495
6533
  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]);
6534
+ 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]);
6535
+ else result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 AND "validTo" IS NULL AND "isDeleted" = false`, [args.id]);
6498
6536
  return result ? this.transformItemRow(result) : null;
6499
6537
  } catch (error) {
6500
6538
  throw new _mastra_core_error.MastraError({
@@ -6510,7 +6548,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6510
6548
  indexName: _mastra_core_storage.TABLE_DATASET_ITEMS,
6511
6549
  schemaName: getSchemaName$5(this.#schema)
6512
6550
  });
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`, [
6551
+ 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
6552
  datasetId,
6515
6553
  version,
6516
6554
  version
@@ -6529,7 +6567,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6529
6567
  indexName: _mastra_core_storage.TABLE_DATASET_ITEMS,
6530
6568
  schemaName: getSchemaName$5(this.#schema)
6531
6569
  });
6532
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 ORDER BY "datasetVersion" DESC`, [itemId]) || []).map((row) => this.transformItemRowFull(row));
6570
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1 ORDER BY "datasetVersion" DESC`, [itemId]) || []).map((row) => this.transformItemRowFull(row));
6533
6571
  } catch (error) {
6534
6572
  throw new _mastra_core_error.MastraError({
6535
6573
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "GET_ITEM_HISTORY", "FAILED"),
@@ -6539,6 +6577,13 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6539
6577
  }
6540
6578
  }
6541
6579
  async listItems(args) {
6580
+ return this.#listItems(this.#db.readClient, args);
6581
+ }
6582
+ /**
6583
+ * Same listing against an explicit client. `updateDataset` validates existing
6584
+ * items on the writer so a lagging replica cannot hide freshly inserted rows.
6585
+ */
6586
+ async #listItems(client, args) {
6542
6587
  try {
6543
6588
  const { page, perPage: perPageInput } = args.pagination;
6544
6589
  const tableName = getTableName$5({
@@ -6575,7 +6620,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6575
6620
  }
6576
6621
  }
6577
6622
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
6578
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
6623
+ const countResult = await client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
6579
6624
  const total = parseInt(countResult.count, 10);
6580
6625
  if (total === 0) return {
6581
6626
  items: [],
@@ -6590,7 +6635,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6590
6635
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6591
6636
  const limitValue = perPageInput === false ? total : perPage;
6592
6637
  return {
6593
- items: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6638
+ items: (await client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6594
6639
  ...queryParams,
6595
6640
  limitValue,
6596
6641
  offset
@@ -6645,7 +6690,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6645
6690
  indexName: _mastra_core_storage.TABLE_DATASET_VERSIONS,
6646
6691
  schemaName: getSchemaName$5(this.#schema)
6647
6692
  });
6648
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "datasetId" = $1`, [input.datasetId]);
6693
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "datasetId" = $1`, [input.datasetId]);
6649
6694
  const total = parseInt(countResult.count, 10);
6650
6695
  if (total === 0) return {
6651
6696
  versions: [],
@@ -6660,7 +6705,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6660
6705
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6661
6706
  const limitValue = perPageInput === false ? total : perPage;
6662
6707
  return {
6663
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "datasetId" = $1 ORDER BY "version" DESC LIMIT $2 OFFSET $3`, [
6708
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "datasetId" = $1 ORDER BY "version" DESC LIMIT $2 OFFSET $3`, [
6664
6709
  input.datasetId,
6665
6710
  limitValue,
6666
6711
  offset
@@ -6710,9 +6755,10 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
6710
6755
  } };
6711
6756
  constructor(config) {
6712
6757
  super();
6713
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
6758
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
6714
6759
  this.#db = new PgDB({
6715
6760
  client,
6761
+ readClient,
6716
6762
  schemaName,
6717
6763
  skipDefaultIndexes
6718
6764
  });
@@ -7050,7 +7096,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7050
7096
  }
7051
7097
  async updateExperiment(input) {
7052
7098
  try {
7053
- if (!await this.getExperimentById({ id: input.id })) throw new _mastra_core_error.MastraError({
7099
+ if (!await this.#getExperimentById(this.#db.client, { id: input.id })) throw new _mastra_core_error.MastraError({
7054
7100
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_EXPERIMENT", "NOT_FOUND"),
7055
7101
  domain: _mastra_core_error.ErrorDomain.STORAGE,
7056
7102
  category: _mastra_core_error.ErrorCategory.USER,
@@ -7106,7 +7152,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7106
7152
  }
7107
7153
  values.push(input.id);
7108
7154
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE "id" = $${paramIndex}`, values);
7109
- return await this.getExperimentById({ id: input.id });
7155
+ return await this.#getExperimentById(this.#db.client, { id: input.id });
7110
7156
  } catch (error) {
7111
7157
  if (error instanceof _mastra_core_error.MastraError) throw error;
7112
7158
  throw new _mastra_core_error.MastraError({
@@ -7116,7 +7162,14 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7116
7162
  }, error);
7117
7163
  }
7118
7164
  }
7119
- async getExperimentById({ id, filters }) {
7165
+ async getExperimentById(args) {
7166
+ return this.#getExperimentById(this.#db.readClient, args);
7167
+ }
7168
+ /**
7169
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
7170
+ * lagging read replica cannot yield stale or missing rows mid-update.
7171
+ */
7172
+ async #getExperimentById(client, { id, filters }) {
7120
7173
  try {
7121
7174
  const tableName = getTableName$5({
7122
7175
  indexName: _mastra_core_storage.TABLE_EXPERIMENTS,
@@ -7124,7 +7177,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7124
7177
  });
7125
7178
  const { conditions, params } = tenancyWhere(filters, 2);
7126
7179
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
7127
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7180
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7128
7181
  return result ? this.transformExperimentRow(result) : null;
7129
7182
  } catch (error) {
7130
7183
  throw new _mastra_core_error.MastraError({
@@ -7192,7 +7245,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7192
7245
  }
7193
7246
  }
7194
7247
  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);
7248
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
7196
7249
  const total = parseInt(countResult.count, 10);
7197
7250
  if (total === 0) return {
7198
7251
  experiments: [],
@@ -7207,7 +7260,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7207
7260
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
7208
7261
  const limitValue = perPageInput === false ? total : perPage;
7209
7262
  return {
7210
- experiments: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7263
+ experiments: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7211
7264
  ...queryParams,
7212
7265
  limitValue,
7213
7266
  offset
@@ -7411,7 +7464,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7411
7464
  values.push(input.comment);
7412
7465
  }
7413
7466
  if (setClauses.length === 0) {
7414
- const existing = await this.getExperimentResultById({ id: input.id });
7467
+ const existing = await this.#getExperimentResultById(this.#db.client, { id: input.id });
7415
7468
  if (!existing) throw new _mastra_core_error.MastraError({
7416
7469
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_EXPERIMENT_RESULT", "NOT_FOUND"),
7417
7470
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -7444,7 +7497,14 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7444
7497
  }, error);
7445
7498
  }
7446
7499
  }
7447
- async getExperimentResultById({ id, filters }) {
7500
+ async getExperimentResultById(args) {
7501
+ return this.#getExperimentResultById(this.#db.readClient, args);
7502
+ }
7503
+ /**
7504
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
7505
+ * lagging read replica cannot yield stale or missing rows mid-update.
7506
+ */
7507
+ async #getExperimentResultById(client, { id, filters }) {
7448
7508
  try {
7449
7509
  const tableName = getTableName$5({
7450
7510
  indexName: _mastra_core_storage.TABLE_EXPERIMENT_RESULTS,
@@ -7452,7 +7512,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7452
7512
  });
7453
7513
  const { conditions, params } = tenancyWhere(filters, 2);
7454
7514
  const whereSql = ["\"id\" = $1", ...conditions].join(" AND ");
7455
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7515
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE ${whereSql}`, [id, ...params]);
7456
7516
  return result ? this.transformExperimentResultRow(result) : null;
7457
7517
  } catch (error) {
7458
7518
  throw new _mastra_core_error.MastraError({
@@ -7492,7 +7552,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7492
7552
  }
7493
7553
  }
7494
7554
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
7495
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
7555
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
7496
7556
  const total = parseInt(countResult.count, 10);
7497
7557
  if (total === 0) return {
7498
7558
  results: [],
@@ -7507,7 +7567,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7507
7567
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
7508
7568
  const limitValue = perPageInput === false ? total : perPage;
7509
7569
  return {
7510
- results: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7570
+ results: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7511
7571
  ...queryParams,
7512
7572
  limitValue,
7513
7573
  offset
@@ -7561,7 +7621,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7561
7621
  indexName: _mastra_core_storage.TABLE_EXPERIMENT_RESULTS,
7562
7622
  schemaName: getSchemaName$5(this.#schema)
7563
7623
  });
7564
- return (await this.#db.client.manyOrNone(`SELECT
7624
+ return (await this.#db.readClient.manyOrNone(`SELECT
7565
7625
  "experimentId",
7566
7626
  COUNT(*)::int as total,
7567
7627
  SUM(CASE WHEN status = 'needs-review' THEN 1 ELSE 0 END)::int as "needsReview",
@@ -7603,9 +7663,10 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7603
7663
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_FAVORITES];
7604
7664
  constructor(config) {
7605
7665
  super();
7606
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
7666
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
7607
7667
  this.#db = new PgDB({
7608
7668
  client,
7669
+ readClient,
7609
7670
  schemaName,
7610
7671
  skipDefaultIndexes
7611
7672
  });
@@ -7771,7 +7832,7 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7771
7832
  schemaName: getSchemaName$5(this.#schema)
7772
7833
  });
7773
7834
  try {
7774
- return await this.#db.client.oneOrNone(`SELECT 1 FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 AND "entityId" = $3 LIMIT 1`, [
7835
+ return await this.#db.readClient.oneOrNone(`SELECT 1 FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 AND "entityId" = $3 LIMIT 1`, [
7775
7836
  input.userId,
7776
7837
  input.entityType,
7777
7838
  input.entityId
@@ -7794,7 +7855,7 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7794
7855
  });
7795
7856
  try {
7796
7857
  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})`, [
7858
+ const rows = await this.#db.readClient.manyOrNone(`SELECT "entityId" FROM ${fullFavoritesTable} WHERE "userId" = $1 AND "entityType" = $2 AND "entityId" IN (${placeholders})`, [
7798
7859
  userId,
7799
7860
  entityType,
7800
7861
  ...entityIds
@@ -7817,7 +7878,7 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
7817
7878
  schemaName: getSchemaName$5(this.#schema)
7818
7879
  });
7819
7880
  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);
7881
+ 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
7882
  } catch (error) {
7822
7883
  if (error instanceof _mastra_core_error.MastraError) throw error;
7823
7884
  throw new _mastra_core_error.MastraError({
@@ -8120,16 +8181,20 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8120
8181
  }
8121
8182
  #client;
8122
8183
  #executor;
8184
+ /** Reader-backed executor for standalone reads; mutations and read-modify-write stay on #executor. */
8185
+ #readExecutor;
8123
8186
  #db;
8124
8187
  #schemaName;
8125
8188
  constructor(config) {
8126
8189
  super();
8127
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
8190
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
8128
8191
  this.#client = client;
8129
8192
  this.#schemaName = schemaName;
8130
8193
  this.#executor = createExecutor(client, schemaName);
8194
+ this.#readExecutor = createExecutor(readClient, schemaName);
8131
8195
  this.#db = new PgDB({
8132
8196
  client,
8197
+ readClient,
8133
8198
  schemaName,
8134
8199
  skipDefaultIndexes
8135
8200
  });
@@ -8231,13 +8296,13 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8231
8296
  });
8232
8297
  }
8233
8298
  async getNode(id) {
8234
- return this.#getNode(this.#executor, id);
8299
+ return this.#getNode(this.#readExecutor, id);
8235
8300
  }
8236
8301
  async getNodeByName(input) {
8237
- return this.#getNodeByName(this.#executor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8302
+ return this.#getNodeByName(this.#readExecutor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8238
8303
  }
8239
8304
  async resolveNode(input) {
8240
- return this.#resolveNode(this.#executor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8305
+ return this.#resolveNode(this.#readExecutor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8241
8306
  }
8242
8307
  async listNodes(input) {
8243
8308
  const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
@@ -8267,7 +8332,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8267
8332
  args.push(updatedAt, updatedAt, cursor.name, cursor.name, cursor.id);
8268
8333
  }
8269
8334
  args.push(input.limit ?? 100);
8270
- return (await this.#executor.execute({
8335
+ return (await this.#readExecutor.execute({
8271
8336
  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
8337
  args
8273
8338
  })).rows.map(parseNode);
@@ -8433,7 +8498,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8433
8498
  });
8434
8499
  }
8435
8500
  async getKnowledge(input) {
8436
- const result = await this.#executor.execute({
8501
+ const result = await this.#readExecutor.execute({
8437
8502
  sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${input.includeDeleted ? "" : " AND deletedAt IS NULL"}`,
8438
8503
  args: [input.id]
8439
8504
  });
@@ -8458,7 +8523,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8458
8523
  if (input.after) args.push(input.after);
8459
8524
  const limit = input.limit ?? 100;
8460
8525
  args.push(limit + 1);
8461
- const records = (await this.#executor.execute({
8526
+ const records = (await this.#readExecutor.execute({
8462
8527
  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
8528
  args
8464
8529
  })).rows.map(parseKnowledge);
@@ -8553,7 +8618,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8553
8618
  const normalizedQuery = input.query.trim().toLocaleLowerCase();
8554
8619
  if (!normalizedQuery) return [];
8555
8620
  const query = `%${escapeLikePattern(normalizedQuery)}%`;
8556
- const results = (await this.#executor.execute({
8621
+ const results = (await this.#readExecutor.execute({
8557
8622
  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
8623
  args: [
8559
8624
  key,
@@ -8577,7 +8642,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8577
8642
  scope: parseJson$1(row.scopeJson)
8578
8643
  }));
8579
8644
  if (results.length < (input.limit ?? 20)) {
8580
- const records = await this.#executor.execute({
8645
+ const records = await this.#readExecutor.execute({
8581
8646
  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
8647
  args: [
8583
8648
  key,
@@ -8630,7 +8695,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8630
8695
  }
8631
8696
  async listActivity(input) {
8632
8697
  const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
8633
- return (await this.#executor.execute({
8698
+ return (await this.#readExecutor.execute({
8634
8699
  sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY}" WHERE ${visibleSql}${input.after ? " AND id < ?" : ""} ORDER BY id DESC LIMIT ?`,
8635
8700
  args: [
8636
8701
  key,
@@ -8774,7 +8839,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8774
8839
  }
8775
8840
  async #queryKnowledge(input, relationship) {
8776
8841
  const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
8777
- const node = await this.#resolveTerminalNode(this.#executor, nodeReferenceId(input.node));
8842
+ const node = await this.#resolveTerminalNode(this.#readExecutor, nodeReferenceId(input.node));
8778
8843
  if (!node) return { records: [] };
8779
8844
  const key = (0, _mastra_core_storage.knowledgeScopeKey)(scope);
8780
8845
  const args = [
@@ -8785,7 +8850,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8785
8850
  ];
8786
8851
  if (input.after) args.push(input.after);
8787
8852
  args.push((input.limit ?? 100) + 1);
8788
- const records = (await this.#executor.execute({
8853
+ const records = (await this.#readExecutor.execute({
8789
8854
  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
8855
  args
8791
8856
  })).rows.map(parseKnowledge);
@@ -8897,9 +8962,10 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
8897
8962
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_MCP_CLIENTS, _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS];
8898
8963
  constructor(config) {
8899
8964
  super();
8900
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
8965
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
8901
8966
  this.#db = new PgDB({
8902
8967
  client,
8968
+ readClient,
8903
8969
  schemaName,
8904
8970
  skipDefaultIndexes
8905
8971
  });
@@ -8963,12 +9029,19 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
8963
9029
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_MCP_CLIENTS });
8964
9030
  }
8965
9031
  async getById(id) {
9032
+ return this.#getById(this.#db.readClient, id);
9033
+ }
9034
+ /**
9035
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
9036
+ * lagging read replica cannot yield stale or missing rows mid-update.
9037
+ */
9038
+ async #getById(client, id) {
8966
9039
  try {
8967
9040
  const tableName = getTableName$5({
8968
9041
  indexName: _mastra_core_storage.TABLE_MCP_CLIENTS,
8969
9042
  schemaName: getSchemaName$5(this.#schema)
8970
9043
  });
8971
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9044
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
8972
9045
  if (!result) return null;
8973
9046
  return this.parseMCPClientRow(result);
8974
9047
  } catch (error) {
@@ -9047,7 +9120,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9047
9120
  indexName: _mastra_core_storage.TABLE_MCP_CLIENTS,
9048
9121
  schemaName: getSchemaName$5(this.#schema)
9049
9122
  });
9050
- const existingClient = await this.getById(id);
9123
+ const existingClient = await this.#getById(this.#db.client, id);
9051
9124
  if (!existingClient) throw new _mastra_core_error.MastraError({
9052
9125
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_CLIENT", "NOT_FOUND"),
9053
9126
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9086,7 +9159,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9086
9159
  values.push(now);
9087
9160
  values.push(id);
9088
9161
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
9089
- const updatedClient = await this.getById(id);
9162
+ const updatedClient = await this.#getById(this.#db.client, id);
9090
9163
  if (!updatedClient) throw new _mastra_core_error.MastraError({
9091
9164
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_CLIENT", "NOT_FOUND_AFTER_UPDATE"),
9092
9165
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9153,7 +9226,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9153
9226
  queryParams.push(JSON.stringify(metadata));
9154
9227
  }
9155
9228
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
9156
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9229
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9157
9230
  const total = parseInt(countResult.count, 10);
9158
9231
  if (total === 0) return {
9159
9232
  mcpClients: [],
@@ -9164,7 +9237,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9164
9237
  };
9165
9238
  const limitValue = perPageInput === false ? total : perPage;
9166
9239
  return {
9167
- mcpClients: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9240
+ mcpClients: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9168
9241
  ...queryParams,
9169
9242
  limitValue,
9170
9243
  offset
@@ -9241,7 +9314,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9241
9314
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9242
9315
  schemaName: getSchemaName$5(this.#schema)
9243
9316
  });
9244
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9317
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9245
9318
  if (!result) return null;
9246
9319
  return this.parseVersionRow(result);
9247
9320
  } catch (error) {
@@ -9260,7 +9333,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9260
9333
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9261
9334
  schemaName: getSchemaName$5(this.#schema)
9262
9335
  });
9263
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 AND "versionNumber" = $2`, [mcpClientId, versionNumber]);
9336
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 AND "versionNumber" = $2`, [mcpClientId, versionNumber]);
9264
9337
  if (!result) return null;
9265
9338
  return this.parseVersionRow(result);
9266
9339
  } catch (error) {
@@ -9282,7 +9355,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9282
9355
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9283
9356
  schemaName: getSchemaName$5(this.#schema)
9284
9357
  });
9285
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpClientId]);
9358
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpClientId]);
9286
9359
  if (!result) return null;
9287
9360
  return this.parseVersionRow(result);
9288
9361
  } catch (error) {
@@ -9311,7 +9384,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9311
9384
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9312
9385
  schemaName: getSchemaName$5(this.#schema)
9313
9386
  });
9314
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9387
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9315
9388
  const total = parseInt(countResult.count, 10);
9316
9389
  if (total === 0) return {
9317
9390
  versions: [],
@@ -9322,7 +9395,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9322
9395
  };
9323
9396
  const limitValue = perPageInput === false ? total : perPage;
9324
9397
  return {
9325
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9398
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpClientId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9326
9399
  mcpClientId,
9327
9400
  limitValue,
9328
9401
  offset
@@ -9392,7 +9465,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9392
9465
  indexName: _mastra_core_storage.TABLE_MCP_CLIENT_VERSIONS,
9393
9466
  schemaName: getSchemaName$5(this.#schema)
9394
9467
  });
9395
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9468
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpClientId" = $1`, [mcpClientId]);
9396
9469
  return parseInt(result.count, 10);
9397
9470
  } catch (error) {
9398
9471
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -9452,9 +9525,10 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9452
9525
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_MCP_SERVERS, _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS];
9453
9526
  constructor(config) {
9454
9527
  super();
9455
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
9528
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
9456
9529
  this.#db = new PgDB({
9457
9530
  client,
9531
+ readClient,
9458
9532
  schemaName,
9459
9533
  skipDefaultIndexes
9460
9534
  });
@@ -9518,12 +9592,19 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9518
9592
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_MCP_SERVERS });
9519
9593
  }
9520
9594
  async getById(id) {
9595
+ return this.#getById(this.#db.readClient, id);
9596
+ }
9597
+ /**
9598
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
9599
+ * lagging read replica cannot yield stale or missing rows mid-update.
9600
+ */
9601
+ async #getById(client, id) {
9521
9602
  try {
9522
9603
  const tableName = getTableName$5({
9523
9604
  indexName: _mastra_core_storage.TABLE_MCP_SERVERS,
9524
9605
  schemaName: getSchemaName$5(this.#schema)
9525
9606
  });
9526
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9607
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9527
9608
  if (!result) return null;
9528
9609
  return this.parseMCPServerRow(result);
9529
9610
  } catch (error) {
@@ -9602,7 +9683,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9602
9683
  indexName: _mastra_core_storage.TABLE_MCP_SERVERS,
9603
9684
  schemaName: getSchemaName$5(this.#schema)
9604
9685
  });
9605
- const existingServer = await this.getById(id);
9686
+ const existingServer = await this.#getById(this.#db.client, id);
9606
9687
  if (!existingServer) throw new _mastra_core_error.MastraError({
9607
9688
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_SERVER", "NOT_FOUND"),
9608
9689
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9641,7 +9722,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9641
9722
  values.push(now);
9642
9723
  values.push(id);
9643
9724
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
9644
- const updatedServer = await this.getById(id);
9725
+ const updatedServer = await this.#getById(this.#db.client, id);
9645
9726
  if (!updatedServer) throw new _mastra_core_error.MastraError({
9646
9727
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_MCP_SERVER", "NOT_FOUND_AFTER_UPDATE"),
9647
9728
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -9708,7 +9789,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9708
9789
  queryParams.push(JSON.stringify(metadata));
9709
9790
  }
9710
9791
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
9711
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9792
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
9712
9793
  const total = parseInt(countResult.count, 10);
9713
9794
  if (total === 0) return {
9714
9795
  mcpServers: [],
@@ -9719,7 +9800,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9719
9800
  };
9720
9801
  const limitValue = perPageInput === false ? total : perPage;
9721
9802
  return {
9722
- mcpServers: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9803
+ mcpServers: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
9723
9804
  ...queryParams,
9724
9805
  limitValue,
9725
9806
  offset
@@ -9806,7 +9887,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9806
9887
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9807
9888
  schemaName: getSchemaName$5(this.#schema)
9808
9889
  });
9809
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9890
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
9810
9891
  if (!result) return null;
9811
9892
  return this.parseVersionRow(result);
9812
9893
  } catch (error) {
@@ -9825,7 +9906,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9825
9906
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9826
9907
  schemaName: getSchemaName$5(this.#schema)
9827
9908
  });
9828
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 AND "versionNumber" = $2`, [mcpServerId, versionNumber]);
9909
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 AND "versionNumber" = $2`, [mcpServerId, versionNumber]);
9829
9910
  if (!result) return null;
9830
9911
  return this.parseVersionRow(result);
9831
9912
  } catch (error) {
@@ -9847,7 +9928,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9847
9928
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9848
9929
  schemaName: getSchemaName$5(this.#schema)
9849
9930
  });
9850
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpServerId]);
9931
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [mcpServerId]);
9851
9932
  if (!result) return null;
9852
9933
  return this.parseVersionRow(result);
9853
9934
  } catch (error) {
@@ -9876,7 +9957,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9876
9957
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9877
9958
  schemaName: getSchemaName$5(this.#schema)
9878
9959
  });
9879
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
9960
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
9880
9961
  const total = parseInt(countResult.count, 10);
9881
9962
  if (total === 0) return {
9882
9963
  versions: [],
@@ -9887,7 +9968,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9887
9968
  };
9888
9969
  const limitValue = perPageInput === false ? total : perPage;
9889
9970
  return {
9890
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9971
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
9891
9972
  mcpServerId,
9892
9973
  limitValue,
9893
9974
  offset
@@ -9957,7 +10038,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9957
10038
  indexName: _mastra_core_storage.TABLE_MCP_SERVER_VERSIONS,
9958
10039
  schemaName: getSchemaName$5(this.#schema)
9959
10040
  });
9960
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
10041
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [mcpServerId]);
9961
10042
  return parseInt(result.count, 10);
9962
10043
  } catch (error) {
9963
10044
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -10126,9 +10207,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10126
10207
  ];
10127
10208
  constructor(config) {
10128
10209
  super();
10129
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
10210
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
10130
10211
  this.#db = new PgDB({
10131
10212
  client,
10213
+ readClient,
10132
10214
  schemaName,
10133
10215
  skipDefaultIndexes
10134
10216
  });
@@ -10377,6 +10459,16 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10377
10459
  };
10378
10460
  }
10379
10461
  async getThreadById({ threadId, resourceId }) {
10462
+ return this.#getThreadById(this.#db.readClient, {
10463
+ threadId,
10464
+ resourceId
10465
+ });
10466
+ }
10467
+ /**
10468
+ * Thread lookup against an explicit client. Mutation paths pass the writer so
10469
+ * a lagging read replica cannot produce false not-found or stale metadata.
10470
+ */
10471
+ async #getThreadById(client, { threadId, resourceId }) {
10380
10472
  try {
10381
10473
  let query = `SELECT * FROM ${getTableName$3({
10382
10474
  indexName: _mastra_core_storage.TABLE_THREADS,
@@ -10387,7 +10479,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10387
10479
  query += ` AND "resourceId" = $2`;
10388
10480
  params.push(resourceId);
10389
10481
  }
10390
- const thread = await this.#db.client.oneOrNone(query, params);
10482
+ const thread = await client.oneOrNone(query, params);
10391
10483
  if (!thread) return null;
10392
10484
  return {
10393
10485
  id: thread.id,
@@ -10456,7 +10548,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10456
10548
  }
10457
10549
  const baseQuery = `FROM ${tableName} ${whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : ""}`;
10458
10550
  const countQuery = `SELECT COUNT(*) ${baseQuery}`;
10459
- const countResult = await this.#db.client.one(countQuery, queryParams);
10551
+ const countResult = await this.#db.readClient.one(countQuery, queryParams);
10460
10552
  const total = parseInt(countResult.count, 10);
10461
10553
  if (total === 0) return {
10462
10554
  threads: [],
@@ -10468,7 +10560,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10468
10560
  const limitValue = perPageInput === false ? total : perPage;
10469
10561
  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
10562
  return {
10471
- threads: (await this.#db.client.manyOrNone(dataQuery, [
10563
+ threads: (await this.#db.readClient.manyOrNone(dataQuery, [
10472
10564
  ...queryParams,
10473
10565
  limitValue,
10474
10566
  offset
@@ -10552,7 +10644,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10552
10644
  indexName: _mastra_core_storage.TABLE_THREADS,
10553
10645
  schemaName: getSchemaName$3(this.#schema)
10554
10646
  });
10555
- const existingThread = await this.getThreadById({ threadId: id });
10647
+ const existingThread = await this.#getThreadById(this.#db.client, { threadId: id });
10556
10648
  if (!existingThread) throw new _mastra_core_error.MastraError({
10557
10649
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_THREAD", "FAILED"),
10558
10650
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -10684,7 +10776,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10684
10776
  if (targetIds.length === 0) return null;
10685
10777
  const idPlaceholders = targetIds.map((_, i) => "$" + (i + 1)).join(", ");
10686
10778
  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);
10779
+ const targetRows = await this.#db.readClient.manyOrNone(`SELECT id, thread_id, "createdAt" FROM ${tableName} WHERE id IN (${idPlaceholders})${targetResourceCondition}`, resourceId ? [...targetIds, resourceId] : targetIds);
10688
10780
  if (targetRows.length === 0) return null;
10689
10781
  const targetMap = new Map(targetRows.map((r) => [r.id, {
10690
10782
  threadId: r.thread_id,
@@ -10735,7 +10827,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10735
10827
  let finalQuery;
10736
10828
  if (unionQueries.length === 1) finalQuery = unionQueries[0].slice(1, -1);
10737
10829
  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);
10830
+ const includedRows = await this.#db.readClient.manyOrNone(finalQuery, params);
10739
10831
  const seen = /* @__PURE__ */ new Set();
10740
10832
  return includedRows.filter((row) => {
10741
10833
  if (seen.has(row.id)) return false;
@@ -10771,7 +10863,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10771
10863
  WHERE id IN (${inPlaceholders(messageIds.length)})
10772
10864
  ORDER BY "createdAt" DESC
10773
10865
  `;
10774
- const resultRows = await this.#db.client.manyOrNone(query, messageIds);
10866
+ const resultRows = await this.#db.readClient.manyOrNone(query, messageIds);
10775
10867
  return { messages: new _mastra_core_agent.MessageList().add(resultRows.map((row) => this.parseRow(row)), "memory").get.all.db() };
10776
10868
  } catch (error) {
10777
10869
  const mastraError = new _mastra_core_error.MastraError({
@@ -10802,7 +10894,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10802
10894
  perPage,
10803
10895
  offset
10804
10896
  ];
10805
- const rows = await this.#db.client.manyOrNone(`${selectStatement}, COUNT(*) OVER () AS "__total" FROM ${tableName} ${whereClause} ${orderByStatement}${limitClause}`, dataParams) || [];
10897
+ const rows = await this.#db.readClient.manyOrNone(`${selectStatement}, COUNT(*) OVER () AS "__total" FROM ${tableName} ${whereClause} ${orderByStatement}${limitClause}`, dataParams) || [];
10806
10898
  if (rows.length > 0) return {
10807
10899
  total: Number(rows[0].__total),
10808
10900
  messages: rows
@@ -10811,7 +10903,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10811
10903
  total: 0,
10812
10904
  messages: []
10813
10905
  };
10814
- const countResult = await this.#db.client.one(`SELECT COUNT(*) FROM ${tableName} ${whereClause}`, queryParams);
10906
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) FROM ${tableName} ${whereClause}`, queryParams);
10815
10907
  return {
10816
10908
  total: parseInt(countResult.count, 10),
10817
10909
  messages: []
@@ -10905,7 +10997,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10905
10997
  let total;
10906
10998
  let messages;
10907
10999
  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));
11000
+ const filteredRows = (await this.#db.readClient.manyOrNone(`${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement}`, queryParams) || []).filter((row) => (0, _mastra_core_storage.storageMessageMatchesMetadataFilter)(row.content, metadataFilter));
10909
11001
  total = filteredRows.length;
10910
11002
  messages = perPageInput === false ? filteredRows : filteredRows.slice(offset, offset + perPage);
10911
11003
  } else ({total, messages} = await this.#fetchMessagePage({
@@ -11051,7 +11143,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11051
11143
  let total;
11052
11144
  let messages;
11053
11145
  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));
11146
+ const filteredRows = (await this.#db.readClient.manyOrNone(`${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement}`, queryParams) || []).filter((row) => (0, _mastra_core_storage.storageMessageMatchesMetadataFilter)(row.content, metadataFilter));
11055
11147
  total = filteredRows.length;
11056
11148
  messages = perPageInput === false ? filteredRows : filteredRows.slice(offset, offset + perPage);
11057
11149
  } else ({total, messages} = await this.#fetchMessagePage({
@@ -11126,7 +11218,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11126
11218
  if (!message.resourceId) throw new Error(`Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`);
11127
11219
  threadIds.add(message.threadId);
11128
11220
  }
11129
- for (const threadIdToCheck of threadIds) if (!await this.getThreadById({ threadId: threadIdToCheck })) throw new _mastra_core_error.MastraError({
11221
+ for (const threadIdToCheck of threadIds) if (!await this.#getThreadById(this.#db.client, { threadId: threadIdToCheck })) throw new _mastra_core_error.MastraError({
11130
11222
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "SAVE_MESSAGES", "FAILED"),
11131
11223
  domain: _mastra_core_error.ErrorDomain.STORAGE,
11132
11224
  category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
@@ -11294,11 +11386,14 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11294
11386
  }
11295
11387
  }
11296
11388
  async getResourceById({ resourceId }) {
11389
+ return this.#getResourceById(this.#db.readClient, resourceId);
11390
+ }
11391
+ async #getResourceById(client, resourceId) {
11297
11392
  const tableName = getTableName$3({
11298
11393
  indexName: _mastra_core_storage.TABLE_RESOURCES,
11299
11394
  schemaName: getSchemaName$3(this.#schema)
11300
11395
  });
11301
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [resourceId]);
11396
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [resourceId]);
11302
11397
  if (!result) return null;
11303
11398
  return {
11304
11399
  id: result.id,
@@ -11323,7 +11418,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11323
11418
  return resource;
11324
11419
  }
11325
11420
  async updateResource({ resourceId, workingMemory, metadata }) {
11326
- const existingResource = await this.getResourceById({ resourceId });
11421
+ const existingResource = await this.#getResourceById(this.#db.client, resourceId);
11327
11422
  if (!existingResource) {
11328
11423
  const newResource = {
11329
11424
  id: resourceId,
@@ -11371,7 +11466,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11371
11466
  }
11372
11467
  async cloneThread(args) {
11373
11468
  const { sourceThreadId, newThreadId: providedThreadId, resourceId, title, metadata, options } = args;
11374
- const sourceThread = await this.getThreadById({ threadId: sourceThreadId });
11469
+ const sourceThread = await this.#getThreadById(this.#db.client, { threadId: sourceThreadId });
11375
11470
  if (!sourceThread) throw new _mastra_core_error.MastraError({
11376
11471
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "CLONE_THREAD", "SOURCE_NOT_FOUND"),
11377
11472
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -11380,7 +11475,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11380
11475
  details: { sourceThreadId }
11381
11476
  });
11382
11477
  const newThreadId = providedThreadId || crypto.randomUUID();
11383
- if (await this.getThreadById({ threadId: newThreadId })) throw new _mastra_core_error.MastraError({
11478
+ if (await this.#getThreadById(this.#db.client, { threadId: newThreadId })) throw new _mastra_core_error.MastraError({
11384
11479
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "CLONE_THREAD", "THREAD_EXISTS"),
11385
11480
  domain: _mastra_core_error.ErrorDomain.STORAGE,
11386
11481
  category: _mastra_core_error.ErrorCategory.USER,
@@ -11555,7 +11650,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11555
11650
  indexName: OM_TABLE,
11556
11651
  schemaName: getSchemaName$3(this.#schema)
11557
11652
  });
11558
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`, [lookupKey]);
11653
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`, [lookupKey]);
11559
11654
  if (!result) return null;
11560
11655
  return this.parseOMRow(result);
11561
11656
  } catch (error) {
@@ -11597,7 +11692,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11597
11692
  params.push(options.offset);
11598
11693
  sql += ` OFFSET $${paramIndex}`;
11599
11694
  }
11600
- const result = await this.#db.client.manyOrNone(sql, params);
11695
+ const result = await this.#db.readClient.manyOrNone(sql, params);
11601
11696
  if (!result) return [];
11602
11697
  return result.map((row) => this.parseOMRow(row));
11603
11698
  } catch (error) {
@@ -12538,9 +12633,10 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12538
12633
  } };
12539
12634
  constructor(config) {
12540
12635
  super();
12541
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12636
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12542
12637
  this.#db = new PgDB({
12543
12638
  client,
12639
+ readClient,
12544
12640
  schemaName,
12545
12641
  skipDefaultIndexes
12546
12642
  });
@@ -12709,7 +12805,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12709
12805
  coalescedCount: (existing.coalescedCount ?? 1) + 1,
12710
12806
  metadata: metadata ?? null
12711
12807
  });
12712
- const updated = await this.getNotification({
12808
+ const updated = await this.#getNotification(this.#db.client, {
12713
12809
  threadId: existing.threadId,
12714
12810
  id: existing.id
12715
12811
  });
@@ -12775,7 +12871,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12775
12871
  indexName: _mastra_core_storage.TABLE_NOTIFICATIONS,
12776
12872
  schemaName: getSchemaName$5(this.#schema)
12777
12873
  });
12778
- return (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY "updatedAt" DESC${limit}`, args)).map((row) => rowToNotification(row));
12874
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY "updatedAt" DESC${limit}`, args)).map((row) => rowToNotification(row));
12779
12875
  }
12780
12876
  async listDueNotifications(input) {
12781
12877
  const conditions = ["\"status\" = $1", "((\"deliverAt\" IS NOT NULL AND \"deliverAt\" <= $2) OR (\"summaryAt\" IS NOT NULL AND \"summaryAt\" <= $3))"];
@@ -12798,18 +12894,25 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12798
12894
  indexName: _mastra_core_storage.TABLE_NOTIFICATIONS,
12799
12895
  schemaName: getSchemaName$5(this.#schema)
12800
12896
  });
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));
12897
+ 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
12898
  }
12803
12899
  async getNotification(input) {
12900
+ return this.#getNotification(this.#db.readClient, input);
12901
+ }
12902
+ /**
12903
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
12904
+ * lagging read replica cannot yield stale or missing rows mid-update.
12905
+ */
12906
+ async #getNotification(client, input) {
12804
12907
  const tableName = getTableName$5({
12805
12908
  indexName: _mastra_core_storage.TABLE_NOTIFICATIONS,
12806
12909
  schemaName: getSchemaName$5(this.#schema)
12807
12910
  });
12808
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "threadId" = $1 AND "id" = $2 LIMIT 1`, [input.threadId, input.id]);
12911
+ const row = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "threadId" = $1 AND "id" = $2 LIMIT 1`, [input.threadId, input.id]);
12809
12912
  return row ? rowToNotification(row) : null;
12810
12913
  }
12811
12914
  async updateNotification(input) {
12812
- if (!await this.getNotification({
12915
+ if (!await this.#getNotification(this.#db.client, {
12813
12916
  threadId: input.threadId,
12814
12917
  id: input.id
12815
12918
  })) throw new Error(`Notification ${input.id} was not found for thread ${input.threadId}`);
@@ -12833,7 +12936,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12833
12936
  ...input.summarySignalId !== void 0 ? { summarySignalId: input.summarySignalId } : {},
12834
12937
  updatedAt: now
12835
12938
  });
12836
- const updated = await this.getNotification({
12939
+ const updated = await this.#getNotification(this.#db.client, {
12837
12940
  threadId: input.threadId,
12838
12941
  id: input.id
12839
12942
  });
@@ -12880,9 +12983,10 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
12880
12983
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SPANS];
12881
12984
  constructor(config) {
12882
12985
  super();
12883
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12986
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
12884
12987
  this.#db = new PgDB({
12885
12988
  client,
12989
+ readClient,
12886
12990
  schemaName,
12887
12991
  skipDefaultIndexes
12888
12992
  });
@@ -13115,7 +13219,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13115
13219
  indexName: _mastra_core_storage.TABLE_SPANS,
13116
13220
  schemaName: getSchemaName$5(this.#schema)
13117
13221
  });
13118
- const row = await this.#db.client.oneOrNone(`SELECT
13222
+ const row = await this.#db.readClient.oneOrNone(`SELECT
13119
13223
  "traceId", "spanId", "parentSpanId", "name",
13120
13224
  "entityType", "entityId", "entityName",
13121
13225
  "userId", "organizationId", "resourceId",
@@ -13151,7 +13255,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13151
13255
  indexName: _mastra_core_storage.TABLE_SPANS,
13152
13256
  schemaName: getSchemaName$5(this.#schema)
13153
13257
  });
13154
- const row = await this.#db.client.oneOrNone(`SELECT
13258
+ const row = await this.#db.readClient.oneOrNone(`SELECT
13155
13259
  "traceId", "spanId", "parentSpanId", "name",
13156
13260
  "entityType", "entityId", "entityName",
13157
13261
  "userId", "organizationId", "resourceId",
@@ -13184,7 +13288,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13184
13288
  indexName: _mastra_core_storage.TABLE_SPANS,
13185
13289
  schemaName: getSchemaName$5(this.#schema)
13186
13290
  });
13187
- const spans = await this.#db.client.manyOrNone(`SELECT
13291
+ const spans = await this.#db.readClient.manyOrNone(`SELECT
13188
13292
  "traceId", "spanId", "parentSpanId", "name",
13189
13293
  "entityType", "entityId", "entityName",
13190
13294
  "userId", "organizationId", "resourceId",
@@ -13221,7 +13325,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13221
13325
  indexName: _mastra_core_storage.TABLE_SPANS,
13222
13326
  schemaName: getSchemaName$5(this.#schema)
13223
13327
  });
13224
- const spans = await this.#db.client.manyOrNone(`SELECT
13328
+ const spans = await this.#db.readClient.manyOrNone(`SELECT
13225
13329
  "traceId", "spanId", "parentSpanId", "name",
13226
13330
  "entityType", "entityId", "entityName",
13227
13331
  "spanType", "error", "isEvent",
@@ -13405,7 +13509,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13405
13509
  let orderClause;
13406
13510
  if (orderField === "endedAt") orderClause = `ORDER BY r."${sortField}" ${sortDirection} ${sortDirection === "DESC" ? "NULLS FIRST" : "NULLS LAST"}`;
13407
13511
  else orderClause = `ORDER BY r."${sortField}" ${sortDirection}`;
13408
- const countResult = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${tableName} r ${whereClause}`, params);
13512
+ const countResult = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${tableName} r ${whereClause}`, params);
13409
13513
  const count = Number(countResult?.count ?? 0);
13410
13514
  if (count === 0) return {
13411
13515
  pagination: {
@@ -13416,7 +13520,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13416
13520
  },
13417
13521
  spans: []
13418
13522
  };
13419
- const spans = await this.#db.client.manyOrNone(`SELECT
13523
+ const spans = await this.#db.readClient.manyOrNone(`SELECT
13420
13524
  r."traceId", r."spanId", r."parentSpanId", r."name",
13421
13525
  r."entityType", r."entityId", r."entityName",
13422
13526
  r."userId", r."organizationId", r."resourceId",
@@ -17771,6 +17875,8 @@ function wrapError(op, error, details) {
17771
17875
  }
17772
17876
  var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext extends _mastra_core_storage.ObservabilityStorage {
17773
17877
  #client;
17878
+ /** Reader-backed client for standalone reads; writes, DDL, and discovery-cache refresh stay on #client. */
17879
+ #readClient;
17774
17880
  #schema;
17775
17881
  #partitioning;
17776
17882
  #discoveryConfig;
@@ -17778,8 +17884,9 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
17778
17884
  #partitionMode;
17779
17885
  constructor(config) {
17780
17886
  super();
17781
- const { client, schemaName } = resolvePgConfig(config);
17887
+ const { client, readClient, schemaName } = resolvePgConfig(config);
17782
17888
  this.#client = client;
17889
+ this.#readClient = readClient;
17783
17890
  this.#schema = schemaName ?? "public";
17784
17891
  this.#partitioning = config.partitioning ?? {};
17785
17892
  this.#discoveryConfig = config.discovery ?? {};
@@ -17964,34 +18071,34 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
17964
18071
  await this.#run("BATCH_CREATE_SPANS", () => batchCreateSpans(this.#client, this.#schema, args), { count: args.records.length });
17965
18072
  }
17966
18073
  async getSpan(args) {
17967
- return this.#run("GET_SPAN", () => getSpan(this.#client, this.#schema, args), {
18074
+ return this.#run("GET_SPAN", () => getSpan(this.#readClient, this.#schema, args), {
17968
18075
  traceId: args.traceId,
17969
18076
  spanId: args.spanId
17970
18077
  });
17971
18078
  }
17972
18079
  async getSpans(args) {
17973
- return this.#run("GET_SPANS", () => getSpans(this.#client, this.#schema, args), {
18080
+ return this.#run("GET_SPANS", () => getSpans(this.#readClient, this.#schema, args), {
17974
18081
  traceId: args.traceId,
17975
18082
  count: args.spanIds.length
17976
18083
  });
17977
18084
  }
17978
18085
  async getRootSpan(args) {
17979
- return this.#run("GET_ROOT_SPAN", () => getRootSpan(this.#client, this.#schema, args), { traceId: args.traceId });
18086
+ return this.#run("GET_ROOT_SPAN", () => getRootSpan(this.#readClient, this.#schema, args), { traceId: args.traceId });
17980
18087
  }
17981
18088
  async getTrace(args) {
17982
- return this.#run("GET_TRACE", () => getTrace(this.#client, this.#schema, args), { traceId: args.traceId });
18089
+ return this.#run("GET_TRACE", () => getTrace(this.#readClient, this.#schema, args), { traceId: args.traceId });
17983
18090
  }
17984
18091
  async getTraceLight(args) {
17985
- return this.#run("GET_TRACE_LIGHT", () => getTraceLight(this.#client, this.#schema, args), { traceId: args.traceId });
18092
+ return this.#run("GET_TRACE_LIGHT", () => getTraceLight(this.#readClient, this.#schema, args), { traceId: args.traceId });
17986
18093
  }
17987
18094
  async listTraces(args) {
17988
- return this.#run("LIST_TRACES", () => listTraces(this.#client, this.#schema, args));
18095
+ return this.#run("LIST_TRACES", () => listTraces(this.#readClient, this.#schema, args));
17989
18096
  }
17990
18097
  async queryTraces(plan) {
17991
- return this.#run("QUERY_TRACES", () => queryTraces(this.#client, this.#schema, plan, this.#traceQueryTimeoutMs));
18098
+ return this.#run("QUERY_TRACES", () => queryTraces(this.#readClient, this.#schema, plan, this.#traceQueryTimeoutMs));
17992
18099
  }
17993
18100
  async listBranches(args) {
17994
- return this.#run("LIST_BRANCHES", () => listBranches(this.#client, this.#schema, args));
18101
+ return this.#run("LIST_BRANCHES", () => listBranches(this.#readClient, this.#schema, args));
17995
18102
  }
17996
18103
  async batchCreateLogs(args) {
17997
18104
  await this.#run("BATCH_CREATE_LOGS", () => batchCreateLogs(this.#client, this.#schema, args), { count: args.logs.length });
@@ -18012,58 +18119,58 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
18012
18119
  await this.#run("BATCH_CREATE_FEEDBACK", () => batchCreateFeedback(this.#client, this.#schema, args), { count: args.feedbacks.length });
18013
18120
  }
18014
18121
  async listLogs(args) {
18015
- return this.#run("LIST_LOGS", () => listLogs(this.#client, this.#schema, args));
18122
+ return this.#run("LIST_LOGS", () => listLogs(this.#readClient, this.#schema, args));
18016
18123
  }
18017
18124
  async listMetrics(args) {
18018
- return this.#run("LIST_METRICS", () => listMetrics(this.#client, this.#schema, args));
18125
+ return this.#run("LIST_METRICS", () => listMetrics(this.#readClient, this.#schema, args));
18019
18126
  }
18020
18127
  async listScores(args) {
18021
- return this.#run("LIST_SCORES", () => listScores(this.#client, this.#schema, args));
18128
+ return this.#run("LIST_SCORES", () => listScores(this.#readClient, this.#schema, args));
18022
18129
  }
18023
18130
  async getScoreById(scoreId) {
18024
- return this.#run("GET_SCORE_BY_ID", () => getScoreById(this.#client, this.#schema, scoreId), { scoreId });
18131
+ return this.#run("GET_SCORE_BY_ID", () => getScoreById(this.#readClient, this.#schema, scoreId), { scoreId });
18025
18132
  }
18026
18133
  async listFeedback(args) {
18027
- return this.#run("LIST_FEEDBACK", () => listFeedback(this.#client, this.#schema, args));
18134
+ return this.#run("LIST_FEEDBACK", () => listFeedback(this.#readClient, this.#schema, args));
18028
18135
  }
18029
18136
  async updateFeedbackReviewStatus(args) {
18030
18137
  return this.#run("UPDATE_FEEDBACK_REVIEW_STATUS", () => updateFeedbackReviewStatus(this.#client, this.#schema, args), { feedbackId: args.feedbackId });
18031
18138
  }
18032
18139
  async getMetricAggregate(args) {
18033
- return this.#run("GET_METRIC_AGGREGATE", () => getMetricAggregate(this.#client, this.#schema, args));
18140
+ return this.#run("GET_METRIC_AGGREGATE", () => getMetricAggregate(this.#readClient, this.#schema, args));
18034
18141
  }
18035
18142
  async getMetricBreakdown(args) {
18036
- return this.#run("GET_METRIC_BREAKDOWN", () => getMetricBreakdown(this.#client, this.#schema, args));
18143
+ return this.#run("GET_METRIC_BREAKDOWN", () => getMetricBreakdown(this.#readClient, this.#schema, args));
18037
18144
  }
18038
18145
  async getMetricTimeSeries(args) {
18039
- return this.#run("GET_METRIC_TIME_SERIES", () => getMetricTimeSeries(this.#client, this.#schema, args));
18146
+ return this.#run("GET_METRIC_TIME_SERIES", () => getMetricTimeSeries(this.#readClient, this.#schema, args));
18040
18147
  }
18041
18148
  async getMetricPercentiles(args) {
18042
- return this.#run("GET_METRIC_PERCENTILES", () => getMetricPercentiles(this.#client, this.#schema, args));
18149
+ return this.#run("GET_METRIC_PERCENTILES", () => getMetricPercentiles(this.#readClient, this.#schema, args));
18043
18150
  }
18044
18151
  async getScoreAggregate(args) {
18045
- return this.#run("GET_SCORE_AGGREGATE", () => getScoreAggregate(this.#client, this.#schema, args));
18152
+ return this.#run("GET_SCORE_AGGREGATE", () => getScoreAggregate(this.#readClient, this.#schema, args));
18046
18153
  }
18047
18154
  async getScoreBreakdown(args) {
18048
- return this.#run("GET_SCORE_BREAKDOWN", () => getScoreBreakdown(this.#client, this.#schema, args));
18155
+ return this.#run("GET_SCORE_BREAKDOWN", () => getScoreBreakdown(this.#readClient, this.#schema, args));
18049
18156
  }
18050
18157
  async getScoreTimeSeries(args) {
18051
- return this.#run("GET_SCORE_TIME_SERIES", () => getScoreTimeSeries(this.#client, this.#schema, args));
18158
+ return this.#run("GET_SCORE_TIME_SERIES", () => getScoreTimeSeries(this.#readClient, this.#schema, args));
18052
18159
  }
18053
18160
  async getScorePercentiles(args) {
18054
- return this.#run("GET_SCORE_PERCENTILES", () => getScorePercentiles(this.#client, this.#schema, args));
18161
+ return this.#run("GET_SCORE_PERCENTILES", () => getScorePercentiles(this.#readClient, this.#schema, args));
18055
18162
  }
18056
18163
  async getFeedbackAggregate(args) {
18057
- return this.#run("GET_FEEDBACK_AGGREGATE", () => getFeedbackAggregate(this.#client, this.#schema, args));
18164
+ return this.#run("GET_FEEDBACK_AGGREGATE", () => getFeedbackAggregate(this.#readClient, this.#schema, args));
18058
18165
  }
18059
18166
  async getFeedbackBreakdown(args) {
18060
- return this.#run("GET_FEEDBACK_BREAKDOWN", () => getFeedbackBreakdown(this.#client, this.#schema, args));
18167
+ return this.#run("GET_FEEDBACK_BREAKDOWN", () => getFeedbackBreakdown(this.#readClient, this.#schema, args));
18061
18168
  }
18062
18169
  async getFeedbackTimeSeries(args) {
18063
- return this.#run("GET_FEEDBACK_TIME_SERIES", () => getFeedbackTimeSeries(this.#client, this.#schema, args));
18170
+ return this.#run("GET_FEEDBACK_TIME_SERIES", () => getFeedbackTimeSeries(this.#readClient, this.#schema, args));
18064
18171
  }
18065
18172
  async getFeedbackPercentiles(args) {
18066
- return this.#run("GET_FEEDBACK_PERCENTILES", () => getFeedbackPercentiles(this.#client, this.#schema, args));
18173
+ return this.#run("GET_FEEDBACK_PERCENTILES", () => getFeedbackPercentiles(this.#readClient, this.#schema, args));
18067
18174
  }
18068
18175
  async getEntityTypes(args) {
18069
18176
  return this.#run("GET_ENTITY_TYPES", () => getEntityTypes(this.#client, this.#schema, args, this.#discovery));
@@ -18122,9 +18229,10 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18122
18229
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_PROMPT_BLOCKS, _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS];
18123
18230
  constructor(config) {
18124
18231
  super();
18125
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18232
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18126
18233
  this.#db = new PgDB({
18127
18234
  client,
18235
+ readClient,
18128
18236
  schemaName,
18129
18237
  skipDefaultIndexes
18130
18238
  });
@@ -18201,12 +18309,19 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18201
18309
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_PROMPT_BLOCKS });
18202
18310
  }
18203
18311
  async getById(id) {
18312
+ return this.#getById(this.#db.readClient, id);
18313
+ }
18314
+ /**
18315
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
18316
+ * lagging read replica cannot yield stale or missing rows mid-update.
18317
+ */
18318
+ async #getById(client, id) {
18204
18319
  try {
18205
18320
  const tableName = getTableName$5({
18206
18321
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCKS,
18207
18322
  schemaName: getSchemaName$5(this.#schema)
18208
18323
  });
18209
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18324
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18210
18325
  if (!result) return null;
18211
18326
  return this.parseBlockRow(result);
18212
18327
  } catch (error) {
@@ -18285,7 +18400,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18285
18400
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCKS,
18286
18401
  schemaName: getSchemaName$5(this.#schema)
18287
18402
  });
18288
- const existingBlock = await this.getById(id);
18403
+ const existingBlock = await this.#getById(this.#db.client, id);
18289
18404
  if (!existingBlock) throw new _mastra_core_error.MastraError({
18290
18405
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND"),
18291
18406
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -18324,7 +18439,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18324
18439
  values.push(now);
18325
18440
  values.push(id);
18326
18441
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
18327
- const updatedBlock = await this.getById(id);
18442
+ const updatedBlock = await this.#getById(this.#db.client, id);
18328
18443
  if (!updatedBlock) throw new _mastra_core_error.MastraError({
18329
18444
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
18330
18445
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -18393,7 +18508,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18393
18508
  queryParams.push(JSON.stringify(metadata));
18394
18509
  }
18395
18510
  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);
18511
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
18397
18512
  const total = parseInt(countResult.count, 10);
18398
18513
  if (total === 0) return {
18399
18514
  promptBlocks: [],
@@ -18404,7 +18519,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18404
18519
  };
18405
18520
  const limitValue = perPageInput === false ? total : perPage;
18406
18521
  return {
18407
- promptBlocks: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
18522
+ promptBlocks: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
18408
18523
  ...queryParams,
18409
18524
  limitValue,
18410
18525
  offset
@@ -18483,7 +18598,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18483
18598
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18484
18599
  schemaName: getSchemaName$5(this.#schema)
18485
18600
  });
18486
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18601
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
18487
18602
  if (!result) return null;
18488
18603
  return this.parseVersionRow(result);
18489
18604
  } catch (error) {
@@ -18502,7 +18617,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18502
18617
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18503
18618
  schemaName: getSchemaName$5(this.#schema)
18504
18619
  });
18505
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 AND "versionNumber" = $2`, [blockId, versionNumber]);
18620
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 AND "versionNumber" = $2`, [blockId, versionNumber]);
18506
18621
  if (!result) return null;
18507
18622
  return this.parseVersionRow(result);
18508
18623
  } catch (error) {
@@ -18524,7 +18639,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18524
18639
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18525
18640
  schemaName: getSchemaName$5(this.#schema)
18526
18641
  });
18527
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [blockId]);
18642
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [blockId]);
18528
18643
  if (!result) return null;
18529
18644
  return this.parseVersionRow(result);
18530
18645
  } catch (error) {
@@ -18553,7 +18668,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18553
18668
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18554
18669
  schemaName: getSchemaName$5(this.#schema)
18555
18670
  });
18556
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18671
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18557
18672
  const total = parseInt(countResult.count, 10);
18558
18673
  if (total === 0) return {
18559
18674
  versions: [],
@@ -18564,7 +18679,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18564
18679
  };
18565
18680
  const limitValue = perPageInput === false ? total : perPage;
18566
18681
  return {
18567
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
18682
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
18568
18683
  blockId,
18569
18684
  limitValue,
18570
18685
  offset
@@ -18634,7 +18749,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
18634
18749
  indexName: _mastra_core_storage.TABLE_PROMPT_BLOCK_VERSIONS,
18635
18750
  schemaName: getSchemaName$5(this.#schema)
18636
18751
  });
18637
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18752
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [blockId]);
18638
18753
  return parseInt(result.count, 10);
18639
18754
  } catch (error) {
18640
18755
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -18735,6 +18850,7 @@ function rowToTrigger(row) {
18735
18850
  var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorage {
18736
18851
  #db;
18737
18852
  #client;
18853
+ #readClient;
18738
18854
  #schema;
18739
18855
  #skipDefaultIndexes;
18740
18856
  #indexes;
@@ -18754,10 +18870,12 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18754
18870
  } };
18755
18871
  constructor(config) {
18756
18872
  super();
18757
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18873
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18758
18874
  this.#client = client;
18875
+ this.#readClient = readClient;
18759
18876
  this.#db = new PgDB({
18760
18877
  client,
18878
+ readClient,
18761
18879
  schemaName,
18762
18880
  skipDefaultIndexes
18763
18881
  });
@@ -18881,7 +18999,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18881
18999
  return getTableName$2(tableName, getSchemaName$2((0, _mastra_core_utils.parseSqlIdentifier)(this.#schema, "schema name")));
18882
19000
  }
18883
19001
  async createSchedule(schedule) {
18884
- if (await this.getSchedule(schedule.id)) throw new Error(`Schedule with id "${schedule.id}" already exists`);
19002
+ if (await this.#getSchedule(this.#client, schedule.id)) throw new Error(`Schedule with id "${schedule.id}" already exists`);
18885
19003
  await this.#db.insert({
18886
19004
  tableName: _mastra_core_storage.TABLE_SCHEDULES,
18887
19005
  record: {
@@ -18903,7 +19021,14 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18903
19021
  return schedule;
18904
19022
  }
18905
19023
  async getSchedule(id) {
18906
- const row = await this.#client.oneOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} WHERE id = $1`, [id]);
19024
+ return this.#getSchedule(this.#readClient, id);
19025
+ }
19026
+ /**
19027
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
19028
+ * lagging read replica cannot yield stale or missing rows mid-update.
19029
+ */
19030
+ async #getSchedule(client, id) {
19031
+ const row = await client.oneOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} WHERE id = $1`, [id]);
18907
19032
  return row ? rowToSchedule(row) : null;
18908
19033
  }
18909
19034
  async listSchedules(filter) {
@@ -18928,7 +19053,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18928
19053
  conditions.push(`owner_id = $${params.length}`);
18929
19054
  }
18930
19055
  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);
19056
+ return (await this.#readClient.manyOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULES)} ${where} ORDER BY created_at ASC`, params)).map(rowToSchedule);
18932
19057
  }
18933
19058
  async listDueSchedules(now, limit) {
18934
19059
  const cap = limit ?? 100;
@@ -18958,13 +19083,13 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
18958
19083
  if ("ownerId" in patch) push("owner_id = ?", patch.ownerId ?? null);
18959
19084
  push("updated_at = ?", Date.now());
18960
19085
  if (setClauses.length === 1) {
18961
- const existing = await this.getSchedule(id);
19086
+ const existing = await this.#getSchedule(this.#client, id);
18962
19087
  if (!existing) throw new Error(`Schedule ${id} not found`);
18963
19088
  return existing;
18964
19089
  }
18965
19090
  params.push(id);
18966
19091
  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);
19092
+ const updated = await this.#getSchedule(this.#client, id);
18968
19093
  if (!updated) throw new Error(`Schedule ${id} not found`);
18969
19094
  return updated;
18970
19095
  }
@@ -19021,7 +19146,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
19021
19146
  params.push(Math.floor(opts.limit));
19022
19147
  limitClause = `LIMIT $${params.length}`;
19023
19148
  }
19024
- return (await this.#client.manyOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULE_TRIGGERS)}
19149
+ return (await this.#readClient.manyOrNone(`SELECT * FROM ${this.#table(_mastra_core_storage.TABLE_SCHEDULE_TRIGGERS)}
19025
19150
  WHERE ${conditions.join(" AND ")}
19026
19151
  ORDER BY actual_fire_at DESC
19027
19152
  ${limitClause}`, params)).map(rowToTrigger);
@@ -19047,9 +19172,10 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19047
19172
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SCORER_DEFINITIONS, _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS];
19048
19173
  constructor(config) {
19049
19174
  super();
19050
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19175
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19051
19176
  this.#db = new PgDB({
19052
19177
  client,
19178
+ readClient,
19053
19179
  schemaName,
19054
19180
  skipDefaultIndexes
19055
19181
  });
@@ -19126,12 +19252,19 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19126
19252
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS });
19127
19253
  }
19128
19254
  async getById(id) {
19255
+ return this.#getById(this.#db.readClient, id);
19256
+ }
19257
+ /**
19258
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
19259
+ * lagging read replica cannot yield stale or missing rows mid-update.
19260
+ */
19261
+ async #getById(client, id) {
19129
19262
  try {
19130
19263
  const tableName = getTableName$5({
19131
19264
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS,
19132
19265
  schemaName: getSchemaName$5(this.#schema)
19133
19266
  });
19134
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19267
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19135
19268
  if (!result) return null;
19136
19269
  return this.parseScorerRow(result);
19137
19270
  } catch (error) {
@@ -19214,7 +19347,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19214
19347
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITIONS,
19215
19348
  schemaName: getSchemaName$5(this.#schema)
19216
19349
  });
19217
- const existingScorer = await this.getById(id);
19350
+ const existingScorer = await this.#getById(this.#db.client, id);
19218
19351
  if (!existingScorer) throw new _mastra_core_error.MastraError({
19219
19352
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND"),
19220
19353
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -19253,7 +19386,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19253
19386
  values.push(now);
19254
19387
  values.push(id);
19255
19388
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
19256
- const updatedScorer = await this.getById(id);
19389
+ const updatedScorer = await this.#getById(this.#db.client, id);
19257
19390
  if (!updatedScorer) throw new _mastra_core_error.MastraError({
19258
19391
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
19259
19392
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -19330,7 +19463,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19330
19463
  queryParams.push(JSON.stringify(metadata));
19331
19464
  }
19332
19465
  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);
19466
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
19334
19467
  const total = parseInt(countResult.count, 10);
19335
19468
  if (total === 0) return {
19336
19469
  scorerDefinitions: [],
@@ -19341,7 +19474,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19341
19474
  };
19342
19475
  const limitValue = perPageInput === false ? total : perPage;
19343
19476
  return {
19344
- scorerDefinitions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
19477
+ scorerDefinitions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
19345
19478
  ...queryParams,
19346
19479
  limitValue,
19347
19480
  offset
@@ -19423,7 +19556,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19423
19556
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19424
19557
  schemaName: getSchemaName$5(this.#schema)
19425
19558
  });
19426
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19559
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
19427
19560
  if (!result) return null;
19428
19561
  return this.parseVersionRow(result);
19429
19562
  } catch (error) {
@@ -19442,7 +19575,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19442
19575
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19443
19576
  schemaName: getSchemaName$5(this.#schema)
19444
19577
  });
19445
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 AND "versionNumber" = $2`, [scorerDefinitionId, versionNumber]);
19578
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 AND "versionNumber" = $2`, [scorerDefinitionId, versionNumber]);
19446
19579
  if (!result) return null;
19447
19580
  return this.parseVersionRow(result);
19448
19581
  } catch (error) {
@@ -19464,7 +19597,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19464
19597
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19465
19598
  schemaName: getSchemaName$5(this.#schema)
19466
19599
  });
19467
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [scorerDefinitionId]);
19600
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [scorerDefinitionId]);
19468
19601
  if (!result) return null;
19469
19602
  return this.parseVersionRow(result);
19470
19603
  } catch (error) {
@@ -19493,7 +19626,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19493
19626
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19494
19627
  schemaName: getSchemaName$5(this.#schema)
19495
19628
  });
19496
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19629
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19497
19630
  const total = parseInt(countResult.count, 10);
19498
19631
  if (total === 0) return {
19499
19632
  versions: [],
@@ -19504,7 +19637,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19504
19637
  };
19505
19638
  const limitValue = perPageInput === false ? total : perPage;
19506
19639
  return {
19507
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
19640
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
19508
19641
  scorerDefinitionId,
19509
19642
  limitValue,
19510
19643
  offset
@@ -19574,7 +19707,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
19574
19707
  indexName: _mastra_core_storage.TABLE_SCORER_DEFINITION_VERSIONS,
19575
19708
  schemaName: getSchemaName$5(this.#schema)
19576
19709
  });
19577
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19710
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [scorerDefinitionId]);
19578
19711
  return parseInt(result.count, 10);
19579
19712
  } catch (error) {
19580
19713
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -19671,9 +19804,10 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19671
19804
  } };
19672
19805
  constructor(config) {
19673
19806
  super();
19674
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19807
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
19675
19808
  this.#db = new PgDB({
19676
19809
  client,
19810
+ readClient,
19677
19811
  schemaName,
19678
19812
  skipDefaultIndexes
19679
19813
  });
@@ -19807,7 +19941,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19807
19941
  }
19808
19942
  async getScoreById({ id }) {
19809
19943
  try {
19810
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${getTableName$1({
19944
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${getTableName$1({
19811
19945
  indexName: _mastra_core_storage.TABLE_SCORERS,
19812
19946
  schemaName: getSchemaName$1(this.#schema)
19813
19947
  })} WHERE id = $1`, [id]);
@@ -19839,7 +19973,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19839
19973
  }
19840
19974
  paramIndex = applyTenancyFilters(conditions, queryParams, paramIndex, filters);
19841
19975
  const whereClause = conditions.join(" AND ");
19842
- const total = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
19976
+ const total = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
19843
19977
  indexName: _mastra_core_storage.TABLE_SCORERS,
19844
19978
  schemaName: getSchemaName$1(this.#schema)
19845
19979
  })} WHERE ${whereClause}`, queryParams);
@@ -19857,7 +19991,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19857
19991
  };
19858
19992
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
19859
19993
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
19860
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
19994
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
19861
19995
  indexName: _mastra_core_storage.TABLE_SCORERS,
19862
19996
  schemaName: getSchemaName$1(this.#schema)
19863
19997
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -19947,7 +20081,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19947
20081
  const queryParams = [runId];
19948
20082
  let paramIndex = applyTenancyFilters(conditions, queryParams, 2, filters);
19949
20083
  const whereClause = conditions.join(" AND ");
19950
- const total = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
20084
+ const total = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
19951
20085
  indexName: _mastra_core_storage.TABLE_SCORERS,
19952
20086
  schemaName: getSchemaName$1(this.#schema)
19953
20087
  })} WHERE ${whereClause}`, queryParams);
@@ -19965,7 +20099,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19965
20099
  };
19966
20100
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
19967
20101
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
19968
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
20102
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
19969
20103
  indexName: _mastra_core_storage.TABLE_SCORERS,
19970
20104
  schemaName: getSchemaName$1(this.#schema)
19971
20105
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -19996,7 +20130,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
19996
20130
  const queryParams = [entityId, entityType];
19997
20131
  let paramIndex = applyTenancyFilters(conditions, queryParams, 3, filters);
19998
20132
  const whereClause = conditions.join(" AND ");
19999
- const total = await this.#db.client.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
20133
+ const total = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) FROM ${getTableName$1({
20000
20134
  indexName: _mastra_core_storage.TABLE_SCORERS,
20001
20135
  schemaName: getSchemaName$1(this.#schema)
20002
20136
  })} WHERE ${whereClause}`, queryParams);
@@ -20014,7 +20148,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20014
20148
  };
20015
20149
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
20016
20150
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
20017
- const result = await this.#db.client.manyOrNone(`SELECT * FROM ${getTableName$1({
20151
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${getTableName$1({
20018
20152
  indexName: _mastra_core_storage.TABLE_SCORERS,
20019
20153
  schemaName: getSchemaName$1(this.#schema)
20020
20154
  })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
@@ -20049,14 +20183,14 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20049
20183
  const queryParams = [traceId, spanId];
20050
20184
  let paramIndex = applyTenancyFilters(conditions, queryParams, 3, filters);
20051
20185
  const whereClause = conditions.join(" AND ");
20052
- const countSQLResult = await this.#db.client.oneOrNone(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`, queryParams);
20186
+ const countSQLResult = await this.#db.readClient.oneOrNone(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`, queryParams);
20053
20187
  const total = Number(countSQLResult?.count ?? 0);
20054
20188
  const { page, perPage: perPageInput } = pagination;
20055
20189
  const perPage = (0, _mastra_core_storage.normalizePerPage)(perPageInput, 100);
20056
20190
  const { offset: start, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
20057
20191
  const limitValue = perPageInput === false ? total : perPage;
20058
20192
  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++}`, [
20193
+ const result = await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`, [
20060
20194
  ...queryParams,
20061
20195
  limitValue,
20062
20196
  start
@@ -20104,9 +20238,10 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20104
20238
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_SKILLS, _mastra_core_storage.TABLE_SKILL_VERSIONS];
20105
20239
  constructor(config) {
20106
20240
  super();
20107
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20241
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20108
20242
  this.#db = new PgDB({
20109
20243
  client,
20244
+ readClient,
20110
20245
  schemaName,
20111
20246
  skipDefaultIndexes
20112
20247
  });
@@ -20180,12 +20315,19 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20180
20315
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_SKILLS });
20181
20316
  }
20182
20317
  async getById(id) {
20318
+ return this.#getById(this.#db.readClient, id);
20319
+ }
20320
+ /**
20321
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
20322
+ * lagging read replica cannot yield stale or missing rows mid-update.
20323
+ */
20324
+ async #getById(client, id) {
20183
20325
  try {
20184
20326
  const tableName = getTableName$5({
20185
20327
  indexName: _mastra_core_storage.TABLE_SKILLS,
20186
20328
  schemaName: getSchemaName$5(this.#schema)
20187
20329
  });
20188
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20330
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20189
20331
  if (!result) return null;
20190
20332
  return this.parseSkillRow(result);
20191
20333
  } catch (error) {
@@ -20267,7 +20409,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20267
20409
  indexName: _mastra_core_storage.TABLE_SKILLS,
20268
20410
  schemaName: getSchemaName$5(this.#schema)
20269
20411
  });
20270
- if (!await this.getById(id)) throw new _mastra_core_error.MastraError({
20412
+ if (!await this.#getById(this.#db.client, id)) throw new _mastra_core_error.MastraError({
20271
20413
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NOT_FOUND"),
20272
20414
  domain: _mastra_core_error.ErrorDomain.STORAGE,
20273
20415
  category: _mastra_core_error.ErrorCategory.USER,
@@ -20279,7 +20421,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20279
20421
  const configFields = {};
20280
20422
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
20281
20423
  if (SNAPSHOT_FIELDS$1.some((field) => field in configFields)) {
20282
- const latestVersion = await this.getLatestVersion(id);
20424
+ const latestVersion = await this.#getLatestVersion(this.#db.client, id);
20283
20425
  if (!latestVersion) throw new _mastra_core_error.MastraError({
20284
20426
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NO_VERSIONS"),
20285
20427
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -20336,7 +20478,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20336
20478
  values.push(now);
20337
20479
  values.push(id);
20338
20480
  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);
20481
+ const updatedSkill = await this.#getById(this.#db.client, id);
20340
20482
  if (!updatedSkill) throw new _mastra_core_error.MastraError({
20341
20483
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_SKILL", "NOT_FOUND_AFTER_UPDATE"),
20342
20484
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -20429,7 +20571,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20429
20571
  const joinClause = useJoin && joinSqlIdx !== null ? `LEFT JOIN ${favoritesTable} sr ON sr."entityType" = 'skill' AND sr."entityId" = s.id AND sr."userId" = $${joinSqlIdx}` : "";
20430
20572
  const joinParams = useJoin && joinUserId ? [joinUserId] : [];
20431
20573
  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]);
20574
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} s ${joinClause} ${whereClause}`, [...joinParams, ...queryParams]);
20433
20575
  const total = parseInt(countResult.count, 10);
20434
20576
  if (total === 0) return {
20435
20577
  skills: [],
@@ -20447,7 +20589,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20447
20589
  const limitIdx = paramIdx++;
20448
20590
  const offsetIdx = paramIdx++;
20449
20591
  return {
20450
- skills: (await this.#db.client.manyOrNone(`SELECT s.* FROM ${tableName} s ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
20592
+ skills: (await this.#db.readClient.manyOrNone(`SELECT s.* FROM ${tableName} s ${joinClause} ${whereClause} ${orderByClause} LIMIT $${limitIdx} OFFSET $${offsetIdx}`, [
20451
20593
  ...joinParams,
20452
20594
  ...queryParams,
20453
20595
  limitValue,
@@ -20535,7 +20677,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20535
20677
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20536
20678
  schemaName: getSchemaName$5(this.#schema)
20537
20679
  });
20538
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20680
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
20539
20681
  if (!result) return null;
20540
20682
  return this.parseVersionRow(result);
20541
20683
  } catch (error) {
@@ -20556,7 +20698,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20556
20698
  schemaName: getSchemaName$5(this.#schema)
20557
20699
  });
20558
20700
  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));
20701
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE id IN (${placeholders})`, ids)).map((row) => this.parseVersionRow(row));
20560
20702
  } catch (error) {
20561
20703
  if (error instanceof _mastra_core_error.MastraError) throw error;
20562
20704
  throw new _mastra_core_error.MastraError({
@@ -20573,7 +20715,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20573
20715
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20574
20716
  schemaName: getSchemaName$5(this.#schema)
20575
20717
  });
20576
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 AND "versionNumber" = $2`, [skillId, versionNumber]);
20718
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 AND "versionNumber" = $2`, [skillId, versionNumber]);
20577
20719
  if (!result) return null;
20578
20720
  return this.parseVersionRow(result);
20579
20721
  } catch (error) {
@@ -20590,12 +20732,19 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20590
20732
  }
20591
20733
  }
20592
20734
  async getLatestVersion(skillId) {
20735
+ return this.#getLatestVersion(this.#db.readClient, skillId);
20736
+ }
20737
+ /**
20738
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
20739
+ * lagging read replica cannot yield stale or missing rows mid-update.
20740
+ */
20741
+ async #getLatestVersion(client, skillId) {
20593
20742
  try {
20594
20743
  const tableName = getTableName$5({
20595
20744
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20596
20745
  schemaName: getSchemaName$5(this.#schema)
20597
20746
  });
20598
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [skillId]);
20747
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [skillId]);
20599
20748
  if (!result) return null;
20600
20749
  return this.parseVersionRow(result);
20601
20750
  } catch (error) {
@@ -20624,7 +20773,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20624
20773
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20625
20774
  schemaName: getSchemaName$5(this.#schema)
20626
20775
  });
20627
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20776
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20628
20777
  const total = parseInt(countResult.count, 10);
20629
20778
  if (total === 0) return {
20630
20779
  versions: [],
@@ -20635,7 +20784,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20635
20784
  };
20636
20785
  const limitValue = perPageInput === false ? total : perPage;
20637
20786
  return {
20638
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
20787
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "skillId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
20639
20788
  skillId,
20640
20789
  limitValue,
20641
20790
  offset
@@ -20705,7 +20854,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
20705
20854
  indexName: _mastra_core_storage.TABLE_SKILL_VERSIONS,
20706
20855
  schemaName: getSchemaName$5(this.#schema)
20707
20856
  });
20708
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20857
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "skillId" = $1`, [skillId]);
20709
20858
  return parseInt(result.count, 10);
20710
20859
  } catch (error) {
20711
20860
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -20780,9 +20929,10 @@ var ThreadStatePG = class ThreadStatePG extends _mastra_core_storage.ThreadState
20780
20929
  } };
20781
20930
  constructor(config) {
20782
20931
  super();
20783
- const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
20932
+ const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
20784
20933
  this.#db = new PgDB({
20785
20934
  client,
20935
+ readClient,
20786
20936
  schemaName,
20787
20937
  skipDefaultIndexes
20788
20938
  });
@@ -20945,9 +21095,10 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
20945
21095
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_TOOL_PROVIDER_CONNECTIONS];
20946
21096
  constructor(config) {
20947
21097
  super();
20948
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21098
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
20949
21099
  this.#db = new PgDB({
20950
21100
  client,
21101
+ readClient,
20951
21102
  schemaName,
20952
21103
  skipDefaultIndexes
20953
21104
  });
@@ -21026,7 +21177,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
21026
21177
  schemaName: getSchemaName$5(this.#schema)
21027
21178
  });
21028
21179
  try {
21029
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "authorId" = $1 AND "providerId" = $2 AND "connectionId" = $3 LIMIT 1`, [
21180
+ const row = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "authorId" = $1 AND "providerId" = $2 AND "connectionId" = $3 LIMIT 1`, [
21030
21181
  authorId,
21031
21182
  providerId,
21032
21183
  connectionId
@@ -21133,7 +21284,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
21133
21284
  clauses.push(`scope = $${args.length}`);
21134
21285
  }
21135
21286
  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));
21287
+ return (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName}${whereClause}`, args)).map((row) => rowToToolProviderConnection(row));
21137
21288
  } catch (error) {
21138
21289
  throw new _mastra_core_error.MastraError({
21139
21290
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "TOOL_PROVIDER_CONNECTION_LIST", "FAILED"),
@@ -21209,9 +21360,10 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21209
21360
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS];
21210
21361
  constructor(config) {
21211
21362
  super();
21212
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21363
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21213
21364
  this.#db = new PgDB({
21214
21365
  client,
21366
+ readClient,
21215
21367
  schemaName,
21216
21368
  skipDefaultIndexes
21217
21369
  });
@@ -21268,7 +21420,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21268
21420
  }
21269
21421
  async upsert(input) {
21270
21422
  const now = /* @__PURE__ */ new Date();
21271
- if (!await this.get(input.id)) {
21423
+ if (!await this.#get(this.#db.client, input.id)) {
21272
21424
  if (!("inputSchema" in input) || !input.inputSchema) throw new Error(`Cannot create workflow definition "${input.id}": inputSchema is required.`);
21273
21425
  if (!("outputSchema" in input) || !input.outputSchema) throw new Error(`Cannot create workflow definition "${input.id}": outputSchema is required.`);
21274
21426
  if (!("graph" in input) || !input.graph) throw new Error(`Cannot create workflow definition "${input.id}": graph is required.`);
@@ -21294,10 +21446,10 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21294
21446
  record
21295
21447
  });
21296
21448
  } catch (error) {
21297
- if (!await this.get(input.id)) throw error;
21449
+ if (!await this.#get(this.#db.client, input.id)) throw error;
21298
21450
  return this.applyUpdate(input, now);
21299
21451
  }
21300
- const created = await this.get(input.id);
21452
+ const created = await this.#get(this.#db.client, input.id);
21301
21453
  if (!created) throw new Error(`Failed to persist workflow definition "${input.id}".`);
21302
21454
  return created;
21303
21455
  }
@@ -21320,16 +21472,23 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21320
21472
  keys: { id: input.id },
21321
21473
  data
21322
21474
  });
21323
- const updated = await this.get(input.id);
21475
+ const updated = await this.#get(this.#db.client, input.id);
21324
21476
  if (!updated) throw new Error(`Failed to update workflow definition "${input.id}".`);
21325
21477
  return updated;
21326
21478
  }
21327
21479
  async get(id) {
21480
+ return this.#get(this.#db.readClient, id);
21481
+ }
21482
+ /**
21483
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
21484
+ * lagging read replica cannot yield stale or missing rows mid-update.
21485
+ */
21486
+ async #get(client, id) {
21328
21487
  const tableName = getTableName$5({
21329
21488
  indexName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
21330
21489
  schemaName: getSchemaName$5(this.#schema)
21331
21490
  });
21332
- const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
21491
+ const row = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
21333
21492
  return row ? rowToDefinition(row) : null;
21334
21493
  }
21335
21494
  async list(args) {
@@ -21348,7 +21507,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
21348
21507
  conditions.push(`"authorId" = $${params.length}`);
21349
21508
  }
21350
21509
  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));
21510
+ const definitions = (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${where} ORDER BY "updatedAt" DESC`, params)).map((row) => rowToDefinition(row));
21352
21511
  return {
21353
21512
  definitions,
21354
21513
  total: definitions.length
@@ -21413,9 +21572,10 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
21413
21572
  } };
21414
21573
  constructor(config) {
21415
21574
  super();
21416
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21575
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21417
21576
  this.#db = new PgDB({
21418
21577
  client,
21578
+ readClient,
21419
21579
  schemaName,
21420
21580
  skipDefaultIndexes
21421
21581
  });
@@ -21738,7 +21898,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
21738
21898
  ORDER BY "createdAt" DESC LIMIT 1
21739
21899
  `;
21740
21900
  const queryValues = values;
21741
- const result = await this.#db.client.oneOrNone(query, queryValues);
21901
+ const result = await this.#db.readClient.oneOrNone(query, queryValues);
21742
21902
  if (!result) return null;
21743
21903
  return this.parseWorkflowRun(result);
21744
21904
  } catch (error) {
@@ -21867,9 +22027,10 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
21867
22027
  static MANAGED_TABLES = [_mastra_core_storage.TABLE_WORKSPACES, _mastra_core_storage.TABLE_WORKSPACE_VERSIONS];
21868
22028
  constructor(config) {
21869
22029
  super();
21870
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
22030
+ const { client, readClient, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
21871
22031
  this.#db = new PgDB({
21872
22032
  client,
22033
+ readClient,
21873
22034
  schemaName,
21874
22035
  skipDefaultIndexes
21875
22036
  });
@@ -21933,12 +22094,19 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
21933
22094
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_WORKSPACES });
21934
22095
  }
21935
22096
  async getById(id) {
22097
+ return this.#getById(this.#db.readClient, id);
22098
+ }
22099
+ /**
22100
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
22101
+ * lagging read replica cannot yield stale or missing rows mid-update.
22102
+ */
22103
+ async #getById(client, id) {
21936
22104
  try {
21937
22105
  const tableName = getTableName$5({
21938
22106
  indexName: _mastra_core_storage.TABLE_WORKSPACES,
21939
22107
  schemaName: getSchemaName$5(this.#schema)
21940
22108
  });
21941
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
22109
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
21942
22110
  if (!result) return null;
21943
22111
  return this.parseWorkspaceRow(result);
21944
22112
  } catch (error) {
@@ -22017,7 +22185,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22017
22185
  indexName: _mastra_core_storage.TABLE_WORKSPACES,
22018
22186
  schemaName: getSchemaName$5(this.#schema)
22019
22187
  });
22020
- const existingWorkspace = await this.getById(id);
22188
+ const existingWorkspace = await this.#getById(this.#db.client, id);
22021
22189
  if (!existingWorkspace) throw new _mastra_core_error.MastraError({
22022
22190
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NOT_FOUND"),
22023
22191
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22030,7 +22198,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22030
22198
  const configFields = {};
22031
22199
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
22032
22200
  if (SNAPSHOT_FIELDS.some((field) => field in configFields)) {
22033
- const latestVersion = await this.getLatestVersion(id);
22201
+ const latestVersion = await this.#getLatestVersion(this.#db.client, id);
22034
22202
  if (!latestVersion) throw new _mastra_core_error.MastraError({
22035
22203
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NO_VERSIONS"),
22036
22204
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22091,7 +22259,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22091
22259
  values.push(now);
22092
22260
  values.push(id);
22093
22261
  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);
22262
+ const updatedWorkspace = await this.#getById(this.#db.client, id);
22095
22263
  if (!updatedWorkspace) throw new _mastra_core_error.MastraError({
22096
22264
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "UPDATE_WORKSPACE", "NOT_FOUND_AFTER_UPDATE"),
22097
22265
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -22156,7 +22324,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22156
22324
  queryParams.push(JSON.stringify(metadata));
22157
22325
  }
22158
22326
  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);
22327
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
22160
22328
  const total = parseInt(countResult.count, 10);
22161
22329
  if (total === 0) return {
22162
22330
  workspaces: [],
@@ -22167,7 +22335,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22167
22335
  };
22168
22336
  const limitValue = perPageInput === false ? total : perPage;
22169
22337
  return {
22170
- workspaces: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
22338
+ workspaces: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`, [
22171
22339
  ...queryParams,
22172
22340
  limitValue,
22173
22341
  offset
@@ -22252,7 +22420,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22252
22420
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22253
22421
  schemaName: getSchemaName$5(this.#schema)
22254
22422
  });
22255
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
22423
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
22256
22424
  if (!result) return null;
22257
22425
  return this.parseVersionRow(result);
22258
22426
  } catch (error) {
@@ -22271,7 +22439,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22271
22439
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22272
22440
  schemaName: getSchemaName$5(this.#schema)
22273
22441
  });
22274
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 AND "versionNumber" = $2`, [workspaceId, versionNumber]);
22442
+ const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 AND "versionNumber" = $2`, [workspaceId, versionNumber]);
22275
22443
  if (!result) return null;
22276
22444
  return this.parseVersionRow(result);
22277
22445
  } catch (error) {
@@ -22288,12 +22456,19 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22288
22456
  }
22289
22457
  }
22290
22458
  async getLatestVersion(workspaceId) {
22459
+ return this.#getLatestVersion(this.#db.readClient, workspaceId);
22460
+ }
22461
+ /**
22462
+ * Same lookup against an explicit client. Mutation paths pass the writer so a
22463
+ * lagging read replica cannot yield stale or missing rows mid-update.
22464
+ */
22465
+ async #getLatestVersion(client, workspaceId) {
22291
22466
  try {
22292
22467
  const tableName = getTableName$5({
22293
22468
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22294
22469
  schemaName: getSchemaName$5(this.#schema)
22295
22470
  });
22296
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [workspaceId]);
22471
+ const result = await client.oneOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`, [workspaceId]);
22297
22472
  if (!result) return null;
22298
22473
  return this.parseVersionRow(result);
22299
22474
  } catch (error) {
@@ -22322,7 +22497,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22322
22497
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22323
22498
  schemaName: getSchemaName$5(this.#schema)
22324
22499
  });
22325
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22500
+ const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22326
22501
  const total = parseInt(countResult.count, 10);
22327
22502
  if (total === 0) return {
22328
22503
  versions: [],
@@ -22333,7 +22508,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22333
22508
  };
22334
22509
  const limitValue = perPageInput === false ? total : perPage;
22335
22510
  return {
22336
- versions: (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
22511
+ versions: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} WHERE "workspaceId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`, [
22337
22512
  workspaceId,
22338
22513
  limitValue,
22339
22514
  offset
@@ -22403,7 +22578,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
22403
22578
  indexName: _mastra_core_storage.TABLE_WORKSPACE_VERSIONS,
22404
22579
  schemaName: getSchemaName$5(this.#schema)
22405
22580
  });
22406
- const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22581
+ const result = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "workspaceId" = $1`, [workspaceId]);
22407
22582
  return parseInt(result.count, 10);
22408
22583
  } catch (error) {
22409
22584
  if (error instanceof _mastra_core_error.MastraError) throw error;
@@ -22979,10 +23154,12 @@ function exportSchemas(schemaName) {
22979
23154
  * ```
22980
23155
  */
22981
23156
  var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
22982
- #pool;
23157
+ #writePool;
23158
+ #readPool;
22983
23159
  #db;
22984
- #ownsPool;
22985
- #poolClosed = false;
23160
+ #readDb;
23161
+ #ownsWritePool;
23162
+ #writePoolClosed = false;
22986
23163
  schema;
22987
23164
  isInitialized = false;
22988
23165
  #initPromise = null;
@@ -22998,15 +23175,21 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
22998
23175
  });
22999
23176
  this.schema = (0, _mastra_core_utils.parseSqlIdentifier)(config.schemaName || "public", "schema name");
23000
23177
  if (isPoolConfig(config)) {
23001
- this.#pool = config.pool;
23002
- this.#ownsPool = false;
23178
+ this.#writePool = config.pool;
23179
+ this.#ownsWritePool = false;
23180
+ } else if (isWritePoolConfig(config)) {
23181
+ this.#writePool = config.writePool;
23182
+ this.#ownsWritePool = false;
23003
23183
  } else {
23004
- this.#pool = this.createPool(config);
23005
- this.#ownsPool = true;
23184
+ this.#writePool = this.createPool(config);
23185
+ this.#ownsWritePool = true;
23006
23186
  }
23007
- this.#db = new RoutingDbClient(new PoolAdapter(this.#pool));
23187
+ this.#readPool = config.readPool ?? this.#writePool;
23188
+ this.#db = new RoutingDbClient(new PoolAdapter(this.#writePool));
23189
+ this.#readDb = this.#readPool === this.#writePool ? this.#db : new PoolAdapter(this.#readPool);
23008
23190
  const domainConfig = {
23009
23191
  client: this.#db,
23192
+ readClient: this.#readDb,
23010
23193
  schemaName: this.schema,
23011
23194
  skipDefaultIndexes: config.skipDefaultIndexes,
23012
23195
  indexes: config.indexes
@@ -23066,8 +23249,8 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
23066
23249
  async #runPinnedInit() {
23067
23250
  let pinnedClient;
23068
23251
  try {
23069
- pinnedClient = await this.#pool.connect();
23070
- const pinned = new PinnedClientAdapter(this.#pool, pinnedClient);
23252
+ pinnedClient = await this.#writePool.connect();
23253
+ const pinned = new PinnedClientAdapter(this.#writePool, pinnedClient);
23071
23254
  this.#db.pin(pinned);
23072
23255
  this.#db.setSchemaSnapshot(await loadSchemaSnapshot(pinned, this.schema));
23073
23256
  await super.init();
@@ -23100,21 +23283,27 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
23100
23283
  get db() {
23101
23284
  return this.#db;
23102
23285
  }
23103
- /**
23104
- * The underlying pg.Pool for direct database access or ORM integration.
23105
- */
23286
+ /** Database client for queries that may run against the configured read replica. */
23287
+ get readDb() {
23288
+ return this.#readDb;
23289
+ }
23290
+ /** The underlying writer pg.Pool for direct database access or ORM integration. */
23106
23291
  get pool() {
23107
- return this.#pool;
23292
+ return this.#writePool;
23293
+ }
23294
+ /** The underlying reader pg.Pool, falling back to the writer pool when unset. */
23295
+ get readPool() {
23296
+ return this.#readPool;
23108
23297
  }
23109
23298
  /**
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.
23299
+ * Closes the writer connection pool if it was created by this store.
23300
+ * Caller-provided writer and reader pools are not closed.
23112
23301
  * Safe to call multiple times — subsequent calls are no-ops.
23113
23302
  */
23114
23303
  async close() {
23115
- if (this.#ownsPool && !this.#poolClosed) {
23116
- this.#poolClosed = true;
23117
- await this.#pool.end();
23304
+ if (this.#ownsWritePool && !this.#writePoolClosed) {
23305
+ this.#writePoolClosed = true;
23306
+ await this.#writePool.end();
23118
23307
  }
23119
23308
  }
23120
23309
  };