@mastra/cloudflare-d1 1.4.1 → 1.4.2-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/index.cjs CHANGED
@@ -128,20 +128,20 @@ var SqlBuilder = class {
128
128
  * @param values Values to insert
129
129
  * @param conflictColumns Columns to check for conflict (usually PK or UNIQUE)
130
130
  * @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
131
+ * @param guard Condition the statement writes under: when it is false, neither the insert nor the conflict update happens
131
132
  */
132
- insert(table, columns, values, conflictColumns, updateMap) {
133
+ insert(table, columns, values, conflictColumns, updateMap, guard) {
133
134
  const parsedTableName = (0, _mastra_core_utils.parseSqlIdentifier)(table, "table name");
134
135
  const parsedColumns = columns.map((col) => (0, _mastra_core_utils.parseSqlIdentifier)(col, "column name"));
135
136
  const placeholders = parsedColumns.map(() => "?").join(", ");
137
+ const source = guard ? `SELECT ${placeholders} WHERE ${guard.sql}` : `VALUES (${placeholders})`;
138
+ this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) ${source}`;
139
+ this.params.push(...values, ...guard?.params ?? []);
136
140
  if (conflictColumns && updateMap) {
137
141
  const parsedConflictColumns = conflictColumns.map((col) => (0, _mastra_core_utils.parseSqlIdentifier)(col, "column name"));
138
142
  const updateClause = Object.entries(updateMap).map(([col, expr]) => `${col} = ${expr}`).join(", ");
139
- this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
140
- this.params.push(...values);
141
- return this;
143
+ this.sql += ` ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
142
144
  }
143
- this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders})`;
144
- this.params.push(...values);
145
145
  return this;
146
146
  }
147
147
  update(table, columns, values) {
@@ -279,6 +279,68 @@ function parseSelectIdentifier(column) {
279
279
  return column;
280
280
  }
281
281
  //#endregion
282
+ //#region src/storage/db/run-fencing.ts
283
+ /**
284
+ * Epoch milliseconds on the database clock. `julianday('now')` rather than
285
+ * `unixepoch('subsec')`, which needs SQLite 3.42.
286
+ */
287
+ const DB_NOW_MS = `CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)`;
288
+ /**
289
+ * The condition a fenced statement writes under: the check's fence is the
290
+ * run's current claim. D1 has no interactive transactions, so a fenced write
291
+ * can't check the claim first and write second; each of its statements
292
+ * carries this condition instead, and SQLite evaluates it atomically with the
293
+ * write.
294
+ */
295
+ function runFenceGuard(check) {
296
+ if (!check) return void 0;
297
+ const { claimsTable, fence } = check;
298
+ return {
299
+ sql: `EXISTS (SELECT 1 FROM ${claimsTable} AS run_fence WHERE run_fence.runId = ? AND run_fence.generation = ? AND run_fence.ownerId = ?)`,
300
+ params: [
301
+ fence.runId,
302
+ fence.generation,
303
+ fence.ownerId
304
+ ]
305
+ };
306
+ }
307
+ /** Throws `RunFenceConflictError` unless the check's fence is the run's current claim. */
308
+ async function assertRunFence(db, { claimsTable, fence, operation }) {
309
+ const row = await db.executeQuery({
310
+ sql: `SELECT generation, ownerId FROM ${claimsTable} WHERE runId = ?`,
311
+ params: [fence.runId],
312
+ first: true
313
+ });
314
+ if (!(0, _mastra_core_storage.matchesRunFence)(row ? {
315
+ generation: Number(row.generation),
316
+ ownerId: String(row.ownerId)
317
+ } : null, fence)) throw new _mastra_core_storage.RunFenceConflictError(fence, operation);
318
+ }
319
+ /**
320
+ * Runs one statement of a fenced write. With a check, `statement` must carry
321
+ * `runFenceGuard(check)`. A guarded statement that changes no row either
322
+ * found no target or was refused by its guard; re-reading the claim tells
323
+ * which, and a refusal throws `RunFenceConflictError`.
324
+ *
325
+ * A write made of several statements stops at the first refused one, so a
326
+ * takeover that lands between them leaves the earlier statements applied.
327
+ * None of the refused writer's statements land after the takeover.
328
+ */
329
+ async function executeFenced(db, check, { sql, params }) {
330
+ if (!check) {
331
+ await db.executeQuery({
332
+ sql,
333
+ params
334
+ });
335
+ return;
336
+ }
337
+ const rows = await db.executeQuery({
338
+ sql: `${sql} RETURNING 1 AS written`,
339
+ params
340
+ });
341
+ if (Array.isArray(rows) && rows.length === 0) await assertRunFence(db, check);
342
+ }
343
+ //#endregion
282
344
  //#region src/storage/db/index.ts
283
345
  /**
284
346
  * Resolves D1DomainConfig to D1DBConfig.
@@ -613,10 +675,12 @@ var D1DB = class extends _mastra_core_base.MastraBase {
613
675
  * Upsert multiple records in a batch operation
614
676
  * @param tableName The table to insert into
615
677
  * @param records The records to insert
678
+ * @param check Run fence every upsert must hold; a refused upsert throws and stops the batch
616
679
  */
617
- async batchUpsert({ tableName, records }) {
680
+ async batchUpsert({ tableName, records, check }) {
618
681
  if (records.length === 0) return;
619
682
  const fullTableName = this.getTableName(tableName);
683
+ const guard = runFenceGuard(check);
620
684
  try {
621
685
  const batchSize = 50;
622
686
  for (let i = 0; i < records.length; i += batchSize) {
@@ -634,17 +698,15 @@ var D1DB = class extends _mastra_core_base.MastraBase {
634
698
  if (col !== "createdAt") acc[col] = `excluded.${col}`;
635
699
  return acc;
636
700
  }, {});
637
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert).build();
638
- await this.executeQuery({
639
- sql,
640
- params
641
- });
701
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert, guard);
702
+ await executeFenced(this, check, query.build());
642
703
  }
643
704
  }
644
705
  this.logger.debug(`Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`);
645
706
  }
646
707
  this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
647
708
  } catch (error) {
709
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
648
710
  throw new _mastra_core_error.MastraError({
649
711
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "BATCH_UPSERT", "FAILED"),
650
712
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1027,11 +1089,76 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1027
1089
  schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_MESSAGES],
1028
1090
  ifNotExists: ["resourceId"]
1029
1091
  });
1092
+ await this.#db.createTable({
1093
+ tableName: _mastra_core_storage.TABLE_MEMORY_RUN_FENCES,
1094
+ schema: _mastra_core_storage.RUN_FENCING_TABLE_SCHEMAS[_mastra_core_storage.TABLE_MEMORY_RUN_FENCES]
1095
+ });
1030
1096
  }
1031
1097
  async dangerouslyClearAll() {
1032
1098
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_MESSAGES });
1033
1099
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_THREADS });
1034
1100
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_RESOURCES });
1101
+ await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_MEMORY_RUN_FENCES });
1102
+ }
1103
+ supportsRunFencing() {
1104
+ return true;
1105
+ }
1106
+ get #fencesTable() {
1107
+ return this.#db.getTableName(_mastra_core_storage.TABLE_MEMORY_RUN_FENCES);
1108
+ }
1109
+ async raiseRunFence(fence) {
1110
+ const table = this.#fencesTable;
1111
+ try {
1112
+ return (await this.#db.executeQuery({
1113
+ sql: `INSERT INTO ${table} (runId, generation, ownerId) VALUES (?, ?, ?)
1114
+ ON CONFLICT(runId) DO UPDATE SET generation = excluded.generation, ownerId = excluded.ownerId, retiredAt = NULL
1115
+ WHERE excluded.generation > ${table}.generation
1116
+ OR (excluded.generation = ${table}.generation AND excluded.ownerId = ${table}.ownerId)
1117
+ RETURNING runId`,
1118
+ params: [
1119
+ fence.runId,
1120
+ fence.generation,
1121
+ fence.ownerId
1122
+ ]
1123
+ })).length > 0;
1124
+ } catch (error) {
1125
+ throw new _mastra_core_error.MastraError({
1126
+ id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "RAISE_RUN_FENCE", "FAILED"),
1127
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1128
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
1129
+ details: { runId: fence.runId }
1130
+ }, error);
1131
+ }
1132
+ }
1133
+ async retireRunFence(fence) {
1134
+ try {
1135
+ return (await this.#db.executeQuery({
1136
+ sql: `UPDATE ${this.#fencesTable} SET retiredAt = ${DB_NOW_MS}
1137
+ WHERE runId = ? AND generation = ? AND ownerId = ?
1138
+ RETURNING runId`,
1139
+ params: [
1140
+ fence.runId,
1141
+ fence.generation,
1142
+ fence.ownerId
1143
+ ]
1144
+ })).length > 0;
1145
+ } catch (error) {
1146
+ throw new _mastra_core_error.MastraError({
1147
+ id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "RETIRE_RUN_FENCE", "FAILED"),
1148
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
1149
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
1150
+ details: { runId: fence.runId }
1151
+ }, error);
1152
+ }
1153
+ }
1154
+ /** The check a write must pass: its own fence, otherwise the one in scope. */
1155
+ #runFenceCheck(fence, operation) {
1156
+ const resolved = (0, _mastra_core_storage.resolveRunFence)(this, fence);
1157
+ return resolved && {
1158
+ claimsTable: this.#fencesTable,
1159
+ fence: resolved,
1160
+ operation
1161
+ };
1035
1162
  }
1036
1163
  async getResourceById({ resourceId }) {
1037
1164
  const resource = await this.#db.load({
@@ -1060,6 +1187,9 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1060
1187
  }
1061
1188
  }
1062
1189
  async saveResource({ resource }) {
1190
+ return this.#insertResource(resource, void 0);
1191
+ }
1192
+ async #insertResource(resource, check) {
1063
1193
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_RESOURCES);
1064
1194
  const resourceToSave = {
1065
1195
  id: resource.id,
@@ -1071,19 +1201,17 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1071
1201
  const processedRecord = await this.#db.processRecord(resourceToSave);
1072
1202
  const columns = Object.keys(processedRecord);
1073
1203
  const values = Object.values(processedRecord);
1074
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1204
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1075
1205
  workingMemory: "excluded.workingMemory",
1076
1206
  metadata: "excluded.metadata",
1077
1207
  createdAt: "excluded.createdAt",
1078
1208
  updatedAt: "excluded.updatedAt"
1079
- }).build();
1209
+ }, runFenceGuard(check));
1080
1210
  try {
1081
- await this.#db.executeQuery({
1082
- sql,
1083
- params
1084
- });
1211
+ await executeFenced(this.#db, check, query.build());
1085
1212
  return resource;
1086
1213
  } catch (error) {
1214
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
1087
1215
  throw new _mastra_core_error.MastraError({
1088
1216
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "SAVE_RESOURCE", "FAILED"),
1089
1217
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1093,7 +1221,8 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1093
1221
  }, error);
1094
1222
  }
1095
1223
  }
1096
- async updateResource({ resourceId, workingMemory, metadata }) {
1224
+ async updateResource({ resourceId, workingMemory, metadata, fence }) {
1225
+ const check = this.#runFenceCheck(fence, "updateResource");
1097
1226
  const existingResource = await this.getResourceById({ resourceId });
1098
1227
  if (!existingResource) {
1099
1228
  const newResource = {
@@ -1103,7 +1232,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1103
1232
  createdAt: /* @__PURE__ */ new Date(),
1104
1233
  updatedAt: /* @__PURE__ */ new Date()
1105
1234
  };
1106
- return this.saveResource({ resource: newResource });
1235
+ return this.#insertResource(newResource, check);
1107
1236
  }
1108
1237
  const updatedAt = /* @__PURE__ */ new Date();
1109
1238
  const updatedResource = {
@@ -1126,14 +1255,14 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1126
1255
  JSON.stringify(updatedResource.metadata),
1127
1256
  updatedAt.toISOString()
1128
1257
  ];
1129
- const { sql, params } = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId).build();
1258
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
1259
+ const guard = runFenceGuard(check);
1260
+ if (guard) query.andWhere(guard.sql, ...guard.params);
1130
1261
  try {
1131
- await this.#db.executeQuery({
1132
- sql,
1133
- params
1134
- });
1262
+ await executeFenced(this.#db, check, query.build());
1135
1263
  return updatedResource;
1136
1264
  } catch (error) {
1265
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
1137
1266
  throw new _mastra_core_error.MastraError({
1138
1267
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "UPDATE_RESOURCE", "FAILED"),
1139
1268
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1268,8 +1397,9 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1268
1397
  throw mastraError;
1269
1398
  }
1270
1399
  }
1271
- async saveThread({ thread }) {
1400
+ async saveThread({ thread, fence }) {
1272
1401
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_THREADS);
1402
+ const check = this.#runFenceCheck(fence, "saveThread");
1273
1403
  const threadToSave = {
1274
1404
  id: thread.id,
1275
1405
  resourceId: thread.resourceId,
@@ -1281,20 +1411,18 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1281
1411
  const processedRecord = await this.#db.processRecord(threadToSave);
1282
1412
  const columns = Object.keys(processedRecord);
1283
1413
  const values = Object.values(processedRecord);
1284
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1414
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1285
1415
  resourceId: "excluded.resourceId",
1286
1416
  title: "excluded.title",
1287
1417
  metadata: "excluded.metadata",
1288
1418
  createdAt: "excluded.createdAt",
1289
1419
  updatedAt: "excluded.updatedAt"
1290
- }).build();
1420
+ }, runFenceGuard(check));
1291
1421
  try {
1292
- await this.#db.executeQuery({
1293
- sql,
1294
- params
1295
- });
1422
+ await executeFenced(this.#db, check, query.build());
1296
1423
  return thread;
1297
1424
  } catch (error) {
1425
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
1298
1426
  throw new _mastra_core_error.MastraError({
1299
1427
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "SAVE_THREAD", "FAILED"),
1300
1428
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1304,7 +1432,8 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1304
1432
  }, error);
1305
1433
  }
1306
1434
  }
1307
- async updateThread({ id, title, metadata }) {
1435
+ async updateThread({ id, title, metadata, fence }) {
1436
+ const check = this.#runFenceCheck(fence, "updateThread");
1308
1437
  const thread = await this.getThreadById({ threadId: id });
1309
1438
  try {
1310
1439
  if (!thread) throw new Error(`Thread ${id} not found`);
@@ -1324,11 +1453,10 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1324
1453
  JSON.stringify(mergedMetadata),
1325
1454
  updatedAt.toISOString()
1326
1455
  ];
1327
- const { sql, params } = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id).build();
1328
- await this.#db.executeQuery({
1329
- sql,
1330
- params
1331
- });
1456
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
1457
+ const guard = runFenceGuard(check);
1458
+ if (guard) query.andWhere(guard.sql, ...guard.params);
1459
+ await executeFenced(this.#db, check, query.build());
1332
1460
  return {
1333
1461
  ...thread,
1334
1462
  title: title ?? thread.title,
@@ -1339,6 +1467,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1339
1467
  updatedAt
1340
1468
  };
1341
1469
  } catch (error) {
1470
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
1342
1471
  throw new _mastra_core_error.MastraError({
1343
1472
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "UPDATE_THREAD", "FAILED"),
1344
1473
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1375,6 +1504,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1375
1504
  async saveMessages(args) {
1376
1505
  const { messages } = args;
1377
1506
  if (messages.length === 0) return { messages: [] };
1507
+ const check = this.#runFenceCheck(args.fence, "saveMessages");
1378
1508
  try {
1379
1509
  const now = /* @__PURE__ */ new Date();
1380
1510
  const threadId = messages[0]?.threadId;
@@ -1398,16 +1528,24 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1398
1528
  resourceId: message.resourceId
1399
1529
  };
1400
1530
  });
1401
- await Promise.all([this.#db.batchUpsert({
1531
+ await this.#db.batchUpsert({
1402
1532
  tableName: _mastra_core_storage.TABLE_MESSAGES,
1403
- records: messagesToInsert
1404
- }), this.#db.executeQuery({
1405
- sql: `UPDATE ${this.#db.getTableName(_mastra_core_storage.TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
1406
- params: [now.toISOString(), threadId]
1407
- })]);
1533
+ records: messagesToInsert,
1534
+ check
1535
+ });
1536
+ const guard = runFenceGuard(check);
1537
+ await executeFenced(this.#db, check, {
1538
+ sql: `UPDATE ${this.#db.getTableName(_mastra_core_storage.TABLE_THREADS)} SET updatedAt = ? WHERE id = ?${guard ? ` AND ${guard.sql}` : ""}`,
1539
+ params: [
1540
+ now.toISOString(),
1541
+ threadId,
1542
+ ...guard?.params ?? []
1543
+ ]
1544
+ });
1408
1545
  this.logger.debug(`Saved ${messages.length} messages`);
