@proofoftech/flowsafe 0.31.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 (77) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +6 -0
  3. package/dist/agent-host/thread-topology.d.ts +1 -0
  4. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  5. package/dist/agent-host/thread-topology.js +3 -2
  6. package/dist/agent-host/thread-topology.js.map +1 -1
  7. package/dist/approval-api/actor-context.d.ts +1 -0
  8. package/dist/approval-api/actor-context.d.ts.map +1 -1
  9. package/dist/approval-api/actor-context.js +12 -1
  10. package/dist/approval-api/actor-context.js.map +1 -1
  11. package/dist/approval-api/resource-ownership.d.ts +3 -0
  12. package/dist/approval-api/resource-ownership.d.ts.map +1 -1
  13. package/dist/approval-api/resource-ownership.js +14 -2
  14. package/dist/approval-api/resource-ownership.js.map +1 -1
  15. package/dist/do-runner/d1-storage.d.ts +6 -4
  16. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  17. package/dist/do-runner/d1-storage.js +23 -32
  18. package/dist/do-runner/d1-storage.js.map +1 -1
  19. package/dist/do-runner/do-error-response.d.ts +1 -5
  20. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  21. package/dist/do-runner/do-error-response.js +3 -6
  22. package/dist/do-runner/do-error-response.js.map +1 -1
  23. package/dist/do-runner/durable-object.d.ts.map +1 -1
  24. package/dist/do-runner/durable-object.js +60 -9
  25. package/dist/do-runner/durable-object.js.map +1 -1
  26. package/dist/do-runner/index.d.ts +6 -4
  27. package/dist/do-runner/index.d.ts.map +1 -1
  28. package/dist/do-runner/index.js +5 -3
  29. package/dist/do-runner/index.js.map +1 -1
  30. package/dist/do-runner/inventory.d.ts +6 -5
  31. package/dist/do-runner/inventory.d.ts.map +1 -1
  32. package/dist/do-runner/inventory.js +116 -26
  33. package/dist/do-runner/inventory.js.map +1 -1
  34. package/dist/do-runner/legacy-drain-classifier.d.ts +23 -0
  35. package/dist/do-runner/legacy-drain-classifier.d.ts.map +1 -0
  36. package/dist/do-runner/legacy-drain-classifier.js +77 -0
  37. package/dist/do-runner/legacy-drain-classifier.js.map +1 -0
  38. package/dist/do-runner/remote-step-expiry.d.ts +6 -0
  39. package/dist/do-runner/remote-step-expiry.d.ts.map +1 -0
  40. package/dist/do-runner/remote-step-expiry.js +5 -0
  41. package/dist/do-runner/remote-step-expiry.js.map +1 -0
  42. package/dist/do-runner/remote-step-journal.d.ts +27 -1
  43. package/dist/do-runner/remote-step-journal.d.ts.map +1 -1
  44. package/dist/do-runner/remote-step-journal.js +350 -2
  45. package/dist/do-runner/remote-step-journal.js.map +1 -1
  46. package/dist/do-runner/runtime.d.ts +19 -1
  47. package/dist/do-runner/runtime.d.ts.map +1 -1
  48. package/dist/do-runner/runtime.js +86 -16
  49. package/dist/do-runner/runtime.js.map +1 -1
  50. package/dist/do-runner/start-idempotency.d.ts +37 -16
  51. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  52. package/dist/do-runner/start-idempotency.js +280 -38
  53. package/dist/do-runner/start-idempotency.js.map +1 -1
  54. package/dist/do-runner/start-reservation-contract.d.ts +9 -5
  55. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -1
  56. package/dist/do-runner/start-reservation-contract.js +18 -4
  57. package/dist/do-runner/start-reservation-contract.js.map +1 -1
  58. package/dist/do-runner/workflow-snapshot-row.d.ts +3 -0
  59. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  60. package/dist/do-runner/workflow-snapshot-row.js +28 -0
  61. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  62. package/dist/host-kit/flowsafe-worker.d.ts +12 -2
  63. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  64. package/dist/host-kit/flowsafe-worker.js +167 -20
  65. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  66. package/dist/host-kit/index.d.ts +1 -0
  67. package/dist/host-kit/index.d.ts.map +1 -1
  68. package/dist/host-kit/index.js +1 -0
  69. package/dist/host-kit/index.js.map +1 -1
  70. package/dist/host-kit/maintenance-capability.d.ts +1 -0
  71. package/dist/host-kit/maintenance-capability.d.ts.map +1 -1
  72. package/dist/host-kit/maintenance-capability.js +1 -0
  73. package/dist/host-kit/maintenance-capability.js.map +1 -1
  74. package/dist/host-kit/run-router.d.ts.map +1 -1
  75. package/dist/host-kit/run-router.js +10 -8
  76. package/dist/host-kit/run-router.js.map +1 -1
  77. package/package.json +2 -2
@@ -2,10 +2,12 @@
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
9
  import { assertMutationEpoch, } from './execution-admission.js';
8
- import { admitsExistingRun, captureExecutionFenceAdmissionSchema, executionFenceAdmissionSql, executionFenceAdmissionValues, } from './execution-fence.js';
10
+ import { admitsDrainableExecution, admitsExistingRun, captureExecutionFenceAdmissionSchema, executionFenceAdmissionSql, executionFenceAdmissionValues, } from './execution-fence.js';
9
11
  import { REMOTE_STEP_TABLE } from './notification-predicate.js';
10
12
  import { isPathSafeId } from './path-safe-id.js';
