@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
2
- import { BackgroundTasksStorage, MastraCompositeStore, MemoryStorage, ScoresStorage, TABLE_BACKGROUND_TASKS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_THREADS, TABLE_WORKFLOW_SNAPSHOT, WorkflowsStorage, calculatePagination, createStorageErrorId, ensureDate, getDefaultValue, getSqlType, normalizePerPage, serializeDate, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
2
+ import { BackgroundTasksStorage, MastraCompositeStore, MemoryStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, ScoresStorage, TABLE_BACKGROUND_TASKS, TABLE_MEMORY_RUN_FENCES, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_THREADS, TABLE_WORKFLOW_RUN_OWNERS, TABLE_WORKFLOW_SNAPSHOT, WorkflowsStorage, calculatePagination, createStorageErrorId, ensureDate, getDefaultValue, getSqlType, isRunFenceConflictError, matchesRunFence, normalizePerPage, resolveRunFence, serializeDate, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
3
3
  import Cloudflare from "cloudflare";
4
4
  import { MastraBase } from "@mastra/core/base";
5
5
  import { parseSqlIdentifier } from "@mastra/core/utils";
@@ -104,20 +104,20 @@ var SqlBuilder = class {
104
104
  * @param values Values to insert
105
105
  * @param conflictColumns Columns to check for conflict (usually PK or UNIQUE)
106
106
  * @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
107
+ * @param guard Condition the statement writes under: when it is false, neither the insert nor the conflict update happens
107
108
  */
108
- insert(table, columns, values, conflictColumns, updateMap) {
109
+ insert(table, columns, values, conflictColumns, updateMap, guard) {
109
110
  const parsedTableName = parseSqlIdentifier(table, "table name");
110
111
  const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
111
112
  const placeholders = parsedColumns.map(() => "?").join(", ");
113
+ const source = guard ? `SELECT ${placeholders} WHERE ${guard.sql}` : `VALUES (${placeholders})`;
114
+ this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) ${source}`;
115
+ this.params.push(...values, ...guard?.params ?? []);
112
116
  if (conflictColumns && updateMap) {
113
117
  const parsedConflictColumns = conflictColumns.map((col) => parseSqlIdentifier(col, "column name"));
114
118
  const updateClause = Object.entries(updateMap).map(([col, expr]) => `${col} = ${expr}`).join(", ");
115
- this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
116
- this.params.push(...values);
117
- return this;
119
+ this.sql += ` ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
118
120
  }
119
- this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders})`;
120
- this.params.push(...values);
121
121
  return this;
122
122
  }
123
123
  update(table, columns, values) {
@@ -255,6 +255,68 @@ function parseSelectIdentifier(column) {
255
255
  return column;
256
256
  }
257
257
  //#endregion
258
+ //#region src/storage/db/run-fencing.ts
259
+ /**
260
+ * Epoch milliseconds on the database clock. `julianday('now')` rather than
261
+ * `unixepoch('subsec')`, which needs SQLite 3.42.
262
+ */
263
+ const DB_NOW_MS = `CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)`;
264
+ /**
265
+ * The condition a fenced statement writes under: the check's fence is the
266
+ * run's current claim. D1 has no interactive transactions, so a fenced write
267
+ * can't check the claim first and write second; each of its statements
268
+ * carries this condition instead, and SQLite evaluates it atomically with the
269
+ * write.
270
+ */
271
+ function runFenceGuard(check) {
272
+ if (!check) return void 0;
273
+ const { claimsTable, fence } = check;
274
+ return {
275
+ sql: `EXISTS (SELECT 1 FROM ${claimsTable} AS run_fence WHERE run_fence.runId = ? AND run_fence.generation = ? AND run_fence.ownerId = ?)`,
276
+ params: [
277
+ fence.runId,
278
+ fence.generation,
279
+ fence.ownerId
280
+ ]
281
+ };
282
+ }
283
+ /** Throws `RunFenceConflictError` unless the check's fence is the run's current claim. */
284
+ async function assertRunFence(db, { claimsTable, fence, operation }) {
285
+ const row = await db.executeQuery({
286
+ sql: `SELECT generation, ownerId FROM ${claimsTable} WHERE runId = ?`,
287
+ params: [fence.runId],
288
+ first: true
289
+ });
290
+ if (!matchesRunFence(row ? {
291
+ generation: Number(row.generation),
292
+ ownerId: String(row.ownerId)
293
+ } : null, fence)) throw new RunFenceConflictError(fence, operation);
294
+ }
295
+ /**
296
+ * Runs one statement of a fenced write. With a check, `statement` must carry
297
+ * `runFenceGuard(check)`. A guarded statement that changes no row either
298
+ * found no target or was refused by its guard; re-reading the claim tells
299
+ * which, and a refusal throws `RunFenceConflictError`.
300
+ *
301
+ * A write made of several statements stops at the first refused one, so a
302
+ * takeover that lands between them leaves the earlier statements applied.
303
+ * None of the refused writer's statements land after the takeover.
304
+ */
305
+ async function executeFenced(db, check, { sql, params }) {
306
+ if (!check) {
307
+ await db.executeQuery({
308
+ sql,
309
+ params
310
+ });
311
+ return;
312
+ }
313
+ const rows = await db.executeQuery({
314
+ sql: `${sql} RETURNING 1 AS written`,
315
+ params
316
+ });
317
+ if (Array.isArray(rows) && rows.length === 0) await assertRunFence(db, check);
318
+ }
319
+ //#endregion
258
320
  //#region src/storage/db/index.ts
259
321
  /**
260
322
  * Resolves D1DomainConfig to D1DBConfig.
@@ -589,10 +651,12 @@ var D1DB = class extends MastraBase {
589
651
  * Upsert multiple records in a batch operation
590
652
  * @param tableName The table to insert into
591
653
  * @param records The records to insert
654
+ * @param check Run fence every upsert must hold; a refused upsert throws and stops the batch
592
655
  */
593
- async batchUpsert({ tableName, records }) {
656
+ async batchUpsert({ tableName, records, check }) {
594
657
  if (records.length === 0) return;
595
658
  const fullTableName = this.getTableName(tableName);
659
+ const guard = runFenceGuard(check);
596
660
  try {
597
661
  const batchSize = 50;
598
662
  for (let i = 0; i < records.length; i += batchSize) {
@@ -610,17 +674,15 @@ var D1DB = class extends MastraBase {
610
674
  if (col !== "createdAt") acc[col] = `excluded.${col}`;
611
675
  return acc;
612
676
  }, {});
613
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert).build();
614
- await this.executeQuery({
615
- sql,
616
- params
617
- });
677
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert, guard);
678
+ await executeFenced(this, check, query.build());
618
679
  }
619
680
  }
620
681
  this.logger.debug(`Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`);
621
682
  }
622
683
  this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
623
684
  } catch (error) {
685
+ if (isRunFenceConflictError(error)) throw error;
624
686
  throw new MastraError({
625
687
  id: createStorageErrorId("CLOUDFLARE_D1", "BATCH_UPSERT", "FAILED"),
626
688
  domain: ErrorDomain.STORAGE,
@@ -1003,11 +1065,76 @@ var MemoryStorageD1 = class extends MemoryStorage {
1003
1065
  schema: TABLE_SCHEMAS[TABLE_MESSAGES],
1004
1066
  ifNotExists: ["resourceId"]
1005
1067
  });
1068
+ await this.#db.createTable({
1069
+ tableName: TABLE_MEMORY_RUN_FENCES,
1070
+ schema: RUN_FENCING_TABLE_SCHEMAS[TABLE_MEMORY_RUN_FENCES]
1071
+ });
1006
1072
  }
1007
1073
  async dangerouslyClearAll() {
1008
1074
  await this.#db.clearTable({ tableName: TABLE_MESSAGES });
1009
1075
  await this.#db.clearTable({ tableName: TABLE_THREADS });
1010
1076
  await this.#db.clearTable({ tableName: TABLE_RESOURCES });
1077
+ await this.#db.clearTable({ tableName: TABLE_MEMORY_RUN_FENCES });
1078
+ }
1079
+ supportsRunFencing() {
1080
+ return true;
1081
+ }
1082
+ get #fencesTable() {
1083
+ return this.#db.getTableName(TABLE_MEMORY_RUN_FENCES);
1084
+ }
1085
+ async raiseRunFence(fence) {
1086
+ const table = this.#fencesTable;
1087
+ try {
1088
+ return (await this.#db.executeQuery({
1089
+ sql: `INSERT INTO ${table} (runId, generation, ownerId) VALUES (?, ?, ?)
1090
+ ON CONFLICT(runId) DO UPDATE SET generation = excluded.generation, ownerId = excluded.ownerId, retiredAt = NULL
1091
+ WHERE excluded.generation > ${table}.generation
1092
+ OR (excluded.generation = ${table}.generation AND excluded.ownerId = ${table}.ownerId)
1093
+ RETURNING runId`,
1094
+ params: [
1095
+ fence.runId,
1096
+ fence.generation,
1097
+ fence.ownerId
1098
+ ]
1099
+ })).length > 0;
1100
+ } catch (error) {
1101
+ throw new MastraError({
1102
+ id: createStorageErrorId("CLOUDFLARE_D1", "RAISE_RUN_FENCE", "FAILED"),
1103
+ domain: ErrorDomain.STORAGE,
1104
+ category: ErrorCategory.THIRD_PARTY,
1105
+ details: { runId: fence.runId }
1106
+ }, error);
1107
+ }
1108
+ }
1109
+ async retireRunFence(fence) {
1110
+ try {
1111
+ return (await this.#db.executeQuery({
1112
+ sql: `UPDATE ${this.#fencesTable} SET retiredAt = ${DB_NOW_MS}
1113
+ WHERE runId = ? AND generation = ? AND ownerId = ?
1114
+ RETURNING runId`,
1115
+ params: [
1116
+ fence.runId,
1117
+ fence.generation,
1118
+ fence.ownerId
1119
+ ]
1120
+ })).length > 0;
1121
+ } catch (error) {
1122
+ throw new MastraError({
1123
+ id: createStorageErrorId("CLOUDFLARE_D1", "RETIRE_RUN_FENCE", "FAILED"),
1124
+ domain: ErrorDomain.STORAGE,
1125
+ category: ErrorCategory.THIRD_PARTY,
1126
+ details: { runId: fence.runId }
1127
+ }, error);
1128
+ }
1129
+ }
1130
+ /** The check a write must pass: its own fence, otherwise the one in scope. */
1131
+ #runFenceCheck(fence, operation) {
1132
+ const resolved = resolveRunFence(this, fence);
1133
+ return resolved && {
1134
+ claimsTable: this.#fencesTable,
1135
+ fence: resolved,
1136
+ operation
1137
+ };
1011
1138
  }
1012
1139
  async getResourceById({ resourceId }) {
1013
1140
  const resource = await this.#db.load({
@@ -1036,6 +1163,9 @@ var MemoryStorageD1 = class extends MemoryStorage {
1036
1163
  }
1037
1164
  }
1038
1165
  async saveResource({ resource }) {
1166
+ return this.#insertResource(resource, void 0);
1167
+ }
1168
+ async #insertResource(resource, check) {
1039
1169
  const fullTableName = this.#db.getTableName(TABLE_RESOURCES);
1040
1170
  const resourceToSave = {
1041
1171
  id: resource.id,
@@ -1047,19 +1177,17 @@ var MemoryStorageD1 = class extends MemoryStorage {
1047
1177
  const processedRecord = await this.#db.processRecord(resourceToSave);
1048
1178
  const columns = Object.keys(processedRecord);
1049
1179
  const values = Object.values(processedRecord);
1050
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1180
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1051
1181
  workingMemory: "excluded.workingMemory",
1052
1182
  metadata: "excluded.metadata",
1053
1183
  createdAt: "excluded.createdAt",
1054
1184
  updatedAt: "excluded.updatedAt"
1055
- }).build();
1185
+ }, runFenceGuard(check));
1056
1186
  try {
1057
- await this.#db.executeQuery({
1058
- sql,
1059
- params
1060
- });
1187
+ await executeFenced(this.#db, check, query.build());
1061
1188
  return resource;
1062
1189
  } catch (error) {
1190
+ if (isRunFenceConflictError(error)) throw error;
1063
1191
  throw new MastraError({
1064
1192
  id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_RESOURCE", "FAILED"),
1065
1193
  domain: ErrorDomain.STORAGE,
@@ -1069,7 +1197,8 @@ var MemoryStorageD1 = class extends MemoryStorage {
1069
1197
  }, error);
1070
1198
  }
1071
1199
  }
1072
- async updateResource({ resourceId, workingMemory, metadata }) {
1200
+ async updateResource({ resourceId, workingMemory, metadata, fence }) {
1201
+ const check = this.#runFenceCheck(fence, "updateResource");
1073
1202
  const existingResource = await this.getResourceById({ resourceId });
1074
1203
  if (!existingResource) {
1075
1204
  const newResource = {
@@ -1079,7 +1208,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1079
1208
  createdAt: /* @__PURE__ */ new Date(),
1080
1209
  updatedAt: /* @__PURE__ */ new Date()
1081
1210
  };
1082
- return this.saveResource({ resource: newResource });
1211
+ return this.#insertResource(newResource, check);
1083
1212
  }
1084
1213
  const updatedAt = /* @__PURE__ */ new Date();
1085
1214
  const updatedResource = {
@@ -1102,14 +1231,14 @@ var MemoryStorageD1 = class extends MemoryStorage {
1102
1231
  JSON.stringify(updatedResource.metadata),
1103
1232
  updatedAt.toISOString()
1104
1233
  ];
1105
- const { sql, params } = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId).build();
1234
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
1235
+ const guard = runFenceGuard(check);
1236
+ if (guard) query.andWhere(guard.sql, ...guard.params);
1106
1237
  try {
1107
- await this.#db.executeQuery({
1108
- sql,
1109
- params
1110
- });
1238
+ await executeFenced(this.#db, check, query.build());
1111
1239
  return updatedResource;
1112
1240
  } catch (error) {
1241
+ if (isRunFenceConflictError(error)) throw error;
1113
1242
  throw new MastraError({
1114
1243
  id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_RESOURCE", "FAILED"),
1115
1244
  domain: ErrorDomain.STORAGE,
@@ -1244,8 +1373,9 @@ var MemoryStorageD1 = class extends MemoryStorage {
1244
1373
  throw mastraError;
1245
1374
  }
1246
1375
  }
1247
- async saveThread({ thread }) {
1376
+ async saveThread({ thread, fence }) {
1248
1377
  const fullTableName = this.#db.getTableName(TABLE_THREADS);
1378
+ const check = this.#runFenceCheck(fence, "saveThread");
1249
1379
  const threadToSave = {
1250
1380
  id: thread.id,
1251
1381
  resourceId: thread.resourceId,
@@ -1257,20 +1387,18 @@ var MemoryStorageD1 = class extends MemoryStorage {
1257
1387
  const processedRecord = await this.#db.processRecord(threadToSave);
1258
1388
  const columns = Object.keys(processedRecord);
1259
1389
  const values = Object.values(processedRecord);
1260
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1390
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], {
1261
1391
  resourceId: "excluded.resourceId",
1262
1392
  title: "excluded.title",
1263
1393
  metadata: "excluded.metadata",
1264
1394
  createdAt: "excluded.createdAt",
1265
1395
  updatedAt: "excluded.updatedAt"
1266
- }).build();
1396
+ }, runFenceGuard(check));
1267
1397
  try {
1268
- await this.#db.executeQuery({
1269
- sql,
1270
- params
1271
- });
1398
+ await executeFenced(this.#db, check, query.build());
1272
1399
  return thread;
1273
1400
  } catch (error) {
1401
+ if (isRunFenceConflictError(error)) throw error;
1274
1402
  throw new MastraError({
1275
1403
  id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_THREAD", "FAILED"),
1276
1404
  domain: ErrorDomain.STORAGE,
@@ -1280,7 +1408,8 @@ var MemoryStorageD1 = class extends MemoryStorage {
1280
1408
  }, error);
1281
1409
  }
1282
1410
  }
1283
- async updateThread({ id, title, metadata }) {
1411
+ async updateThread({ id, title, metadata, fence }) {
1412
+ const check = this.#runFenceCheck(fence, "updateThread");
1284
1413
  const thread = await this.getThreadById({ threadId: id });
1285
1414
  try {
1286
1415
  if (!thread) throw new Error(`Thread ${id} not found`);
@@ -1300,11 +1429,10 @@ var MemoryStorageD1 = class extends MemoryStorage {
1300
1429
  JSON.stringify(mergedMetadata),
1301
1430
  updatedAt.toISOString()
1302
1431
  ];
1303
- const { sql, params } = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id).build();
1304
- await this.#db.executeQuery({
1305
- sql,
1306
- params
1307
- });
1432
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
1433
+ const guard = runFenceGuard(check);
1434
+ if (guard) query.andWhere(guard.sql, ...guard.params);
1435
+ await executeFenced(this.#db, check, query.build());
1308
1436
  return {
1309
1437
  ...thread,
1310
1438
  title: title ?? thread.title,
@@ -1315,6 +1443,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1315
1443
  updatedAt
1316
1444
  };
1317
1445
  } catch (error) {
1446
+ if (isRunFenceConflictError(error)) throw error;
1318
1447
  throw new MastraError({
1319
1448
  id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_THREAD", "FAILED"),
1320
1449
  domain: ErrorDomain.STORAGE,
@@ -1351,6 +1480,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1351
1480
  async saveMessages(args) {
1352
1481
  const { messages } = args;
1353
1482
  if (messages.length === 0) return { messages: [] };
1483
+ const check = this.#runFenceCheck(args.fence, "saveMessages");
1354
1484
  try {
1355
1485
  const now = /* @__PURE__ */ new Date();
1356
1486
  const threadId = messages[0]?.threadId;
@@ -1374,16 +1504,24 @@ var MemoryStorageD1 = class extends MemoryStorage {
1374
1504
  resourceId: message.resourceId
1375
1505
  };
1376
1506
  });
1377
- await Promise.all([this.#db.batchUpsert({
1507
+ await this.#db.batchUpsert({
1378
1508
  tableName: TABLE_MESSAGES,
1379
- records: messagesToInsert
1380
- }), this.#db.executeQuery({
1381
- sql: `UPDATE ${this.#db.getTableName(TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
1382
- params: [now.toISOString(), threadId]
1383
- })]);
1509
+ records: messagesToInsert,
1510
+ check
1511
+ });
1512
+ const guard = runFenceGuard(check);
1513
+ await executeFenced(this.#db, check, {
1514
+ sql: `UPDATE ${this.#db.getTableName(TABLE_THREADS)} SET updatedAt = ? WHERE id = ?${guard ? ` AND ${guard.sql}` : ""}`,
1515
+ params: [
1516
+ now.toISOString(),
1517
+ threadId,
1518
+ ...guard?.params ?? []
1519
+ ]
1520
+ });
1384
1521
  this.logger.debug(`Saved ${messages.length} messages`);
