@proofoftech/flowsafe 0.30.0 → 0.32.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 (130) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +8 -2
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +2 -2
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-host/thread-topology.d.ts +1 -0
  7. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  8. package/dist/agent-host/thread-topology.js +3 -2
  9. package/dist/agent-host/thread-topology.js.map +1 -1
  10. package/dist/approval-api/actor-context.d.ts +1 -0
  11. package/dist/approval-api/actor-context.d.ts.map +1 -1
  12. package/dist/approval-api/actor-context.js +12 -1
  13. package/dist/approval-api/actor-context.js.map +1 -1
  14. package/dist/approval-api/resource-ownership.d.ts +3 -0
  15. package/dist/approval-api/resource-ownership.d.ts.map +1 -1
  16. package/dist/approval-api/resource-ownership.js +14 -2
  17. package/dist/approval-api/resource-ownership.js.map +1 -1
  18. package/dist/do-runner/d1-storage.d.ts +6 -4
  19. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  20. package/dist/do-runner/d1-storage.js +23 -32
  21. package/dist/do-runner/d1-storage.js.map +1 -1
  22. package/dist/do-runner/do-error-response.d.ts +1 -5
  23. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  24. package/dist/do-runner/do-error-response.js +3 -6
  25. package/dist/do-runner/do-error-response.js.map +1 -1
  26. package/dist/do-runner/durable-object.d.ts.map +1 -1
  27. package/dist/do-runner/durable-object.js +60 -9
  28. package/dist/do-runner/durable-object.js.map +1 -1
  29. package/dist/do-runner/execution-admission.d.ts +29 -0
  30. package/dist/do-runner/execution-admission.d.ts.map +1 -1
  31. package/dist/do-runner/execution-admission.js +14 -0
  32. package/dist/do-runner/execution-admission.js.map +1 -1
  33. package/dist/do-runner/execution-fence.d.ts +10 -1
  34. package/dist/do-runner/execution-fence.d.ts.map +1 -1
  35. package/dist/do-runner/execution-fence.js +44 -1
  36. package/dist/do-runner/execution-fence.js.map +1 -1
  37. package/dist/do-runner/index.d.ts +7 -5
  38. package/dist/do-runner/index.d.ts.map +1 -1
  39. package/dist/do-runner/index.js +6 -4
  40. package/dist/do-runner/index.js.map +1 -1
  41. package/dist/do-runner/inventory.d.ts +6 -5
  42. package/dist/do-runner/inventory.d.ts.map +1 -1
  43. package/dist/do-runner/inventory.js +116 -26
  44. package/dist/do-runner/inventory.js.map +1 -1
  45. package/dist/do-runner/legacy-drain-classifier.d.ts +23 -0
  46. package/dist/do-runner/legacy-drain-classifier.d.ts.map +1 -0
  47. package/dist/do-runner/legacy-drain-classifier.js +77 -0
  48. package/dist/do-runner/legacy-drain-classifier.js.map +1 -0
  49. package/dist/do-runner/notification-predicate.d.ts +1 -0
  50. package/dist/do-runner/notification-predicate.d.ts.map +1 -1
  51. package/dist/do-runner/notification-predicate.js +1 -0
  52. package/dist/do-runner/notification-predicate.js.map +1 -1
  53. package/dist/do-runner/remote-step-expiry.d.ts +6 -0
  54. package/dist/do-runner/remote-step-expiry.d.ts.map +1 -0
  55. package/dist/do-runner/remote-step-expiry.js +5 -0
  56. package/dist/do-runner/remote-step-expiry.js.map +1 -0
  57. package/dist/do-runner/remote-step-journal.d.ts +30 -29
  58. package/dist/do-runner/remote-step-journal.d.ts.map +1 -1
  59. package/dist/do-runner/remote-step-journal.js +353 -4
  60. package/dist/do-runner/remote-step-journal.js.map +1 -1
  61. package/dist/do-runner/runtime.d.ts +19 -1
  62. package/dist/do-runner/runtime.d.ts.map +1 -1
  63. package/dist/do-runner/runtime.js +86 -16
  64. package/dist/do-runner/runtime.js.map +1 -1
  65. package/dist/do-runner/start-idempotency.d.ts +37 -16
  66. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  67. package/dist/do-runner/start-idempotency.js +280 -38
  68. package/dist/do-runner/start-idempotency.js.map +1 -1
  69. package/dist/do-runner/start-reservation-contract.d.ts +9 -5
  70. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -1
  71. package/dist/do-runner/start-reservation-contract.js +18 -4
  72. package/dist/do-runner/start-reservation-contract.js.map +1 -1
  73. package/dist/do-runner/workflow-snapshot-row.d.ts +3 -0
  74. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  75. package/dist/do-runner/workflow-snapshot-row.js +28 -0
  76. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  77. package/dist/host-kit/flowsafe-worker.d.ts +12 -2
  78. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  79. package/dist/host-kit/flowsafe-worker.js +167 -20
  80. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  81. package/dist/host-kit/index.d.ts +1 -0
  82. package/dist/host-kit/index.d.ts.map +1 -1
  83. package/dist/host-kit/index.js +1 -0
  84. package/dist/host-kit/index.js.map +1 -1
  85. package/dist/host-kit/maintenance-capability.d.ts +1 -0
  86. package/dist/host-kit/maintenance-capability.d.ts.map +1 -1
  87. package/dist/host-kit/maintenance-capability.js +1 -0
  88. package/dist/host-kit/maintenance-capability.js.map +1 -1
  89. package/dist/host-kit/run-router.d.ts.map +1 -1
  90. package/dist/host-kit/run-router.js +10 -8
  91. package/dist/host-kit/run-router.js.map +1 -1
  92. package/dist/schedules/schedules-d1.d.ts +3 -3
  93. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  94. package/dist/schedules/schedules-d1.js +61 -62
  95. package/dist/schedules/schedules-d1.js.map +1 -1
  96. package/dist/schedules/tick.d.ts +4 -0
  97. package/dist/schedules/tick.d.ts.map +1 -1
  98. package/dist/schedules/tick.js +28 -7
  99. package/dist/schedules/tick.js.map +1 -1
  100. package/dist/signal-providers/delivery.d.ts +2 -1
  101. package/dist/signal-providers/delivery.d.ts.map +1 -1
  102. package/dist/signal-providers/delivery.js +20 -4
  103. package/dist/signal-providers/delivery.js.map +1 -1
  104. package/dist/signal-providers/host-do.d.ts +2 -0
  105. package/dist/signal-providers/host-do.d.ts.map +1 -1
  106. package/dist/signal-providers/host-do.js +16 -5
  107. package/dist/signal-providers/host-do.js.map +1 -1
  108. package/dist/signal-providers/subscription-d1.d.ts +3 -2
  109. package/dist/signal-providers/subscription-d1.d.ts.map +1 -1
  110. package/dist/signal-providers/subscription-d1.js +25 -7
  111. package/dist/signal-providers/subscription-d1.js.map +1 -1
  112. package/dist/signal-providers/webhook-route.d.ts +2 -0
  113. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  114. package/dist/signal-providers/webhook-route.js +18 -18
  115. package/dist/signal-providers/webhook-route.js.map +1 -1
  116. package/dist/signals/index.d.ts +1 -1
  117. package/dist/signals/index.d.ts.map +1 -1
  118. package/dist/signals/index.js.map +1 -1
  119. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  120. package/dist/signals/notification-dispatch.js +20 -2
  121. package/dist/signals/notification-dispatch.js.map +1 -1
  122. package/dist/signals/notifications-d1.d.ts +10 -2
  123. package/dist/signals/notifications-d1.d.ts.map +1 -1
  124. package/dist/signals/notifications-d1.js +116 -19
  125. package/dist/signals/notifications-d1.js.map +1 -1
  126. package/dist/signals/thread-do-routes.d.ts +6 -3
  127. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  128. package/dist/signals/thread-do-routes.js +30 -5
  129. package/dist/signals/thread-do-routes.js.map +1 -1
  130. package/package.json +2 -2