1409
1546
  return { messages: new _mastra_core_agent.MessageList().add(messages, "memory").get.all.db() };
1410
1547
  } catch (error) {
1548
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
1411
1549
  throw new _mastra_core_error.MastraError({
1412
1550
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "SAVE_MESSAGES", "FAILED"),
1413
1551
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1723,6 +1861,10 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1723
1861
  const { messages } = args;
1724
1862
  this.logger.debug("Updating messages", { count: messages.length });
1725
1863
  if (!messages.length) return [];
1864
+ const check = this.#runFenceCheck(args.fence, "updateMessages");
1865
+ const guard = runFenceGuard(check);
1866
+ const guardSql = guard ? ` AND ${guard.sql}` : "";
1867
+ const guardParams = guard?.params ?? [];
1726
1868
  const messageIds = messages.map((m) => m.id);
1727
1869
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_MESSAGES);
1728
1870
  const threadsTableName = this.#db.getTableName(_mastra_core_storage.TABLE_THREADS);
@@ -1771,19 +1913,23 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1771
1913
  values.push(updatableFields[key]);
1772
1914
  }
1773
1915
  if (setClauses.length > 0) {
1774
- values.push(id);
1775
- const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?`;
1916
+ values.push(id, ...guardParams);
1917
+ const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?${guardSql}`;
1776
1918
  updateQueries.push({
1777
1919
  sql: updateQuery,
1778
1920
  params: values
1779
1921
  });
1780
1922
  }
