@mastra/libsql 1.29.0 → 1.30.0-alpha.0
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/dist/docs/SKILL.md +5 -2
- package/dist/docs/assets/SOURCE_MAP.json +148 -2
- package/dist/docs/references/docs-knowledge-load-your-content.md +86 -0
- package/dist/docs/references/docs-knowledge-overview.md +106 -0
- package/dist/docs/references/docs-knowledge-search.md +63 -0
- package/dist/docs/references/docs-memory-overview.md +19 -7
- package/dist/docs/references/reference-core-getMemory.md +2 -2
- package/dist/docs/references/reference-core-listMemory.md +3 -3
- package/dist/index.cjs +821 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +822 -45
- package/dist/index.js.map +1 -1
- package/dist/storage/db/index.d.ts +4 -4
- package/dist/storage/db/index.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +100 -6
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/retention.d.ts +3 -1
- package/dist/storage/retention.d.ts.map +1 -1
- package/package.json +6 -6
package/dist/index.cjs
CHANGED
|
@@ -1862,6 +1862,21 @@ function resolveClient(config) {
|
|
|
1862
1862
|
function assertPositiveLimit(limit) {
|
|
1863
1863
|
if (!Number.isSafeInteger(limit) || limit <= 0) throw new Error(`prune limit must be a positive integer; received ${limit}`);
|
|
1864
1864
|
}
|
|
1865
|
+
/**
|
|
1866
|
+
* Parses JSON object/array text in the table's `jsonb` columns only. A `text` column, such as a
|
|
1867
|
+
* span preview of `{}`, must read back as the stored string.
|
|
1868
|
+
*/
|
|
1869
|
+
function parseJsonColumns(tableName, row) {
|
|
1870
|
+
const schema = _mastra_core_storage.TABLE_SCHEMAS[tableName];
|
|
1871
|
+
return Object.fromEntries(Object.entries(row).map(([k, v]) => {
|
|
1872
|
+
if (schema[k]?.type !== "jsonb" || typeof v !== "string" || !(v.startsWith("{") || v.startsWith("["))) return [k, v];
|
|
1873
|
+
try {
|
|
1874
|
+
return [k, JSON.parse(v)];
|
|
1875
|
+
} catch {
|
|
1876
|
+
return [k, v];
|
|
1877
|
+
}
|
|
1878
|
+
}));
|
|
1879
|
+
}
|
|
1865
1880
|
var LibSQLDB = class extends _mastra_core_base.MastraBase {
|
|
1866
1881
|
client;
|
|
1867
1882
|
maxRetries;
|
|
@@ -2157,7 +2172,7 @@ var LibSQLDB = class extends _mastra_core_base.MastraBase {
|
|
|
2157
2172
|
/**
|
|
2158
2173
|
* Selects a single record from the specified table by key(s).
|
|
2159
2174
|
* Returns the most recently created record if multiple matches exist.
|
|
2160
|
-
*
|
|
2175
|
+
* Parses `jsonb` column values back to objects/arrays.
|
|
2161
2176
|
*
|
|
2162
2177
|
* @typeParam R - The expected return type of the record
|
|
2163
2178
|
* @param args - The select arguments
|
|
@@ -2175,14 +2190,7 @@ var LibSQLDB = class extends _mastra_core_base.MastraBase {
|
|
|
2175
2190
|
args: values
|
|
2176
2191
|
});
|
|
2177
2192
|
if (!result.rows || result.rows.length === 0) return null;
|
|
2178
|
-
|
|
2179
|
-
return Object.fromEntries(Object.entries(row || {}).map(([k, v]) => {
|
|
2180
|
-
try {
|
|
2181
|
-
return [k, typeof v === "string" ? v.startsWith("{") || v.startsWith("[") ? JSON.parse(v) : v : v];
|
|
2182
|
-
} catch {
|
|
2183
|
-
return [k, v];
|
|
2184
|
-
}
|
|
2185
|
-
}));
|
|
2193
|
+
return parseJsonColumns(tableName, result.rows[0] ?? {});
|
|
2186
2194
|
}
|
|
2187
2195
|
/**
|
|
2188
2196
|
* Selects multiple records from the specified table with optional filtering, ordering, and pagination.
|
|
@@ -2207,15 +2215,7 @@ var LibSQLDB = class extends _mastra_core_base.MastraBase {
|
|
|
2207
2215
|
return ((await this.client.execute({
|
|
2208
2216
|
sql: statement,
|
|
2209
2217
|
args: [...whereClause?.args ?? [], ...args ?? []]
|
|
2210
|
-
})).rows ?? []).map((row) => {
|
|
2211
|
-
return Object.fromEntries(Object.entries(row || {}).map(([k, v]) => {
|
|
2212
|
-
try {
|
|
2213
|
-
return [k, typeof v === "string" ? v.startsWith("{") || v.startsWith("[") ? JSON.parse(v) : v : v];
|
|
2214
|
-
} catch {
|
|
2215
|
-
return [k, v];
|
|
2216
|
-
}
|
|
2217
|
-
}));
|
|
2218
|
-
});
|
|
2218
|
+
})).rows ?? []).map((row) => parseJsonColumns(tableName, row ?? {}));
|
|
2219
2219
|
}
|
|
2220
2220
|
/**
|
|
2221
2221
|
* Returns the total count of records matching the optional WHERE clause.
|
|
@@ -3363,14 +3363,14 @@ function cutoffFor(policy, anchorType, now = Date.now()) {
|
|
|
3363
3363
|
return anchorType === "epoch-ms" ? cutoffMs : new Date(cutoffMs).toISOString();
|
|
3364
3364
|
}
|
|
3365
3365
|
const runBatchedDelete = _mastra_core_storage.runRetentionBatches;
|
|
3366
|
-
function runPrune({ db, domain, targets, options, logger }) {
|
|
3366
|
+
function runPrune({ db, domain, targets, options, logger, deleteBatch }) {
|
|
3367
3367
|
return (0, _mastra_core_storage.executeRetentionPrune)({
|
|
3368
3368
|
domain,
|
|
3369
3369
|
targets,
|
|
3370
3370
|
options,
|
|
3371
3371
|
beforeTarget: (target) => ensureAnchorIndex(db, target, logger),
|
|
3372
3372
|
cutoffFor: (target, now) => cutoffFor(target.policy, target.anchorType ?? "timestamp", now),
|
|
3373
|
-
deleteBatch: (target, cutoff, limit) => db.pruneBatch({
|
|
3373
|
+
deleteBatch: (target, cutoff, limit) => deleteBatch?.(target, cutoff, limit) ?? db.pruneBatch({
|
|
3374
3374
|
tableName: target.table,
|
|
3375
3375
|
column: target.column,
|
|
3376
3376
|
cutoff,
|
|
@@ -15136,6 +15136,228 @@ var WorkflowDefinitionsLibSQL = class extends _mastra_core_storage.WorkflowDefin
|
|
|
15136
15136
|
};
|
|
15137
15137
|
// src/storage/domains/workflows/index.ts
|
|
15138
15138
|
const RUN_OWNER_COLUMNS = `generation, ownerId, leaseExpiresAt, ${DB_NOW_MS} AS nowMs`;
|
|
15139
|
+
/**
|
|
15140
|
+
* The entries a storage v2 write adds: one per step, in order, then one per step patch, then the
|
|
15141
|
+
* state or state base (a checkpoint with neither starts the state over at `{}`), then the state
|
|
15142
|
+
* patch unless a full state was given.
|
|
15143
|
+
*/
|
|
15144
|
+
function journalEntries(steps, { state, stateBase, statePatch }, checkpoint, stepPatches = {}) {
|
|
15145
|
+
const entries = Object.entries(steps).map(([stepId, result]) => ({
|
|
15146
|
+
kind: "step",
|
|
15147
|
+
step_id: stepId,
|
|
15148
|
+
payload: result
|
|
15149
|
+
}));
|
|
15150
|
+
for (const [stepId, ops] of Object.entries(stepPatches)) entries.push({
|
|
15151
|
+
kind: "step-patch",
|
|
15152
|
+
step_id: stepId,
|
|
15153
|
+
payload: ops
|
|
15154
|
+
});
|
|
15155
|
+
if (state !== void 0) entries.push({
|
|
15156
|
+
kind: "state",
|
|
15157
|
+
step_id: null,
|
|
15158
|
+
payload: state
|
|
15159
|
+
});
|
|
15160
|
+
else if (stateBase !== void 0) entries.push({
|
|
15161
|
+
kind: "state-base",
|
|
15162
|
+
step_id: null,
|
|
15163
|
+
payload: stateBase
|
|
15164
|
+
});
|
|
15165
|
+
else if (checkpoint) entries.push({
|
|
15166
|
+
kind: "state",
|
|
15167
|
+
step_id: null,
|
|
15168
|
+
payload: {}
|
|
15169
|
+
});
|
|
15170
|
+
if (state === void 0 && statePatch !== void 0) entries.push({
|
|
15171
|
+
kind: "state-patch",
|
|
15172
|
+
step_id: null,
|
|
15173
|
+
payload: statePatch
|
|
15174
|
+
});
|
|
15175
|
+
return entries;
|
|
15176
|
+
}
|
|
15177
|
+
/**
|
|
15178
|
+
* Upserts a storage v2 run's header, adds `entryCount` (the number of entries the write adds) to
|
|
15179
|
+
* its `lastSeq`, for {@link insertEntries} to number them up to, and returns the new `lastSeq` and
|
|
15180
|
+
* the `runToken` (picked when the write creates the run, otherwise the stored one). A checkpoint's
|
|
15181
|
+
* state entries come last, so its `startStateSeq` is the new `lastSeq`; an append keeps the stored
|
|
15182
|
+
* one unless given `startStateSeq`.
|
|
15183
|
+
*/
|
|
15184
|
+
function upsertHeader(run, entryCount, write) {
|
|
15185
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
15186
|
+
const startStateSeq = write.checkpoint ? {
|
|
15187
|
+
insert: "?",
|
|
15188
|
+
update: `${_mastra_core_storage.TABLE_WORKFLOW_RUNS}.lastSeq + excluded.lastSeq`,
|
|
15189
|
+
args: [entryCount]
|
|
15190
|
+
} : {
|
|
15191
|
+
insert: "COALESCE(?, 0)",
|
|
15192
|
+
update: `COALESCE(?, ${_mastra_core_storage.TABLE_WORKFLOW_RUNS}.startStateSeq)`,
|
|
15193
|
+
args: [write.startStateSeq ?? null]
|
|
15194
|
+
};
|
|
15195
|
+
return {
|
|
15196
|
+
sql: `INSERT INTO ${_mastra_core_storage.TABLE_WORKFLOW_RUNS}
|
|
15197
|
+
(workflow_name, run_id, resourceId, threadId, status, header, lastSeq, startStateSeq, stateShared, runToken, createdAt, updatedAt)
|
|
15198
|
+
VALUES (?, ?, ?, ?, ?, jsonb(?), ?, ${startStateSeq.insert}, 0, ?, ?, ?)
|
|
15199
|
+
ON CONFLICT(workflow_name, run_id) DO UPDATE SET
|
|
15200
|
+
resourceId = COALESCE(excluded.resourceId, ${_mastra_core_storage.TABLE_WORKFLOW_RUNS}.resourceId), threadId = excluded.threadId,
|
|
15201
|
+
status = excluded.status, header = excluded.header, lastSeq = ${_mastra_core_storage.TABLE_WORKFLOW_RUNS}.lastSeq + excluded.lastSeq,
|
|
15202
|
+
startStateSeq = ${startStateSeq.update}, updatedAt = excluded.updatedAt
|
|
15203
|
+
RETURNING lastSeq, runToken`,
|
|
15204
|
+
args: [
|
|
15205
|
+
run.workflowName,
|
|
15206
|
+
run.runId,
|
|
15207
|
+
run.resourceId ?? null,
|
|
15208
|
+
run.threadId ?? null,
|
|
15209
|
+
run.header.status,
|
|
15210
|
+
safeStringify(run.header),
|
|
15211
|
+
entryCount,
|
|
15212
|
+
...startStateSeq.args,
|
|
15213
|
+
crypto.randomUUID(),
|
|
15214
|
+
now,
|
|
15215
|
+
now,
|
|
15216
|
+
...write.checkpoint ? [] : startStateSeq.args
|
|
15217
|
+
]
|
|
15218
|
+
};
|
|
15219
|
+
}
|
|
15220
|
+
/**
|
|
15221
|
+
* Inserts the entries in the JSON array parameter after the run's header has been bumped by
|
|
15222
|
+
* their count, numbering them up to the header's `lastSeq`. `-> '$.payload'` keeps a JSON null
|
|
15223
|
+
* apart from an undefined payload (dropped by `JSON.stringify`), which becomes SQL NULL.
|
|
15224
|
+
* Args: entry count, entries JSON, workflow name, run id.
|
|
15225
|
+
*/
|
|
15226
|
+
const INSERT_ENTRIES = `INSERT INTO ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} (workflow_name, run_id, seq, kind, step_id, payload)
|
|
15227
|
+
SELECT h.workflow_name, h.run_id, h.lastSeq - ? + j.key + 1, j.value ->> '$.kind', j.value ->> '$.step_id', jsonb(j.value -> '$.payload')
|
|
15228
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} h, json_each(?) j
|
|
15229
|
+
WHERE h.workflow_name = ? AND h.run_id = ?`;
|
|
15230
|
+
function insertEntries(run, entries) {
|
|
15231
|
+
return {
|
|
15232
|
+
sql: INSERT_ENTRIES,
|
|
15233
|
+
args: [
|
|
15234
|
+
entries.length,
|
|
15235
|
+
safeStringify(entries),
|
|
15236
|
+
run.workflowName,
|
|
15237
|
+
run.runId
|
|
15238
|
+
]
|
|
15239
|
+
};
|
|
15240
|
+
}
|
|
15241
|
+
/**
|
|
15242
|
+
* The run a `state-base` entry's payload names: the expressions of the state base index, which
|
|
15243
|
+
* a lookup must repeat exactly to use it.
|
|
15244
|
+
*/
|
|
15245
|
+
const STATE_BASE_WORKFLOW_EXPR = `payload ->> '$.workflowName'`;
|
|
15246
|
+
const STATE_BASE_RUN_EXPR = `payload ->> '$.runId'`;
|
|
15247
|
+
/**
|
|
15248
|
+
* A JSON array of {@link EntryRow} for the storage v2 run `alias` refers to: each step's
|
|
15249
|
+
* latest entry, the step patches after it (for `latestStepResults`), and the entries
|
|
15250
|
+
* `materializeState` uses for the latest state: the latest full state or state base and every
|
|
15251
|
+
* state patch after it. Drafts are left out.
|
|
15252
|
+
*
|
|
15253
|
+
* With `summary`, successful steps other than `input` come back as their summary, built here
|
|
15254
|
+
* so their data is never sent, unless step patches follow it (the caller summarizes the patched
|
|
15255
|
+
* result instead). Like `summarizeStepResult`, it keeps a field that is JSON null
|
|
15256
|
+
* and leaves out one that is absent. It then takes one arg, `STEP_RESULT_SUMMARY_FIELDS` as
|
|
15257
|
+
* JSON, bound where this SQL sits in the statement.
|
|
15258
|
+
*/
|
|
15259
|
+
function entriesSql(alias, { summary } = {}) {
|
|
15260
|
+
let payload = "json(x.payload)";
|
|
15261
|
+
if (summary) {
|
|
15262
|
+
const summarized = `(x.kind = 'step' AND x.step_id <> 'input' AND x.payload ->> '$.status' = 'success'
|
|
15263
|
+
AND (x.patch_seq IS NULL OR x.patch_seq < x.seq))`;
|
|
15264
|
+
payload = `json(CASE WHEN ${summarized} THEN (
|
|
15265
|
+
SELECT json_group_object(f.key, json(x.payload -> f.fullkey))
|
|
15266
|
+
FROM json_each(x.payload) f WHERE f.key IN (SELECT value FROM json_each(?))
|
|
15267
|
+
) ELSE x.payload END), 'summarized', ${summarized}`;
|
|
15268
|
+
}
|
|
15269
|
+
return `(SELECT json_group_array(json_object(
|
|
15270
|
+
'seq', x.seq, 'ord', CASE WHEN x.kind = 'step' THEN x.first_seq ELSE x.seq END, 'kind', x.kind, 'step_id', x.step_id,
|
|
15271
|
+
'absent', x.payload IS NULL, 'payload', ${payload}
|
|
15272
|
+
))
|
|
15273
|
+
FROM (
|
|
15274
|
+
SELECT e.seq, e.kind, e.step_id, e.payload,
|
|
15275
|
+
ROW_NUMBER() OVER (PARTITION BY e.kind, e.step_id ORDER BY e.seq DESC) AS rn,
|
|
15276
|
+
MIN(e.seq) OVER (PARTITION BY e.kind, e.step_id) AS first_seq,
|
|
15277
|
+
MAX(CASE WHEN e.kind = 'step' THEN e.seq END) OVER (PARTITION BY e.step_id) AS step_seq,
|
|
15278
|
+
MAX(CASE WHEN e.kind = 'step-patch' THEN e.seq END) OVER (PARTITION BY e.step_id) AS patch_seq,
|
|
15279
|
+
MAX(CASE WHEN e.kind IN ('state', 'state-base') THEN e.seq END) OVER () AS base_seq
|
|
15280
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} e
|
|
15281
|
+
WHERE e.workflow_name = ${alias}.workflow_name AND e.run_id = ${alias}.run_id AND e.kind <> 'state-draft'
|
|
15282
|
+
) x
|
|
15283
|
+
WHERE CASE x.kind
|
|
15284
|
+
WHEN 'step' THEN x.rn = 1
|
|
15285
|
+
WHEN 'step-patch' THEN x.seq > x.step_seq
|
|
15286
|
+
ELSE x.base_seq IS NULL OR x.seq >= x.base_seq
|
|
15287
|
+
END)`;
|
|
15288
|
+
}
|
|
15289
|
+
/**
|
|
15290
|
+
* A JSON array of {@link EntryRow} with the entries `materializeState` uses for the state of the
|
|
15291
|
+
* storage v2 run `alias` refers to as of a version. For a draft, every state entry up to it, as
|
|
15292
|
+
* the drafts it is on can build on any earlier version; otherwise the latest full state or state
|
|
15293
|
+
* base up to it and the state patches after it. Takes two args, bound where this SQL sits in the
|
|
15294
|
+
* statement: the version's `seq`, then 1 when it is a draft, else 0.
|
|
15295
|
+
*/
|
|
15296
|
+
function stateEntriesSql(alias) {
|
|
15297
|
+
return `(SELECT json_group_array(json_object(
|
|
15298
|
+
'seq', x.seq, 'ord', x.seq, 'kind', x.kind, 'step_id', x.step_id, 'absent', x.payload IS NULL, 'payload', json(x.payload)
|
|
15299
|
+
))
|
|
15300
|
+
FROM (
|
|
15301
|
+
SELECT e.seq, e.kind, e.step_id, e.payload,
|
|
15302
|
+
MAX(CASE WHEN e.kind IN ('state', 'state-base') THEN e.seq END) OVER () AS base_seq
|
|
15303
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} e
|
|
15304
|
+
WHERE e.workflow_name = ${alias}.workflow_name AND e.run_id = ${alias}.run_id
|
|
15305
|
+
AND e.kind NOT IN ('step', 'step-patch') AND e.seq <= ?
|
|
15306
|
+
) x
|
|
15307
|
+
WHERE ? OR (x.kind <> 'state-draft' AND (x.base_seq IS NULL OR x.seq >= x.base_seq)))`;
|
|
15308
|
+
}
|
|
15309
|
+
/** `entriesSql`, `stateEntriesSql` or `loadWorkflowRunSteps` rows, in the order to apply them. */
|
|
15310
|
+
function entryRows(json) {
|
|
15311
|
+
return JSON.parse(json).sort((a, b) => a.ord - b.ord);
|
|
15312
|
+
}
|
|
15313
|
+
/** The entries of {@link entryRows}; an undefined payload reads back as undefined, as in v1. */
|
|
15314
|
+
function toEntries(rows) {
|
|
15315
|
+
return rows.map((row) => {
|
|
15316
|
+
const payload = row.absent ? void 0 : row.payload;
|
|
15317
|
+
switch (row.kind) {
|
|
15318
|
+
case "step": return {
|
|
15319
|
+
seq: row.seq,
|
|
15320
|
+
kind: "step",
|
|
15321
|
+
stepId: row.step_id,
|
|
15322
|
+
result: payload
|
|
15323
|
+
};
|
|
15324
|
+
case "step-patch": return {
|
|
15325
|
+
seq: row.seq,
|
|
15326
|
+
kind: "step-patch",
|
|
15327
|
+
stepId: row.step_id,
|
|
15328
|
+
ops: payload
|
|
15329
|
+
};
|
|
15330
|
+
case "state": return {
|
|
15331
|
+
seq: row.seq,
|
|
15332
|
+
kind: "state",
|
|
15333
|
+
state: payload
|
|
15334
|
+
};
|
|
15335
|
+
case "state-patch": return {
|
|
15336
|
+
seq: row.seq,
|
|
15337
|
+
kind: "state-patch",
|
|
15338
|
+
ops: payload
|
|
15339
|
+
};
|
|
15340
|
+
case "state-base": return {
|
|
15341
|
+
seq: row.seq,
|
|
15342
|
+
kind: "state-base",
|
|
15343
|
+
base: payload
|
|
15344
|
+
};
|
|
15345
|
+
case "state-draft": {
|
|
15346
|
+
const draft = payload;
|
|
15347
|
+
return "state" in draft ? {
|
|
15348
|
+
seq: row.seq,
|
|
15349
|
+
kind: "state-draft",
|
|
15350
|
+
state: draft.state
|
|
15351
|
+
} : {
|
|
15352
|
+
seq: row.seq,
|
|
15353
|
+
kind: "state-draft",
|
|
15354
|
+
on: draft.on,
|
|
15355
|
+
ops: draft.ops
|
|
15356
|
+
};
|
|
15357
|
+
}
|
|
15358
|
+
}
|
|
15359
|
+
});
|
|
15360
|
+
}
|
|
15139
15361
|
function toRunOwnershipRecord(runId, row) {
|
|
15140
15362
|
const leaseExpiresAt = row.leaseExpiresAt === null ? null : Number(row.leaseExpiresAt);
|
|
15141
15363
|
return {
|
|
@@ -15226,14 +15448,36 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15226
15448
|
tableName: _mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS,
|
|
15227
15449
|
schema: _mastra_core_storage.RUN_FENCING_TABLE_SCHEMAS[_mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS]
|
|
15228
15450
|
});
|
|
15451
|
+
for (const [tableName, config] of Object.entries(_mastra_core_storage.WORKFLOW_RUN_JOURNAL_TABLE_CONFIGS)) await this.#db.createTable({
|
|
15452
|
+
tableName,
|
|
15453
|
+
schema: config.columns,
|
|
15454
|
+
compositePrimaryKey: config.compositePrimaryKey
|
|
15455
|
+
});
|
|
15456
|
+
await withClientWriteLock(this.#client, () => this.#client.batch([
|
|
15457
|
+
`CREATE INDEX IF NOT EXISTS mastra_workflow_runs_name_createdat_idx ON ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} (workflow_name, createdAt DESC)`,
|
|
15458
|
+
`CREATE INDEX IF NOT EXISTS mastra_workflow_runs_name_status_createdat_idx ON ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} (workflow_name, status, createdAt DESC)`,
|
|
15459
|
+
`CREATE INDEX IF NOT EXISTS mastra_workflow_runs_threadid_idx ON ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} (threadId)`,
|
|
15460
|
+
`CREATE INDEX IF NOT EXISTS mastra_workflow_run_entries_step_idx ON ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} (workflow_name, run_id, kind, step_id, seq)`,
|
|
15461
|
+
`CREATE INDEX IF NOT EXISTS mastra_workflow_run_entries_state_base_idx ON ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES}
|
|
15462
|
+
(${STATE_BASE_WORKFLOW_EXPR}, ${STATE_BASE_RUN_EXPR}) WHERE kind = 'state-base'`
|
|
15463
|
+
].map((sql) => ({
|
|
15464
|
+
sql,
|
|
15465
|
+
args: []
|
|
15466
|
+
})), "write"));
|
|
15229
15467
|
}
|
|
15230
15468
|
async dangerouslyClearAll() {
|
|
15231
15469
|
await this.#db.deleteData({ tableName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT });
|
|
15232
15470
|
await this.#db.deleteData({ tableName: _mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS });
|
|
15471
|
+
await this.#db.deleteData({ tableName: _mastra_core_storage.TABLE_WORKFLOW_RUNS });
|
|
15472
|
+
await this.#db.deleteData({ tableName: _mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES });
|
|
15233
15473
|
}
|
|
15234
15474
|
supportsRunFencing() {
|
|
15235
15475
|
return true;
|
|
15236
15476
|
}
|
|
15477
|
+
/** @experimental */
|
|
15478
|
+
supportsRunJournal() {
|
|
15479
|
+
return true;
|
|
15480
|
+
}
|
|
15237
15481
|
#runFenceCheck(fence, runId, operation) {
|
|
15238
15482
|
const resolved = (0, _mastra_core_storage.resolveRunFence)(this, fence, runId);
|
|
15239
15483
|
return resolved && {
|
|
@@ -15242,6 +15486,399 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15242
15486
|
operation
|
|
15243
15487
|
};
|
|
15244
15488
|
}
|
|
15489
|
+
/**
|
|
15490
|
+
* Runs a storage v2 write's statements behind the run's fence. With `expectedStatus` or
|
|
15491
|
+
* `stateBase`, in a write transaction that first reads the stored run: it writes nothing
|
|
15492
|
+
* (resolving to null) when the run is stored and its status doesn't match `expectedStatus`, and
|
|
15493
|
+
* throws when the state version `stateBase` names isn't stored.
|
|
15494
|
+
*/
|
|
15495
|
+
#writeRun(check, run, { expectedStatus, stateBase }, statements) {
|
|
15496
|
+
if (expectedStatus === void 0 && stateBase === void 0) return withRunFence(this.#client, check, (writer) => writer.batch(statements));
|
|
15497
|
+
return inWriteTransaction(this.#client, async (tx) => {
|
|
15498
|
+
if (check) await assertRunFence(tx, check);
|
|
15499
|
+
if (expectedStatus !== void 0) {
|
|
15500
|
+
const { rows } = await tx.execute({
|
|
15501
|
+
sql: `SELECT status FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?`,
|
|
15502
|
+
args: [run.workflowName, run.runId]
|
|
15503
|
+
});
|
|
15504
|
+
if (rows[0] && !(0, _mastra_core_storage.matchesExpectedWorkflowStatus)(rows[0].status, expectedStatus)) return null;
|
|
15505
|
+
}
|
|
15506
|
+
if (stateBase !== void 0) {
|
|
15507
|
+
const { rows } = await tx.execute({
|
|
15508
|
+
sql: `SELECT 1 FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} WHERE workflow_name = ? AND run_id = ?
|
|
15509
|
+
AND CASE WHEN ? THEN kind = 'state-draft' AND seq = ? ELSE kind IN ('state', 'state-base') AND seq <= ? END
|
|
15510
|
+
AND ? <= (SELECT lastSeq FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?)
|
|
15511
|
+
LIMIT 1`,
|
|
15512
|
+
args: [
|
|
15513
|
+
stateBase.workflowName,
|
|
15514
|
+
stateBase.runId,
|
|
15515
|
+
stateBase.draft ? 1 : 0,
|
|
15516
|
+
stateBase.seq,
|
|
15517
|
+
stateBase.seq,
|
|
15518
|
+
stateBase.seq,
|
|
15519
|
+
stateBase.workflowName,
|
|
15520
|
+
stateBase.runId
|
|
15521
|
+
]
|
|
15522
|
+
});
|
|
15523
|
+
if (!rows[0]) throw new Error(`Workflow run ${run.workflowName}/${run.runId} builds on state version ${stateBase.seq} of ${stateBase.workflowName}/${stateBase.runId}, which is not stored`);
|
|
15524
|
+
}
|
|
15525
|
+
const results = [];
|
|
15526
|
+
for (const statement of statements) results.push(await tx.execute(statement));
|
|
15527
|
+
return results;
|
|
15528
|
+
});
|
|
15529
|
+
}
|
|
15530
|
+
/**
|
|
15531
|
+
* Selects v1 snapshot rows and storage v2 runs as one result, newest first. Each version
|
|
15532
|
+
* has its own WHERE clause; `null` leaves it out. Storage v2 rows carry their header and
|
|
15533
|
+
* entries, or in summary mode only the summary snapshot. `page` is appended to the
|
|
15534
|
+
* combined, ordered rows (e.g. `LIMIT 1`). Bind the v1 args, then the v2 args, then `page`'s.
|
|
15535
|
+
*/
|
|
15536
|
+
#runsSql({ v1Where, v2Where, summary, page = "" }) {
|
|
15537
|
+
const branches = [];
|
|
15538
|
+
if (v1Where !== null) {
|
|
15539
|
+
const snapshot = summary ? `json_object('status', json_extract(snapshot, '$.status'), 'timestamp', json_extract(snapshot, '$.timestamp'))` : "json(snapshot)";
|
|
15540
|
+
branches.push(`SELECT workflow_name, run_id, resourceId, ${snapshot} AS snapshot, NULL AS header, createdAt, updatedAt, 1 AS version
|
|
15541
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT} ${v1Where}`);
|
|
15542
|
+
}
|
|
15543
|
+
if (v2Where !== null) {
|
|
15544
|
+
const columns = summary ? `json_object('status', status, 'timestamp', json_extract(header, '$.timestamp')) AS snapshot, NULL AS header` : "NULL AS snapshot, json(header) AS header";
|
|
15545
|
+
branches.push(`SELECT workflow_name, run_id, resourceId, ${columns}, createdAt, updatedAt, 2 AS version
|
|
15546
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} ${v2Where}`);
|
|
15547
|
+
}
|
|
15548
|
+
return `SELECT p.*${summary ? "" : `, CASE WHEN p.version = 2 THEN ${entriesSql("p")} END AS entries`}
|
|
15549
|
+
FROM (${branches.join(" UNION ALL ")} ORDER BY createdAt DESC ${page}) p
|
|
15550
|
+
ORDER BY p.createdAt DESC`;
|
|
15551
|
+
}
|
|
15552
|
+
/**
|
|
15553
|
+
* The `base` that `materializeState` takes for a run's entries (as of `at`, or latest): the state
|
|
15554
|
+
* version of another run it builds on (`stateBaseOf`), resolved recursively, else undefined. `{}`
|
|
15555
|
+
* when that run isn't stored. One query per run in the chain.
|
|
15556
|
+
*/
|
|
15557
|
+
async #stateBase(q, entries, at) {
|
|
15558
|
+
const ref = (0, _mastra_core_storage.stateBaseOf)(entries, at);
|
|
15559
|
+
if (!ref) return void 0;
|
|
15560
|
+
return (await this.#stateAt(q, ref.workflowName, ref.runId, ref))?.state ?? {};
|
|
15561
|
+
}
|
|
15562
|
+
/** A storage v2 run's state as of the version `at`, or null when the run isn't stored. */
|
|
15563
|
+
async #stateAt(q, workflowName, runId, at) {
|
|
15564
|
+
const row = (await q.execute({
|
|
15565
|
+
sql: `SELECT ${stateEntriesSql("r")} AS entries
|
|
15566
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} r WHERE r.workflow_name = ? AND r.run_id = ?`,
|
|
15567
|
+
args: [
|
|
15568
|
+
at.seq,
|
|
15569
|
+
at.draft === true ? 1 : 0,
|
|
15570
|
+
workflowName,
|
|
15571
|
+
runId
|
|
15572
|
+
]
|
|
15573
|
+
})).rows[0];
|
|
15574
|
+
if (!row) return null;
|
|
15575
|
+
const entries = toEntries(entryRows(row.entries));
|
|
15576
|
+
return (0, _mastra_core_storage.materializeState)(entries, {
|
|
15577
|
+
at,
|
|
15578
|
+
base: await this.#stateBase(q, entries, at)
|
|
15579
|
+
});
|
|
15580
|
+
}
|
|
15581
|
+
/**
|
|
15582
|
+
* Before a run is deleted, stores the full state in place of every `state-base` entry built on
|
|
15583
|
+
* it, so the runs built on it keep reading the same state. Runs inside the delete's transaction.
|
|
15584
|
+
*/
|
|
15585
|
+
async #detachStateChildren(q, workflowName, runId) {
|
|
15586
|
+
const children = await q.execute({
|
|
15587
|
+
sql: `SELECT workflow_name, run_id, seq, json(payload) AS payload FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES}
|
|
15588
|
+
WHERE kind = 'state-base' AND ${STATE_BASE_WORKFLOW_EXPR} = ? AND ${STATE_BASE_RUN_EXPR} = ?`,
|
|
15589
|
+
args: [workflowName, runId]
|
|
15590
|
+
});
|
|
15591
|
+
const states = /* @__PURE__ */ new Map();
|
|
15592
|
+
for (const child of children.rows) {
|
|
15593
|
+
const ref = JSON.parse(child.payload);
|
|
15594
|
+
const version = `${ref.seq}:${ref.draft === true}`;
|
|
15595
|
+
let state = states.get(version);
|
|
15596
|
+
if (!state) {
|
|
15597
|
+
state = (await this.#stateAt(q, workflowName, runId, ref))?.state ?? {};
|
|
15598
|
+
states.set(version, state);
|
|
15599
|
+
}
|
|
15600
|
+
await q.execute({
|
|
15601
|
+
sql: `UPDATE ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} SET kind = 'state', payload = jsonb(?)
|
|
15602
|
+
WHERE workflow_name = ? AND run_id = ? AND seq = ?`,
|
|
15603
|
+
args: [
|
|
15604
|
+
safeStringify(state),
|
|
15605
|
+
child.workflow_name,
|
|
15606
|
+
child.run_id,
|
|
15607
|
+
child.seq
|
|
15608
|
+
]
|
|
15609
|
+
});
|
|
15610
|
+
}
|
|
15611
|
+
}
|
|
15612
|
+
/** Rebuilds a storage v2 run's `WorkflowRunState` from its header and `entriesSql` JSON. */
|
|
15613
|
+
async #materializeRun(q, header, rows) {
|
|
15614
|
+
const parsedHeader = typeof header === "string" ? JSON.parse(header) : header;
|
|
15615
|
+
const entries = toEntries(entryRows(rows));
|
|
15616
|
+
return (0, _mastra_core_storage.materializeWorkflowRun)(parsedHeader, entries, await this.#stateBase(q, entries));
|
|
15617
|
+
}
|
|
15618
|
+
/** Parses a row of `#runsSql`. */
|
|
15619
|
+
async #parseRun(row) {
|
|
15620
|
+
if (Number(row.version) !== 2) return this.parseWorkflowRun(row);
|
|
15621
|
+
const snapshot = row.entries ? await this.#materializeRun(this.#client, row.header, row.entries) : row.snapshot;
|
|
15622
|
+
return {
|
|
15623
|
+
...this.parseWorkflowRun({
|
|
15624
|
+
...row,
|
|
15625
|
+
snapshot
|
|
15626
|
+
}),
|
|
15627
|
+
storageVersion: 2
|
|
15628
|
+
};
|
|
15629
|
+
}
|
|
15630
|
+
#runError(operation, workflowName, runId, error) {
|
|
15631
|
+
return new _mastra_core_error.MastraError({
|
|
15632
|
+
id: (0, _mastra_core_storage.createStorageErrorId)("LIBSQL", operation, "FAILED"),
|
|
15633
|
+
domain: _mastra_core_error.ErrorDomain.STORAGE,
|
|
15634
|
+
category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
|
|
15635
|
+
details: {
|
|
15636
|
+
workflowName,
|
|
15637
|
+
runId
|
|
15638
|
+
}
|
|
15639
|
+
}, error);
|
|
15640
|
+
}
|
|
15641
|
+
async loadWorkflowRunHeader({ workflowName, runId }) {
|
|
15642
|
+
try {
|
|
15643
|
+
const row = (await this.#client.execute({
|
|
15644
|
+
sql: `SELECT json(header) AS header, lastSeq, startStateSeq, runToken FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?`,
|
|
15645
|
+
args: [workflowName, runId]
|
|
15646
|
+
})).rows[0];
|
|
15647
|
+
return row ? {
|
|
15648
|
+
header: JSON.parse(row.header),
|
|
15649
|
+
lastSeq: Number(row.lastSeq),
|
|
15650
|
+
startStateSeq: Number(row.startStateSeq),
|
|
15651
|
+
runToken: row.runToken
|
|
15652
|
+
} : null;
|
|
15653
|
+
} catch (error) {
|
|
15654
|
+
throw this.#runError("LOAD_WORKFLOW_RUN_HEADER", workflowName, runId, error);
|
|
15655
|
+
}
|
|
15656
|
+
}
|
|
15657
|
+
async loadWorkflowRun({ workflowName, runId, successfulSteps }) {
|
|
15658
|
+
try {
|
|
15659
|
+
const summary = successfulSteps === "summary";
|
|
15660
|
+
const run = (await this.#client.execute({
|
|
15661
|
+
sql: `SELECT json(r.header) AS header, r.lastSeq, r.startStateSeq, r.runToken, ${entriesSql("r", { summary })} AS entries
|
|
15662
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} r WHERE r.workflow_name = ? AND r.run_id = ?`,
|
|
15663
|
+
args: summary ? [
|
|
15664
|
+
JSON.stringify(_mastra_core_storage.STEP_RESULT_SUMMARY_FIELDS),
|
|
15665
|
+
workflowName,
|
|
15666
|
+
runId
|
|
15667
|
+
] : [workflowName, runId]
|
|
15668
|
+
})).rows[0];
|
|
15669
|
+
if (!run) return null;
|
|
15670
|
+
const header = JSON.parse(run.header);
|
|
15671
|
+
const rows = entryRows(run.entries);
|
|
15672
|
+
const entries = toEntries(rows);
|
|
15673
|
+
const summarizedInQuery = new Set(rows.filter((row) => row.summarized).map((row) => row.step_id));
|
|
15674
|
+
const steps = {};
|
|
15675
|
+
const summarizedStepIds = [];
|
|
15676
|
+
for (const [stepId, result] of (0, _mastra_core_storage.latestStepResults)(entries)) {
|
|
15677
|
+
steps[stepId] = result;
|
|
15678
|
+
if (summary && stepId !== "input" && result?.status === "success") {
|
|
15679
|
+
if (!summarizedInQuery.has(stepId)) steps[stepId] = (0, _mastra_core_storage.summarizeStepResult)(result);
|
|
15680
|
+
summarizedStepIds.push(stepId);
|
|
15681
|
+
}
|
|
15682
|
+
}
|
|
15683
|
+
const base = await this.#stateBase(this.#client, entries);
|
|
15684
|
+
const { state, statePatchBytes } = (0, _mastra_core_storage.materializeState)(entries, { base });
|
|
15685
|
+
return {
|
|
15686
|
+
header,
|
|
15687
|
+
lastSeq: Number(run.lastSeq),
|
|
15688
|
+
startStateSeq: Number(run.startStateSeq),
|
|
15689
|
+
runToken: run.runToken,
|
|
15690
|
+
state,
|
|
15691
|
+
statePatchBytes,
|
|
15692
|
+
steps,
|
|
15693
|
+
summarizedStepIds
|
|
15694
|
+
};
|
|
15695
|
+
} catch (error) {
|
|
15696
|
+
throw this.#runError("LOAD_WORKFLOW_RUN", workflowName, runId, error);
|
|
15697
|
+
}
|
|
15698
|
+
}
|
|
15699
|
+
async loadWorkflowRunSteps({ workflowName, runId, stepIds, expectedLastSeq, expectedRunToken }) {
|
|
15700
|
+
try {
|
|
15701
|
+
const run = (await this.#client.execute({
|
|
15702
|
+
sql: `SELECT r.lastSeq, r.runToken, (SELECT json_group_array(json_object(
|
|
15703
|
+
'seq', x.seq, 'ord', x.seq, 'kind', x.kind, 'step_id', x.step_id, 'absent', x.payload IS NULL, 'payload', json(x.payload)
|
|
15704
|
+
))
|
|
15705
|
+
FROM (
|
|
15706
|
+
SELECT e.seq, e.kind, e.step_id, e.payload,
|
|
15707
|
+
MAX(CASE WHEN e.kind = 'step' THEN e.seq END) OVER (PARTITION BY e.step_id) AS step_seq
|
|
15708
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} e
|
|
15709
|
+
WHERE e.workflow_name = r.workflow_name AND e.run_id = r.run_id AND e.kind IN ('step', 'step-patch')
|
|
15710
|
+
AND e.step_id IN (SELECT value FROM json_each(?))
|
|
15711
|
+
) x
|
|
15712
|
+
WHERE x.seq >= x.step_seq) AS entries
|
|
15713
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} r WHERE r.workflow_name = ? AND r.run_id = ?`,
|
|
15714
|
+
args: [
|
|
15715
|
+
JSON.stringify(stepIds),
|
|
15716
|
+
workflowName,
|
|
15717
|
+
runId
|
|
15718
|
+
]
|
|
15719
|
+
})).rows[0];
|
|
15720
|
+
if (!run) return null;
|
|
15721
|
+
if (expectedLastSeq !== void 0 && Number(run.lastSeq) !== expectedLastSeq) return null;
|
|
15722
|
+
if (expectedRunToken !== void 0 && run.runToken !== expectedRunToken) return null;
|
|
15723
|
+
return Object.fromEntries((0, _mastra_core_storage.latestStepResults)(toEntries(entryRows(run.entries))));
|
|
15724
|
+
} catch (error) {
|
|
15725
|
+
throw this.#runError("LOAD_WORKFLOW_RUN_STEPS", workflowName, runId, error);
|
|
15726
|
+
}
|
|
15727
|
+
}
|
|
15728
|
+
async updateWorkflowRunHeader({ workflowName, runId, opts, fence }) {
|
|
15729
|
+
const check = this.#runFenceCheck(fence, runId, "updateWorkflowRunHeader");
|
|
15730
|
+
try {
|
|
15731
|
+
return await this.executeWithRetry(() => inWriteTransaction(this.#client, async (tx) => {
|
|
15732
|
+
if (check) await assertRunFence(tx, check);
|
|
15733
|
+
const row = (await tx.execute({
|
|
15734
|
+
sql: `SELECT json(header) AS header, lastSeq, startStateSeq, runToken FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?`,
|
|
15735
|
+
args: [workflowName, runId]
|
|
15736
|
+
})).rows[0];
|
|
15737
|
+
if (!row) return void 0;
|
|
15738
|
+
const current = JSON.parse(row.header);
|
|
15739
|
+
const { expectedStatus, ...patch } = opts;
|
|
15740
|
+
if (!(0, _mastra_core_storage.matchesExpectedWorkflowStatus)(current.status, expectedStatus)) return void 0;
|
|
15741
|
+
const header = {
|
|
15742
|
+
...current,
|
|
15743
|
+
...patch
|
|
15744
|
+
};
|
|
15745
|
+
await tx.execute({
|
|
15746
|
+
sql: `UPDATE ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} SET header = jsonb(?), status = ?, updatedAt = ? WHERE workflow_name = ? AND run_id = ?`,
|
|
15747
|
+
args: [
|
|
15748
|
+
safeStringify(header),
|
|
15749
|
+
header.status,
|
|
15750
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
15751
|
+
workflowName,
|
|
15752
|
+
runId
|
|
15753
|
+
]
|
|
15754
|
+
});
|
|
15755
|
+
return {
|
|
15756
|
+
header,
|
|
15757
|
+
lastSeq: Number(row.lastSeq),
|
|
15758
|
+
startStateSeq: Number(row.startStateSeq),
|
|
15759
|
+
runToken: row.runToken
|
|
15760
|
+
};
|
|
15761
|
+
}), "updateWorkflowRunHeader");
|
|
15762
|
+
} catch (error) {
|
|
15763
|
+
if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
|
|
15764
|
+
throw this.#runError("UPDATE_WORKFLOW_RUN_HEADER", workflowName, runId, error);
|
|
15765
|
+
}
|
|
15766
|
+
}
|
|
15767
|
+
/**
|
|
15768
|
+
* One batch behind the write lock (see `#writeRun` for `expectedStatus` and `stateBase`): marking
|
|
15769
|
+
* the run a state base builds on as shared, the header upsert, then the deletion of the run's
|
|
15770
|
+
* entries (only its steps when another run builds on its state, see `stateShared`), then the new ones.
|
|
15771
|
+
*/
|
|
15772
|
+
async writeWorkflowRunCheckpoint({ fence, expectedStatus, steps, state, stateBase, statePatch, ...run }) {
|
|
15773
|
+
const entries = journalEntries(steps, {
|
|
15774
|
+
state,
|
|
15775
|
+
stateBase,
|
|
15776
|
+
statePatch
|
|
15777
|
+
}, true);
|
|
15778
|
+
const check = this.#runFenceCheck(fence, run.runId, "writeWorkflowRunCheckpoint");
|
|
15779
|
+
try {
|
|
15780
|
+
const base = state === void 0 ? stateBase : void 0;
|
|
15781
|
+
const statements = [];
|
|
15782
|
+
if (base) statements.push({
|
|
15783
|
+
sql: `UPDATE ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} SET stateShared = 1 WHERE workflow_name = ? AND run_id = ? AND NOT stateShared`,
|
|
15784
|
+
args: [base.workflowName, base.runId]
|
|
15785
|
+
});
|
|
15786
|
+
statements.push(upsertHeader(run, entries.length, { checkpoint: true }), {
|
|
15787
|
+
sql: `DELETE FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} WHERE workflow_name = ? AND run_id = ?
|
|
15788
|
+
AND (kind IN ('step', 'step-patch') OR NOT (SELECT stateShared FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?))`,
|
|
15789
|
+
args: [
|
|
15790
|
+
run.workflowName,
|
|
15791
|
+
run.runId,
|
|
15792
|
+
run.workflowName,
|
|
15793
|
+
run.runId
|
|
15794
|
+
]
|
|
15795
|
+
}, insertEntries(run, entries));
|
|
15796
|
+
const results = await this.executeWithRetry(() => this.#writeRun(check, run, {
|
|
15797
|
+
expectedStatus,
|
|
15798
|
+
stateBase: base
|
|
15799
|
+
}, statements), "writeWorkflowRunCheckpoint");
|
|
15800
|
+
if (!results) return null;
|
|
15801
|
+
const header = results[statements.length - 3].rows[0];
|
|
15802
|
+
return {
|
|
15803
|
+
lastSeq: Number(header.lastSeq),
|
|
15804
|
+
runToken: header.runToken
|
|
15805
|
+
};
|
|
15806
|
+
} catch (error) {
|
|
15807
|
+
if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
|
|
15808
|
+
throw this.#runError("WRITE_WORKFLOW_RUN_CHECKPOINT", run.workflowName, run.runId, error);
|
|
15809
|
+
}
|
|
15810
|
+
}
|
|
15811
|
+
/**
|
|
15812
|
+
* One batch behind the write lock (see `#writeRun` for `expectedStatus`): the header upsert adds
|
|
15813
|
+
* the entry count to `lastSeq`, and the insert numbers the entries up to it, so writes to one run
|
|
15814
|
+
* never interleave.
|
|
15815
|
+
*/
|
|
15816
|
+
async appendWorkflowRunEntries({ fence, steps, stepPatches, state, statePatch, startStateSeq, expectedStatus, ...run }) {
|
|
15817
|
+
const entries = journalEntries(steps, {
|
|
15818
|
+
state,
|
|
15819
|
+
statePatch
|
|
15820
|
+
}, false, stepPatches);
|
|
15821
|
+
const check = this.#runFenceCheck(fence, run.runId, "appendWorkflowRunEntries");
|
|
15822
|
+
try {
|
|
15823
|
+
const results = await this.executeWithRetry(() => this.#writeRun(check, run, { expectedStatus }, [upsertHeader(run, entries.length, {
|
|
15824
|
+
checkpoint: false,
|
|
15825
|
+
startStateSeq
|
|
15826
|
+
}), insertEntries(run, entries)]), "appendWorkflowRunEntries");
|
|
15827
|
+
if (!results) return null;
|
|
15828
|
+
const header = results[0].rows[0];
|
|
15829
|
+
return {
|
|
15830
|
+
lastSeq: Number(header.lastSeq),
|
|
15831
|
+
runToken: header.runToken
|
|
15832
|
+
};
|
|
15833
|
+
} catch (error) {
|
|
15834
|
+
if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
|
|
15835
|
+
throw this.#runError("APPEND_WORKFLOW_RUN_ENTRIES", run.workflowName, run.runId, error);
|
|
15836
|
+
}
|
|
15837
|
+
}
|
|
15838
|
+
async loadWorkflowRunState({ workflowName, runId, seq }) {
|
|
15839
|
+
try {
|
|
15840
|
+
return (await this.#stateAt(this.#client, workflowName, runId, { seq }))?.state ?? null;
|
|
15841
|
+
} catch (error) {
|
|
15842
|
+
throw this.#runError("LOAD_WORKFLOW_RUN_STATE", workflowName, runId, error);
|
|
15843
|
+
}
|
|
15844
|
+
}
|
|
15845
|
+
/**
|
|
15846
|
+
* One batch behind the write lock (or the run's fence): the header's `lastSeq` bump, then the
|
|
15847
|
+
* draft numbered at it.
|
|
15848
|
+
*/
|
|
15849
|
+
async appendWorkflowRunStateDraft(args) {
|
|
15850
|
+
const { workflowName, runId } = args;
|
|
15851
|
+
const payload = "state" in args ? { state: args.state } : {
|
|
15852
|
+
on: args.on.draft ? {
|
|
15853
|
+
seq: args.on.seq,
|
|
15854
|
+
draft: true
|
|
15855
|
+
} : { seq: args.on.seq },
|
|
15856
|
+
ops: args.ops
|
|
15857
|
+
};
|
|
15858
|
+
let row;
|
|
15859
|
+
try {
|
|
15860
|
+
const [header] = await this.executeWithRetry(() => withRunFence(this.#client, this.#runFenceCheck(void 0, runId, "appendWorkflowRunStateDraft"), (writer) => writer.batch([{
|
|
15861
|
+
sql: `UPDATE ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} SET lastSeq = lastSeq + 1, stateShared = 1
|
|
15862
|
+
WHERE workflow_name = ? AND run_id = ? RETURNING lastSeq`,
|
|
15863
|
+
args: [workflowName, runId]
|
|
15864
|
+
}, {
|
|
15865
|
+
sql: `INSERT INTO ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} (workflow_name, run_id, seq, kind, step_id, payload)
|
|
15866
|
+
SELECT workflow_name, run_id, lastSeq, 'state-draft', NULL, jsonb(?)
|
|
15867
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?`,
|
|
15868
|
+
args: [
|
|
15869
|
+
safeStringify(payload),
|
|
15870
|
+
workflowName,
|
|
15871
|
+
runId
|
|
15872
|
+
]
|
|
15873
|
+
}])), "appendWorkflowRunStateDraft");
|
|
15874
|
+
row = header.rows[0];
|
|
15875
|
+
} catch (error) {
|
|
15876
|
+
if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
|
|
15877
|
+
throw this.#runError("APPEND_WORKFLOW_RUN_STATE_DRAFT", workflowName, runId, error);
|
|
15878
|
+
}
|
|
15879
|
+
if (!row) throw new Error(`Storage v2 run ${workflowName}/${runId} is not stored`);
|
|
15880
|
+
return { seq: Number(row.lastSeq) };
|
|
15881
|
+
}
|
|
15245
15882
|
async #readRunOwner(q, runId) {
|
|
15246
15883
|
const row = (await q.execute({
|
|
15247
15884
|
sql: `SELECT ${RUN_OWNER_COLUMNS} FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS} WHERE runId = ?`,
|
|
@@ -15342,21 +15979,56 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15342
15979
|
throw this.#ownershipError("GET_RUN_OWNERSHIP", runId, error);
|
|
15343
15980
|
}
|
|
15344
15981
|
}
|
|
15345
|
-
/**
|
|
15982
|
+
/**
|
|
15983
|
+
* Delete workflow runs and run ownership rows older than their policy's `maxAge`, batched.
|
|
15984
|
+
* The `workflowSnapshot` policy covers both storage versions: storage v2 runs are pruned by
|
|
15985
|
+
* their header's last write, together with their entries.
|
|
15986
|
+
*/
|
|
15346
15987
|
async prune(policies, options) {
|
|
15347
15988
|
const targets = resolveTargets({
|
|
15348
15989
|
policies,
|
|
15349
15990
|
descriptor: WorkflowsLibSQL.retentionTables,
|
|
15350
15991
|
order: ["workflowSnapshot", "runOwnership"]
|
|
15351
15992
|
});
|
|
15993
|
+
const snapshotTarget = targets.findIndex((target) => target.table === _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
15994
|
+
if (snapshotTarget !== -1) targets.splice(snapshotTarget + 1, 0, {
|
|
15995
|
+
...targets[snapshotTarget],
|
|
15996
|
+
table: _mastra_core_storage.TABLE_WORKFLOW_RUNS
|
|
15997
|
+
});
|
|
15352
15998
|
return runPrune({
|
|
15353
15999
|
db: this.#db,
|
|
15354
16000
|
domain: "workflows",
|
|
15355
16001
|
targets,
|
|
15356
16002
|
options,
|
|
15357
|
-
logger: this.logger
|
|
16003
|
+
logger: this.logger,
|
|
16004
|
+
deleteBatch: (target, cutoff, limit) => target.table === _mastra_core_storage.TABLE_WORKFLOW_RUNS ? this.#pruneRunsBatch(cutoff, limit) : void 0
|
|
15358
16005
|
});
|
|
15359
16006
|
}
|
|
16007
|
+
/**
|
|
16008
|
+
* Deletes up to `limit` aged storage v2 runs in one write transaction: detaches the runs built on
|
|
16009
|
+
* their state, then deletes their entries and headers. Every statement selects the same runs, and
|
|
16010
|
+
* the transaction holds the write lock, so they agree.
|
|
16011
|
+
*/
|
|
16012
|
+
async #pruneRunsBatch(cutoff, limit) {
|
|
16013
|
+
const doomed = `SELECT workflow_name, run_id FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS}
|
|
16014
|
+
WHERE updatedAt < ? ORDER BY updatedAt, workflow_name, run_id LIMIT ?`;
|
|
16015
|
+
return this.executeWithRetry(() => inWriteTransaction(this.#client, async (tx) => {
|
|
16016
|
+
const shared = await tx.execute({
|
|
16017
|
+
sql: `SELECT d.workflow_name, d.run_id FROM (${doomed}) d
|
|
16018
|
+
JOIN ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} r USING (workflow_name, run_id) WHERE r.stateShared`,
|
|
16019
|
+
args: [cutoff, limit]
|
|
16020
|
+
});
|
|
16021
|
+
for (const run of shared.rows) await this.#detachStateChildren(tx, run.workflow_name, run.run_id);
|
|
16022
|
+
await tx.execute({
|
|
16023
|
+
sql: `DELETE FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES} WHERE (workflow_name, run_id) IN (${doomed})`,
|
|
16024
|
+
args: [cutoff, limit]
|
|
16025
|
+
});
|
|
16026
|
+
return (await tx.execute({
|
|
16027
|
+
sql: `DELETE FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE (workflow_name, run_id) IN (${doomed})`,
|
|
16028
|
+
args: [cutoff, limit]
|
|
16029
|
+
})).rowsAffected;
|
|
16030
|
+
}), `prune ${_mastra_core_storage.TABLE_WORKFLOW_RUNS}`);
|
|
16031
|
+
}
|
|
15360
16032
|
async setupPragmaSettings() {
|
|
15361
16033
|
try {
|
|
15362
16034
|
await this.#client.execute("PRAGMA busy_timeout = 10000;");
|
|
@@ -15388,6 +16060,10 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15388
16060
|
args: [workflowName, runId]
|
|
15389
16061
|
});
|
|
15390
16062
|
if (!existingSnapshotResult.rows?.[0]) {
|
|
16063
|
+
if ((await tx.execute({
|
|
16064
|
+
sql: `SELECT 1 FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?`,
|
|
16065
|
+
args: [workflowName, runId]
|
|
16066
|
+
})).rows.length > 0) throw new Error(`updateWorkflowResults does not support storage v2 runs (run ${runId})`);
|
|
15391
16067
|
await tx.rollback();
|
|
15392
16068
|
return {};
|
|
15393
16069
|
}
|
|
@@ -15422,12 +16098,51 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15422
16098
|
}
|
|
15423
16099
|
}), "updateWorkflowResults");
|
|
15424
16100
|
}
|
|
15425
|
-
async updateWorkflowState({ workflowName, runId, opts, fence: explicitFence }) {
|
|
16101
|
+
async updateWorkflowState({ workflowName, runId, opts, fence: explicitFence, storageVersion }) {
|
|
15426
16102
|
const check = this.#runFenceCheck(explicitFence, runId, "updateWorkflowState");
|
|
15427
16103
|
return this.executeWithRetry(() => withClientWriteLock(this.#client, async () => {
|
|
15428
16104
|
const tx = await this.#client.transaction("write");
|
|
15429
16105
|
try {
|
|
15430
16106
|
if (check) await assertRunFence(tx, check);
|
|
16107
|
+
if (storageVersion !== 1) {
|
|
16108
|
+
const row = (await tx.execute({
|
|
16109
|
+
sql: `SELECT json(header) AS header FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?`,
|
|
16110
|
+
args: [workflowName, runId]
|
|
16111
|
+
})).rows[0];
|
|
16112
|
+
if (row) {
|
|
16113
|
+
const current = JSON.parse(row.header);
|
|
16114
|
+
const { expectedStatus, ...patch } = opts;
|
|
16115
|
+
if (!(0, _mastra_core_storage.matchesExpectedWorkflowStatus)(current.status, expectedStatus)) {
|
|
16116
|
+
await tx.rollback();
|
|
16117
|
+
return;
|
|
16118
|
+
}
|
|
16119
|
+
const header = {
|
|
16120
|
+
...current,
|
|
16121
|
+
...patch
|
|
16122
|
+
};
|
|
16123
|
+
await tx.execute({
|
|
16124
|
+
sql: `UPDATE ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} SET header = jsonb(?), status = ?, updatedAt = ? WHERE workflow_name = ? AND run_id = ?`,
|
|
16125
|
+
args: [
|
|
16126
|
+
safeStringify(header),
|
|
16127
|
+
header.status,
|
|
16128
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
16129
|
+
workflowName,
|
|
16130
|
+
runId
|
|
16131
|
+
]
|
|
16132
|
+
});
|
|
16133
|
+
const entries = await tx.execute({
|
|
16134
|
+
sql: `SELECT ${entriesSql("r")} AS entries FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} r WHERE r.workflow_name = ? AND r.run_id = ?`,
|
|
16135
|
+
args: [workflowName, runId]
|
|
16136
|
+
});
|
|
16137
|
+
const snapshot = await this.#materializeRun(tx, header, entries.rows[0].entries);
|
|
16138
|
+
await tx.commit();
|
|
16139
|
+
return snapshot;
|
|
16140
|
+
}
|
|
16141
|
+
if (storageVersion === 2) {
|
|
16142
|
+
await tx.rollback();
|
|
16143
|
+
return;
|
|
16144
|
+
}
|
|
16145
|
+
}
|
|
15431
16146
|
const existingSnapshotResult = await tx.execute({
|
|
15432
16147
|
sql: `SELECT json(snapshot) as snapshot FROM ${_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT} WHERE workflow_name = ? AND run_id = ?`,
|
|
15433
16148
|
args: [workflowName, runId]
|
|
@@ -15497,15 +16212,32 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15497
16212
|
}
|
|
15498
16213
|
async loadWorkflowRunStatus({ workflowName, runId }) {
|
|
15499
16214
|
return (await this.#client.execute({
|
|
15500
|
-
sql: `SELECT
|
|
15501
|
-
|
|
16215
|
+
sql: `SELECT COALESCE(
|
|
16216
|
+
(SELECT status FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?),
|
|
16217
|
+
(SELECT json_extract(snapshot, '$.status') FROM ${_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT} WHERE workflow_name = ? AND run_id = ?)
|
|
16218
|
+
) AS status`,
|
|
16219
|
+
args: [
|
|
16220
|
+
workflowName,
|
|
16221
|
+
runId,
|
|
16222
|
+
workflowName,
|
|
16223
|
+
runId
|
|
16224
|
+
]
|
|
15502
16225
|
})).rows?.[0]?.status ?? null;
|
|
15503
16226
|
}
|
|
15504
|
-
async loadWorkflowSnapshot({ workflowName, runId }) {
|
|
16227
|
+
async loadWorkflowSnapshot({ workflowName, runId, storageVersion }) {
|
|
15505
16228
|
this.logger.debug("Loading workflow snapshot", {
|
|
15506
16229
|
workflowName,
|
|
15507
16230
|
runId
|
|
15508
16231
|
});
|
|
16232
|
+
if (storageVersion !== 1) {
|
|
16233
|
+
const row = (await this.#client.execute({
|
|
16234
|
+
sql: `SELECT json(r.header) AS header, ${entriesSql("r")} AS entries
|
|
16235
|
+
FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} r WHERE r.workflow_name = ? AND r.run_id = ?`,
|
|
16236
|
+
args: [workflowName, runId]
|
|
16237
|
+
})).rows[0];
|
|
16238
|
+
if (row) return this.#materializeRun(this.#client, row.header, row.entries);
|
|
16239
|
+
if (storageVersion === 2) return null;
|
|
16240
|
+
}
|
|
15509
16241
|
const d = await this.#db.select({
|
|
15510
16242
|
tableName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
15511
16243
|
keys: {
|
|
@@ -15515,7 +16247,7 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15515
16247
|
});
|
|
15516
16248
|
return d ? d.snapshot : null;
|
|
15517
16249
|
}
|
|
15518
|
-
async getWorkflowRunById({ runId, workflowName }) {
|
|
16250
|
+
async getWorkflowRunById({ runId, workflowName, storageVersion }) {
|
|
15519
16251
|
const conditions = [];
|
|
15520
16252
|
const args = [];
|
|
15521
16253
|
if (runId) {
|
|
@@ -15529,11 +16261,15 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15529
16261
|
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
15530
16262
|
try {
|
|
15531
16263
|
const result = await this.#client.execute({
|
|
15532
|
-
sql:
|
|
15533
|
-
|
|
16264
|
+
sql: this.#runsSql({
|
|
16265
|
+
v1Where: storageVersion === 2 ? null : whereClause,
|
|
16266
|
+
v2Where: storageVersion === 1 ? null : whereClause,
|
|
16267
|
+
page: "LIMIT 1"
|
|
16268
|
+
}),
|
|
16269
|
+
args: [...storageVersion === 2 ? [] : args, ...storageVersion === 1 ? [] : args]
|
|
15534
16270
|
});
|
|
15535
16271
|
if (!result.rows?.[0]) return null;
|
|
15536
|
-
return this
|
|
16272
|
+
return await this.#parseRun(result.rows[0]);
|
|
15537
16273
|
} catch (error) {
|
|
15538
16274
|
throw new _mastra_core_error.MastraError({
|
|
15539
16275
|
id: (0, _mastra_core_storage.createStorageErrorId)("LIBSQL", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
|
|
@@ -15542,14 +16278,33 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15542
16278
|
}, error);
|
|
15543
16279
|
}
|
|
15544
16280
|
}
|
|
15545
|
-
async deleteWorkflowRunById({ runId, workflowName, fence }) {
|
|
16281
|
+
async deleteWorkflowRunById({ runId, workflowName, storageVersion, fence }) {
|
|
15546
16282
|
const check = this.#runFenceCheck(fence, runId, "deleteWorkflowRunById");
|
|
15547
16283
|
return this.executeWithRetry(async () => {
|
|
15548
16284
|
try {
|
|
15549
|
-
|
|
15550
|
-
|
|
15551
|
-
|
|
15552
|
-
|
|
16285
|
+
if (storageVersion === 1) {
|
|
16286
|
+
await withRunFence(this.#client, check, (writer) => writer.execute({
|
|
16287
|
+
sql: `DELETE FROM ${_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT} WHERE workflow_name = ? AND run_id = ?`,
|
|
16288
|
+
args: [workflowName, runId]
|
|
16289
|
+
}));
|
|
16290
|
+
return;
|
|
16291
|
+
}
|
|
16292
|
+
await inWriteTransaction(this.#client, async (tx) => {
|
|
16293
|
+
if (check) await assertRunFence(tx, check);
|
|
16294
|
+
const run = await tx.execute({
|
|
16295
|
+
sql: `SELECT stateShared FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} WHERE workflow_name = ? AND run_id = ?`,
|
|
16296
|
+
args: [workflowName, runId]
|
|
16297
|
+
});
|
|
16298
|
+
if (Number(run.rows[0]?.stateShared)) await this.#detachStateChildren(tx, workflowName, runId);
|
|
16299
|
+
for (const table of [
|
|
16300
|
+
_mastra_core_storage.TABLE_WORKFLOW_RUNS,
|
|
16301
|
+
_mastra_core_storage.TABLE_WORKFLOW_RUN_ENTRIES,
|
|
16302
|
+
...storageVersion === 2 ? [] : [_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT]
|
|
16303
|
+
]) await tx.execute({
|
|
16304
|
+
sql: `DELETE FROM ${table} WHERE workflow_name = ? AND run_id = ?`,
|
|
16305
|
+
args: [workflowName, runId]
|
|
16306
|
+
});
|
|
16307
|
+
});
|
|
15553
16308
|
} catch (error) {
|
|
15554
16309
|
if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
|
|
15555
16310
|
throw new _mastra_core_error.MastraError({
|
|
@@ -15568,52 +16323,74 @@ var WorkflowsLibSQL = class WorkflowsLibSQL extends _mastra_core_storage.Workflo
|
|
|
15568
16323
|
try {
|
|
15569
16324
|
const conditions = [];
|
|
15570
16325
|
const args = [];
|
|
16326
|
+
const v2Conditions = [];
|
|
16327
|
+
const v2Args = [];
|
|
15571
16328
|
if (workflowName) {
|
|
15572
16329
|
conditions.push("workflow_name = ?");
|
|
15573
16330
|
args.push(workflowName);
|
|
16331
|
+
v2Conditions.push("workflow_name = ?");
|
|
16332
|
+
v2Args.push(workflowName);
|
|
15574
16333
|
}
|
|
15575
16334
|
if (status) {
|
|
15576
16335
|
conditions.push("json_extract(snapshot, '$.status') = ?");
|
|
15577
16336
|
args.push(status);
|
|
16337
|
+
v2Conditions.push("status = ?");
|
|
16338
|
+
v2Args.push(status);
|
|
15578
16339
|
}
|
|
15579
16340
|
if (fromDate) {
|
|
15580
16341
|
conditions.push("createdAt >= ?");
|
|
15581
16342
|
args.push(fromDate.toISOString());
|
|
16343
|
+
v2Conditions.push("createdAt >= ?");
|
|
16344
|
+
v2Args.push(fromDate.toISOString());
|
|
15582
16345
|
}
|
|
15583
16346
|
if (toDate) {
|
|
15584
16347
|
conditions.push("createdAt <= ?");
|
|
15585
16348
|
args.push(toDate.toISOString());
|
|
16349
|
+
v2Conditions.push("createdAt <= ?");
|
|
16350
|
+
v2Args.push(toDate.toISOString());
|
|
15586
16351
|
}
|
|
15587
16352
|
if (resourceId) {
|
|
15588
16353
|
if (await this.#db.hasColumn(_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId")) {
|
|
15589
16354
|
conditions.push("resourceId = ?");
|
|
15590
16355
|
args.push(resourceId);
|
|
15591
16356
|
} else this.logger.warn(`[${_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
|
|
16357
|
+
v2Conditions.push("resourceId = ?");
|
|
16358
|
+
v2Args.push(resourceId);
|
|
15592
16359
|
}
|
|
15593
16360
|
if (threadId) {
|
|
15594
16361
|
conditions.push(`(EXISTS (SELECT 1 FROM json_each(snapshot, '$.context') AS je WHERE json_extract(je.value, '$.status') = 'suspended' AND json_extract(je.value, '$.suspendPayload.__streamState.messageList.memoryInfo.threadId') = ?) OR json_extract(snapshot, '$.context.input.messageListState.memoryInfo.threadId') = ?)`);
|
|
15595
16362
|
args.push(threadId, threadId);
|
|
16363
|
+
v2Conditions.push("threadId = ?");
|
|
16364
|
+
v2Args.push(threadId);
|
|
15596
16365
|
}
|
|
15597
16366
|
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
16367
|
+
const v2WhereClause = v2Conditions.length > 0 ? `WHERE ${v2Conditions.join(" AND ")}` : "";
|
|
15598
16368
|
let total = 0;
|
|
15599
16369
|
const usePagination = typeof perPage === "number" && typeof page === "number";
|
|
15600
16370
|
if (usePagination) {
|
|
15601
16371
|
const countResult = await this.#client.execute({
|
|
15602
|
-
sql: `SELECT COUNT(*)
|
|
15603
|
-
|
|
16372
|
+
sql: `SELECT (SELECT COUNT(*) FROM ${_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause})
|
|
16373
|
+
+ (SELECT COUNT(*) FROM ${_mastra_core_storage.TABLE_WORKFLOW_RUNS} ${v2WhereClause}) AS count`,
|
|
16374
|
+
args: [...args, ...v2Args]
|
|
15604
16375
|
});
|
|
15605
16376
|
total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
15606
16377
|
}
|
|
15607
16378
|
const normalizedPerPage = usePagination ? (0, _mastra_core_storage.normalizePerPage)(perPage, Number.MAX_SAFE_INTEGER) : 0;
|
|
15608
16379
|
const offset = usePagination ? page * normalizedPerPage : 0;
|
|
15609
|
-
const
|
|
15610
|
-
sql:
|
|
15611
|
-
|
|
16380
|
+
const result = await this.#client.execute({
|
|
16381
|
+
sql: this.#runsSql({
|
|
16382
|
+
v1Where: whereClause,
|
|
16383
|
+
v2Where: v2WhereClause,
|
|
16384
|
+
summary,
|
|
16385
|
+
page: usePagination ? "LIMIT ? OFFSET ?" : ""
|
|
16386
|
+
}),
|
|
16387
|
+
args: [
|
|
15612
16388
|
...args,
|
|
15613
|
-
|
|
15614
|
-
offset
|
|
15615
|
-
]
|
|
15616
|
-
})
|
|
16389
|
+
...v2Args,
|
|
16390
|
+
...usePagination ? [normalizedPerPage, offset] : []
|
|
16391
|
+
]
|
|
16392
|
+
});
|
|
16393
|
+
const runs = await Promise.all((result.rows || []).map((row) => this.#parseRun(row)));
|
|
15617
16394
|
return {
|
|
15618
16395
|
runs,
|
|
15619
16396
|
total: total || runs.length
|