1385
1522
  return { messages: new MessageList().add(messages, "memory").get.all.db() };
1386
1523
  } catch (error) {
1524
+ if (isRunFenceConflictError(error)) throw error;
1387
1525
  throw new MastraError({
1388
1526
  id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_MESSAGES", "FAILED"),
1389
1527
  domain: ErrorDomain.STORAGE,
@@ -1699,6 +1837,10 @@ var MemoryStorageD1 = class extends MemoryStorage {
1699
1837
  const { messages } = args;
1700
1838
  this.logger.debug("Updating messages", { count: messages.length });
1701
1839
  if (!messages.length) return [];
1840
+ const check = this.#runFenceCheck(args.fence, "updateMessages");
1841
+ const guard = runFenceGuard(check);
1842
+ const guardSql = guard ? ` AND ${guard.sql}` : "";
1843
+ const guardParams = guard?.params ?? [];
1702
1844
  const messageIds = messages.map((m) => m.id);
1703
1845
  const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1704
1846
  const threadsTableName = this.#db.getTableName(TABLE_THREADS);
@@ -1747,19 +1889,23 @@ var MemoryStorageD1 = class extends MemoryStorage {
1747
1889
  values.push(updatableFields[key]);
1748
1890
  }
1749
1891
  if (setClauses.length > 0) {
1750
- values.push(id);
1751
- const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?`;
1892
+ values.push(id, ...guardParams);
1893
+ const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?${guardSql}`;
1752
1894
  updateQueries.push({
1753
1895
  sql: updateQuery,
1754
1896
  params: values
1755
1897
  });
1756
1898
  }
1757
1899
  }
1758
- for (const query of updateQueries) await this.#db.executeQuery(query);
1900
+ for (const query of updateQueries) await executeFenced(this.#db, check, query);
1759
1901
  if (threadIdsToUpdate.size > 0) {
1760
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${Array.from(threadIdsToUpdate).map(() => "?").join(",")})`;
1761
- const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...Array.from(threadIdsToUpdate)];
1762
- await this.#db.executeQuery({
1902
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${Array.from(threadIdsToUpdate).map(() => "?").join(",")})${guardSql}`;
1903
+ const threadUpdateParams = [
1904
+ (/* @__PURE__ */ new Date()).toISOString(),
1905
+ ...Array.from(threadIdsToUpdate),
1906
+ ...guardParams
1907
+ ];
1908
+ await executeFenced(this.#db, check, {
1763
1909
  sql: threadUpdateQuery,
1764
1910
  params: threadUpdateParams
1765
1911
  });
@@ -1774,6 +1920,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1774
1920
  return message;
1775
1921
  });
1776
1922
  } catch (error) {
1923
+ if (isRunFenceConflictError(error)) throw error;
1777
1924
  throw new MastraError({
1778
1925
  id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_MESSAGES", "FAILED"),
1779
1926
  domain: ErrorDomain.STORAGE,
@@ -1782,10 +1929,12 @@ var MemoryStorageD1 = class extends MemoryStorage {
1782
1929
  }, error);
1783
1930
  }
1784
1931
  }