1781
1923
  }
1782
- for (const query of updateQueries) await this.#db.executeQuery(query);
1924
+ for (const query of updateQueries) await executeFenced(this.#db, check, query);
1783
1925
  if (threadIdsToUpdate.size > 0) {
1784
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${Array.from(threadIdsToUpdate).map(() => "?").join(",")})`;
1785
- const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...Array.from(threadIdsToUpdate)];
1786
- await this.#db.executeQuery({
1926
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${Array.from(threadIdsToUpdate).map(() => "?").join(",")})${guardSql}`;
1927
+ const threadUpdateParams = [
1928
+ (/* @__PURE__ */ new Date()).toISOString(),
1929
+ ...Array.from(threadIdsToUpdate),
1930
+ ...guardParams
1931
+ ];
1932
+ await executeFenced(this.#db, check, {
1787
1933
  sql: threadUpdateQuery,
1788
1934
  params: threadUpdateParams
1789
1935
  });
@@ -1798,6 +1944,7 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1798
1944
  return message;
1799
1945
  });
1800
1946
  } catch (error) {
1947
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
1801
1948
  throw new _mastra_core_error.MastraError({
1802
1949
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "UPDATE_MESSAGES", "FAILED"),
1803
1950
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -1806,10 +1953,12 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1806
1953
  }, error);
