@proofoftech/flowsafe 0.31.0 → 0.33.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 (114) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +6 -0
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +18 -19
  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 +29 -5
  19. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  20. package/dist/do-runner/d1-storage.js +244 -84
  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 +4 -5
  27. package/dist/do-runner/durable-object.d.ts.map +1 -1
  28. package/dist/do-runner/durable-object.js +74 -17
  29. package/dist/do-runner/durable-object.js.map +1 -1
  30. package/dist/do-runner/index.d.ts +7 -5
  31. package/dist/do-runner/index.d.ts.map +1 -1
  32. package/dist/do-runner/index.js +5 -3
  33. package/dist/do-runner/index.js.map +1 -1
  34. package/dist/do-runner/inventory.d.ts +6 -5
  35. package/dist/do-runner/inventory.d.ts.map +1 -1
  36. package/dist/do-runner/inventory.js +116 -26
  37. package/dist/do-runner/inventory.js.map +1 -1
  38. package/dist/do-runner/legacy-drain-classifier.d.ts +23 -0
  39. package/dist/do-runner/legacy-drain-classifier.d.ts.map +1 -0
  40. package/dist/do-runner/legacy-drain-classifier.js +77 -0
  41. package/dist/do-runner/legacy-drain-classifier.js.map +1 -0
  42. package/dist/do-runner/own-data-copy.d.ts +2 -0
  43. package/dist/do-runner/own-data-copy.d.ts.map +1 -0
  44. package/dist/do-runner/own-data-copy.js +14 -0
  45. package/dist/do-runner/own-data-copy.js.map +1 -0
  46. package/dist/do-runner/remote-step-expiry.d.ts +6 -0
  47. package/dist/do-runner/remote-step-expiry.d.ts.map +1 -0
  48. package/dist/do-runner/remote-step-expiry.js +5 -0
  49. package/dist/do-runner/remote-step-expiry.js.map +1 -0
  50. package/dist/do-runner/remote-step-journal.d.ts +27 -1
  51. package/dist/do-runner/remote-step-journal.d.ts.map +1 -1
  52. package/dist/do-runner/remote-step-journal.js +350 -2
  53. package/dist/do-runner/remote-step-journal.js.map +1 -1
  54. package/dist/do-runner/runtime.d.ts +19 -1
  55. package/dist/do-runner/runtime.d.ts.map +1 -1
  56. package/dist/do-runner/runtime.js +86 -16
  57. package/dist/do-runner/runtime.js.map +1 -1
  58. package/dist/do-runner/start-idempotency.d.ts +37 -16
  59. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  60. package/dist/do-runner/start-idempotency.js +280 -38
  61. package/dist/do-runner/start-idempotency.js.map +1 -1
  62. package/dist/do-runner/start-reservation-contract.d.ts +9 -5
  63. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -1
  64. package/dist/do-runner/start-reservation-contract.js +18 -4
  65. package/dist/do-runner/start-reservation-contract.js.map +1 -1
  66. package/dist/do-runner/workflow-snapshot-row.d.ts +3 -0
  67. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  68. package/dist/do-runner/workflow-snapshot-row.js +28 -0
  69. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  70. package/dist/host-kit/approval-bridge.d.ts +12 -13
  71. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  72. package/dist/host-kit/approval-bridge.js +69 -21
  73. package/dist/host-kit/approval-bridge.js.map +1 -1
  74. package/dist/host-kit/do-response.d.ts.map +1 -1
  75. package/dist/host-kit/do-response.js +3 -10
  76. package/dist/host-kit/do-response.js.map +1 -1
  77. package/dist/host-kit/do-run-topology.d.ts +3 -1
  78. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  79. package/dist/host-kit/do-run-topology.js +8 -0
  80. package/dist/host-kit/do-run-topology.js.map +1 -1
  81. package/dist/host-kit/flowsafe-worker.d.ts +17 -10
  82. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  83. package/dist/host-kit/flowsafe-worker.js +214 -25
  84. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  85. package/dist/host-kit/host-approval-service.d.ts +2 -2
  86. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  87. package/dist/host-kit/host-approval-service.js +2 -2
  88. package/dist/host-kit/host-approval-service.js.map +1 -1
  89. package/dist/host-kit/index.d.ts +2 -1
  90. package/dist/host-kit/index.d.ts.map +1 -1
  91. package/dist/host-kit/index.js +1 -0
  92. package/dist/host-kit/index.js.map +1 -1
  93. package/dist/host-kit/maintenance-capability.d.ts +1 -0
  94. package/dist/host-kit/maintenance-capability.d.ts.map +1 -1
  95. package/dist/host-kit/maintenance-capability.js +1 -0
  96. package/dist/host-kit/maintenance-capability.js.map +1 -1
  97. package/dist/host-kit/memory-boundary.js +4 -2
  98. package/dist/host-kit/memory-boundary.js.map +1 -1
  99. package/dist/host-kit/run-router.d.ts +3 -3
  100. package/dist/host-kit/run-router.d.ts.map +1 -1
  101. package/dist/host-kit/run-router.js +10 -17
  102. package/dist/host-kit/run-router.js.map +1 -1
  103. package/dist/schedules/router.d.ts.map +1 -1
  104. package/dist/schedules/router.js +7 -6
  105. package/dist/schedules/router.js.map +1 -1
  106. package/dist/schedules/target-policy.d.ts +2 -2
  107. package/dist/schedules/target-policy.d.ts.map +1 -1
  108. package/dist/schedules/target-policy.js +3 -0
  109. package/dist/schedules/target-policy.js.map +1 -1
  110. package/dist/schedules/tick.d.ts +3 -4
  111. package/dist/schedules/tick.d.ts.map +1 -1
  112. package/dist/schedules/tick.js +13 -10
  113. package/dist/schedules/tick.js.map +1 -1
  114. package/package.json +2 -2