1785
- async deleteMessages(messageIds) {
1932
+ async deleteMessages(messageIds, options) {
1786
1933
  if (messageIds.length === 0) return;
1787
1934
  const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1788
1935
  const threadsTableName = this.#db.getTableName(TABLE_THREADS);
1936
+ const check = this.#runFenceCheck(options?.fence, "deleteMessages");
1937
+ const guard = runFenceGuard(check);
1789
1938
  try {
1790
1939
  const placeholders = messageIds.map(() => "?").join(",");
1791
1940
  const selectQuery = `SELECT DISTINCT thread_id FROM ${fullTableName} WHERE id IN (${placeholders})`;
@@ -1793,20 +1942,23 @@ var MemoryStorageD1 = class extends MemoryStorage {
1793
1942
  sql: selectQuery,
1794
1943
  params: messageIds
1795
1944
  })).map((r) => r.thread_id).filter(Boolean);
1796
- const { sql, params } = createSqlBuilder().delete(fullTableName).where(`id IN (${placeholders})`, ...messageIds).build();
1797
- await this.#db.executeQuery({
1798
- sql,
1799
- params
1800
- });
1945
+ const deleteQuery = createSqlBuilder().delete(fullTableName).where(`id IN (${placeholders})`, ...messageIds);
1946
+ if (guard) deleteQuery.andWhere(guard.sql, ...guard.params);
1947
+ await executeFenced(this.#db, check, deleteQuery.build());
1801
1948
  if (threadIds.length > 0) {
1802
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadIds.map(() => "?").join(",")})`;
1803
- const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...threadIds];
1804
- await this.#db.executeQuery({
1949
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadIds.map(() => "?").join(",")})${guard ? ` AND ${guard.sql}` : ""}`;
1950
+ const threadUpdateParams = [
1951
+ (/* @__PURE__ */ new Date()).toISOString(),
1952
+ ...threadIds,
1953
+ ...guard?.params ?? []
1954
+ ];
1955
+ await executeFenced(this.#db, check, {
1805
1956
  sql: threadUpdateQuery,
1806
1957
  params: threadUpdateParams
1807
1958
  });
