@mastra/pg 1.26.0-alpha.1 → 1.26.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.
@@ -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.26.0-alpha.1"
6
+ version: "1.26.0-alpha.2"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.26.0-alpha.1",
2
+ "version": "1.26.0-alpha.2",
3
3
  "package": "@mastra/pg",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -6,11 +6,37 @@
6
6
 
7
7
  Because storage grows without bound by default, Mastra provides an opt-in, age-based retention system. Declare per-table `maxAge` policies in the `retention` config, then call `storage.prune()` to delete rows older than their configured age. Unconfigured data is kept forever, so behavior doesn't change until you opt in.
8
8
 
9
- `prune()` deletes rows. It caps growth and is safe to run against large tables (batched, bounded, resumable, cancellable). It never reclaims disk: on SQLite/libSQL the freed pages are reused by future writes so the file stops growing, but handing disk back to the OS (for example a `VACUUM`) is left to the underlying database and the operator to manage.
9
+ `prune()` deletes rows in bounded batches. Runs are resumable and cancellable, so you can limit how much work each maintenance window performs. Pruning doesn't reclaim disk space by itself. Use the database-specific maintenance guidance below when you need to return freed space to the operating system.
10
10
 
11
11
  Retention covers **growth tables** only: tables that accumulate rows unbounded as a side effect of normal operation (conversation history, telemetry, job and run records, schedule fire history, event feeds). User-authored artifacts and config (agents, skills, workspaces, prompt blocks, datasets, schedule definitions, channel installations, and so on) grow with user intent and are edited or deleted explicitly, so they're not valid retention keys.
12
12
 
