@proofoftech/flowsafe 0.24.0 → 0.26.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +6 -4
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +64 -3
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  7. package/dist/agent-host/thread-topology.js +2 -1
  8. package/dist/agent-host/thread-topology.js.map +1 -1
  9. package/dist/agent-runner/durable-agent-runner.d.ts +12 -3
  10. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  11. package/dist/agent-runner/durable-agent-runner.js +217 -102
  12. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  13. package/dist/approval-api/grants.d.ts +11 -1
  14. package/dist/approval-api/grants.d.ts.map +1 -1
  15. package/dist/approval-api/grants.js +20 -0
  16. package/dist/approval-api/grants.js.map +1 -1
  17. package/dist/approval-api/index.d.ts +1 -1
  18. package/dist/approval-api/index.d.ts.map +1 -1
  19. package/dist/approval-api/index.js +1 -1
  20. package/dist/approval-api/index.js.map +1 -1
  21. package/dist/approval-api/retention.d.ts.map +1 -1
  22. package/dist/approval-api/retention.js +6 -5
  23. package/dist/approval-api/retention.js.map +1 -1
  24. package/dist/approval-api/service.d.ts +4 -1
  25. package/dist/approval-api/service.d.ts.map +1 -1
  26. package/dist/approval-api/service.js +12 -5
  27. package/dist/approval-api/service.js.map +1 -1
  28. package/dist/approval-api/types.d.ts +8 -1
  29. package/dist/approval-api/types.d.ts.map +1 -1
  30. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  31. package/dist/background-tasks/d1-storage.js +7 -12
  32. package/dist/background-tasks/d1-storage.js.map +1 -1
  33. package/dist/do-runner/durable-object.d.ts +29 -10
  34. package/dist/do-runner/durable-object.d.ts.map +1 -1
  35. package/dist/do-runner/durable-object.js +56 -33
  36. package/dist/do-runner/durable-object.js.map +1 -1
  37. package/dist/do-runner/fenced-workflow-capability.d.ts +35 -5
  38. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  39. package/dist/do-runner/fenced-workflows-d1.d.ts +8 -0
  40. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  41. package/dist/do-runner/fenced-workflows-d1.js +402 -39
  42. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  43. package/dist/do-runner/index.d.ts +1 -1
  44. package/dist/do-runner/index.d.ts.map +1 -1
  45. package/dist/do-runner/index.js +1 -1
  46. package/dist/do-runner/index.js.map +1 -1
  47. package/dist/do-runner/run-input-depth.d.ts +15 -0
  48. package/dist/do-runner/run-input-depth.d.ts.map +1 -0
  49. package/dist/do-runner/run-input-depth.js +32 -0
  50. package/dist/do-runner/run-input-depth.js.map +1 -0
  51. package/dist/do-runner/run-lifecycle.d.ts +68 -3
  52. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  53. package/dist/do-runner/run-lifecycle.js +76 -12
  54. package/dist/do-runner/run-lifecycle.js.map +1 -1
  55. package/dist/do-runner/runtime.d.ts +46 -9
  56. package/dist/do-runner/runtime.d.ts.map +1 -1
  57. package/dist/do-runner/runtime.js +361 -115
  58. package/dist/do-runner/runtime.js.map +1 -1
  59. package/dist/do-runner/workflow-snapshot-row.d.ts +4 -5
  60. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  61. package/dist/do-runner/workflow-snapshot-row.js +14 -18
  62. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  63. package/dist/host-kit/approval-bridge.d.ts +20 -2
  64. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  65. package/dist/host-kit/approval-bridge.js +66 -7
  66. package/dist/host-kit/approval-bridge.js.map +1 -1
  67. package/dist/host-kit/do-run-topology.d.ts +3 -1
  68. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  69. package/dist/host-kit/do-run-topology.js +2 -1
  70. package/dist/host-kit/do-run-topology.js.map +1 -1
  71. package/dist/host-kit/flowsafe-worker.d.ts +6 -1
  72. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  73. package/dist/host-kit/flowsafe-worker.js +2 -2
  74. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  75. package/dist/host-kit/host-approval-service.d.ts +3 -1
  76. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  77. package/dist/host-kit/host-approval-service.js.map +1 -1
  78. package/dist/host-kit/run-router.d.ts +4 -1
  79. package/dist/host-kit/run-router.d.ts.map +1 -1
  80. package/dist/host-kit/run-router.js +14 -0
  81. package/dist/host-kit/run-router.js.map +1 -1
  82. package/dist/schedules/tick.d.ts +28 -2
  83. package/dist/schedules/tick.d.ts.map +1 -1
  84. package/dist/schedules/tick.js +35 -11
  85. package/dist/schedules/tick.js.map +1 -1
  86. package/package.json +2 -2