@@ -2,10 +2,10 @@
2
2
  import { APPROVAL_ROLES, createActorResolver, createApprovalRouter, createPrincipalActorContext, createResourceOwnershipSchema, DECIDER_ROLES, RESOURCE_OWNERSHIP_TABLE, selfDecisionExempts, trustAutomationPrincipal, } from '../approval-api/index.js';
3
3
  import { createAuditProxyDurableObjectBinding, createAuditProxyQueue, } from '../audit-export/index.js';
4
4
  import { parseRunRetentionCursor } from '../do-runner/d1-storage.js';
5
- import { credentialsMatch } from '../do-runner/deployment-identity.js';
5
+ import { credentialsMatch, isDatabaseBinding, } from '../do-runner/deployment-identity.js';
6
6
  import { isRefusalStatus, refusalBody } from '../do-runner/do-status-error.js';
7
7
  import { InvalidMutationEpochError, normalizeMutationEpoch, } from '../do-runner/execution-admission.js';
8
- import { assertExecutionFenceState, DEPLOYMENT_IDENTITY_HEADER, DeploymentIdentityError, DeploymentInventory, DoStatusError, deploymentIdentityHeaders, ensureDeploymentIdentityBindings, executionFenceFor, executionFenceReadingPayload, InvalidInventoryRequestError, isInventoryCategory, purgeExpiredBackgroundTasks, purgeExpiredNotifications, purgeExpiredScheduleTriggers, purgeExpiredThreadState, purgeExpiredThreads, purgeExpiredWorkflowRuns, START_IDEMPOTENCY_TABLE, startIdempotencyFor, sweepExpiredRunDeadlines, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from '../do-runner/index.js';
8
+ import { admitsDrainableExecution, assertExecutionFenceState, BOUND_RESERVATION_SETTLEMENT_AGE_MS, countUnreadableExpiredRunDeadlines, DEPLOYMENT_IDENTITY_HEADER, DeploymentIdentityError, DeploymentInventory, DoStatusError, deploymentIdentityHeaders, ExecutionFencedError, ensureDeploymentIdentityBindings, executionFenceFor, executionFenceReadingPayload, InvalidInventoryRequestError, isExecutionFenceRefusal, isInventoryCategory, purgeAbandonedStartReservations, purgeExpiredBackgroundTasks, purgeExpiredNotifications, purgeExpiredScheduleTriggers, purgeExpiredThreadState, purgeExpiredThreads, purgeExpiredWorkflowRuns, START_IDEMPOTENCY_TABLE, startIdempotencyFor, sweepExpiredRunDeadlines, UNBOUND_RESERVATION_EXPIRY_MS, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from '../do-runner/index.js';
9
9
  import { isPathSafeId } from '../do-runner/path-safe-id.js';
10
10
  import { validateTablePrefix } from '../do-runner/table-prefix.js';
11
11
  import { readBoundedBody } from '../http-body.js';
@@ -184,11 +184,19 @@ const INJECTED_TICK_DUTIES = {
184
184
  interval: 'remoteStepRecoveryIntervalMs',
185
185
  logType: 'remote-step-notification-recovery',
186
186
  },
187
+ remoteStepExpiry: {
188
+ builder: 'remoteStepExpiryTick',
189
+ interval: 'remoteStepExpiryIntervalMs',
190
+ logType: 'remote-step-expiry',
191
+ },
187
192
  };
188
193
  function json(payload, status = 200) {
189
194
  return new Response(JSON.stringify(payload), {
190
195
  status,
191
- headers: { 'content-type': 'application/json' },
196
+ headers: {
197
+ 'content-type': 'application/json',
198
+ 'cache-control': 'no-store',
199
+ },
192
200
  });
193
201
  }
194
202
  const MAINTENANCE_ADMIN_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
@@ -495,11 +503,102 @@ async function inventoryAdminResponse(request, env, storageTablePrefix) {
495
503
  return json({ error: 'deployment inventory failed' }, 500);
496
504
  }
497
505
  }
