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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # @mastra/pg
2
2
 
3
+ ## 1.20.0-alpha.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Fixed `include` in `listMessages` and `listMessagesByResourceId` so it can no longer return a message that belongs to a different resource. When you pass a `resourceId`, the target message and its surrounding context messages now stay inside that resource. Includes that cross threads inside the same resource keep working, so semantic recall with `scope: 'resource'` is unchanged. ([#20984](https://github.com/mastra-ai/mastra/pull/20984))
8
+
9
+ **Behaviour change in the in-memory store**
10
+
11
+ The in-memory store read the context window from the thread you queried. It now reads the window from the thread that owns the target message, which is what the SQL stores already did. This only changes the result when an `include` entry names a message from another thread.
12
+
13
+ The in-memory store also ignored `include` in `listMessagesByResourceId`. It now returns the included messages, like `@mastra/libsql` and `@mastra/pg` do.
14
+
15
+ Fixes #20604.
16
+
17
+ - Add a persistent `threadState` domain to `PostgresStore` ([#20994](https://github.com/mastra-ai/mastra/pull/20994))
18
+
19
+ `PostgresStore` did not register a `threadState` domain, so durable task and goal
20
+ state fell back to in-memory storage and was lost on restart. Anything relying on
21
+ thread state (task tools, long-running agent goals) could not be backed by Postgres
22
+ alone, and required composing a second adapter through `MastraCompositeStore`.
23
+
24
+ `ThreadStatePG` now stores state as JSONB keyed by `(threadId, type)` with an atomic
25
+ upsert that preserves `createdAt`, participates in `exportSchemas()` and `init()`, and
26
+ supports retention pruning anchored on `updatedAtZ` so state for still-active threads
27
+ survives age-based pruning.
28
+
29
+ - Updated dependencies [[`6445eba`](https://github.com/mastra-ai/mastra/commit/6445eba6020abac681aba1cc9289f446cb400cbe), [`df31eb0`](https://github.com/mastra-ai/mastra/commit/df31eb0c7087d782a0d9346e467f9a4af4b0eef6), [`fcd0667`](https://github.com/mastra-ai/mastra/commit/fcd0667a4e378be35c9a1b1eb19cce78fbfd7282), [`bab06b1`](https://github.com/mastra-ai/mastra/commit/bab06b18923873a584bdfc71a6b4ec7fb4727fb7)]:
30
+ - @mastra/core@1.58.0-alpha.5
31
+
3
32
  ## 1.20.0-alpha.1
4
33
 
5
34
  ### Patch Changes
@@ -3,7 +3,7 @@ name: mastra-pg
3
3
  description: Documentation for @mastra/pg. Use when working with @mastra/pg APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/pg"
6
- version: "1.20.0-alpha.1"
6
+ version: "1.20.0-alpha.2"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.20.0-alpha.1",
2
+ "version": "1.20.0-alpha.2",
3
3
  "package": "@mastra/pg",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -92,7 +92,7 @@ Each domain declares which of its tables can be age-pruned and which timestamp c
92
92
  > - Experiments prune as whole units: an aged experiment's result rows are deleted together with it (results cascade with their parent), so a run is never left partially deleted. Retention doesn't have a separate `results` key.
93
93
  > - For `schedules`, the growth table is the fire history (`schedule_triggers`, one row per fire): schedule definitions are config and aren't pruned.
94
94
  > - On PostgreSQL, timestamp anchors use the timezone-aware mirror columns (for example `createdAtZ`, `completedAtZ`).
95
- > - LibSQL supports all domains above; PostgreSQL and MongoDB support all except `threadState` and `harness`, which they don't implement.
95
+ > - LibSQL and PostgreSQL support all domains above except `harness`, which PostgreSQL doesn't implement. MongoDB supports all except `threadState` and `harness`.
96
96
  > - The v-next PostgreSQL observability domain stores signal events in day-partitioned tables (`spans`, `metrics`, `logs`, `scores`, `feedback`). For it, `prune()` drops whole day partitions (or TimescaleDB chunks) that are entirely older than the cutoff instead of deleting rows: effective level of detail is one day, and a partition is only dropped once its entire day is past `maxAge`. `PruneResult.deleted` reports the number of rows in the dropped partitions.
97
97
 
98
98
  ## Methods
package/dist/index.cjs CHANGED
@@ -9307,7 +9307,13 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9307
9307
  return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
9308
9308
  });
9309
9309
  }
9310
- async _getIncludedMessages({ include }) {
9310
+ /**
9311
+ * Fetches included messages by ID, discovering their thread automatically.
9312
+ * This handles cross-thread includes where the include item doesn't specify a threadId.
9313
+ * When a resourceId is given, both the target lookup and the surrounding window stay
9314
+ * inside that resource, so an include never leaks another resource's messages.
9315
+ */
9316
+ async _getIncludedMessages({ include, resourceId }) {
9311
9317
  if (!include || include.length === 0) return null;
9312
9318
  const tableName = getTableName$3({
9313
9319
  indexName: _mastra_core_storage.TABLE_MESSAGES,
@@ -9317,7 +9323,8 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9317
9323
  const targetIds = include.map((inc) => inc.id).filter(Boolean);
9318
9324
  if (targetIds.length === 0) return null;
9319
9325
  const idPlaceholders = targetIds.map((_, i) => "$" + (i + 1)).join(", ");
9320
- const targetRows = await this.#db.client.manyOrNone(`SELECT id, thread_id, "createdAt" FROM ${tableName} WHERE id IN (${idPlaceholders})`, targetIds);
9326
+ const targetResourceCondition = resourceId ? ` AND "resourceId" = $${targetIds.length + 1}` : "";
9327
+ const targetRows = await this.#db.client.manyOrNone(`SELECT id, thread_id, "createdAt" FROM ${tableName} WHERE id IN (${idPlaceholders})${targetResourceCondition}`, resourceId ? [...targetIds, resourceId] : targetIds);
9321
9328
  if (targetRows.length === 0) return null;
9322
9329
  const targetMap = new Map(targetRows.map((r) => [r.id, {
9323
9330
  threadId: r.thread_id,
@@ -9325,7 +9332,12 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9325
9332
  }]));
9326
9333
  const unionQueries = [];
9327
9334
  const params = [];
9328
- let paramIdx = 1;
9335
+ let resourceCondition = "";
9336
+ if (resourceId) {
9337
+ params.push(resourceId);
9338
+ resourceCondition = ` AND m."resourceId" = $1`;
9339
+ }
9340
+ let paramIdx = params.length + 1;
9329
9341
  for (const inc of include) {
9330
9342
  const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
9331
9343
  const target = targetMap.get(id);
@@ -9337,7 +9349,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9337
9349
  SELECT ${selectColumns}
9338
9350
  FROM ${tableName} m
9339
9351
  WHERE m.thread_id = ${p1}
9340
- AND m."createdAt" <= ${p2}
9352
+ AND m."createdAt" <= ${p2}${resourceCondition}
9341
9353
  ORDER BY m."createdAt" DESC, m.id DESC
9342
9354
  LIMIT ${p3}
9343
9355
  )`);
@@ -9351,7 +9363,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9351
9363
  SELECT ${selectColumns}
9352
9364
  FROM ${tableName} m
9353
9365
  WHERE m.thread_id = ${p4}
9354
- AND m."createdAt" > ${p5}
9366
+ AND m."createdAt" > ${p5}${resourceCondition}
9355
9367
  ORDER BY m."createdAt" ASC, m.id ASC
9356
9368
  LIMIT ${p6}
9357
9369
  )`);
@@ -9501,7 +9513,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9501
9513
  hasMore: false
9502
9514
  };
9503
9515
  if (perPage === 0 && include && include.length > 0) {
9504
- const includeMessages = await this._getIncludedMessages({ include });
9516
+ const includeMessages = await this._getIncludedMessages({
9517
+ include,
9518
+ resourceId
9519
+ });
9505
9520
  if (!includeMessages || includeMessages.length === 0) return {
9506
9521
  messages: [],
9507
9522
  total: 0,
@@ -9520,7 +9535,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9520
9535
  };
9521
9536
  }
9522
9537
  let includeFailure;
9523
- const includePromise = include && include.length > 0 ? this._getIncludedMessages({ include }).catch((error) => {
9538
+ const includePromise = include && include.length > 0 ? this._getIncludedMessages({
9539
+ include,
9540
+ resourceId
9541
+ }).catch((error) => {
9524
9542
  includeFailure = error;
9525
9543
  return null;
9526
9544
  }) : null;
@@ -9641,7 +9659,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9641
9659
  hasMore: false
9642
9660
  };
9643
9661
  if (perPage === 0 && include && include.length > 0) {
9644
- const includeMessages = await this._getIncludedMessages({ include });
9662
+ const includeMessages = await this._getIncludedMessages({
9663
+ include,
9664
+ resourceId
9665
+ });
9645
9666
  if (!includeMessages || includeMessages.length === 0) return {
9646
9667
  messages: [],
9647
9668
  total: 0,
@@ -9660,7 +9681,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
9660
9681
  };
9661
9682
  }
9662
9683
  let includeFailure;
9663
- const includePromise = include && include.length > 0 ? this._getIncludedMessages({ include }).catch((error) => {
9684
+ const includePromise = include && include.length > 0 ? this._getIncludedMessages({
9685
+ include,
9686
+ resourceId
9687
+ }).catch((error) => {
9664
9688
  includeFailure = error;
9665
9689
  return null;
9666
9690
  }) : null;
@@ -18688,6 +18712,171 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
18688
18712
  }
18689
18713
  };
18690
18714
  //#endregion
18715
+ //#region src/storage/domains/thread-state/index.ts
18716
+ const COMPOSITE_PRIMARY_KEY = ["threadId", "type"];
18717
+ /**
18718
+ * PostgreSQL implementation of {@link ThreadStateStorage}.
18719
+ *
18720
+ * Stores per-thread, per-type state in `mastra_thread_state`, keyed by the
18721
+ * composite primary key `(threadId, type)`. The `value` column is `jsonb`, so
18722
+ * payloads (the task list for `type = 'task'`, the goal objective for
18723
+ * `type = 'goal'`) come back already parsed.
18724
+ */
18725
+ var ThreadStatePG = class ThreadStatePG extends _mastra_core_storage.ThreadStateStorage {
18726
+ #db;
18727
+ #schema;
18728
+ static MANAGED_TABLES = [_mastra_core_storage.TABLE_THREAD_STATE];
18729
+ /**
18730
+ * `thread_state` grows as a side effect of thread activity (one row per
18731
+ * thread per state type). It anchors on `updatedAtZ` (last activity), so
18732
+ * state for a thread that is still being written to is not pruned by
18733
+ * creation age.
18734
+ */
18735
+ static retentionTables = { threadState: {
18736
+ table: _mastra_core_storage.TABLE_THREAD_STATE,
18737
+ column: "updatedAtZ",
18738
+ indexed: true
18739
+ } };
18740
+ constructor(config) {
18741
+ super();
18742
+ const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
18743
+ this.#db = new PgDB({
18744
+ client,
18745
+ schemaName,
18746
+ skipDefaultIndexes
18747
+ });
18748
+ this.#schema = schemaName || "public";
18749
+ }
18750
+ static getExportDDL(schemaName) {
18751
+ return [generateTableSQL({
18752
+ tableName: _mastra_core_storage.TABLE_THREAD_STATE,
18753
+ schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_THREAD_STATE],
18754
+ schemaName,
18755
+ compositePrimaryKey: COMPOSITE_PRIMARY_KEY,
18756
+ includeAllConstraints: true
18757
+ })];
18758
+ }
18759
+ async init() {
18760
+ await this.#db.createTable({
18761
+ tableName: _mastra_core_storage.TABLE_THREAD_STATE,
18762
+ schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_THREAD_STATE],
18763
+ compositePrimaryKey: COMPOSITE_PRIMARY_KEY
18764
+ });
18765
+ }
18766
+ get #table() {
18767
+ return getTableName$5({
18768
+ indexName: _mastra_core_storage.TABLE_THREAD_STATE,
18769
+ schemaName: getSchemaName$5(this.#schema)
18770
+ });
18771
+ }
18772
+ /**
18773
+ * Create the retention index on demand, mirroring the other PG domains: only
18774
+ * deployments that configure retention pay for the extra index. Best-effort —
18775
+ * a failure here leaves pruning correct, just slower.
18776
+ */
18777
+ async #ensureRetentionIndexes(policies) {
18778
+ const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
18779
+ for (const [key, entry] of Object.entries(ThreadStatePG.retentionTables)) {
18780
+ if (!entry.indexed || !policies[key]) continue;
18781
+ try {
18782
+ await this.#db.ensureIndex({
18783
+ indexName: `${prefix}mastra_${key}_retention_idx`,
18784
+ tableName: entry.table,
18785
+ column: entry.column
18786
+ });
18787
+ } catch (error) {
18788
+ this.logger?.warn?.(`Failed to create retention index for ${entry.table}:`, error);
18789
+ }
18790
+ }
18791
+ }
18792
+ /** Delete thread state older than the `threadState` policy's `maxAge`, batched. */
18793
+ async prune(policies, options) {
18794
+ await this.#ensureRetentionIndexes(policies);
18795
+ const targets = resolveTargets({
18796
+ policies,
18797
+ descriptor: ThreadStatePG.retentionTables,
18798
+ order: ["threadState"]
18799
+ });
18800
+ return runPrune({
18801
+ db: this.#db,
18802
+ domain: "threadState",
18803
+ targets,
18804
+ options
18805
+ });
18806
+ }
18807
+ async dangerouslyClearAll() {
18808
+ try {
18809
+ await this.#db.client.none(`DELETE FROM ${this.#table}`);
18810
+ } catch (error) {
18811
+ throw new _mastra_core_error.MastraError({
18812
+ id: (0, _mastra_core_storage.createStorageErrorId)("PG", "THREAD_STATE_CLEAR_ALL", "FAILED"),
18813
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
18814
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY
18815
+ }, error);
18816
+ }
18817
+ }
18818
+ async getState({ threadId, type }) {
18819
+ try {
18820
+ const row = await this.#db.client.oneOrNone(`SELECT "value" FROM ${this.#table} WHERE "threadId" = $1 AND "type" = $2 LIMIT 1`, [threadId, type]);
18821
+ if (!row || row.value === null || row.value === void 0) return void 0;
18822
+ return typeof row.value === "string" ? JSON.parse(row.value) : row.value;
18823
+ } catch (error) {
18824
+ throw new _mastra_core_error.MastraError({
18825
+ id: (0, _mastra_core_storage.createStorageErrorId)("PG", "THREAD_STATE_GET", "FAILED"),
18826
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
18827
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
18828
+ details: {
18829
+ threadId,
18830
+ type
18831
+ }
18832
+ }, error);
18833
+ }
18834
+ }
18835
+ async setState({ threadId, type, value }) {
18836
+ const now = (/* @__PURE__ */ new Date()).toISOString();
18837
+ const serialized = JSON.stringify(value ?? null);
18838
+ try {
18839
+ await this.#db.client.none(`INSERT INTO ${this.#table} ("threadId", "type", "value", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ")
18840
+ VALUES ($1, $2, $3::jsonb, $4::timestamp, $5::timestamptz, $4::timestamp, $5::timestamptz)
18841
+ ON CONFLICT ("threadId", "type")
18842
+ DO UPDATE SET "value" = EXCLUDED."value",
18843
+ "updatedAt" = EXCLUDED."updatedAt",
18844
+ "updatedAtZ" = EXCLUDED."updatedAtZ"`, [
18845
+ threadId,
18846
+ type,
18847
+ serialized,
18848
+ now,
18849
+ now
18850
+ ]);
18851
+ } catch (error) {
18852
+ throw new _mastra_core_error.MastraError({
18853
+ id: (0, _mastra_core_storage.createStorageErrorId)("PG", "THREAD_STATE_SET", "FAILED"),
18854
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
18855
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
18856
+ details: {
18857
+ threadId,
18858
+ type
18859
+ }
18860
+ }, error);
18861
+ }
18862
+ }
18863
+ async deleteState({ threadId, type }) {
18864
+ try {
18865
+ await this.#db.client.none(`DELETE FROM ${this.#table} WHERE "threadId" = $1 AND "type" = $2`, [threadId, type]);
18866
+ } catch (error) {
18867
+ throw new _mastra_core_error.MastraError({
18868
+ id: (0, _mastra_core_storage.createStorageErrorId)("PG", "THREAD_STATE_DELETE", "FAILED"),
18869
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
18870
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
18871
+ details: {
18872
+ threadId,
18873
+ type
18874
+ }
18875
+ }, error);
18876
+ }
18877
+ }
18878
+ };
18879
+ //#endregion
18691
18880
  //#region src/storage/domains/tool-provider-connections/index.ts