11
13
  import { lifecycleFromRequestContext, RUN_LIFECYCLE_CONTEXT_KEY, } from './run-lifecycle.js';
@@ -114,6 +116,49 @@ export const MAX_REMOTE_STEP_REQUEST_BYTES = 16_384;
114
116
  export const MAX_REMOTE_STEP_RESULT_BYTES = 16_384;
115
117
  const SHA256_HEX = /^[a-f0-9]{64}$/;
116
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`;
117
162
  function remoteStepTableSql(name, version = 5) {
118
163
  return `CREATE TABLE IF NOT EXISTS ${name} (
119
164
  invocation_id TEXT PRIMARY KEY,
@@ -218,6 +263,12 @@ class RemoteStepRefusal extends DoStatusError {
218
263
  this.status = status;
219
264
  }
220
265
  }
266
+ export class RemoteStepSettlementFencedError extends RemoteStepRefusal {
267
+ constructor() {
268
+ super(503, 'remote step execution is fenced');
269
+ this.name = 'RemoteStepSettlementFencedError';
270
+ }
271
+ }
221
272
  function record(value) {
222
273
  return value !== null && typeof value === 'object' && !Array.isArray(value)
223
274
  ? value
@@ -434,6 +485,28 @@ function decodeAny(row) {
434
485
  return decodeWorkflow(row);
435
486
  throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
436
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
+ }
437
510
  function decodeNotificationOperation(row) {
438
511
  if (row.operation_state === null) {
439
512
  if (row.operation_key !== null ||
@@ -1223,6 +1296,271 @@ export class RemoteStepJournal {
1223
1296
  });
1224
1297
  return { predicate, values, bind, observed: observed.reading };
1225
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
+ }
1226
1564
  async issuePermit(invocationId, lifetimeMs) {
1227
1565
  const invocation = await this.#getAny(invocationId);
1228
1566
  if (!invocation)
@@ -1307,6 +1645,8 @@ export class RemoteStepJournal {
1307
1645
  invocation.permitRevision !== permit.transitionRevision ||
1308
1646
  invocation.permitExpiresAt !== permit.expiresAt)
1309
1647
  throw new RemoteStepRefusal(409, 'remote step permit changed');
1648
+ if (invocation.status === 'failed')
1649
+ throw new RemoteStepRefusal(409, INVOCATION_SETTLED);
1310
1650
  if (invocation.permitConsumedAt !== undefined)
1311
1651
  return { kind: 'already-consumed' };
1312
1652
  const now = this.#now();
@@ -1343,6 +1683,8 @@ export class RemoteStepJournal {
1343
1683
  if (rowResult(result))
1344
1684
  return { kind: 'accepted', rawPermit };
1345
1685
  const after = await this.#getAny(permit.invocationId);
1686
+ if (after?.status === 'failed')
1687
+ throw new RemoteStepRefusal(409, INVOCATION_SETTLED);
1346
1688
  if (after?.permitGeneration === permit.generation &&
1347
1689
  after.permitConsumedAt !== undefined)
1348
1690
  return { kind: 'already-consumed' };
@@ -1360,6 +1702,7 @@ export class RemoteStepJournal {
1360
1702
  if (!stored)
1361
1703
  throw new RemoteStepRefusal(404, 'invocation not found');
1362
1704
  const invocation = decodeAny(stored);
1705
+ assertResultCanBeRecorded(stored);
1363
1706
  const permitDigest = stored.permit_digest;
1364
1707
  if (typeof permitDigest !== 'string' ||
1365
1708
  !SHA256_HEX.test(permitDigest) ||
@@ -1380,6 +1723,7 @@ export class RemoteStepJournal {
1380
1723
  };
1381
1724
  if (stored.result_json !== null)
1382
1725
  return replay(stored);
1726
+ assertWorkflowResultDeadline(stored, this.#now());
1383
1727
  if ('targetKind' in invocation) {
1384
1728
  if (!this.#verifyWorkflowCompletion)
1385
1729
  throw new RemoteStepRefusal(503, 'workflow remote step completion is unavailable');
@@ -1398,6 +1742,7 @@ export class RemoteStepJournal {
1398
1742
  evidenceJson,
1399
1743
  });
1400
1744
  }
1745
+ const now = this.#now();
1401
1746
  const result = await this.#db
1402
1747
  .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1403
1748
  SET result_json = ?, result_digest = ?, quiescence_digest = ?,
@@ -1406,8 +1751,9 @@ export class RemoteStepJournal {
1406
1751
  WHERE invocation_id = ? AND permit_digest = ?
1407
1752
  AND permit_consumed_at IS NOT NULL AND result_json IS NULL
1408
1753
  AND status = 'dispatched'
1754
+ AND (target_kind <> 'workflow' OR deadline_at > ?)
1409
1755
  RETURNING *`)
1410
- .bind(resultJson, resultDigest, quiescenceDigest, this.#now(), invocationId, permitDigest)
1756
+ .bind(resultJson, resultDigest, quiescenceDigest, now, invocationId, permitDigest, now)
1411
1757
  .all();
1412
1758
  if (rowResult(result))
1413
1759
  return { kind: 'recorded', resultJson, resultDigest };
@@ -1417,6 +1763,8 @@ export class RemoteStepJournal {
1417
1763
  .all());
1418
1764
  if (!after)
1419
1765
  throw new RemoteStepRefusal(503, 'remote step result is unreadable');
1766
+ assertResultCanBeRecorded(after);
1767
+ assertWorkflowResultDeadline(after, now);
1420
1768
  return replay(after);
1421
1769
  }
1422
1770
  async readRetainedResult(invocationId) {