506
+ const SETTLE_UNPROGRESSABLE_PATH = '/admin/settle-unprogressable';
507
+ const SETTLE_UNPROGRESSABLE_SURFACE = 'unprogressable settlement';
508
+ async function settleStartReservations(env, tablePrefix, options, counts, cursor, advanceCursor) {
509
+ const store = startIdempotencyForEnv(env);
510
+ const fence = executionFenceForEnv(env);
511
+ counts.abandoned = await store.abandonUnboundReservations({
512
+ ...options,
513
+ fence,
514
+ });
515
+ await store.settleOrphanedBoundReservations({
516
+ fence,
517
+ tablePrefix,
518
+ // The workflow DO requires a fenced runtime when it verifies its D1
519
+ // binding. Custom thread runtimes need separate evidence.
520
+ settleAbsentWorkflowRuns: isDatabaseBinding(env.DB),
521
+ cursor,
522
+ onPage: (settled, next) => {
523
+ counts.settledBound += settled;
524
+ return advanceCursor(next);
525
+ },
526
+ olderThanMs: Math.max(options.olderThanMs, BOUND_RESERVATION_SETTLEMENT_AGE_MS),
527
+ });
528
+ }
529
+ async function settlementAdminResponse(request, env, tablePrefix, remoteStepExpiryTick, cursors) {
530
+ if (new URL(request.url).pathname !== SETTLE_UNPROGRESSABLE_PATH)
531
+ return null;
532
+ if (request.method !== 'POST')
533
+ return json({ error: 'method not allowed' }, 405);
534
+ const gate = await authorizeAdminCredential(request, env, {
535
+ surface: SETTLE_UNPROGRESSABLE_SURFACE,
536
+ delegateCapability: false,
537
+ });
538
+ if (!gate.authorized)
539
+ return gate.response;
540
+ const raw = await readBoundedBody(request, 4_096);
541
+ if (!raw.ok)
542
+ return json({ error: 'a JSON object body is required' }, raw.reason === 'payload-too-large' ? 413 : 400);
543
+ let parsed;
544
+ try {
545
+ parsed = raw.text === '' ? {} : JSON.parse(raw.text);
546
+ }
547
+ catch {
548
+ return json({ error: 'a JSON object body is required' }, 400);
549
+ }
550
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
551
+ return json({ error: 'a JSON object body is required' }, 400);
552
+ const { olderThanMs = UNBOUND_RESERVATION_EXPIRY_MS, key } = parsed;
553
+ if (typeof olderThanMs !== 'number' ||
554
+ !Number.isSafeInteger(olderThanMs) ||
555
+ olderThanMs < UNBOUND_RESERVATION_EXPIRY_MS)
556
+ return json({
557
+ error: `olderThanMs must be a safe integer of at least ${UNBOUND_RESERVATION_EXPIRY_MS}`,
558
+ }, 400);
559
+ if (key !== undefined && !isPathSafeId(key))
560
+ return json({ error: 'key must be a URL-path-safe identifier' }, 400);
561
+ const counts = { abandoned: 0, settledBound: 0 };
562
+ try {
563
+ const fence = executionFenceForEnv(env);
564
+ const reading = await fence.read();
565
+ if (!admitsDrainableExecution(reading))
566
+ throw new ExecutionFencedError(reading.state);
567
+ await settleStartReservations(env, tablePrefix, { olderThanMs, key, principal: SETTLE_UNPROGRESSABLE_SURFACE }, counts, cursors.get(env.DB), (next) => {
568
+ if (next)
569
+ cursors.set(env.DB, next);
570
+ else
571
+ cursors.delete(env.DB);
572
+ });
573
+ if (!remoteStepExpiryTick)
574
+ return json(counts);
575
+ const after = await fence.read();
576
+ if (!admitsDrainableExecution(after))
577
+ throw new ExecutionFencedError(after.state);
578
+ return json({ ...counts, remoteSteps: await remoteStepExpiryTick(env)() });
579
+ }
580
+ catch (error) {
581
+ if (isExecutionFenceRefusal(error)) {
582
+ const refusal = refusalBody(error.message, error.reason);
583
+ return counts.abandoned > 0 || counts.settledBound > 0
584
+ ? json({ ...counts, ...refusal })
585
+ : json(refusal, error.status);
586
+ }
587
+ if (error instanceof DoStatusError && isRefusalStatus(error.status))
588
+ return json(refusalBody(error.message, error.reason), error.status);
589
+ console.error(JSON.stringify({
590
+ type: 'unprogressable-settlement-admin-error',
591
+ reason: hostErrorText(error, true),
592
+ }));
593
+ return json({ error: 'unprogressable settlement failed' }, 500);
594
+ }
595
+ }
498
596
  export function createFlowsafeWorker(config) {
499
597
  const epochSource = config.mutationEpoch;
500
598
  if (typeof epochSource !== 'function')
501
599
  normalizeMutationEpoch(epochSource);
502
600
  const storageTablePrefix = validateTablePrefix(config.storageTablePrefix, 'storageTablePrefix');
601
+ const adminSettlementCursors = new WeakMap();
503
602
  // Authenticate before constructing request-scoped services.
504
603
  const buildContexts = (env, topology, waitUntil, notify, selfDecision, stream, mutationEpoch) => {
505
604
  const storeFactory = approvalStoreFactoryFor(env.DB, storageTablePrefix);
@@ -567,6 +666,36 @@ export function createFlowsafeWorker(config) {
567
666
  error: failure,
568
667
  }));
