@proofoftech/flowsafe 0.25.0 → 0.26.1

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 (83) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +3 -1
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +50 -7
  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 +10 -1
  10. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  11. package/dist/agent-runner/durable-agent-runner.js +158 -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/service.d.ts +4 -1
  22. package/dist/approval-api/service.d.ts.map +1 -1
  23. package/dist/approval-api/service.js +8 -1
  24. package/dist/approval-api/service.js.map +1 -1
  25. package/dist/approval-api/types.d.ts +8 -1
  26. package/dist/approval-api/types.d.ts.map +1 -1
  27. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  28. package/dist/background-tasks/d1-storage.js +2 -10
  29. package/dist/background-tasks/d1-storage.js.map +1 -1
  30. package/dist/do-runner/durable-object.d.ts +6 -4
  31. package/dist/do-runner/durable-object.d.ts.map +1 -1
  32. package/dist/do-runner/durable-object.js +27 -11
  33. package/dist/do-runner/durable-object.js.map +1 -1
  34. package/dist/do-runner/fenced-workflow-capability.d.ts +6 -3
  35. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  36. package/dist/do-runner/fenced-workflows-d1.d.ts +8 -0
  37. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  38. package/dist/do-runner/fenced-workflows-d1.js +310 -34
  39. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  40. package/dist/do-runner/index.d.ts +1 -1
  41. package/dist/do-runner/index.d.ts.map +1 -1
  42. package/dist/do-runner/index.js +1 -1
  43. package/dist/do-runner/index.js.map +1 -1
  44. package/dist/do-runner/run-input-depth.d.ts +17 -0
  45. package/dist/do-runner/run-input-depth.d.ts.map +1 -0
  46. package/dist/do-runner/run-input-depth.js +33 -0
  47. package/dist/do-runner/run-input-depth.js.map +1 -0
  48. package/dist/do-runner/run-lifecycle.d.ts +68 -3
  49. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  50. package/dist/do-runner/run-lifecycle.js +76 -12
  51. package/dist/do-runner/run-lifecycle.js.map +1 -1
  52. package/dist/do-runner/runtime.d.ts +27 -3
  53. package/dist/do-runner/runtime.d.ts.map +1 -1
  54. package/dist/do-runner/runtime.js +168 -55
  55. package/dist/do-runner/runtime.js.map +1 -1
  56. package/dist/host-kit/approval-bridge.d.ts +6 -1
  57. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  58. package/dist/host-kit/approval-bridge.js +9 -1
  59. package/dist/host-kit/approval-bridge.js.map +1 -1
  60. package/dist/host-kit/do-run-topology.d.ts +3 -1
  61. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  62. package/dist/host-kit/do-run-topology.js +2 -1
  63. package/dist/host-kit/do-run-topology.js.map +1 -1
  64. package/dist/host-kit/flowsafe-worker.d.ts +6 -1
  65. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  66. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  67. package/dist/host-kit/host-approval-service.d.ts +3 -1
  68. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  69. package/dist/host-kit/host-approval-service.js.map +1 -1
  70. package/dist/host-kit/run-router.d.ts.map +1 -1
  71. package/dist/host-kit/run-router.js +19 -0
  72. package/dist/host-kit/run-router.js.map +1 -1
  73. package/dist/schedules/router.d.ts.map +1 -1
  74. package/dist/schedules/router.js +20 -2
  75. package/dist/schedules/router.js.map +1 -1
  76. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  77. package/dist/schedules/schedules-d1.js +4 -1
  78. package/dist/schedules/schedules-d1.js.map +1 -1
  79. package/dist/schedules/tick.d.ts +36 -2
  80. package/dist/schedules/tick.d.ts.map +1 -1
  81. package/dist/schedules/tick.js +109 -22
  82. package/dist/schedules/tick.js.map +1 -1
  83. package/package.json +1 -1
@@ -10,7 +10,7 @@ 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';
@@ -19,6 +19,23 @@ import { captureReservation, sameReservationIdentity, } from './start-reservatio
19
19
  import { validateTablePrefix } from './table-prefix.js';
20
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
  }
@@ -288,12 +309,23 @@ async function replaceSnapshotRow(database, tablePrefix, expected, replacement)
288
309
  snapshot,