13
- The reference implementations are [libSQL](https://mastra.ai/integrations/databases/libsql), [PostgreSQL](https://mastra.ai/integrations/databases/postgresql), and [MongoDB](https://mastra.ai/integrations/databases/mongodb). Other adapters keep rows forever until they implement retention.
13
+ Storage adapters use the shared core retention contract for `prune()`, or a database-native mechanism when that better matches the backend.
14
+
15
+ | Adapter | Mechanism | Retention support |
16
+ | -------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17
+ | libSQL | `prune()` | All supported growth domains |
18
+ | PostgreSQL | `prune()` | All supported growth domains. V-next observability drops expired partitions or chunks |
19
+ | MongoDB | `prune()` or native TTL | All supported growth domains. Native TTL indexes are also available |
20
+ | DuckDB | `prune()` | Observability spans, metrics, logs, scores, and feedback |
21
+ | MySQL | `prune()` | Observability spans |
22
+ | Microsoft SQL Server | `prune()` | Observability spans |
23
+ | Oracle Database | `prune()` | Observability spans and logs |
24
+ | Amazon Aurora DSQL | `prune()` | Observability spans |
25
+ | Google Cloud Spanner | `prune()` | Observability spans, plus metrics when metrics storage is enabled |
26
+ | ClickHouse | Native TTL | Observability spans, metrics, logs, scores, and feedback. When all five signals have finite retention, deletion-request records expire after the longest signal retention plus 30 days |
27
+
28
+ ## Storage-specific maintenance
29
+
30
+ | Adapter | Maintenance guidance |
31
+ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
32
+ | SQLite and libSQL | Freed pages are reused by future writes, which stops the database file from growing. Reclaiming disk space requires database-level maintenance. |
33
+ | DuckDB | For file-backed stores, run `CHECKPOINT` after pruning to reclaim deleted rows in storage. DuckDB's `VACUUM` doesn't reclaim deleted rows. |
34
+
35
+ ## Schedule pruning
36
+
37
+ Run `prune()` from a scheduler or maintenance worker, not from application startup or shutdown hooks. For deployments that share a database, prefer a single active scheduler or worker for pruning.
38
+
39
+ Prefer lower-traffic periods when pruning large tables. Use `maxBatches`, `maxRows`, and `pauseMs` to bound each run, and pass an `AbortSignal` when the maintenance process needs to stop promptly. These recommendations apply to adapters that expose `prune()`. ClickHouse applies its native time to live (TTL) policy within the database.
14
40
 
15
41
  ## Usage example
16
42
 
@@ -94,7 +120,8 @@ Each domain specifies its age-prunable tables and the timestamp column that anch
94
120
  > - 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.
95
121
  > - For `schedules`, the growth table is the fire history (`schedule_triggers`, one row per fire): schedule definitions are config and aren't pruned.
96
122
  > - On PostgreSQL, timestamp anchors use the timezone-aware mirror columns (for example `createdAtZ`, `completedAtZ`).
97
- > - LibSQL and PostgreSQL support all domains above except `harness`, which PostgreSQL doesn't implement. MongoDB supports all except `threadState` and `harness`.
123
+ > - DuckDB observability stores append-only events for all five signals. Its `spans` policy uses the event `timestamp` column rather than `startedAt`.
124
+ > - LibSQL and PostgreSQL support all domains above except `harness`, which PostgreSQL doesn't implement. MongoDB supports all except `threadState` and `harness`. DuckDB, MySQL, Microsoft SQL Server, Oracle Database, Amazon Aurora DSQL, and Google Cloud Spanner currently support retention only in their `observability` domains, with the signal coverage shown in the support matrix.
98
125
  > - 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.
99
126
 
100
127
  ## Methods
@@ -109,7 +136,7 @@ Deletes rows older than their configured `maxAge` across every domain that has a
109
136
 
110
137
  Pass `options.retention` to replace the configured policies for that call only: for example to skip a domain (keep chat history) or prune more aggressively than the standing config. The store's configured `retention` is unchanged.
111
138
 
112
- Anchor-column indexes are created lazily on the first `prune()` call for each table with a policy (never at `init()`) so deployments that don't configure retention pay no extra index write or disk overhead. The first prune of an existing large table pays a one-time index build. Subsequent prunes reuse the index.
139
+ Adapters that use anchor-column indexes create them lazily on the first `prune()` call for each table with a policy (never at `init()`) so deployments that don't configure retention pay no extra index write or disk overhead. The first prune of an existing large table pays a one-time index build. Subsequent prunes reuse the index. DuckDB uses its built-in zone maps instead of creating retention indexes.
113
140
 
114
141
  ```typescript
115
142
  const results = await storage.prune({
@@ -177,6 +204,31 @@ async function retentionTick() {
177
204
 
178
205
  You can also cancel a long-running prune with an `AbortSignal`: the loop stops between batches and returns partial results with `done: false`, so the next run resumes cleanly.
179
206
 
207
+ ## ClickHouse native TTL
208
+
209
+ ClickHouse observability storage uses native table TTLs instead of `prune()`. Configure retention as days per signal. `init()` applies the TTLs to new and existing tables and skips `ALTER TABLE` statements when the configured TTL is already present.
210
+
211
+ For deployments that need to update TTL configuration without running the full initialization path, call `applyRetention()` on the v-next observability store:
212
+
213
+ ```typescript
214
+ import { ObservabilityStorageClickhouseVNext } from '@mastra/clickhouse'
215
+
216
+ const observability = new ObservabilityStorageClickhouseVNext({
217
+ client,
218
+ retention: {
219
+ tracing: 30,
220
+ logs: 7,
221
+ metrics: 14,
222
+ scores: 90,
223
+ feedback: 60,
224
+ },
225
+ })
226
+
227
+ await observability.applyRetention()
228
+ ```
229
+
230
+ Deletion requests are retained long enough to keep enforcing erasure after signal rows expire. Mastra applies a TTL to `mastra_deletion_requests` only when tracing, logs, metrics, scores, and feedback all have finite retention. The deletion-request TTL is the longest of those periods plus 30 days. For example, if score retention is the longest period at 90 days, deletion requests expire after 120 days. When any signal is unbounded, deletion requests remain unbounded because trace deletion requests cover rows across all five signals.
231
+
180
232
  ## MongoDB TTL indexes (alternative to prune)
181
233
 
182
234
  MongoDB offers native [TTL (Time-To-Live) indexes](https://www.mongodb.com/docs/manual/core/index-ttl/) that automatically delete expired documents without requiring manual `prune()` calls. This is a database-level feature that runs as a background thread.
package/dist/index.cjs CHANGED
@@ -4927,137 +4927,31 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4927
4927
  };
4928
4928
  //#endregion
4929
4929
  //#region src/storage/retention.ts
4930
- const DEFAULT_BATCH_SIZE = 1e3;
4931
- async function sleep(ms, signal) {
4932
- if (ms <= 0 || signal?.aborted) return;
4933
- await new Promise((resolve) => {
4934
- const timer = setTimeout(() => {
4935
- signal?.removeEventListener("abort", onAbort);
4936
- resolve();
4937
- }, ms);
4938
- const onAbort = () => {
4939
- clearTimeout(timer);
4940
- resolve();
4941
- };
4942
- signal?.addEventListener("abort", onAbort, { once: true });
4943
- });
4944
- }
4945
- /**
4946
- * Convert a policy's `maxAge` into a cutoff bound matching the anchor's storage
4947
- * type: a `Date` for `timestamptz` columns (pg compares timezone-aware), or a
4948
- * raw millisecond number for `bigint` epoch-ms columns.
4949
- */
4950
4930
  function cutoffFor(policy, anchorType, now = Date.now()) {
4951
- const cutoffMs = now - (0, _mastra_core_storage.parseDuration)(policy.maxAge);
4931
+ const cutoffMs = (0, _mastra_core_storage.retentionCutoffMs)(policy, now);
4952
4932
  return anchorType === "epoch-ms" ? cutoffMs : new Date(cutoffMs);
4953
4933
  }
4954
- /**
4955
- * Run the bounded/cancellable batched-delete loop for a single logical target,
4956
- * delegating the actual delete of up to `limit` rows to `deleteBatch`. Returns
4957
- * `{ deleted, done }`; `done: false` means the loop stopped on a bound or the
4958
- * abort signal and eligible rows may remain.
4959
- */
4960
- async function runBatchedDelete({ deleteBatch, batchSize, options }) {
4961
- if (!Number.isSafeInteger(batchSize) || batchSize <= 0) throw new Error(`retention batchSize must be a positive integer; received ${batchSize}`);
4962
- let deleted = 0;
4963
- let batches = 0;
4964
- while (true) {
4965
- if (options?.signal?.aborted) return {
4966
- deleted,
4967
- done: false
4968
- };
4969
- if (options?.maxBatches !== void 0 && batches >= options.maxBatches) return {
4970
- deleted,
4971
- done: false
4972
- };
4973
- let limit = batchSize;
4974
- if (options?.maxRows !== void 0) {
4975
- const remaining = options.maxRows - deleted;
4976
- if (remaining <= 0) return {
4977
- deleted,
4978
- done: false
4979
- };
4980
- limit = Math.min(limit, remaining);
4981
- }
4982
- const affected = await deleteBatch(limit);
4983
- deleted += affected;
4984
- batches += 1;
4985
- if (affected < limit) return {
4986
- deleted,
4987
- done: true
4988
- };
4989
- if (options?.pauseMs) await sleep(options.pauseMs, options.signal);
4990
- }
4991
- }
4992
- /**
4993
- * Runs the bounded, batched, cancellable delete loop for a set of tables in the
4994
- * given order (callers pass children before parents for cascade-safe pruning),
4995
- * and returns one {@link PruneResult} per table.
4996
- *
4997
- * The loop:
4998
- * - deletes in chunks of `batchSize` (default 1000), each its own statement;
4999
- * - stops a table's loop when a batch deletes fewer rows than requested (drained),
5000
- * or when `maxBatches`/`maxRows` is hit, or the `signal` aborts — the latter
5001
- * three leave `done: false` so the caller can resume;
5002
- * - pauses `pauseMs` between batches when set, to avoid starving live traffic.
5003
- *
5004
- * `prune()` only deletes rows; it never reclaims disk. PostgreSQL reuses freed
5005
- * space (dead tuples) via autovacuum on subsequent writes, so tables stop
5006
- * growing. Returning disk to the OS (e.g. `VACUUM FULL`) is left to the operator.
5007
- */
5008
- async function runPrune({ db, domain, targets, options }) {
5009
- const results = [];
5010
- const now = Date.now();
5011
- for (const target of targets) {
5012
- if (options?.signal?.aborted) {
5013
- results.push({
5014
- domain,
5015
- table: target.table,
5016
- deleted: 0,
5017
- done: false
5018
- });
5019
- continue;
5020
- }
5021
- const cutoff = cutoffFor(target.policy, target.anchorType, now);
5022
- const { deleted, done } = await runBatchedDelete({
5023
- deleteBatch: (limit) => db.pruneBatch({
5024
- tableName: target.table,
5025
- column: target.column,
5026
- cutoff,
5027
- limit
5028
- }),
5029
- batchSize: target.policy.batchSize ?? DEFAULT_BATCH_SIZE,
5030
- options
5031
- });
5032
- results.push({
5033
- domain,
5034
- table: target.table,
5035
- deleted,
5036
- done
5037
- });
5038
- }
5039
- return results;
4934
+ const runBatchedDelete = _mastra_core_storage.runRetentionBatches;
4935
+ function runPrune({ db, domain, targets, options }) {
4936
+ return (0, _mastra_core_storage.executeRetentionPrune)({
4937
+ domain,
4938
+ targets,
4939
+ options,
4940
+ cutoffFor: (target, now) => cutoffFor(target.policy, target.anchorType ?? "timestamp", now),
4941
+ deleteBatch: (target, cutoff, limit) => db.pruneBatch({
4942
+ tableName: target.table,
4943
+ column: target.column,
4944
+ cutoff,
4945
+ limit
4946
+ })
4947
+ });
5040
4948
  }
5041
- /**
5042
- * Resolve a domain's `{ tableKey: policy }` map plus its descriptor into an
5043
- * ordered list of {@link PruneTarget}s. `order` lists table keys children-first
5044
- * so cascade-dependent rows are removed before their parents. Table keys not in
5045
- * `policies` are skipped (unset = keep forever).
5046
- */
5047
4949
  function resolveTargets({ policies, descriptor, order }) {
5048
- const targets = [];
5049
- for (const key of order) {
5050
- const policy = policies[key];
5051
- const entry = descriptor[key];
5052
- if (!policy || !entry) continue;
5053
- targets.push({
5054
- table: entry.table,
5055
- column: entry.column,
5056
- anchorType: entry.anchorType ?? "timestamp",
5057
- policy
5058
- });
5059
- }
5060
- return targets;
4950
+ return (0, _mastra_core_storage.resolveRetentionTargets)({
4951
+ policies,
4952
+ descriptor,
4953
+ order
4954
+ });
5061
4955
  }
5062
4956
  //#endregion
5063
4957
  //#region src/storage/domains/background-tasks/index.ts
@@ -17315,6 +17209,11 @@ const FEEDBACK_FIELDS = {
17315
17209
  const TRACE_SELECT = `
17316
17210
  r."traceId" AS "traceId",
17317
17211
  r."spanId" AS "rootSpanId",
17212
+ r."name" AS "name",
17213
+ r."entityId" AS "entityId",
17214
+ r."parentSpanId" AS "parentSpanId",
17215
+ r."metadata" AS "metadata",
17216
+ r."input" AS "input",
17318
17217
  r."threadId" AS "threadId",
17319
17218
  r."resourceId" AS "resourceId",
17320
17219
  r."startedAt" AS "startedAt",
@@ -17794,6 +17693,11 @@ function isPostgresStatementTimeout(error) {
17794
17693
  const candidate = error;
17795
17694
  return candidate.code === "57014" && String(candidate.message ?? "").includes("statement timeout");
17796
17695
  }
17696
+ function isPostgresResourceLimit(error) {
17697
+ if (!error || typeof error !== "object") return false;
17698
+ const candidate = error;
17699
+ return candidate.code === "53200" || candidate.code === "53400";
17700
+ }
17797
17701
  async function runWithPostgresTraceQueryTimeout(client, timeoutMs, execute) {
17798
17702
  const resolvedTimeoutMs = _mastra_core_storage.resolveTraceQueryTimeoutMs(timeoutMs);
17799
17703
  try {
@@ -17803,6 +17707,7 @@ async function runWithPostgresTraceQueryTimeout(client, timeoutMs, execute) {
17803
17707
  });
17804
17708
  } catch (error) {
17805
17709
  if (isPostgresStatementTimeout(error)) throw new _mastra_core_storage.TraceQueryExecutionError();
17710
+ if (isPostgresResourceLimit(error)) throw new _mastra_core_storage.TraceQueryResourceLimitError();
17806
17711
  throw error;
17807
17712
  }
17808
17713
  }