569
668
  };
669
+ const settlements = { abandoned: 0, settledBound: 0 };
670
+ try {
671
+ await settleStartReservations(env, storageTablePrefix, {
672
+ olderThanMs: UNBOUND_RESERVATION_EXPIRY_MS,
673
+ }, settlements, context.advanceBoundReservationCursor
674
+ ? context.boundReservationCursor
675
+ : undefined, (next) => context.advanceBoundReservationCursor?.(next));
676
+ }
677
+ catch (error) {
678
+ if (isExecutionFenceRefusal(error)) {
679
+ console.log(JSON.stringify({
680
+ type: 'maintenance-idle',
681
+ surface: 'start-reservation-abandon',
682
+ trigger,
683
+ reason: error.reason,
684
+ }));
685
+ }
686
+ else
687
+ recordFailure('start-reservation-abandon', error);
688
+ }
689
+ const dayMs = 24 * 60 * 60 * 1_000;
690
+ const ttlMs = numberVar(env.RUN_RETENTION_DAYS, 30, 'RUN_RETENTION_DAYS', {
691
+ allowZero: true,
692
+ }) * dayMs;
693
+ const startIdempotencyTtlMs = env.START_IDEMPOTENCY_RETENTION_DAYS === undefined
694
+ ? undefined
695
+ : numberVar(env.START_IDEMPOTENCY_RETENTION_DAYS, 30, 'START_IDEMPOTENCY_RETENTION_DAYS', {
696
+ allowZero: true,
697
+ }) * dayMs;
698
+ const now = Date.now();
570
699
  let purged;