1808
1959
  }
1809
1960
  } catch (error) {
1961
+ if (isRunFenceConflictError(error)) throw error;
1810
1962
  throw new MastraError({
1811
1963
  id: createStorageErrorId("CLOUDFLARE_D1", "DELETE_MESSAGES", "FAILED"),
1812
1964
  domain: ErrorDomain.STORAGE,
@@ -2126,6 +2278,22 @@ var ScoresStorageD1 = class extends ScoresStorage {
2126
2278
  };
2127
2279
  //#endregion
2128
2280
  //#region src/storage/domains/workflows/index.ts
2281
+ const RUN_OWNER_COLUMNS = `generation, ownerId, leaseExpiresAt, ${DB_NOW_MS} AS nowMs`;
2282
+ /**
2283
+ * A run's first generation is the database clock, so a run claimed again after
2284
+ * its ownership record was pruned still gets a higher generation than its fence.
2285
+ */
2286
+ const FIRST_GENERATION = `MAX(1, ${DB_NOW_MS})`;
2287
+ function toRunOwnershipRecord(runId, row) {
2288
+ const leaseExpiresAt = row.leaseExpiresAt === null ? null : Number(row.leaseExpiresAt);
2289
+ return {
2290
+ runId,
2291
+ generation: Number(row.generation),
2292
+ ownerId: String(row.ownerId),
2293
+ leaseExpiresAt: leaseExpiresAt === null ? null : new Date(leaseExpiresAt),
2294
+ live: leaseExpiresAt !== null && leaseExpiresAt > Number(row.nowMs)
2295
+ };
2296
+ }
2129
2297
  var WorkflowsStorageD1 = class extends WorkflowsStorage {
2130
2298
  #db;
2131
2299
  constructor(config) {
@@ -2140,9 +2308,148 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2140
2308
  tableName: TABLE_WORKFLOW_SNAPSHOT,
2141
2309
  schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT]
2142
2310
  });
2311
+ await this.#db.createTable({
2312
+ tableName: TABLE_WORKFLOW_RUN_OWNERS,
2313
+ schema: RUN_FENCING_TABLE_SCHEMAS[TABLE_WORKFLOW_RUN_OWNERS]
2314
+ });
2143
2315
  }