@@ -2,15 +2,18 @@
2
2
  import { EXECUTION_FENCE_TABLE } from '#deployment-identity-protocol';
3
3
  import { assertExecutionPrincipal, } from '../approval-api/principal.js';
4
4
  import { D1NotificationsStorage, DEFAULT_NOTIFICATION_OPERATION_RECEIPT_LIMIT, NOTIFICATION_OPERATION_PROJECTION_VERSION, NOTIFICATION_OPERATION_RECEIPTS_TABLE, projectNotificationOperation, } from '../signals/notifications-d1.js';
5
+ import { missingTableReadsEmpty } from './cause-chain.js';
6
+ import { RUN_TERMINAL_SNAPSHOT_SQL, RUN_TERMINAL_STATUSES, } from './d1-storage.js';
5
7
  import { credentialsMatch } from './deployment-identity.js';
6
8
  import { DoStatusError } from './do-status-error.js';
7
- import { assertMutationEpoch } from './execution-admission.js';
8
- import { admitsExistingRun, captureExecutionFenceAdmissionSchema, executionFenceAdmissionSql, executionFenceAdmissionValues, } from './execution-fence.js';
9
+ import { assertMutationEpoch, } from './execution-admission.js';
10
+ import { admitsDrainableExecution, admitsExistingRun, captureExecutionFenceAdmissionSchema, executionFenceAdmissionSql, executionFenceAdmissionValues, } from './execution-fence.js';
11
+ import { REMOTE_STEP_TABLE } from './notification-predicate.js';
9
12
  import { isPathSafeId } from './path-safe-id.js';