571
700
  try {
572
701
  const advanceCursor = context.advanceRetentionCursor;
@@ -594,32 +723,28 @@ export function createFlowsafeWorker(config) {
594
723
  purged = await purgeExpiredWorkflowRuns(retentionDb, {
595
724
  cursor,
596
725
  advanceCursor,
597
- // allowZero: RUN_RETENTION_DAYS=0 means "purge terminal runs now".
598
- ttlMs: numberVar(env.RUN_RETENTION_DAYS, 30, 'RUN_RETENTION_DAYS', {
599
- allowZero: true,
600
- }) *
601
- 24 *
602
- 60 *
603
- 60 *
604
- 1000,
726
+ ttlMs,
727
+ now: () => now,
605
728
  artifactStore,
606
729
  tablePrefix: storageTablePrefix,
607
730
  resourceOwnerTable: RESOURCE_OWNERSHIP_TABLE,
608
731
  startIdempotencyTable: START_IDEMPOTENCY_TABLE,
609
- ...(env.START_IDEMPOTENCY_RETENTION_DAYS === undefined
610
- ? {}
611
- : {
612
- startIdempotencyTtlMs: numberVar(env.START_IDEMPOTENCY_RETENTION_DAYS, 30, 'START_IDEMPOTENCY_RETENTION_DAYS', { allowZero: true }) *
613
- 24 *
614
- 60 *
615
- 60 *
616
- 1000,
617
- }),
732
+ startIdempotencyTtlMs,
618
733
  });
619
734
  }
620
735
  catch (error) {
621
736
  recordFailure('retention-purge', error);
622
737
  }
738
+ let abandonedStartReservationsPurged;
739
+ try {
740
+ abandonedStartReservationsPurged = await purgeAbandonedStartReservations(env.DB, {
741
+ table: START_IDEMPOTENCY_TABLE,
742
+ keyCutoff: now - Math.max(ttlMs, startIdempotencyTtlMs ?? ttlMs),
743
+ });
744
+ }
745
+ catch (error) {
746
+ recordFailure('start-reservation-abandoned-purge', error);
747
+ }
623
748
  const approvalPurge = await runApprovalRetentionPurge({
624
749
  store: approvalStoreFactoryFor(env.DB, storageTablePrefix).store(),
625
750
  retentionDays: env.APPROVAL_RETENTION_DAYS,
@@ -716,6 +841,9 @@ export function createFlowsafeWorker(config) {
716
841
  trigger,
717
842
  purged,
718
843
  approvalsPurged,
844
+ abandonedStartReservations: settlements.abandoned,
845
+ settledBoundStartReservations: settlements.settledBound,
846
+ abandonedStartReservationsPurged,
719
847
  threadsPurged,
720
848
  threadMessagesPurged,
721
849
  backgroundTasksCompletedPurged: backgroundTasksPurged?.completed,
@@ -734,6 +862,10 @@ export function createFlowsafeWorker(config) {
734
862
  // versa (the same failure-isolation rationale).
735
863
  async function runInjectedTickDuty(duty, env) {
736
864
  const { builder, logType } = INJECTED_TICK_DUTIES[duty];
865
+ if (duty === 'remoteStepExpiry' &&
866
+ config.remoteStepExpiryTick &&
867
+ !admitsDrainableExecution(await executionFenceForEnv(env).read()))
868
+ return { ok: true, value: undefined };
737
869
  const tick = config[builder]?.(env);
738
870
  if (!tick) {
739
871
  // The duty ran but its builder is not wired — a misconfig. Do not fall
@@ -781,6 +913,12 @@ export function createFlowsafeWorker(config) {
781
913
  advanceCursor: context.advanceDeadlineCursor,
782
914
  }
783
915
  : {}),
916
+ ...(context?.advanceUnreadableDeadlineCursor
917
+ ? {
918
+ unreadableCursor: context.unreadableDeadlineCursor,
919
+ advanceUnreadableCursor: context.advanceUnreadableDeadlineCursor,
920
+ }
921
+ : {}),
784
922
  transition: async (candidate) => {
785
923
  await topology.timeOut(candidate.workflowId, candidate.runId, {
786
924
  expectedRevision: candidate.revision,
@@ -827,6 +965,9 @@ export function createFlowsafeWorker(config) {
827
965
  const inventoryAdmin = await inventoryAdminResponse(request, env, storageTablePrefix);
828
966
  if (inventoryAdmin)
829
967
  return inventoryAdmin;
968
+ const settlementAdmin = await settlementAdminResponse(request, env, storageTablePrefix, config.remoteStepExpiryTick, adminSettlementCursors);
969
+ if (settlementAdmin)
970
+ return settlementAdmin;
830
971
  const waitUntil = (promise) => ctx.waitUntil(promise);
831
972
  const topology = createDoRunTopology(env.RUNNER, env.DEPLOYMENT_IDENTITY_SECRET);
832
973
  const notify = config.notify?.(env);
@@ -971,7 +1112,7 @@ export function createFlowsafeWorker(config) {
971
1112
  : undefined,
972
1113
  // Self-healing approval reconciliation is waitUntil-detached; the
973
1114
  // shared wrapper owns the detach + reconcile-error logging.
974
- reconcileApprovals: reconcileApprovalsOnStatusDetached(config.systemPrincipalId, waitUntil),
1115
+ reconcileApprovals: reconcileApprovalsOnStatusDetached(config.systemPrincipalId, waitUntil, { readCurrentSummary: topology.authoritativeStatus }),
975
1116
  })(request);
976
1117
  if (runResponse)
977
1118
  return runResponse;
@@ -1060,7 +1201,10 @@ export function createFlowsafeWorker(config) {
1060
1201
  const MAINTENANCE_HEALTH_KEY = 'flowsafe:maintenance-health:v1';
1061
1202
  const MAINTENANCE_NONCES_KEY = 'flowsafe:maintenance-nonces:v1';
1062
1203
  const MAINTENANCE_DEADLINE_CURSOR_KEY = 'flowsafe:maintenance-deadline-cursor:v1';
1204
+ const MAINTENANCE_DEADLINE_UNREADABLE_CURSOR_KEY = 'flowsafe:maintenance-deadline-unreadable-cursor:v1';
1205
+ const MAINTENANCE_DEADLINE_COUNT_CACHE_MS = 30_000;
1063
1206
  const MAINTENANCE_RUN_RETENTION_CURSOR_KEY = 'flowsafe:maintenance-run-retention-cursor:v1';
1207
+ const MAINTENANCE_BOUND_RESERVATION_CURSOR_KEY = 'flowsafe:maintenance-bound-reservation-cursor:v1';
1064
1208
  const DUTY_ORDER = [
1065
1209
  'deadline',
1066
1210
  'sweep',
@@ -1068,6 +1212,7 @@ const DUTY_ORDER = [
1068
1212
  'tick',
1069
1213
  'notification',
1070
1214
  'remoteStepRecovery',
1215
+ 'remoteStepExpiry',
1071
1216
  ];
1072
1217
  /** Build the fixed-name maintenance Durable Object class for one host. */
1073
1218
  export function createFlowsafeMaintenanceDurableObject(config) {
@@ -1079,6 +1224,7 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1079
1224
  tick: config.maintenance.tickIntervalMs,
1080
1225
  notification: config.maintenance.notificationIntervalMs,
1081
1226
  remoteStepRecovery: config.maintenance.remoteStepRecoveryIntervalMs,
1227
+ remoteStepExpiry: config.maintenance.remoteStepExpiryIntervalMs,
1082
1228
  };
1083
1229
  for (const duty of DUTY_ORDER) {
1084
1230
  const interval = intervals[duty];
@@ -1094,9 +1240,12 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1094
1240
  }
1095
1241
  }
1096
1242
  const worker = createFlowsafeWorker(config);
1243
+ const { storageTablePrefix } = config;
1244
+ const boundReservationCursorKey = `${MAINTENANCE_BOUND_RESERVATION_CURSOR_KEY}:${storageTablePrefix?.toLowerCase() ?? ''}`;
1097
1245
  return class FlowsafeMaintenanceDurableObject {
1098
1246
  #state;
1099
1247
  #env;
1248
+ #unreadableDeadlineCountCache;
1100
1249
  constructor(state, env) {
1101
1250
  this.#state = state;
1102
1251
  this.#env = env;
@@ -1256,6 +1405,21 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1256
1405
  response.headers.set(MAINTENANCE_RECEIPT_HEADER, receipt);
1257
1406
  return response;
1258
1407
  }
1408
+ #readUnreadableDeadlineCount() {
1409
+ const now = Date.now();
1410
+ const cached = this.#unreadableDeadlineCountCache;
1411
+ if (cached && now < cached.expiresAt)
1412
+ return cached.result;
1413
+ const result = countUnreadableExpiredRunDeadlines(this.#env.DB, {
1414
+ tablePrefix: storageTablePrefix,
1415
+ now: () => now,
1416
+ }).catch(() => ({ error: 'deadline-count-unavailable' }));
1417
+ this.#unreadableDeadlineCountCache = {
1418
+ expiresAt: now + MAINTENANCE_DEADLINE_COUNT_CACHE_MS,
1419
+ result,
1420
+ };
1421
+ return result;
1422
+ }
1259
1423
  async fetch(request) {
1260
1424
  try {
1261
1425
  this.#assertInstanceName();
@@ -1277,9 +1441,11 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1277
1441
  return json({ error: 'authentication required' }, 401);
1278
1442
  }
1279
1443
  const health = await this.#state.storage.get(MAINTENANCE_HEALTH_KEY);
1444
+ const unreadableExpiredRunDeadlines = await this.#readUnreadableDeadlineCount();
1280
1445
  return this.#response({
1281
1446
  ...(health ?? {}),
1282
1447
  alarmAt: await this.#state.storage.getAlarm(),
1448
+ unreadableExpiredRunDeadlines,
1283
1449
  }, authorized);
1284
1450
  }
1285
1451
  return json({ error: 'not found' }, 404);
@@ -1318,23 +1484,39 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1318
1484
  setNextAt(health, duty, advancePast(dueAt, interval, now));
1319
1485
  const followUpAt = nextAlarmAt(health, intervals);
1320
1486
  await this.#persistAndArm(health, hasDueDuty(health, intervals, now) ? now : followUpAt);
1321
- // Each duty carries the cursor pair it owns, so the call sits inside the
1487
+ // Each duty carries the cursors it owns, so the call sits inside the
1322
1488
  // branch that builds it: the purge seam is required by its context type,
1323
1489
  // which a single call over the whole duty union cannot satisfy.
1324
1490
  let outcome;
1325
1491
  if (duty === 'deadline') {
1326
- const deadlineCursor = await this.#state.storage.get(MAINTENANCE_DEADLINE_CURSOR_KEY);
1492
+ const [deadlineCursor, storedUnreadableCursor] = await Promise.all([
1493
+ this.#state.storage.get(MAINTENANCE_DEADLINE_CURSOR_KEY),
1494
+ this.#state.storage.get(MAINTENANCE_DEADLINE_UNREADABLE_CURSOR_KEY),
1495
+ ]);
1496
+ let unreadableDeadlineCursor = storedUnreadableCursor ?? undefined;
1327
1497
  outcome = await worker.runMaintenanceDuty(duty, this.#env, {
1328
1498
  ...(deadlineCursor ? { deadlineCursor } : {}),
1329
1499
  advanceDeadlineCursor: (cursor) => this.#state.storage.transaction(async (transaction) => {
1330
1500
  await transaction.put(MAINTENANCE_DEADLINE_CURSOR_KEY, cursor);
1331
1501
  }),
1502
+ unreadableDeadlineCursor,
1503
+ advanceUnreadableDeadlineCursor: async (cursor) => {
1504
+ if (cursor === undefined && unreadableDeadlineCursor === undefined)
1505
+ return;
1506
+ await this.#state.storage.transaction((transaction) => transaction.put(MAINTENANCE_DEADLINE_UNREADABLE_CURSOR_KEY, cursor ?? null));
1507
+ unreadableDeadlineCursor = cursor;
1508
+ },
1332
1509
  });
1333
1510
  }
1334
1511
  else if (duty === 'purge') {
1335
- const retentionCursor = await this.#state.storage.get(MAINTENANCE_RUN_RETENTION_CURSOR_KEY);
1512
+ const [retentionCursor, boundReservationCursor] = await Promise.all([
1513
+ this.#state.storage.get(MAINTENANCE_RUN_RETENTION_CURSOR_KEY),
1514
+ this.#state.storage.get(boundReservationCursorKey),
1515
+ ]);
1336
1516
  outcome = await worker.runMaintenanceDuty(duty, this.#env, {
1337
1517
  ...(retentionCursor === undefined ? {} : { retentionCursor }),
1518
+ boundReservationCursor: boundReservationCursor ?? undefined,
1519
+ advanceBoundReservationCursor: (cursor) => this.#state.storage.transaction((transaction) => transaction.put(boundReservationCursorKey, cursor ?? null)),
1338
1520
  advanceRetentionCursor: (cursor) => this.#state.storage.transaction(async (transaction) => {
1339
1521
  await transaction.put(MAINTENANCE_RUN_RETENTION_CURSOR_KEY, cursor);
1340
1522
  }),
@@ -1390,6 +1572,12 @@ const DUTY_HEALTH_FIELDS = {
1390
1572
  attempt: 'lastRemoteStepRecoveryAttemptAt',
1391
1573
  error: 'lastRemoteStepRecoveryError',
1392
1574
  },
1575
+ remoteStepExpiry: {
1576
+ next: 'nextRemoteStepExpiryAt',
1577
+ last: 'lastRemoteStepExpiryAt',
1578
+ attempt: 'lastRemoteStepExpiryAttemptAt',
1579
+ error: 'lastRemoteStepExpiryError',
1580
+ },
1393
1581
  };
1394
1582
  function nextAt(health, duty) {
1395
1583
  return health?.[DUTY_HEALTH_FIELDS[duty].next];
@@ -1414,7 +1602,8 @@ function setLastAttemptAt(health, duty, value) {
1414
1602
  health[DUTY_HEALTH_FIELDS[duty].attempt] = value;
1415
1603
  }
1416
1604
  function setLastError(health, duty, value) {
1417
- health[DUTY_HEALTH_FIELDS[duty].error] = value.slice(0, 1_024);
1605
+ const text = value.length > 0 ? value : 'unknown error';
1606
+ health[DUTY_HEALTH_FIELDS[duty].error] = text.slice(0, 1_024);
1418
1607
  }
1419
1608
  function clearLastError(health, duty) {
1420
1609
  delete health[DUTY_HEALTH_FIELDS[duty].error];