2144
2316
  async dangerouslyClearAll() {
2145
2317
  await this.#db.clearTable({ tableName: TABLE_WORKFLOW_SNAPSHOT });
2318
+ await this.#db.clearTable({ tableName: TABLE_WORKFLOW_RUN_OWNERS });
2319
+ }
2320
+ supportsRunFencing() {
2321
+ return true;
2322
+ }
2323
+ get #ownersTable() {
2324
+ return this.#db.getTableName(TABLE_WORKFLOW_RUN_OWNERS);
2325
+ }
2326
+ #runFenceCheck(fence, runId, operation) {
2327
+ const resolved = resolveRunFence(this, fence, runId);
2328
+ return resolved && {
2329
+ claimsTable: this.#ownersTable,
2330
+ fence: resolved,
2331
+ operation
2332
+ };
2333
+ }
2334
+ async #readRunOwner(runId) {
2335
+ const row = await this.#db.executeQuery({
2336
+ sql: `SELECT ${RUN_OWNER_COLUMNS} FROM ${this.#ownersTable} WHERE runId = ?`,
2337
+ params: [runId],
2338
+ first: true
2339
+ });
2340
+ return row ? toRunOwnershipRecord(runId, row) : null;
2341
+ }
2342
+ #ownershipError(operation, runId, error) {
2343
+ return new MastraError({
2344
+ id: createStorageErrorId("CLOUDFLARE_D1", operation, "FAILED"),
2345
+ domain: ErrorDomain.STORAGE,
2346
+ category: ErrorCategory.THIRD_PARTY,
2347
+ details: { runId }
2348
+ }, error);
2349
+ }
2350
+ async claimRunOwnership({ runId, ownerId, leaseMs, force, expectedGeneration }) {
2351
+ const notLive = `(leaseExpiresAt IS NULL OR leaseExpiresAt <= ${DB_NOW_MS})`;
2352
+ let statement;
2353
+ if (expectedGeneration === void 0) statement = {
2354
+ sql: `INSERT INTO ${this.#ownersTable} (runId, generation, ownerId, leaseExpiresAt, updatedAt)
2355
+ VALUES (?, ${FIRST_GENERATION}, ?, ${DB_NOW_MS} + ?, ${DB_NOW_MS})
2356
+ ON CONFLICT(runId) DO UPDATE SET
2357
+ generation = generation + 1,
2358
+ ownerId = excluded.ownerId,
2359
+ leaseExpiresAt = excluded.leaseExpiresAt,
2360
+ updatedAt = excluded.updatedAt
2361
+ ${force ? "" : `WHERE ${notLive}`}`,
2362
+ params: [
2363
+ runId,
2364
+ ownerId,
2365
+ leaseMs
2366
+ ]
2367
+ };
2368
+ else if (expectedGeneration === 0) statement = {
2369
+ sql: `INSERT INTO ${this.#ownersTable} (runId, generation, ownerId, leaseExpiresAt, updatedAt)
2370
+ VALUES (?, ${FIRST_GENERATION}, ?, ${DB_NOW_MS} + ?, ${DB_NOW_MS})
2371
+ ON CONFLICT(runId) DO NOTHING`,
2372
+ params: [
2373
+ runId,
2374
+ ownerId,
2375
+ leaseMs
2376
+ ]
2377
+ };
2378
+ else statement = {
2379
+ sql: `UPDATE ${this.#ownersTable}
2380
+ SET generation = generation + 1, ownerId = ?, leaseExpiresAt = ${DB_NOW_MS} + ?, updatedAt = ${DB_NOW_MS}
2381
+ WHERE runId = ? AND generation = ?${force ? "" : ` AND ${notLive}`}`,
2382
+ params: [
2383
+ ownerId,
2384
+ leaseMs,
2385
+ runId,
2386
+ expectedGeneration
2387
+ ]
2388
+ };
2389
+ try {
2390
+ const claimed = (await this.#db.executeQuery({
2391
+ sql: `${statement.sql} RETURNING ${RUN_OWNER_COLUMNS}`,
2392
+ params: statement.params
2393
+ }))[0];
2394
+ if (claimed) return {
2395
+ acquired: true,
2396
+ record: toRunOwnershipRecord(runId, claimed)
2397
+ };
2398
+ return {
2399
+ acquired: false,
2400
+ record: await this.#readRunOwner(runId)
2401
+ };
2402
+ } catch (error) {
2403
+ throw this.#ownershipError("CLAIM_RUN_OWNERSHIP", runId, error);
2404
+ }
2405
+ }
2406
+ async renewRunOwnership({ leaseMs, ...fence }) {
2407
+ try {
2408
+ const renewed = (await this.#db.executeQuery({
2409
+ sql: `UPDATE ${this.#ownersTable} SET leaseExpiresAt = ${DB_NOW_MS} + ?, updatedAt = ${DB_NOW_MS}
2410
+ WHERE runId = ? AND generation = ? AND ownerId = ? AND leaseExpiresAt IS NOT NULL
2411
+ RETURNING ${RUN_OWNER_COLUMNS}`,
2412
+ params: [
2413
+ leaseMs,
2414
+ fence.runId,
2415
+ fence.generation,
2416
+ fence.ownerId
2417
+ ]
2418
+ }))[0];
2419
+ if (renewed) return {
2420
+ renewed: true,
2421
+ record: toRunOwnershipRecord(fence.runId, renewed)
2422
+ };
2423
+ return {
2424
+ renewed: false,
2425
+ record: await this.#readRunOwner(fence.runId)
2426
+ };
2427
+ } catch (error) {
2428
+ throw this.#ownershipError("RENEW_RUN_OWNERSHIP", fence.runId, error);
2429
+ }
2430
+ }
2431
+ async releaseRunOwnership(fence) {
2432
+ try {
2433
+ return (await this.#db.executeQuery({
2434
+ sql: `UPDATE ${this.#ownersTable} SET leaseExpiresAt = NULL, updatedAt = ${DB_NOW_MS}
2435
+ WHERE runId = ? AND generation = ? AND ownerId = ?
2436
+ RETURNING runId`,
2437
+ params: [
2438
+ fence.runId,
2439
+ fence.generation,
2440
+ fence.ownerId
2441
+ ]
2442
+ })).length > 0;
2443
+ } catch (error) {
2444
+ throw this.#ownershipError("RELEASE_RUN_OWNERSHIP", fence.runId, error);
2445
+ }
2446
+ }
2447
+ async getRunOwnership({ runId }) {
2448
+ try {
2449
+ return await this.#readRunOwner(runId);
2450
+ } catch (error) {
2451
+ throw this.#ownershipError("GET_RUN_OWNERSHIP", runId, error);
2452
+ }
2146
2453
  }