1807
1954
  }
1808
1955
  }
1809
- async deleteMessages(messageIds) {
1956
+ async deleteMessages(messageIds, options) {
1810
1957
  if (messageIds.length === 0) return;
1811
1958
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_MESSAGES);
1812
1959
  const threadsTableName = this.#db.getTableName(_mastra_core_storage.TABLE_THREADS);
1960
+ const check = this.#runFenceCheck(options?.fence, "deleteMessages");
1961
+ const guard = runFenceGuard(check);
1813
1962
  try {
1814
1963
  const placeholders = messageIds.map(() => "?").join(",");
1815
1964
  const selectQuery = `SELECT DISTINCT thread_id FROM ${fullTableName} WHERE id IN (${placeholders})`;
@@ -1817,20 +1966,23 @@ var MemoryStorageD1 = class extends _mastra_core_storage.MemoryStorage {
1817
1966
  sql: selectQuery,
1818
1967
  params: messageIds
1819
1968
  })).map((r) => r.thread_id).filter(Boolean);
1820
- const { sql, params } = createSqlBuilder().delete(fullTableName).where(`id IN (${placeholders})`, ...messageIds).build();
1821
- await this.#db.executeQuery({
1822
- sql,
1823
- params
1824
- });
1969
+ const deleteQuery = createSqlBuilder().delete(fullTableName).where(`id IN (${placeholders})`, ...messageIds);
1970
+ if (guard) deleteQuery.andWhere(guard.sql, ...guard.params);
1971
+ await executeFenced(this.#db, check, deleteQuery.build());
1825
1972
  if (threadIds.length > 0) {
1826
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadIds.map(() => "?").join(",")})`;
1827
- const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...threadIds];
1828
- await this.#db.executeQuery({
1973
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadIds.map(() => "?").join(",")})${guard ? ` AND ${guard.sql}` : ""}`;
1974
+ const threadUpdateParams = [
1975
+ (/* @__PURE__ */ new Date()).toISOString(),
1976
+ ...threadIds,
1977
+ ...guard?.params ?? []
1978
+ ];
1979
+ await executeFenced(this.#db, check, {
1829
1980
  sql: threadUpdateQuery,
1830
1981
  params: threadUpdateParams
1831
1982
  });