10
13
  import { lifecycleFromRequestContext, RUN_LIFECYCLE_CONTEXT_KEY, } from './run-lifecycle.js';
11
14
  import { MASTRA_WORKFLOW_META_KEY } from './suspension-deadline.js';
12
15
  import { validateTablePrefix } from './table-prefix.js';
13
- export const REMOTE_STEP_TABLE = 'flowsafe_remote_step_invocations';
16
+ export { REMOTE_STEP_TABLE } from './notification-predicate.js';
14
17
  export const REMOTE_STEP_SCHEMA_TABLE = 'flowsafe_remote_step_schema';
15
18
  export const REMOTE_STEP_NOTIFICATION_CURSOR_TABLE = 'flowsafe_remote_step_notification_cursor';
16
19
  const REMOTE_STEP_NOTIFICATION_CURSOR_SQL = `CREATE TABLE ${REMOTE_STEP_NOTIFICATION_CURSOR_TABLE} (
@@ -113,6 +116,49 @@ export const MAX_REMOTE_STEP_REQUEST_BYTES = 16_384;
113
116
  export const MAX_REMOTE_STEP_RESULT_BYTES = 16_384;
114
117
  const SHA256_HEX = /^[a-f0-9]{64}$/;
115
118
  const RAW_PERMIT = /^[A-Za-z0-9_-]{43}$/;
119
+ const RESULT_RETAINED = 'remote step result is retained';
120
+ const INVOCATION_SETTLED = 'remote step invocation is settled';
121
+ const RUN_CAN_USE_RESULT = 'remote step run can still use a result';
122
+ const RESULTLESS_OPEN_INVOCATION_SQL = "status IN ('pending', 'dispatched') AND result_json IS NULL";
123
+ const RETAINED_WORKFLOW_INVOCATION_SQL = "target_kind = 'workflow' AND status = 'result-retained' AND result_json IS NOT NULL";
124
+ const TERMINAL_SNAPSHOT_SQL = `CASE WHEN json_valid(snapshot)
125
+ THEN (${RUN_TERMINAL_SNAPSHOT_SQL}) IS TRUE ELSE 0 END`;
126
+ const SNAPSHOT_LIFECYCLE_PATH = `$.requestContext."${RUN_LIFECYCLE_CONTEXT_KEY}"`;
127
+ const SNAPSHOT_DEADLINE_PATH = `${SNAPSHOT_LIFECYCLE_PATH}.deadlineAt`;
128
+ // SQLite and the runtime can read different values from duplicate JSON keys.
129
+ const AGENT_RUN_CAN_USE_RESULT_SQL = `CASE WHEN json_valid(snapshot) THEN
130
+ NOT (${TERMINAL_SNAPSHOT_SQL})
131
+ AND json_extract(snapshot, '$.status') IN (
132
+ 'running', 'suspended', 'waiting', 'paused', 'waiting_callback', 'waiting_signal',
133
+ 'retry_wait', 'cancelled', 'timed_out'
134
+ )
135
+ AND (SELECT count(*) FROM json_each(snapshot) WHERE key COLLATE BINARY = 'status') = 1
136
+ AND (SELECT count(*) FROM json_each(snapshot) WHERE key COLLATE BINARY = 'requestContext') <= 1
137
+ AND (SELECT count(*) FROM json_each(snapshot, '$.requestContext') WHERE key COLLATE BINARY = '${RUN_LIFECYCLE_CONTEXT_KEY}') <= 1
138
+ AND (SELECT count(*) FROM json_each(snapshot, '${SNAPSHOT_LIFECYCLE_PATH}') WHERE key COLLATE BINARY = 'deadlineAt') <= 1
139
+ AND (
140
+ json_type(snapshot, '${SNAPSHOT_LIFECYCLE_PATH}') IS NULL
141
+ OR (
142
+ json_type(snapshot, '${SNAPSHOT_LIFECYCLE_PATH}') = 'object'
143
+ AND json_extract(snapshot, '${SNAPSHOT_LIFECYCLE_PATH}.version') = 1
144
+ AND json_extract(snapshot, '${SNAPSHOT_LIFECYCLE_PATH}.revision') BETWEEN 1 AND 9007199254740991
145
+ AND json_extract(snapshot, '${SNAPSHOT_LIFECYCLE_PATH}.revision') = CAST(
146
+ json_extract(snapshot, '${SNAPSHOT_LIFECYCLE_PATH}.revision') AS INTEGER
147
+ )
148
+ AND (
149
+ json_type(snapshot, '${SNAPSHOT_DEADLINE_PATH}') IS NULL
150
+ OR (
151
+ json_type(snapshot, '${SNAPSHOT_DEADLINE_PATH}') IN ('integer', 'real')
152
+ AND json_extract(snapshot, '${SNAPSHOT_DEADLINE_PATH}') > ?
153
+ AND json_extract(snapshot, '${SNAPSHOT_DEADLINE_PATH}') <= 9007199254740991
154
+ AND json_extract(snapshot, '${SNAPSHOT_DEADLINE_PATH}') = CAST(
155
+ json_extract(snapshot, '${SNAPSHOT_DEADLINE_PATH}') AS INTEGER
156
+ )
157
+ )
158
+ )
159
+ )
160
+ )
161
+ ELSE 0 END`;
116
162
  function remoteStepTableSql(name, version = 5) {
117
163
  return `CREATE TABLE IF NOT EXISTS ${name} (
118
164
  invocation_id TEXT PRIMARY KEY,
@@ -217,6 +263,12 @@ class RemoteStepRefusal extends DoStatusError {
217
263
  this.status = status;
218
264
  }
219
265
  }