2147
2454
  async updateWorkflowResults(_args) {
2148
2455
  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.");
@@ -2150,9 +2457,10 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2150
2457
  async updateWorkflowState(_args) {
2151
2458
  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.");
2152
2459
  }
2153
- async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt }) {
2460
+ async persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt, fence }) {
2154
2461
  const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2155
2462
  const now = (/* @__PURE__ */ new Date()).toISOString();
2463
+ const check = this.#runFenceCheck(fence, runId, "persistWorkflowSnapshot");
2156
2464
  const currentSnapshot = await this.#db.load({
2157
2465
  tableName: TABLE_WORKFLOW_SNAPSHOT,
2158
2466
  keys: {
@@ -2184,13 +2492,11 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2184
2492
  workflowName,
2185
2493
  runId
2186
2494
  });
2187
- const { sql, params } = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap).build();
2495
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap, runFenceGuard(check));
2188
2496
  try {
2189
- await this.#db.executeQuery({
2190
- sql,
2191
- params
2192
- });
2497
+ await executeFenced(this.#db, check, query.build());
2193
2498
  } catch (error) {
2499
+ if (isRunFenceConflictError(error)) throw error;
2194
2500
  throw new MastraError({
2195
2501
  id: createStorageErrorId("CLOUDFLARE_D1", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2196
2502
  domain: ErrorDomain.STORAGE,
@@ -2342,16 +2648,16 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2342
2648
  }, error);
2343
2649
  }
2344
2650
  }
2345
- async deleteWorkflowRunById({ runId, workflowName }) {
2651
+ async deleteWorkflowRunById({ runId, workflowName, fence }) {
2346
2652
  const fullTableName = this.#db.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2653
+ const check = this.#runFenceCheck(fence, runId, "deleteWorkflowRunById");
2347
2654
  try {
2348
- const sql = `DELETE FROM ${fullTableName} WHERE workflow_name = ? AND run_id = ?`;
2349
- const params = [workflowName, runId];
2350
- await this.#db.executeQuery({
2351
- sql,
2352
- params
2353
- });
2655
+ const query = createSqlBuilder().delete(fullTableName).where("workflow_name = ?", workflowName).andWhere("run_id = ?", runId);
2656
+ const guard = runFenceGuard(check);
2657
+ if (guard) query.andWhere(guard.sql, ...guard.params);
2658
+ await executeFenced(this.#db, check, query.build());
2354
2659
  } catch (error) {
2660
+ if (isRunFenceConflictError(error)) throw error;
2355
2661
  throw new MastraError({
2356
2662
  id: createStorageErrorId("CLOUDFLARE_D1", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2357
2663
  domain: ErrorDomain.STORAGE,