289
310
  updatedAt,
290
311
  }).all();
291
- return decodeSnapshotReplace(result, expected) !== undefined;
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;
292
321
  }
293
322
  /**
294
323
  * The timestamp is bound as JSON text because a bound JS number would be
295
324
  * stored as a REAL (`456.0`). A request context that is not an object makes
296
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.
297
329
  */
298
330
  async function patchLifecycleRow(database, tablePrefix, address, expected, patch) {
299
331
  const { workflowId, runId } = address;
@@ -315,7 +347,7 @@ async function patchLifecycleRow(database, tablePrefix, address, expected, patch
315
347
  const result = await database
316
348
  .prepare(`UPDATE "${tablePrefix}mastra_workflow_snapshot"
317
349
  SET snapshot = json_set(snapshot,
318
- '$.requestContext."${RUN_LIFECYCLE_CONTEXT_KEY}"', json(?1),
350
+ ${lifecyclePath()}, json(?1),
319
351
  '$.timestamp', json(?2)),
320
352
  updatedAt = ?3
321
353
  WHERE workflow_name = ?4 AND run_id = ?5
@@ -325,6 +357,7 @@ async function patchLifecycleRow(database, tablePrefix, address, expected, patch
325
357
  ELSE json_extract(snapshot, '$.status') = ?6
326
358
  AND ${lifecycleSql('snapshot', 'revision')} IS ?7
327
359
  AND ${STORED_UNSETTLED_SQL}
360
+ AND NOT ${disputedSql('snapshot')}
328
361
  END
329
362
  RETURNING workflow_name`)
330
363
  .bind(JSON.stringify(lifecycle), String(timestamp), updatedAt, workflowId, runId, status, lifecycleRevision ?? null)
@@ -361,33 +394,256 @@ function mastraSnapshotRow(args, nowIso) {
361
394
  updatedAt: updatedAt ? updatedAt.toISOString() : nowIso,
362
395
  };
363
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. */
364
399
  function lifecyclePath(path) {
365
- return `'$.requestContext."${RUN_LIFECYCLE_CONTEXT_KEY}".${path}'`;
400
+ return `'${LIFECYCLE_JSON_PATH}${path === undefined ? '' : `.${path}`}'`;
366
401
  }
367
402
  function lifecycleSql(column, path) {
368
403
  return `json_extract(${column}, ${lifecyclePath(path)})`;
369
404
  }
370
- 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
+ }
371
420
  /**
372
421
  * Upsert condition over a stored row: unsettled, or the incoming write
373
- * advances the revision and keeps the settlement. JSON SQLite cannot read
374
- * (malformed, or nested past its depth limit) is written as Mastra's upsert
375
- * writes it, except an unreadable write over a settled row. CASE, unlike OR,
376
- * 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.
377
426
  */
378
- const SETTLED_ROW_GUARD_SQL = `CASE
379
- WHEN NOT json_valid(snapshot) THEN 1
380
- WHEN NOT json_valid(excluded.snapshot) THEN ${STORED_UNSETTLED_SQL}
381
- ELSE (${STORED_UNSETTLED_SQL})
382
- OR (json_type(excluded.snapshot, ${lifecyclePath('revision')}) = 'integer'
383
- AND ${lifecycleSql('excluded.snapshot', 'revision')} > ${lifecycleSql('snapshot', 'revision')}
384
- 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 ')})
385
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`;
386
483
  /**
387
- * A stored row's liveness for a leg's touch: unsettled is live, and so is
388
- * JSON SQLite cannot read, which the guard also writes over.
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.
389
486
  */
390
- const STORED_LIVE_SQL = `CASE WHEN NOT json_valid(snapshot) THEN 1 ELSE (${STORED_UNSETTLED_SQL}) END`;
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
+ }
391
647
  /**
392
648
  * SQLite counts a matched row as changed even when `updatedAt` is set to
393
649
  * itself, so on a settled row `meta.changes` and the returned row still agree.
@@ -416,6 +672,8 @@ async function touchRunRow(database, tablePrefix, address, nowMs) {
416
672
  return 'live';
417
673
  if (live === 0)
418
674
  return 'settled';
675
+ if (live === null)
676
+ return touchUnreadableRow(database, tablePrefix, address, nowMs);
419
677
  throw new Error('workflow snapshot touch result is malformed');
420
678
  }
421
679
  function terminalizationUnreadable(cause) {
@@ -541,12 +799,7 @@ function prepareTerminalization(source, tablePrefix) {
541
799
  nextContext[RUN_LIFECYCLE_CONTEXT_KEY] = next;
542
800
  fields = {
543
801
  ...terminalStateFields(intent.status),
544
- error: {
545
- name: intent.status === 'cancelled'
546
- ? 'RunCancelledError'
547
- : 'RunTimedOutError',
548
- message: next.terminal.error.message,
549
- },
802
+ error: runTerminalError(intent.status),
550
803
  };
551
804
  cleanup = terminalCleanupFor(next);
552
805
  }
@@ -585,6 +838,7 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
585
838
  [FENCED_WORKFLOW_STORAGE];
586
839
  #admission;
587
840
  #scopes = new AsyncLocalStorage();
841
+ #unreadableRowTails = new Map();
588
842
  constructor(config) {
589
843
  const captured = captureD1DomainConfig(config);
590
844
  super(captured);
@@ -737,20 +991,39 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
737
991
  throw error;
738
992
  }
739
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
+ */
740
999
  async #persistUnlessSettled(capability, args) {