1832
1983
  }
1833
1984
  } catch (error) {
1985
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
1834
1986
  throw new _mastra_core_error.MastraError({
1835
1987
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "DELETE_MESSAGES", "FAILED"),
1836
1988
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -2150,6 +2302,22 @@ var ScoresStorageD1 = class extends _mastra_core_storage.ScoresStorage {
2150
2302
  };
2151
2303
  //#endregion
2152
2304
  //#region src/storage/domains/workflows/index.ts
2305
+ const RUN_OWNER_COLUMNS = `generation, ownerId, leaseExpiresAt, ${DB_NOW_MS} AS nowMs`;
2306
+ /**
2307
+ * A run's first generation is the database clock, so a run claimed again after
2308
+ * its ownership record was pruned still gets a higher generation than its fence.
2309
+ */
2310
+ const FIRST_GENERATION = `MAX(1, ${DB_NOW_MS})`;
2311
+ function toRunOwnershipRecord(runId, row) {
2312
+ const leaseExpiresAt = row.leaseExpiresAt === null ? null : Number(row.leaseExpiresAt);
2313
+ return {
2314
+ runId,
2315
+ generation: Number(row.generation),
2316
+ ownerId: String(row.ownerId),
2317
+ leaseExpiresAt: leaseExpiresAt === null ? null : new Date(leaseExpiresAt),
2318
+ live: leaseExpiresAt !== null && leaseExpiresAt > Number(row.nowMs)
2319
+ };
2320
+ }
2153
2321
  var WorkflowsStorageD1 = class extends _mastra_core_storage.WorkflowsStorage {
2154
2322
  #db;
2155
2323
  constructor(config) {
@@ -2164,9 +2332,148 @@ var WorkflowsStorageD1 = class extends _mastra_core_storage.WorkflowsStorage {
2164
2332
  tableName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT,
2165
2333
  schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT]
2166
2334
  });
2335
+ await this.#db.createTable({
2336
+ tableName: _mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS,
2337
+ schema: _mastra_core_storage.RUN_FENCING_TABLE_SCHEMAS[_mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS]
2338
+ });
2167
2339
  }