@@ -10,15 +10,32 @@ import { admitsRunStart, captureExecutionFenceAdmissionSchema, decodeExecutionFe
10
10
  import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
11
11
  import { definitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
12
12
  import { isPathSafeId } from './path-safe-id.js';
13
- import { advanceLifecycle, hasDisputedSettlement, parseRunLifecycle, projectTerminalLifecycle, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLED_IDENTITY_PATHS, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, terminalCleanupFor, } from './run-lifecycle.js';
13
+ import { advanceLifecycle, hasDisputedSettlement, parseRunLifecycle, projectTerminalLifecycle, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLED_IDENTITY_PATHS, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, runTerminalError, terminalCleanupFor, } from './run-lifecycle.js';
14
14
  import { decodeInitialRunProvenance, decodeProgressRunProvenance, } from './run-provenance.js';
15
15
  import { RESOURCE_OWNER_TABLE } from './run-storage-tables.js';
16
16
  import { isRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
17
17
  import { decodeStartReservationAdmissionResult, START_IDEMPOTENCY_TABLE, StartReservationOwnerMismatchError, StartReservationTargetMismatchError, validateStartReservationAdmissionSchema, } from './start-idempotency.js';
18
18
  import { captureReservation, sameReservationIdentity, } from './start-reservation-contract.js';
19
19
  import { validateTablePrefix } from './table-prefix.js';
20
- import { decodeRawWorkflowSnapshotResult, prepareRawWorkflowSnapshotRead, readRawWorkflowSnapshot, snapshotResultRows, touchRawWorkflowSnapshot, } from './workflow-snapshot-row.js';
20
+ import { decodeRawWorkflowSnapshotResult, parseSnapshotObject, prepareRawWorkflowSnapshotRead, readRawWorkflowSnapshot, snapshotResultRows, } from './workflow-snapshot-row.js';
21
21
  const PROVENANCE = 'flowsafe.runProvenance';
22
+ /**
23
+ * @internal Runs `work` once every earlier call with the same `key` on `tails`
24
+ * has settled, in call order; a failed call does not block the next. An entry
25
+ * leaves `tails` when its last call settles. Each owner keeps its own `tails`:
26
+ * a caller that holds its queue across a call into another owner's would
27
+ * deadlock on a shared one.
28
+ */
29
+ export function serializedByKey(tails, key, work) {
30
+ const previous = tails.get(key) ?? Promise.resolve();
31
+ const current = previous.then(work, work);
32
+ const settled = current.then(() => undefined, () => undefined);
33
+ tails.set(key, settled);
34
+ return current.finally(() => {
35
+ if (tails.get(key) === settled)
36
+ tails.delete(key);
37
+ });
38
+ }
22
39
  /** @internal Match the pinned standalone resolver's property-presence precedence. */
23
40
  export function captureD1DomainConfig(config) {
24
41
  if ('client' in config) {
@@ -249,7 +266,10 @@ function writtenRowCount({ results, meta, }) {
249
266
  throw new Error('statement changes disagree with returned rows');
250
267
  return results.length;
251
268
  }
252
- /** Exact-row compare-and-set of a snapshot row's `snapshot` and `updatedAt`. */
269
+ /**
270
+ * Exact-row compare-and-set of a snapshot row's `snapshot` and `updatedAt`. It
271
+ * matches nothing for a replacement SQLite cannot parse over a row it can.
272
+ */
253
273
  function prepareSnapshotReplace(database, expected, replacement) {
254
274
  return database
255
275
  .prepare(`UPDATE "${expected.tablePrefix}mastra_workflow_snapshot"
@@ -257,6 +277,7 @@ function prepareSnapshotReplace(database, expected, replacement) {
257
277
  WHERE workflow_name = ?3 AND run_id = ?4
258
278
  AND snapshot = ?5 AND createdAt IS ?6 AND updatedAt IS ?7
259
279
  AND resourceId IS ?8
280
+ AND (json_valid(?1) OR NOT json_valid(?5))
260
281
  RETURNING workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt`)
261
282
  .bind(replacement.snapshot, replacement.updatedAt, expected.workflowId, expected.runId, expected.snapshot, expected.createdAt, expected.updatedAt, expected.resourceId);
262
283
  }
@@ -266,15 +287,82 @@ function decodeSnapshotReplace(result, expected) {
266
287
  writtenRowCount(captured);
267
288
  return decodeRawWorkflowSnapshotResult(captured, expected);
268
289
  }
290
+ /**
291
+ * Run retention compares a row's stored `updatedAt` with its cutoff as text, so
292
+ * only the `Date.prototype.toISOString()` form orders correctly.
293
+ */
294
+ function isCanonicalIsoTime(text) {
295
+ const ms = Date.parse(text);
296
+ return Number.isFinite(ms) && new Date(ms).toISOString() === text;
297
+ }
269
298
  async function replaceSnapshotRow(database, tablePrefix, expected, replacement) {
299
+ const { snapshot, updatedAt } = replacement;
270
300
  if (expected.tablePrefix !== tablePrefix ||
271
301
  !isPathSafeId(expected.workflowId) ||
272
302
  !isPathSafeId(expected.runId) ||
273
- typeof replacement.snapshot !== 'string' ||
274
- typeof replacement.updatedAt !== 'string')
303
+ typeof snapshot !== 'string' ||
304
+ typeof updatedAt !== 'string' ||
305
+ parseSnapshotObject(snapshot) === undefined ||
306
+ !isCanonicalIsoTime(updatedAt))
275
307
  throw new Error('workflow snapshot replacement is malformed');
276
- const result = await prepareSnapshotReplace(database, expected, replacement).all();
277
- return decodeSnapshotReplace(result, expected) !== undefined;
308
+ const result = await prepareSnapshotReplace(database, expected, {
309
+ snapshot,
310
+ updatedAt,
311
+ }).all();
312
+ if (decodeSnapshotReplace(result, expected) !== undefined)
313
+ return true;
314
+ // A miss is a refusal when the bound texts alone decide it, and a row that
315
+ // changed otherwise.
316
+ const verdict = await decisionRow(database, 'SELECT json_valid(?1) AS storable, json_valid(?2) AS expected_readable', [snapshot, expected.snapshot]);
317
+ if (!decisionFlag(verdict, 'storable') &&
318
+ decisionFlag(verdict, 'expected_readable'))
319
+ throw new RunStateNotStorableError(expected.workflowId, expected.runId);
320
+ return false;
321
+ }
322
+ /**
323
+ * The timestamp is bound as JSON text because a bound JS number would be
324
+ * stored as a REAL (`456.0`). A request context that is not an object makes
325
+ * json_set write nothing yet still count a row, so the predicate refuses it.
326
+ * The patch replaces the whole lifecycle, and a revision does not identify one
327
+ * across instances (a resume elsewhere reaches the same revision), so a stored
328
+ * dispute refuses it as it refuses recording an intent.
329
+ */
330
+ async function patchLifecycleRow(database, tablePrefix, address, expected, patch) {
331
+ const { workflowId, runId } = address;
332
+ const { status, lifecycleRevision } = expected;
333
+ const { lifecycle, timestamp, updatedAt } = patch;
334
+ if (!isPathSafeId(workflowId) ||
335
+ !isPathSafeId(runId) ||
336
+ typeof status !== 'string' ||
337
+ (lifecycleRevision !== undefined &&
338
+ !Number.isSafeInteger(lifecycleRevision)) ||
339
+ lifecycle === null ||
340
+ typeof lifecycle !== 'object' ||
341
+ Array.isArray(lifecycle) ||
342
+ !Number.isSafeInteger(timestamp) ||
343
+ timestamp < 0 ||
344
+ typeof updatedAt !== 'string' ||
345
+ !isCanonicalIsoTime(updatedAt))
346
+ throw new Error('workflow lifecycle patch is malformed');
347
+ const result = await database
348
+ .prepare(`UPDATE "${tablePrefix}mastra_workflow_snapshot"
349
+ SET snapshot = json_set(snapshot,
350
+ ${lifecyclePath()}, json(?1),
351
+ '$.timestamp', json(?2)),
352
+ updatedAt = ?3
353
+ WHERE workflow_name = ?4 AND run_id = ?5
354
+ AND CASE
355
+ WHEN NOT json_valid(snapshot) THEN 0
356
+ WHEN coalesce(json_type(snapshot, '$.requestContext'), 'object') <> 'object' THEN 0
357
+ ELSE json_extract(snapshot, '$.status') = ?6
358
+ AND ${lifecycleSql('snapshot', 'revision')} IS ?7
359
+ AND ${STORED_UNSETTLED_SQL}
360
+ AND NOT ${disputedSql('snapshot')}
361
+ END
362
+ RETURNING workflow_name`)
363
+ .bind(JSON.stringify(lifecycle), String(timestamp), updatedAt, workflowId, runId, status, lifecycleRevision ?? null)
364
+ .all();
365
+ return writtenRowCount(captureStatementResult(result)) === 1;
278
366
  }
279
367
  /**
280
368
  * The columns @mastra/cloudflare-d1's `persistWorkflowSnapshot` writes for a
@@ -306,28 +394,288 @@ function mastraSnapshotRow(args, nowIso) {
306
394
  updatedAt: updatedAt ? updatedAt.toISOString() : nowIso,
307
395
  };
308
396
  }
397
+ const LIFECYCLE_JSON_PATH = `$.requestContext."${RUN_LIFECYCLE_CONTEXT_KEY}"`;
398
+ /** The run lifecycle's JSON path, or one of its fields', as an SQL literal. */
309
399
  function lifecyclePath(path) {
310
- return `'$.requestContext."${RUN_LIFECYCLE_CONTEXT_KEY}".${path}'`;
400
+ return `'${LIFECYCLE_JSON_PATH}${path === undefined ? '' : `.${path}`}'`;
311
401
  }
312
402
  function lifecycleSql(column, path) {
313
403
  return `json_extract(${column}, ${lifecyclePath(path)})`;
314
404
  }
315
- const STORED_UNSETTLED_SQL = RUN_SETTLING_MARKERS.map((marker) => `${lifecycleSql('snapshot', marker)} IS NULL`).join(' AND ');
405
+ function unsettledSql(stored) {
406
+ return RUN_SETTLING_MARKERS.map((marker) => `${lifecycleSql(stored, marker)} IS NULL`).join(' AND ');
407
+ }
408
+ const STORED_UNSETTLED_SQL = unsettledSql('snapshot');
409
+ /** Whether the lifecycle in `column` records a disputed economic operation. */
410
+ function disputedSql(column) {
411
+ return `EXISTS (
412
+ SELECT 1 FROM json_each(${column}, ${lifecyclePath('economicOperations')})
413
+ WHERE json_extract(value, '$.settlementState') = 'disputed'
414
+ )`;
415
+ }
416
+ /** A rule read as 1 or 0, as a WHERE or a CASE reads it: NULL reads 0. */
417
+ function decisionSql(rule) {
418
+ return `CASE WHEN ${rule} THEN 1 ELSE 0 END`;
419
+ }
316
420
  /**
317
421
  * Upsert condition over a stored row: unsettled, or the incoming write
318
- * advances the revision and keeps the settlement. JSON SQLite cannot read
319
- * (malformed, or nested past its depth limit) is written as Mastra's upsert
320
- * writes it, except an unreadable write over a settled row. CASE, unlike OR,
321
- * never evaluates json_extract on JSON its guard found unreadable.
422
+ * advances the revision and keeps the settlement. A stored row SQLite cannot
423
+ * read (malformed, or nested past its depth limit) fails it, and
424
+ * #persistUnlessSettled then evaluates it on that row's lifecycle. CASE,
425
+ * unlike OR, never evaluates json_extract on JSON its guard found unreadable.
322
426
  */
323
- const SETTLED_ROW_GUARD_SQL = `CASE
324
- WHEN NOT json_valid(snapshot) THEN 1
325
- WHEN NOT json_valid(excluded.snapshot) THEN ${STORED_UNSETTLED_SQL}
326
- ELSE (${STORED_UNSETTLED_SQL})
327
- OR (json_type(excluded.snapshot, ${lifecyclePath('revision')}) = 'integer'
328
- AND ${lifecycleSql('excluded.snapshot', 'revision')} > ${lifecycleSql('snapshot', 'revision')}
329
- AND ${RUN_SETTLED_IDENTITY_PATHS.map((path) => `${lifecycleSql('excluded.snapshot', path)} IS ${lifecycleSql('snapshot', path)}`).join(' AND ')})
427
+ function settledRowGuardSql(stored, incoming) {
428
+ return `CASE
429
+ WHEN NOT json_valid(${stored}) THEN 0
430
+ WHEN NOT json_valid(${incoming}) THEN ${unsettledSql(stored)}
431
+ ELSE (${unsettledSql(stored)})
432
+ OR (json_type(${incoming}, ${lifecyclePath('revision')}) = 'integer'
433
+ AND ${lifecycleSql(incoming, 'revision')} > ${lifecycleSql(stored, 'revision')}
434
+ AND ${RUN_SETTLED_IDENTITY_PATHS.map((path) => `${lifecycleSql(incoming, path)} IS ${lifecycleSql(stored, path)}`).join(' AND ')})
330
435
  END`;
436
+ }
437
+ const SETTLED_ROW_GUARD_SQL = settledRowGuardSql('snapshot', 'excluded.snapshot');
438
+ /**
439
+ * How an admitted write over an unsettled row treats the stored run
440
+ * lifecycle, following effectiveLifecycle's revision order in the runtime: a
441
+ * write whose revision is lower or absent takes the stored lifecycle (a
442
+ * writer's revisions only grow, so the write was serialized before the stored
443
+ * lifecycle landed; only the dispute arm below lowers a stored revision); a
444
+ * write of the same revision without a transitionIntent
445
+ * takes the stored intent; any other write is stored as written. A stored
446
+ * intent never joins a write it was not checked against: a write that records
447
+ * a disputed economic operation is stored as written over an intent, as the
448
+ * dispute would have refused it, and a run-deadline intent does not join a
449
+ * write that moved its deadline. CASE reads no field of text an earlier branch
450
+ * found unreadable, and a NULL comparison falls through to 'as written'.
451
+ */
452
+ function lifecycleMergeSql(stored, incoming) {
453
+ const storedIntent = `json_type(${stored}, ${lifecyclePath('transitionIntent')}) = 'object'`;
454
+ return `CASE
455
+ WHEN NOT json_valid(${stored}) OR NOT json_valid(${incoming}) THEN 'as written'
456
+ WHEN NOT (${unsettledSql(stored)}) THEN 'as written'
457
+ WHEN json_type(${stored}, ${lifecyclePath()}) IS NOT 'object' THEN 'as written'
458
+ WHEN coalesce(json_type(${incoming}, '$.requestContext'), 'object') <> 'object'
459
+ THEN 'as written'
460
+ WHEN ${storedIntent}
461
+ AND json_type(${incoming}, ${lifecyclePath('revision')}) = 'integer'
462
+ AND ${disputedSql(incoming)}
463
+ THEN 'as written'
464
+ WHEN ${lifecycleSql(incoming, 'revision')} IS NULL
465
+ OR ${lifecycleSql(incoming, 'revision')} < ${lifecycleSql(stored, 'revision')}
466
+ THEN 'stored lifecycle'
467
+ WHEN ${lifecycleSql(incoming, 'revision')} = ${lifecycleSql(stored, 'revision')}
468
+ AND ${storedIntent}
469
+ AND ${lifecycleSql(incoming, 'transitionIntent')} IS NULL
470
+ AND (${lifecycleSql(stored, 'transitionIntent.expectedDeadlineAt')} IS NULL
471
+ OR ${lifecycleSql(incoming, 'deadlineAt')}
472
+ IS ${lifecycleSql(stored, 'transitionIntent.expectedDeadlineAt')})
473
+ THEN 'stored intent'
474
+ ELSE 'as written' END`;
475
+ }
476
+ const UPSERT_SNAPSHOT_SQL = `CASE (${lifecycleMergeSql('snapshot', 'excluded.snapshot')})
477
+ WHEN 'stored lifecycle' THEN json_set(excluded.snapshot, ${lifecyclePath()},
478
+ snapshot -> ${lifecyclePath()})
479
+ WHEN 'stored intent' THEN json_set(excluded.snapshot,
480
+ ${lifecyclePath('transitionIntent')},
481
+ snapshot -> ${lifecyclePath('transitionIntent')})
482
+ ELSE excluded.snapshot END`;
483
+ /**
484
+ * A stored row's liveness for a leg's touch: 1 unsettled, 0 settled, NULL for
485
+ * JSON SQLite cannot read, which touchRunRow decides on the row's lifecycle.
486
+ */
487
+ function storedLiveSql(stored) {
488
+ return `CASE WHEN json_valid(${stored}) THEN (${unsettledSql(stored)}) END`;
489
+ }
490
+ const STORED_LIVE_SQL = storedLiveSql('snapshot');
491
+ /**
492
+ * Compare-and-set attempts a write over a row SQLite cannot read makes before
493
+ * answering that the row keeps changing.
494
+ */
495
+ const UNREADABLE_ROW_WRITE_ATTEMPTS = 3;
496
+ function decisionInput(text) {
497
+ let parsed;
498
+ try {
499
+ parsed = JSON.parse(text);
500
+ }
501
+ catch (cause) {
502
+ if (cause instanceof SyntaxError)
503
+ return { projection: '{}' };
504
+ throw new ExecutionFenceUnreadableError('workflow snapshot is not readable', { cause });
505
+ }
506
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
507
+ return { projection: '{}' };
508
+ const snapshot = parsed;
509
+ if (!Object.hasOwn(snapshot, 'requestContext'))
510
+ return { snapshot, projection: '{}' };
511
+ const context = snapshot.requestContext;
512
+ if (context === null || typeof context !== 'object' || Array.isArray(context))
513
+ return { snapshot, projection: JSON.stringify({ requestContext: null }) };
514
+ if (!Object.hasOwn(context, RUN_LIFECYCLE_CONTEXT_KEY))
515
+ return { snapshot, projection: JSON.stringify({ requestContext: {} }) };
516
+ const lifecycle = context[RUN_LIFECYCLE_CONTEXT_KEY];
517
+ return {
518
+ snapshot,
519
+ ...(lifecycle !== null &&
520
+ typeof lifecycle === 'object' &&
521
+ !Array.isArray(lifecycle)
522
+ ? { lifecycle: lifecycle }
523
+ : {}),
524
+ projection: JSON.stringify({
525
+ requestContext: { [RUN_LIFECYCLE_CONTEXT_KEY]: lifecycle },
526
+ }),
527
+ };
528
+ }
529
+ /**
530
+ * The single row of a statement that decides a refused write or a touch. A
531
+ * failure reads as an unreadable row, as readRawWorkflowSnapshot reports one.
532
+ */
533
+ async function decisionRow(database, sql, values) {
534
+ try {
535
+ const rows = snapshotResultRows(await database
536
+ .prepare(sql)
537
+ .bind(...values)
538
+ .all());
539
+ const row = rows[0];
540
+ if (rows.length !== 1 || row === undefined)
541
+ throw new Error('workflow snapshot decision is malformed');
542
+ return row;
543
+ }
544
+ catch (cause) {
545
+ throw new ExecutionFenceUnreadableError('workflow snapshot is not readable', { cause });
546
+ }
547
+ }
548
+ function decisionFlag(row, column) {
549
+ const value = row[column];
550
+ if (value !== 0 && value !== 1)
551
+ throw new Error('workflow snapshot decision is malformed');
552
+ return value === 1;
553
+ }
554
+ /**
555
+ * Whether SQLite can read the row a write was refused over (undefined when it
556
+ * is gone), and whether it can read the refused write.
557
+ */
558
+ async function probeRefusedWrite(database, tablePrefix, address, incoming) {
559
+ const row = await decisionRow(database, `SELECT (SELECT json_valid(snapshot) FROM "${tablePrefix}mastra_workflow_snapshot"
560
+ WHERE workflow_name = ?1 AND run_id = ?2) AS readable,
561
+ json_valid(?3) AS storable`, [address.workflowId, address.runId, incoming]);
562
+ return {
563
+ readable: row.readable === null ? undefined : decisionFlag(row, 'readable'),
564
+ storable: decisionFlag(row, 'storable'),
565
+ };
566
+ }
567
+ /**
568
+ * The guard's verdict on a write over a stored row SQLite cannot read, and how
569
+ * the upsert would merge the stored lifecycle into it.
570
+ */
571
+ async function decideOverUnreadableRow(database, stored, incoming) {
572
+ const row = await decisionRow(database, `SELECT ${decisionSql(settledRowGuardSql('?1', '?2'))} AS admitted,
573
+ ${lifecycleMergeSql('?1', '?2')} AS merge`, [stored.projection, incoming.projection]);
574
+ const merge = row.merge;
575
+ if (merge !== 'as written' &&
576
+ merge !== 'stored lifecycle' &&
577
+ merge !== 'stored intent')
578
+ throw new Error('workflow snapshot decision is malformed');
579
+ return { admitted: decisionFlag(row, 'admitted'), merge };
580
+ }
581
+ /**
582
+ * The bytes an admitted write over a row SQLite cannot read stores, placing
583
+ * the stored lifecycle or its transitionIntent where the upsert's json_set
584
+ * places it: an object spread keeps an existing key's position and appends a
585
+ * new one.
586
+ */
587
+ function mergedSnapshot(stored, incoming, incomingText, merge) {
588
+ if (merge === 'as written' || !incoming.snapshot || !stored.lifecycle)
589
+ return incomingText;
590
+ const context = (incoming.snapshot.requestContext ?? {});
591
+ const lifecycle = merge === 'stored lifecycle'
592
+ ? stored.lifecycle
593
+ : {
594
+ ...incoming.lifecycle,
595
+ transitionIntent: stored.lifecycle.transitionIntent,
596
+ };
597
+ return JSON.stringify({
598
+ ...incoming.snapshot,
599
+ requestContext: { ...context, [RUN_LIFECYCLE_CONTEXT_KEY]: lifecycle },
600
+ });
601
+ }
602
+ /**
603
+ * A snapshot written over a row SQLite cannot read: the guard's rule and the
604
+ * lifecycle merge decide it on the lifecycle parsed from the row just read,
605
+ * and an admitted write is a compare-and-set against that row. A miss reads
606
+ * the row again, so a row purged meanwhile is refused rather than inserted
607
+ * afresh.
608
+ */
609
+ async function writeOverUnreadableRow(database, tablePrefix, row) {
610
+ const address = { workflowId: row.workflowName, runId: row.runId };
611
+ const incoming = decisionInput(row.snapshot);
612
+ for (let attempt = 0; attempt < UNREADABLE_ROW_WRITE_ATTEMPTS; attempt++) {
613
+ const stored = await readRawWorkflowSnapshot(database, { tablePrefix, ...address }, { missingTable: 'error' });
614
+ if (stored === undefined)
615
+ throw new RunSettledConflictError(row.workflowName, row.runId);
616
+ const storedInput = decisionInput(stored.snapshot);
617
+ const decision = await decideOverUnreadableRow(database, storedInput, incoming);
618
+ if (!decision.admitted)
619
+ throw new RunSettledConflictError(row.workflowName, row.runId);
620
+ if (await replaceSnapshotRow(database, tablePrefix, stored, {
621
+ snapshot: mergedSnapshot(storedInput, incoming, row.snapshot, decision.merge),
622
+ updatedAt: row.updatedAt,
623
+ }))
624
+ return;
625
+ }
626
+ throw new ExecutionFenceUnreadableError('workflow snapshot write kept missing a changing row SQLite cannot parse');
627
+ }
628
+ /**
629
+ * The touch of a row SQLite cannot read: its parsed lifecycle decides, and
630
+ * `updatedAt` moves only on the exact row decided on. A row that changed in
631
+ * between reads live; the next touch decides again.
632
+ */
633
+ async function touchUnreadableRow(database, tablePrefix, address, nowMs) {
634
+ const stored = await readRawWorkflowSnapshot(database, { tablePrefix, ...address }, { missingTable: 'error' });
635
+ if (stored === undefined)
636
+ return 'absent';
637
+ const live = decisionFlag(await decisionRow(database, `SELECT ${decisionSql(storedLiveSql('?1'))} AS live`, [decisionInput(stored.snapshot).projection]), 'live');
638
+ if (!live)
639
+ return 'settled';
640
+ // Not replaceSnapshotRow, which refuses stored bytes that are not JSON.
641
+ decodeSnapshotReplace(await prepareSnapshotReplace(database, stored, {
642
+ snapshot: stored.snapshot,
643
+ updatedAt: new Date(nowMs).toISOString(),
644
+ }).all(), stored);
645
+ return 'live';
646
+ }
647
+ /**
648
+ * SQLite counts a matched row as changed even when `updatedAt` is set to
649
+ * itself, so on a settled row `meta.changes` and the returned row still agree.
650
+ * `SET` reads the row before the update and `RETURNING` after it, and the
651
+ * predicate reads only `snapshot`, which the statement leaves alone.
652
+ */
653
+ async function touchRunRow(database, tablePrefix, address, nowMs) {
654
+ const { workflowId, runId } = address;
655
+ if (!isPathSafeId(workflowId) ||
656
+ !isPathSafeId(runId) ||
657
+ !Number.isSafeInteger(nowMs) ||
658
+ nowMs < 0)
659
+ throw new Error('workflow snapshot address is malformed');
660
+ const result = await database
661
+ .prepare(`UPDATE "${tablePrefix}mastra_workflow_snapshot"
662
+ SET updatedAt = CASE WHEN ${STORED_LIVE_SQL} THEN ?1 ELSE updatedAt END
663
+ WHERE workflow_name = ?2 AND run_id = ?3
664
+ RETURNING ${STORED_LIVE_SQL} AS live`)
665
+ .bind(new Date(nowMs).toISOString(), workflowId, runId)
666
+ .all();
667
+ const captured = captureStatementResult(result);
668
+ if (writtenRowCount(captured) === 0)
669
+ return 'absent';
670
+ const live = captured.results[0]?.live;
671
+ if (live === 1)
672
+ return 'live';
673
+ if (live === 0)
674
+ return 'settled';
675
+ if (live === null)
676
+ return touchUnreadableRow(database, tablePrefix, address, nowMs);
677
+ throw new Error('workflow snapshot touch result is malformed');
678
+ }
331
679
  function terminalizationUnreadable(cause) {
332
680
  return new ExecutionFenceUnreadableError('initial admission cannot be terminalized', { cause });
333
681
  }
@@ -451,12 +799,7 @@ function prepareTerminalization(source, tablePrefix) {
451
799
  nextContext[RUN_LIFECYCLE_CONTEXT_KEY] = next;
452
800
  fields = {
453
801
  ...terminalStateFields(intent.status),
454
- error: {
455
- name: intent.status === 'cancelled'
456
- ? 'RunCancelledError'
457
- : 'RunTimedOutError',
458
- message: next.terminal.error.message,
459
- },
802
+ error: runTerminalError(intent.status),
460
803
  };
461
804
  cleanup = terminalCleanupFor(next);
462
805
  }
@@ -495,6 +838,7 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
495
838
  [FENCED_WORKFLOW_STORAGE];
496
839
  #admission;
497
840
  #scopes = new AsyncLocalStorage();
841
+ #unreadableRowTails = new Map();
498
842
  constructor(config) {
499
843
  const captured = captureD1DomainConfig(config);
500
844
  super(captured);
@@ -511,12 +855,9 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
511
855
  runId: address.runId,
512
856
  }, { missingTable: 'empty' }),
513
857
  terminalizeInitialAdmission: (request) => this.#terminalizeInitialAdmission(request),
514
- touchRun: (address, nowMs) => touchRawWorkflowSnapshot(database, {
515
- tablePrefix,
516
- workflowId: address.workflowId,
517
- runId: address.runId,
518
- }, nowMs),
858
+ touchRun: (address, nowMs) => touchRunRow(database, tablePrefix, address, nowMs),
519
859
  replaceSnapshot: (expected, replacement) => replaceSnapshotRow(database, tablePrefix, expected, replacement),
860
+ patchRunLifecycle: (address, expected, patch) => patchLifecycleRow(database, tablePrefix, address, expected, patch),
520
861
  });
521
862
  this[FENCED_WORKFLOW_STORAGE] = this.#admission;
522
863
  }
@@ -650,20 +991,39 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
650
991
  throw error;
651
992
  }
652
993
  }
994
+ /**
995
+ * The upsert refuses a snapshot SQLite cannot parse, and any write over a row
996
+ * SQLite cannot parse; the probe then sends such a row to
997
+ * writeOverUnreadableRow, so a row stored earlier stays writable.
998
+ */
653
999
  async #persistUnlessSettled(capability, args) {
654
1000
  const row = mastraSnapshotRow(args, new Date().toISOString());
655
- const result = await capability.database
656
- .prepare(`INSERT INTO "${capability.tablePrefix}mastra_workflow_snapshot"
1001
+ const { database, tablePrefix } = capability;
1002
+ const result = await database
1003
+ .prepare(`INSERT INTO "${tablePrefix}mastra_workflow_snapshot"
657
1004
  (workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt)
658
- VALUES (?1, ?2, ?3, ?4, ?5, ?6)
1005
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6
1006
+ WHERE json_valid(?4)
659
1007
  ON CONFLICT (workflow_name, run_id) DO UPDATE
660
- SET snapshot = excluded.snapshot, updatedAt = excluded.updatedAt
1008
+ SET snapshot = ${UPSERT_SNAPSHOT_SQL}, updatedAt = excluded.updatedAt
661
1009
  WHERE ${SETTLED_ROW_GUARD_SQL}
662
1010
  RETURNING workflow_name`)
663
1011
  .bind(row.workflowName, row.runId, row.resourceId, row.snapshot, row.createdAt, row.updatedAt)
664
1012
  .all();
665
- if (writtenRowCount(captureStatementResult(result)) === 0)
1013
+ if (writtenRowCount(captureStatementResult(result)) === 1)
1014
+ return;
1015
+ // The guard refused a readable row, or the write is not storable; a row
1016
+ // gone since the upsert met it is refused too, so a purged settlement is
1017
+ // not written over.
1018
+ const refused = await probeRefusedWrite(database, tablePrefix, { workflowId: row.workflowName, runId: row.runId }, row.snapshot);
1019
+ if (refused.readable !== false) {
1020
+ if (!refused.storable)
1021
+ throw new RunStateNotStorableError(row.workflowName, row.runId);
666
1022
  throw new RunSettledConflictError(row.workflowName, row.runId);
1023
+ }
1024
+ // Persists through this storage over one run's unreadable row run one at a
1025
+ // time, so they do not make each other's compare-and-set miss.
1026
+ await serializedByKey(this.#unreadableRowTails, `${row.workflowName}\0${row.runId}`, () => writeOverUnreadableRow(database, tablePrefix, row));
667
1027
  }
668
1028
  #initialRow(args, input) {
669
1029
  const snapshot = { ...args.snapshot };
@@ -770,7 +1130,7 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
770
1130
  .prepare(`INSERT INTO "${row.tablePrefix}mastra_workflow_snapshot"
771
1131
  (workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt)
772
1132
  SELECT ${fields.join(', ')}
773
- WHERE ${fencePredicate} ${reservation} ${owner}
1133
+ WHERE ${fencePredicate} AND json_valid(${fields[3]}) ${reservation} ${owner}
774
1134
  ON CONFLICT (workflow_name, run_id) DO NOTHING
775
1135
  RETURNING workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt`)
776
1136
  .bind(...values),
@@ -815,7 +1175,7 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
815
1175
  const positive = this.#decodeBatch(result, input, row, observed, nowMs);
816
1176
  if (positive)
817
1177
  return Object.freeze({ execution: input.execution, row });
818
- const refusal = await this.#diagnoseZero(database, input, observed);
1178
+ const refusal = await this.#diagnoseZero(database, input, observed, row.snapshot);
819
1179
  throw definitiveInitialAdmissionRefusal(input.execution, refusal);
820
1180
  }
821
1181
  #decodeBatch(result, input, row, observed, nowMs) {
@@ -905,8 +1265,11 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
905
1265
  updated_at: nowMs,
906
1266
  })));
907
1267
  }
908
- async #diagnoseZero(database, input, observed) {
1268
+ async #diagnoseZero(database, input, observed, admissionSnapshot) {
909
1269
  try {
1270
+ const admission = await decisionRow(database, 'SELECT json_valid(?1) AS storable', [admissionSnapshot]);
1271
+ if (!decisionFlag(admission, 'storable'))
1272
+ return new RunStateNotStorableError(input.execution.workflowId, input.execution.runId);
910
1273
  const [current, snapshot, reservation, owner] = await Promise.all([
911
1274
  input.fence.readForAdmission(),
912
1275
  readRawWorkflowSnapshot(database, input.execution, {