741
1000
  const row = mastraSnapshotRow(args, new Date().toISOString());
742
- const result = await capability.database
743
- .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"
744
1004
  (workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt)
745
- VALUES (?1, ?2, ?3, ?4, ?5, ?6)
1005
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6
1006
+ WHERE json_valid(?4)
746
1007
  ON CONFLICT (workflow_name, run_id) DO UPDATE
747
- SET snapshot = excluded.snapshot, updatedAt = excluded.updatedAt
1008
+ SET snapshot = ${UPSERT_SNAPSHOT_SQL}, updatedAt = excluded.updatedAt
748
1009
  WHERE ${SETTLED_ROW_GUARD_SQL}
749
1010
  RETURNING workflow_name`)
750
1011
  .bind(row.workflowName, row.runId, row.resourceId, row.snapshot, row.createdAt, row.updatedAt)
751
1012
  .all();
752
- 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);
753
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));
754
1027
  }
755
1028
  #initialRow(args, input) {
756
1029
  const snapshot = { ...args.snapshot };
@@ -857,7 +1130,7 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
857
1130
  .prepare(`INSERT INTO "${row.tablePrefix}mastra_workflow_snapshot"
858
1131
  (workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt)
859
1132
  SELECT ${fields.join(', ')}
860
- WHERE ${fencePredicate} ${reservation} ${owner}
1133
+ WHERE ${fencePredicate} AND json_valid(${fields[3]}) ${reservation} ${owner}
861
1134
  ON CONFLICT (workflow_name, run_id) DO NOTHING
862
1135
  RETURNING workflow_name, run_id, resourceId, snapshot, createdAt, updatedAt`)
863
1136
  .bind(...values),
@@ -902,7 +1175,7 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
902
1175
  const positive = this.#decodeBatch(result, input, row, observed, nowMs);
903
1176
  if (positive)
904
1177
  return Object.freeze({ execution: input.execution, row });
905
- const refusal = await this.#diagnoseZero(database, input, observed);
1178
+ const refusal = await this.#diagnoseZero(database, input, observed, row.snapshot);
906
1179
  throw definitiveInitialAdmissionRefusal(input.execution, refusal);
907
1180
  }
908
1181
  #decodeBatch(result, input, row, observed, nowMs) {
@@ -992,8 +1265,11 @@ export class FencedWorkflowsStorageD1 extends WorkflowsStorageD1 {
992
1265
  updated_at: nowMs,
993
1266
  })));
994
1267
  }
995
- async #diagnoseZero(database, input, observed) {
1268
+ async #diagnoseZero(database, input, observed, admissionSnapshot) {
996
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);
997
1273
  const [current, snapshot, reservation, owner] = await Promise.all([
998
1274
  input.fence.readForAdmission(),
999
1275
  readRawWorkflowSnapshot(database, input.execution, {