2168
2340
  async dangerouslyClearAll() {
2169
2341
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT });
2342
+ await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS });
2343
+ }
2344
+ supportsRunFencing() {
2345
+ return true;
2346
+ }
2347
+ get #ownersTable() {
2348
+ return this.#db.getTableName(_mastra_core_storage.TABLE_WORKFLOW_RUN_OWNERS);
2349
+ }
2350
+ #runFenceCheck(fence, runId, operation) {
2351
+ const resolved = (0, _mastra_core_storage.resolveRunFence)(this, fence, runId);
2352
+ return resolved && {
2353
+ claimsTable: this.#ownersTable,
2354
+ fence: resolved,
2355
+ operation
2356
+ };
2357
+ }
2358
+ async #readRunOwner(runId) {
2359
+ const row = await this.#db.executeQuery({
2360
+ sql: `SELECT ${RUN_OWNER_COLUMNS} FROM ${this.#ownersTable} WHERE runId = ?`,
2361
+ params: [runId],
2362
+ first: true
2363
+ });
2364
+ return row ? toRunOwnershipRecord(runId, row) : null;
2365
+ }
2366
+ #ownershipError(operation, runId, error) {
2367
+ return new _mastra_core_error.MastraError({
2368
+ id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", operation, "FAILED"),
2369
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2370
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2371
+ details: { runId }
2372
+ }, error);
2373
+ }
2374
+ async claimRunOwnership({ runId, ownerId, leaseMs, force, expectedGeneration }) {
2375
+ const notLive = `(leaseExpiresAt IS NULL OR leaseExpiresAt <= ${DB_NOW_MS})`;
2376
+ let statement;
2377
+ if (expectedGeneration === void 0) statement = {
2378
+ sql: `INSERT INTO ${this.#ownersTable} (runId, generation, ownerId, leaseExpiresAt, updatedAt)
2379
+ VALUES (?, ${FIRST_GENERATION}, ?, ${DB_NOW_MS} + ?, ${DB_NOW_MS})
2380
+ ON CONFLICT(runId) DO UPDATE SET
2381
+ generation = generation + 1,
2382
+ ownerId = excluded.ownerId,
2383
+ leaseExpiresAt = excluded.leaseExpiresAt,
2384
+ updatedAt = excluded.updatedAt
2385
+ ${force ? "" : `WHERE ${notLive}`}`,
2386
+ params: [
2387
+ runId,
2388
+ ownerId,
2389
+ leaseMs
2390
+ ]
2391
+ };
2392
+ else if (expectedGeneration === 0) statement = {
2393
+ sql: `INSERT INTO ${this.#ownersTable} (runId, generation, ownerId, leaseExpiresAt, updatedAt)
2394
+ VALUES (?, ${FIRST_GENERATION}, ?, ${DB_NOW_MS} + ?, ${DB_NOW_MS})
2395
+ ON CONFLICT(runId) DO NOTHING`,
2396
+ params: [
2397
+ runId,
2398
+ ownerId,
2399
+ leaseMs
2400
+ ]
2401
+ };
2402
+ else statement = {
2403
+ sql: `UPDATE ${this.#ownersTable}
2404
+ SET generation = generation + 1, ownerId = ?, leaseExpiresAt = ${DB_NOW_MS} + ?, updatedAt = ${DB_NOW_MS}
2405
+ WHERE runId = ? AND generation = ?${force ? "" : ` AND ${notLive}`}`,
2406
+ params: [
2407
+ ownerId,
2408
+ leaseMs,
2409
+ runId,
2410
+ expectedGeneration
2411
+ ]
2412
+ };
2413
+ try {
2414
+ const claimed = (await this.#db.executeQuery({
2415
+ sql: `${statement.sql} RETURNING ${RUN_OWNER_COLUMNS}`,
2416
+ params: statement.params
2417
+ }))[0];
2418
+ if (claimed) return {
2419
+ acquired: true,
2420
+ record: toRunOwnershipRecord(runId, claimed)
2421
+ };
2422
+ return {
2423
+ acquired: false,
2424
+ record: await this.#readRunOwner(runId)
2425
+ };
2426
+ } catch (error) {
2427
+ throw this.#ownershipError("CLAIM_RUN_OWNERSHIP", runId, error);
2428
+ }
2429
+ }
2430
+ async renewRunOwnership({ leaseMs, ...fence }) {
2431
+ try {
2432
+ const renewed = (await this.#db.executeQuery({
2433
+ sql: `UPDATE ${this.#ownersTable} SET leaseExpiresAt = ${DB_NOW_MS} + ?, updatedAt = ${DB_NOW_MS}
2434
+ WHERE runId = ? AND generation = ? AND ownerId = ? AND leaseExpiresAt IS NOT NULL
2435
+ RETURNING ${RUN_OWNER_COLUMNS}`,
2436
+ params: [
2437
+ leaseMs,
2438
+ fence.runId,
2439
+ fence.generation,
2440
+ fence.ownerId
2441
+ ]
2442
+ }))[0];
2443
+ if (renewed) return {
2444
+ renewed: true,
2445
+ record: toRunOwnershipRecord(fence.runId, renewed)
2446
+ };
2447
+ return {
2448
+ renewed: false,
2449
+ record: await this.#readRunOwner(fence.runId)
2450
+ };
2451
+ } catch (error) {
2452
+ throw this.#ownershipError("RENEW_RUN_OWNERSHIP", fence.runId, error);
2453
+ }
2454
+ }
2455
+ async releaseRunOwnership(fence) {
2456
+ try {
2457
+ return (await this.#db.executeQuery({
2458
+ sql: `UPDATE ${this.#ownersTable} SET leaseExpiresAt = NULL, updatedAt = ${DB_NOW_MS}
2459
+ WHERE runId = ? AND generation = ? AND ownerId = ?
2460
+ RETURNING runId`,
2461
+ params: [
2462
+ fence.runId,
2463
+ fence.generation,
2464
+ fence.ownerId
2465
+ ]
2466
+ })).length > 0;
2467
+ } catch (error) {
2468
+ throw this.#ownershipError("RELEASE_RUN_OWNERSHIP", fence.runId, error);
2469
+ }
2470
+ }
2471
+ async getRunOwnership({ runId }) {
2472
+ try {
2473
+ return await this.#readRunOwner(runId);
2474
+ } catch (error) {
2475
+ throw this.#ownershipError("GET_RUN_OWNERSHIP", runId, error);
2476
+ }
2170
2477
  }