@@ -17847,6 +17752,12 @@ async function queryTraces(client, schema, plan, timeoutMs) {
17847
17752
  const traces = visibleRows.map((row) => ({
17848
17753
  traceId: String(row.traceId),
17849
17754
  rootSpanId: String(row.rootSpanId),
17755
+ name: row.name,
17756
+ entityId: row.entityId ?? null,
17757
+ parentSpanId: row.parentSpanId ?? null,
17758
+ createdAt: asIsoTimestamp$1(row.startedAt),
17759
+ metadata: row.metadata ?? null,
17760
+ inputPreview: _mastra_core_storage.buildInputPreview(row.input) ?? null,
17850
17761
  threadId: row.threadId == null ? null : String(row.threadId),
17851
17762
  resourceId: row.resourceId == null ? null : String(row.resourceId),
17852
17763
  startedAt: asIsoTimestamp$1(row.startedAt),
@@ -18594,7 +18505,7 @@ async function dangerouslyClearTracing(client, schema) {
18594
18505
  * Use it through `MastraCompositeStore` with a dedicated Postgres connection.
18595
18506
  */
18596
18507
  function wrapError(op, error, details) {
18597
- if (error instanceof _mastra_core_error.MastraError || error instanceof _mastra_core_storage.TraceQueryExecutionError) throw error;
18508
+ if (error instanceof _mastra_core_error.MastraError || error instanceof _mastra_core_storage.TraceQueryExecutionError || error instanceof _mastra_core_storage.TraceQueryResourceLimitError) throw error;
18598
18509
  throw new _mastra_core_error.MastraError({
18599
18510
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", op, "FAILED"),
18600
18511
  domain: _mastra_core_error.ErrorDomain.STORAGE,