18692
18881
  function normaliseScope(raw) {
18693
18882
  const value = raw == null ? "per-author" : String(raw);
@@ -20622,7 +20811,8 @@ const ALL_DOMAINS = [
20622
20811
  BackgroundTasksPG,
20623
20812
  FavoritesPG,
20624
20813
  ChannelsPG,
20625
- SchedulesPG
20814
+ SchedulesPG,
20815
+ ThreadStatePG
20626
20816
  ];
20627
20817
  /**
20628
20818
  * Exports the Mastra database schema as SQL DDL statements, including tables, indexes, and triggers.
@@ -20716,7 +20906,8 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
20716
20906
  experiments: new ExperimentsPG(domainConfig),
20717
20907
  backgroundTasks: new BackgroundTasksPG(domainConfig),
20718
20908
  channels: new ChannelsPG(domainConfig),
20719
- schedules: new SchedulesPG(domainConfig)
20909
+ schedules: new SchedulesPG(domainConfig),
20910
+ threadState: new ThreadStatePG(domainConfig)
20720
20911
  };
20721
20912
  } catch (e) {
20722
20913
  throw new _mastra_core_error.MastraError({
@@ -21047,6 +21238,7 @@ exports.SchedulesPG = SchedulesPG;
21047
21238
  exports.ScorerDefinitionsPG = ScorerDefinitionsPG;
21048
21239
  exports.ScoresPG = ScoresPG;
21049
21240
  exports.SkillsPG = SkillsPG;
21241
+ exports.ThreadStatePG = ThreadStatePG;
21050
21242
  exports.ToolProviderConnectionsPG = ToolProviderConnectionsPG;
21051
21243
  exports.WorkflowDefinitionsPG = WorkflowDefinitionsPG;
21052
21244
  exports.WorkflowsPG = WorkflowsPG;