2171
2478
  async updateWorkflowResults(_args) {
2172
2479
  throw new Error("updateWorkflowResults is not implemented for Cloudflare D1 storage. D1 does not support atomic read-modify-write operations needed for concurrent workflow updates.");
@@ -2174,9 +2481,10 @@ var WorkflowsStorageD1 = class extends _mastra_core_storage.WorkflowsStorage {
2174
2481
  async updateWorkflowState(_args) {
2175
2482
  throw new Error("updateWorkflowState is not implemented for Cloudflare D1 storage. D1 does not support atomic read-modify-write operations needed for concurrent workflow updates.");
2176
2483
  }
2177
- async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt }) {
2484
+ async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt, fence }) {
2178
2485
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT);
2179
2486
  const now = (/* @__PURE__ */ new Date()).toISOString();
2487
+ const check = this.#runFenceCheck(fence, runId, "persistWorkflowSnapshot");
2180
2488
  const currentSnapshot = await this.#db.load({
2181
2489
  tableName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT,
2182
2490
  keys: {
@@ -2208,13 +2516,11 @@ var WorkflowsStorageD1 = class extends _mastra_core_storage.WorkflowsStorage {
2208
2516
  workflowName,
2209
2517
  runId
2210
2518
  });
2211
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap).build();
2519
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap, runFenceGuard(check));
2212
2520
  try {
2213
- await this.#db.executeQuery({
2214
- sql,
2215
- params
2216
- });
2521
+ await executeFenced(this.#db, check, query.build());
2217
2522
  } catch (error) {
2523
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
2218
2524
  throw new _mastra_core_error.MastraError({
2219
2525
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2220
2526
  domain: _mastra_core_error.ErrorDomain.STORAGE,
@@ -2366,16 +2672,16 @@ var WorkflowsStorageD1 = class extends _mastra_core_storage.WorkflowsStorage {
2366
2672
  }, error);
2367
2673
  }
2368
2674
  }