266
+ export class RemoteStepSettlementFencedError extends RemoteStepRefusal {
267
+ constructor() {
268
+ super(503, 'remote step execution is fenced');
269
+ this.name = 'RemoteStepSettlementFencedError';
270
+ }
271
+ }
220
272
  function record(value) {
221
273
  return value !== null && typeof value === 'object' && !Array.isArray(value)
222
274
  ? value
@@ -433,6 +485,28 @@ function decodeAny(row) {
433
485
  return decodeWorkflow(row);
434
486
  throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
435
487
  }
488
+ function replaysExpirySettlement(row, settlingRetainedResult) {
489
+ if (settlingRetainedResult)
490
+ return (row.target_kind === 'workflow' &&
491
+ row.status === 'failed' &&
492
+ row.result_json !== null &&
493
+ row.settlement_outcome === 'terminal-not-success');
494
+ return (row.status === 'failed' &&
495
+ row.result_json === null &&
496
+ (row.settlement_outcome === 'deadline-expired' ||
497
+ row.settlement_outcome === 'terminal-not-success'));
498
+ }
499
+ function assertResultCanBeRecorded(row) {
500
+ if (row.result_json === null &&
501
+ (row.status === 'failed' || row.status === 'settled'))
502
+ throw new RemoteStepRefusal(409, INVOCATION_SETTLED);
503
+ }
504
+ function assertWorkflowResultDeadline(row, now) {
505
+ if (row.target_kind === 'workflow' &&
506
+ row.result_json === null &&
507
+ row.deadline_at <= now)
508
+ throw new RemoteStepRefusal(409, 'remote step deadline elapsed');
509
+ }
436
510
  function decodeNotificationOperation(row) {
437
511
  if (row.operation_state === null) {
438
512
  if (row.operation_key !== null ||
@@ -1222,6 +1296,271 @@ export class RemoteStepJournal {
1222
1296
  });
1223
1297
  return { predicate, values, bind, observed: observed.reading };
1224
1298
  }
1299
+ async #settlementAdmission(priorBindings) {
1300
+ const observed = await this.#fence.readForAdmission();
1301
+ if (!admitsDrainableExecution(observed.reading))
1302
+ throw new RemoteStepSettlementFencedError();
1303
+ const schema = await captureExecutionFenceAdmissionSchema(await this.#db
1304
+ .prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`)
1305
+ .all());
1306
+ const values = [];
1307
+ const bind = (value) => {
1308
+ values.push(value);
1309
+ return `?${priorBindings + values.length}`;
1310
+ };
1311
+ const predicate = executionFenceAdmissionSql({
1312
+ callerEpoch: bind(observed.reading.mutationEpoch ?? null),
1313
+ semantic: executionFenceAdmissionValues(observed).map(bind),
1314
+ schema: bind(schema),
1315
+ statePredicate: "f.state IN ('open', 'draining')",
1316
+ });
1317
+ return { predicate, values, observed: observed.reading };
1318
+ }
1319
+ async settleClosedRunInvocations(workflowId, runId) {
1320
+ const now = this.#now();
1321
+ const bindings = [
1322
+ now,
1323
+ this.#deploymentId,
1324
+ this.#tablePrefix,
1325
+ workflowId,
1326
+ runId,
1327
+ workflowId,
1328
+ runId,
1329
+ ...RUN_TERMINAL_STATUSES,
1330
+ ];
1331
+ const gate = await this.#settlementAdmission(bindings.length);
1332
+ let settled = 0;
1333
+ for (const targetKind of ['workflow', 'agent']) {
1334
+ const invocationPredicate = targetKind === 'workflow'
1335
+ ? `(${RESULTLESS_OPEN_INVOCATION_SQL}) OR (${RETAINED_WORKFLOW_INVOCATION_SQL})`
1336
+ : RESULTLESS_OPEN_INVOCATION_SQL;
1337
+ const { results } = await this.#db
1338
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1339
+ SET status = 'failed',
1340
+ settlement_outcome = CASE WHEN result_json IS NULL AND deadline_at <= ?1
1341
+ THEN 'deadline-expired' ELSE 'terminal-not-success' END,
1342
+ settled_at = ?1, write_revision = write_revision + 1, write_generation = write_generation + 1
1343
+ WHERE deployment_id = ? AND table_prefix = ? AND workflow_id = ? AND run_id = ?
1344
+ AND target_kind = '${targetKind}'
1345
+ AND (${invocationPredicate}) AND operation_state IS NULL
1346
+ AND EXISTS (
1347
+ SELECT 1 FROM "${this.#tablePrefix}mastra_workflow_snapshot"
1348
+ WHERE workflow_name = ? AND run_id = ? AND (${TERMINAL_SNAPSHOT_SQL}))
1349
+ AND ${gate.predicate}
1350
+ RETURNING invocation_id`)
1351
+ .bind(...bindings, ...gate.values)
1352
+ .all();
1353
+ settled += results.length;
1354
+ }
1355
+ return { settled };
1356
+ }
1357
+ async settleExpiredInvocation(invocationId) {
1358
+ const { kind, invocation } = await this.#settleExpiredInvocation(invocationId);
1359
+ return { kind, invocation };
1360
+ }
1361
+ async #settleExpiredInvocation(invocationId, settlingRetainedResult = false) {
1362
+ const stored = await this.#getRow(invocationId);
1363
+ if (!stored ||
1364
+ stored.deployment_id !== this.#deploymentId ||
1365
+ stored.table_prefix !== this.#tablePrefix)
1366
+ throw new RemoteStepRefusal(404, 'invocation not found');
1367
+ const invocation = decodeAny(stored);
1368
+ if (replaysExpirySettlement(stored, settlingRetainedResult))
1369
+ return { kind: 'replay', invocation };
1370
+ const wrongResultState = settlingRetainedResult
1371
+ ? stored.target_kind !== 'workflow' ||
1372
+ stored.status !== 'result-retained' ||
1373
+ stored.result_json === null
1374
+ : stored.result_json !== null ||
1375
+ ['result-retained', 'resuming', 'settled'].includes(stored.status);
1376
+ if (wrongResultState)
1377
+ throw new RemoteStepRefusal(409, RESULT_RETAINED);
1378
+ if (stored.status === 'failed')
1379
+ throw new RemoteStepRefusal(409, INVOCATION_SETTLED);
1380
+ const now = this.#now();
1381
+ if (!settlingRetainedResult && stored.deadline_at > now)
1382
+ throw new RemoteStepRefusal(409, 'remote step deadline has not elapsed');
1383
+ const snapshotTable = `"${this.#tablePrefix}mastra_workflow_snapshot"`;
1384
+ const { results: snapshots } = await this.#db
1385
+ .prepare(`SELECT snapshot, ${TERMINAL_SNAPSHOT_SQL} AS terminal FROM ${snapshotTable}
1386
+ WHERE workflow_name = ? AND run_id = ? LIMIT 2`)
1387
+ .bind(...RUN_TERMINAL_STATUSES, invocation.workflowId, invocation.runId)
1388
+ .all();
1389
+ if (snapshots.length > 1)
1390
+ throw new RemoteStepRefusal(503, 'remote step snapshot is unreadable');
1391
+ const liveSnapshot = snapshots.find(({ terminal }) => terminal !== 1);
1392
+ let suspendedRun = false;
1393
+ if (liveSnapshot) {
1394
+ if (settlingRetainedResult)
1395
+ throw new RemoteStepRefusal(409, RUN_CAN_USE_RESULT);
1396
+ if (typeof liveSnapshot.snapshot !== 'string')
1397
+ throw new RemoteStepRefusal(503, 'remote step snapshot is unreadable');
1398
+ const summary = await this.#runtime.authoritativeStatus(invocation.workflowId, invocation.runId);
1399
+ if (!summary || summary.runId !== invocation.runId)
1400
+ throw new RemoteStepRefusal(503, 'remote step run status is unreadable');
1401
+ if (stored.target_kind === 'agent' &&
1402
+ !(summary.deadlineAt !== undefined && summary.deadlineAt <= now))
1403
+ throw new RemoteStepRefusal(409, RUN_CAN_USE_RESULT);
1404
+ suspendedRun =
1405
+ stored.target_kind === 'workflow' &&
1406
+ summary.deadlineAt === undefined &&
1407
+ summary.status === 'suspended';
1408
+ }
1409
+ const bindings = [
1410
+ now,
1411
+ invocationId,
1412
+ this.#deploymentId,
1413
+ this.#tablePrefix,
1414
+ stored.start_token,
1415
+ stored.principal_json,
1416
+ stored.permit_generation,
1417
+ stored.permit_epoch,
1418
+ stored.write_revision,
1419
+ stored.write_generation,
1420
+ invocation.workflowId,
1421
+ invocation.runId,
1422
+ ];
1423
+ // An accepted resume can replace the run deadline.
1424
+ const runPredicate = liveSnapshot
1425
+ ? `EXISTS (
1426
+ SELECT 1 FROM ${snapshotTable} WHERE workflow_name = ? AND run_id = ? AND snapshot = ?)`
1427
+ : `NOT EXISTS (
1428
+ SELECT 1 FROM ${snapshotTable} WHERE workflow_name = ? AND run_id = ?
1429
+ AND NOT (${TERMINAL_SNAPSHOT_SQL}))`;
1430
+ if (liveSnapshot)
1431
+ bindings.push(liveSnapshot.snapshot);
1432
+ else
1433
+ bindings.push(...RUN_TERMINAL_STATUSES);
1434
+ const gate = await this.#settlementAdmission(bindings.length);
1435
+ const invocationPredicate = settlingRetainedResult
1436
+ ? RETAINED_WORKFLOW_INVOCATION_SQL
1437
+ : `${RESULTLESS_OPEN_INVOCATION_SQL} AND deadline_at <= ?1`;
1438
+ const outcome = settlingRetainedResult
1439
+ ? 'terminal-not-success'
1440
+ : 'deadline-expired';
1441
+ const settled = rowResult(await this.#db
1442
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1443
+ SET status = 'failed', settlement_outcome = '${outcome}', settled_at = ?1,
1444
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1445
+ WHERE invocation_id = ? AND ${invocationPredicate} AND operation_state IS NULL
1446
+ AND deployment_id = ? AND table_prefix = ?
1447
+ AND start_token = ? AND principal_json = ? AND permit_generation = ? AND permit_epoch IS ?
1448
+ AND write_revision = ? AND write_generation = ?
1449
+ AND ${runPredicate} AND ${gate.predicate}
1450
+ RETURNING *`)
1451
+ .bind(...bindings, ...gate.values)
1452
+ .all());
1453
+ if (settled)
1454
+ return { kind: 'settled', invocation: decodeAny(settled), suspendedRun };
1455
+ const after = await this.#getRow(invocationId);
1456
+ if (after?.deployment_id === this.#deploymentId &&
1457
+ after.table_prefix === this.#tablePrefix) {
1458
+ if (replaysExpirySettlement(after, settlingRetainedResult))
1459
+ return { kind: 'replay', invocation: decodeAny(after) };
1460
+ if (!settlingRetainedResult && after.result_json !== null)
1461
+ throw new RemoteStepRefusal(409, RESULT_RETAINED);
1462
+ }
1463
+ const fence = await this.#fence.readForAdmission();
1464
+ if (!admitsDrainableExecution(fence.reading) ||
1465
+ fence.reading.transitionRevision !== gate.observed.transitionRevision)
1466
+ throw new RemoteStepSettlementFencedError();
1467
+ throw new RemoteStepRefusal(409, 'remote step settlement changed');
1468
+ }
1469
+ async settleExpiredInvocations({ limit, }) {
1470
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100)
1471
+ throw new RemoteStepRefusal(400, 'remote step expiry limit is malformed');
1472
+ const now = this.#now();
1473
+ const snapshotTable = `"${this.#tablePrefix}mastra_workflow_snapshot"`;
1474
+ const result = {
1475
+ settled: 0,
1476
+ replayed: 0,
1477
+ skippedLiveRun: 0,
1478
+ suspendedRuns: 0,
1479
+ refused: 0,
1480
+ };
1481
+ let after;
1482
+ let firstFailure;
1483
+ for (let page = 0; page < 10 && result.settled < limit; page += 1) {
1484
+ const bindings = [
1485
+ this.#deploymentId,
1486
+ this.#tablePrefix,
1487
+ now,
1488
+ ...RUN_TERMINAL_STATUSES,
1489
+ now,
1490
+ ...RUN_TERMINAL_STATUSES,
1491
+ ];
1492
+ const keyset = after ? 'AND (deadline_at, invocation_id) > (?, ?)' : '';
1493
+ if (after)
1494
+ bindings.push(after.deadline_at, after.invocation_id);
1495
+ const { results: candidates } = await this.#db
1496
+ .prepare(`SELECT deadline_at, invocation_id, status FROM ${REMOTE_STEP_TABLE} AS i
1497
+ WHERE deployment_id = ? AND table_prefix = ? AND operation_state IS NULL
1498
+ AND (
1499
+ (${RESULTLESS_OPEN_INVOCATION_SQL} AND deadline_at <= ?
1500
+ AND (target_kind IS NOT 'agent' OR NOT EXISTS (
1501
+ SELECT 1 FROM ${snapshotTable}
1502
+ WHERE workflow_name = i.workflow_id AND run_id = i.run_id
1503
+ AND (${AGENT_RUN_CAN_USE_RESULT_SQL})
1504
+ )))
1505
+ OR (${RETAINED_WORKFLOW_INVOCATION_SQL} AND NOT EXISTS (
1506
+ SELECT 1 FROM ${snapshotTable}
1507
+ WHERE workflow_name = i.workflow_id AND run_id = i.run_id
1508
+ AND NOT (${TERMINAL_SNAPSHOT_SQL})
1509
+ ))
1510
+ )
1511
+ ${keyset}
1512
+ ORDER BY deadline_at, invocation_id LIMIT ?`)
1513
+ .bind(...bindings, limit)
1514
+ .all()
1515
+ .catch((error) => {
1516
+ if (missingTableReadsEmpty(error, REMOTE_STEP_TABLE))
1517
+ return { results: [] };
1518
+ throw error;
1519
+ });
1520
+ for (const candidate of candidates) {
1521
+ try {
1522
+ const settlement = await this.#settleExpiredInvocation(candidate.invocation_id, candidate.status === 'result-retained');
1523
+ if (settlement.kind === 'replay') {
1524
+ result.replayed += 1;
1525
+ }
1526
+ else {
1527
+ result.settled += 1;
1528
+ if (settlement.suspendedRun) {
1529
+ const { workflowId, runId, invocationId } = settlement.invocation;
1530
+ console.log(JSON.stringify({
1531
+ type: 'remote-step-expired-run-suspended',
1532
+ workflowId,
1533
+ runId,
1534
+ invocationId,
1535
+ }));
1536
+ result.suspendedRuns += 1;
1537
+ }
1538
+ if (result.settled === limit)
1539
+ break;
1540
+ }
1541
+ }
1542
+ catch (error) {
1543
+ if (error instanceof RemoteStepRefusal &&
1544
+ error.status === 409 &&
1545
+ error.message === RUN_CAN_USE_RESULT) {
1546
+ result.skippedLiveRun += 1;
1547
+ }
1548
+ else if (error instanceof DoStatusError && error.status === 409) {
1549
+ result.refused += 1;
1550
+ }
1551
+ else {
1552
+ firstFailure ??= { error };
1553
+ }
1554
+ }
1555
+ }
1556
+ if (candidates.length < limit)
1557
+ break;
1558
+ after = candidates.at(-1);
1559
+ }
1560
+ if (firstFailure)
1561
+ throw firstFailure.error;
1562
+ return result;
1563
+ }
1225
1564
  async issuePermit(invocationId, lifetimeMs) {
1226
1565
  const invocation = await this.#getAny(invocationId);
1227
1566
  if (!invocation)
@@ -1306,6 +1645,8 @@ export class RemoteStepJournal {
1306
1645
  invocation.permitRevision !== permit.transitionRevision ||
1307
1646
  invocation.permitExpiresAt !== permit.expiresAt)
1308
1647
  throw new RemoteStepRefusal(409, 'remote step permit changed');
1648
+ if (invocation.status === 'failed')
1649
+ throw new RemoteStepRefusal(409, INVOCATION_SETTLED);
1309
1650
  if (invocation.permitConsumedAt !== undefined)
1310
1651
  return { kind: 'already-consumed' };
1311
1652
  const now = this.#now();
@@ -1342,6 +1683,8 @@ export class RemoteStepJournal {
1342
1683
  if (rowResult(result))
1343
1684
  return { kind: 'accepted', rawPermit };
1344
1685
  const after = await this.#getAny(permit.invocationId);
1686
+ if (after?.status === 'failed')
1687
+ throw new RemoteStepRefusal(409, INVOCATION_SETTLED);
1345
1688
  if (after?.permitGeneration === permit.generation &&
1346
1689
  after.permitConsumedAt !== undefined)
1347
1690
  return { kind: 'already-consumed' };
@@ -1359,6 +1702,7 @@ export class RemoteStepJournal {
1359
1702
  if (!stored)
1360
1703
  throw new RemoteStepRefusal(404, 'invocation not found');
1361
1704
  const invocation = decodeAny(stored);
1705
+ assertResultCanBeRecorded(stored);
1362
1706
  const permitDigest = stored.permit_digest;
1363
1707
  if (typeof permitDigest !== 'string' ||
1364
1708
  !SHA256_HEX.test(permitDigest) ||
@@ -1379,6 +1723,7 @@ export class RemoteStepJournal {
1379
1723
  };
1380
1724
  if (stored.result_json !== null)
1381
1725
  return replay(stored);
1726
+ assertWorkflowResultDeadline(stored, this.#now());
1382
1727
  if ('targetKind' in invocation) {
1383
1728
  if (!this.#verifyWorkflowCompletion)
1384
1729
  throw new RemoteStepRefusal(503, 'workflow remote step completion is unavailable');
@@ -1397,6 +1742,7 @@ export class RemoteStepJournal {
1397
1742
  evidenceJson,
1398
1743
  });
1399
1744
  }
1745
+ const now = this.#now();
1400
1746
  const result = await this.#db
1401
1747
  .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1402
1748
  SET result_json = ?, result_digest = ?, quiescence_digest = ?,
@@ -1405,8 +1751,9 @@ export class RemoteStepJournal {
1405
1751
  WHERE invocation_id = ? AND permit_digest = ?
1406
1752
  AND permit_consumed_at IS NOT NULL AND result_json IS NULL
1407
1753
  AND status = 'dispatched'
1754
+ AND (target_kind <> 'workflow' OR deadline_at > ?)
1408
1755
  RETURNING *`)
1409
- .bind(resultJson, resultDigest, quiescenceDigest, this.#now(), invocationId, permitDigest)
1756
+ .bind(resultJson, resultDigest, quiescenceDigest, now, invocationId, permitDigest, now)
1410
1757
  .all();
1411
1758
  if (rowResult(result))
1412
1759
  return { kind: 'recorded', resultJson, resultDigest };
@@ -1416,6 +1763,8 @@ export class RemoteStepJournal {
1416
1763
  .all());
1417
1764
  if (!after)
1418
1765
  throw new RemoteStepRefusal(503, 'remote step result is unreadable');
1766
+ assertResultCanBeRecorded(after);
1767
+ assertWorkflowResultDeadline(after, now);
1419
1768
  return replay(after);
1420
1769
  }
1421
1770
  async readRetainedResult(invocationId) {