2369
- async deleteWorkflowRunById({ runId, workflowName }) {
2675
+ async deleteWorkflowRunById({ runId, workflowName, fence }) {
2370
2676
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT);
2677
+ const check = this.#runFenceCheck(fence, runId, "deleteWorkflowRunById");
2371
2678
  try {
2372
- const sql = `DELETE FROM ${fullTableName} WHERE workflow_name = ? AND run_id = ?`;
2373
- const params = [workflowName, runId];
2374
- await this.#db.executeQuery({
2375
- sql,
2376
- params
2377
- });
2679
+ const query = createSqlBuilder().delete(fullTableName).where("workflow_name = ?", workflowName).andWhere("run_id = ?", runId);
2680
+ const guard = runFenceGuard(check);
2681
+ if (guard) query.andWhere(guard.sql, ...guard.params);
2682
+ await executeFenced(this.#db, check, query.build());
2378
2683
  } catch (error) {
2684
+ if ((0, _mastra_core_storage.isRunFenceConflictError)(error)) throw error;
2379
2685
  throw new _mastra_core_error.MastraError({
2380
2686
  id: (0, _mastra_core_storage.createStorageErrorId)("CLOUDFLARE_D1", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2381
2687
  domain: _mastra_core_error.ErrorDomain.STORAGE,