@proofoftech/flowsafe 0.20.0 → 0.22.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 (238) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +55 -10
  3. package/deployment-identity-protocol.d.mts +28 -3
  4. package/deployment-identity-protocol.mjs +275 -21
  5. package/dist/agent-host/router.d.ts.map +1 -1
  6. package/dist/agent-host/router.js +11 -2
  7. package/dist/agent-host/router.js.map +1 -1
  8. package/dist/agent-host/thread-host.d.ts +3 -1
  9. package/dist/agent-host/thread-host.d.ts.map +1 -1
  10. package/dist/agent-host/thread-host.js +858 -351
  11. package/dist/agent-host/thread-host.js.map +1 -1
  12. package/dist/agent-host/thread-topology.d.ts +8 -0
  13. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  14. package/dist/agent-host/thread-topology.js +243 -64
  15. package/dist/agent-host/thread-topology.js.map +1 -1
  16. package/dist/agent-runner/durable-agent-runner.d.ts +89 -14
  17. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  18. package/dist/agent-runner/durable-agent-runner.js +369 -44
  19. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  20. package/dist/agent-runner/index.d.ts +1 -1
  21. package/dist/agent-runner/index.d.ts.map +1 -1
  22. package/dist/agent-runner/index.js.map +1 -1
  23. package/dist/approval-api/actor-context.d.ts +4 -0
  24. package/dist/approval-api/actor-context.d.ts.map +1 -1
  25. package/dist/approval-api/actor-context.js +53 -5
  26. package/dist/approval-api/actor-context.js.map +1 -1
  27. package/dist/approval-api/principal.d.ts +1 -1
  28. package/dist/approval-api/principal.js +1 -1
  29. package/dist/approval-api/retention.d.ts +1 -2
  30. package/dist/approval-api/retention.d.ts.map +1 -1
  31. package/dist/approval-api/retention.js.map +1 -1
  32. package/dist/approval-api/service.d.ts +13 -20
  33. package/dist/approval-api/service.d.ts.map +1 -1
  34. package/dist/approval-api/service.js +52 -28
  35. package/dist/approval-api/service.js.map +1 -1
  36. package/dist/audit-export/index.d.ts +2 -2
  37. package/dist/audit-export/index.js +2 -2
  38. package/dist/background-tasks/d1-storage.d.ts +4 -3
  39. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  40. package/dist/background-tasks/d1-storage.js +8 -14
  41. package/dist/background-tasks/d1-storage.js.map +1 -1
  42. package/dist/background-tasks/host.d.ts.map +1 -1
  43. package/dist/background-tasks/host.js +3 -2
  44. package/dist/background-tasks/host.js.map +1 -1
  45. package/dist/do-runner/constants.d.ts +3 -0
  46. package/dist/do-runner/constants.d.ts.map +1 -0
  47. package/dist/do-runner/constants.js +3 -0
  48. package/dist/do-runner/constants.js.map +1 -0
  49. package/dist/do-runner/d1-storage.d.ts +34 -158
  50. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  51. package/dist/do-runner/d1-storage.js +935 -402
  52. package/dist/do-runner/d1-storage.js.map +1 -1
  53. package/dist/do-runner/durable-object.d.ts.map +1 -1
  54. package/dist/do-runner/durable-object.js +472 -185
  55. package/dist/do-runner/durable-object.js.map +1 -1
  56. package/dist/do-runner/execution-admission.d.ts +114 -0
  57. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  58. package/dist/do-runner/execution-admission.js +206 -0
  59. package/dist/do-runner/execution-admission.js.map +1 -0
  60. package/dist/do-runner/execution-context.d.ts +5 -1
  61. package/dist/do-runner/execution-context.d.ts.map +1 -1
  62. package/dist/do-runner/execution-context.js +6 -1
  63. package/dist/do-runner/execution-context.js.map +1 -1
  64. package/dist/do-runner/execution-fence.d.ts +74 -30
  65. package/dist/do-runner/execution-fence.d.ts.map +1 -1
  66. package/dist/do-runner/execution-fence.js +684 -120
  67. package/dist/do-runner/execution-fence.js.map +1 -1
  68. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  69. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  70. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  71. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  72. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  73. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  74. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  75. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  76. package/dist/do-runner/index.d.ts +13 -8
  77. package/dist/do-runner/index.d.ts.map +1 -1
  78. package/dist/do-runner/index.js +6 -2
  79. package/dist/do-runner/index.js.map +1 -1
  80. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  81. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  82. package/dist/do-runner/initial-admission-refusal.js +41 -0
  83. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  84. package/dist/do-runner/inventory.d.ts +2 -1
  85. package/dist/do-runner/inventory.d.ts.map +1 -1
  86. package/dist/do-runner/inventory.js +28 -39
  87. package/dist/do-runner/inventory.js.map +1 -1
  88. package/dist/do-runner/notification-predicate.d.ts +7 -7
  89. package/dist/do-runner/notification-predicate.d.ts.map +1 -1
  90. package/dist/do-runner/notification-predicate.js +134 -7
  91. package/dist/do-runner/notification-predicate.js.map +1 -1
  92. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  93. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  94. package/dist/do-runner/run-lifecycle.js +69 -15
  95. package/dist/do-runner/run-lifecycle.js.map +1 -1
  96. package/dist/do-runner/run-provenance.d.ts +38 -0
  97. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  98. package/dist/do-runner/run-provenance.js +152 -0
  99. package/dist/do-runner/run-provenance.js.map +1 -0
  100. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  101. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  102. package/dist/do-runner/run-storage-tables.js +4 -0
  103. package/dist/do-runner/run-storage-tables.js.map +1 -0
  104. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  105. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  106. package/dist/do-runner/run-terminal-state.js +105 -0
  107. package/dist/do-runner/run-terminal-state.js.map +1 -0
  108. package/dist/do-runner/runtime.d.ts +108 -46
  109. package/dist/do-runner/runtime.d.ts.map +1 -1
  110. package/dist/do-runner/runtime.js +927 -438
  111. package/dist/do-runner/runtime.js.map +1 -1
  112. package/dist/do-runner/start-idempotency.d.ts +35 -258
  113. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  114. package/dist/do-runner/start-idempotency.js +606 -498
  115. package/dist/do-runner/start-idempotency.js.map +1 -1
  116. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  117. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  118. package/dist/do-runner/start-reservation-contract.js +338 -0
  119. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  120. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  121. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  122. package/dist/do-runner/suspension-deadline.js +8 -12
  123. package/dist/do-runner/suspension-deadline.js.map +1 -1
  124. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  125. package/dist/do-runner/table-prefix.js +2 -1
  126. package/dist/do-runner/table-prefix.js.map +1 -1
  127. package/dist/do-runner/testing.d.ts +3 -0
  128. package/dist/do-runner/testing.d.ts.map +1 -0
  129. package/dist/do-runner/testing.js +3 -0
  130. package/dist/do-runner/testing.js.map +1 -0
  131. package/dist/do-runner/thread-do.d.ts +2 -1
  132. package/dist/do-runner/thread-do.d.ts.map +1 -1
  133. package/dist/do-runner/thread-do.js +14 -10
  134. package/dist/do-runner/thread-do.js.map +1 -1
  135. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  136. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  137. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  138. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  139. package/dist/goals/objective-routes.d.ts +1 -5
  140. package/dist/goals/objective-routes.d.ts.map +1 -1
  141. package/dist/goals/objective-routes.js +32 -53
  142. package/dist/goals/objective-routes.js.map +1 -1
  143. package/dist/host-kit/approval-bridge.d.ts +8 -8
  144. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  145. package/dist/host-kit/approval-bridge.js +18 -15
  146. package/dist/host-kit/approval-bridge.js.map +1 -1
  147. package/dist/host-kit/do-response.d.ts +16 -0
  148. package/dist/host-kit/do-response.d.ts.map +1 -1
  149. package/dist/host-kit/do-response.js +181 -0
  150. package/dist/host-kit/do-response.js.map +1 -1
  151. package/dist/host-kit/do-run-topology.d.ts +2 -14
  152. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  153. package/dist/host-kit/do-run-topology.js +31 -24
  154. package/dist/host-kit/do-run-topology.js.map +1 -1
  155. package/dist/host-kit/env-vars.d.ts.map +1 -1
  156. package/dist/host-kit/env-vars.js +5 -6
  157. package/dist/host-kit/env-vars.js.map +1 -1
  158. package/dist/host-kit/flowsafe-worker.d.ts +38 -6
  159. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  160. package/dist/host-kit/flowsafe-worker.js +115 -93
  161. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  162. package/dist/host-kit/host-approval-service.d.ts +4 -14
  163. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  164. package/dist/host-kit/host-approval-service.js +23 -40
  165. package/dist/host-kit/host-approval-service.js.map +1 -1
  166. package/dist/host-kit/index.d.ts +7 -1
  167. package/dist/host-kit/index.d.ts.map +1 -1
  168. package/dist/host-kit/index.js +4 -0
  169. package/dist/host-kit/index.js.map +1 -1
  170. package/dist/host-kit/run-route-error.d.ts +3 -17
  171. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  172. package/dist/host-kit/run-route-error.js +4 -24
  173. package/dist/host-kit/run-route-error.js.map +1 -1
  174. package/dist/host-kit/run-router.d.ts +6 -2
  175. package/dist/host-kit/run-router.d.ts.map +1 -1
  176. package/dist/host-kit/run-router.js +93 -80
  177. package/dist/host-kit/run-router.js.map +1 -1
  178. package/dist/host-kit/thread-topology.d.ts +1 -1
  179. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  180. package/dist/host-kit/thread-topology.js +7 -3
  181. package/dist/host-kit/thread-topology.js.map +1 -1
  182. package/dist/internal-error-response.d.ts.map +1 -1
  183. package/dist/internal-error-response.js +16 -6
  184. package/dist/internal-error-response.js.map +1 -1
  185. package/dist/schedules/index.d.ts +1 -0
  186. package/dist/schedules/index.d.ts.map +1 -1
  187. package/dist/schedules/index.js +1 -7
  188. package/dist/schedules/index.js.map +1 -1
  189. package/dist/schedules/mutation-contract.d.ts +38 -0
  190. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  191. package/dist/schedules/mutation-contract.js +21 -0
  192. package/dist/schedules/mutation-contract.js.map +1 -0
  193. package/dist/schedules/router.d.ts +11 -19
  194. package/dist/schedules/router.d.ts.map +1 -1
  195. package/dist/schedules/router.js +130 -49
  196. package/dist/schedules/router.js.map +1 -1
  197. package/dist/schedules/schedules-d1.d.ts +11 -5
  198. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  199. package/dist/schedules/schedules-d1.js +571 -144
  200. package/dist/schedules/schedules-d1.js.map +1 -1
  201. package/dist/schedules/storage.d.ts +0 -7
  202. package/dist/schedules/storage.d.ts.map +1 -1
  203. package/dist/schedules/storage.js +0 -27
  204. package/dist/schedules/storage.js.map +1 -1
  205. package/dist/schedules/tick.d.ts +1 -8
  206. package/dist/schedules/tick.d.ts.map +1 -1
  207. package/dist/schedules/tick.js +15 -20
  208. package/dist/schedules/tick.js.map +1 -1
  209. package/dist/signal-providers/webhook-route.d.ts +1 -1
  210. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  211. package/dist/signal-providers/webhook-route.js +99 -109
  212. package/dist/signal-providers/webhook-route.js.map +1 -1
  213. package/dist/signals/d1-shared.d.ts +11 -8
  214. package/dist/signals/d1-shared.d.ts.map +1 -1
  215. package/dist/signals/d1-shared.js +2 -7
  216. package/dist/signals/d1-shared.js.map +1 -1
  217. package/dist/signals/index.d.ts +1 -1
  218. package/dist/signals/index.d.ts.map +1 -1
  219. package/dist/signals/index.js +1 -1
  220. package/dist/signals/index.js.map +1 -1
  221. package/dist/signals/notification-dispatch.d.ts +84 -4
  222. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  223. package/dist/signals/notification-dispatch.js +365 -53
  224. package/dist/signals/notification-dispatch.js.map +1 -1
  225. package/dist/signals/notifications-d1.d.ts +6 -1
  226. package/dist/signals/notifications-d1.d.ts.map +1 -1
  227. package/dist/signals/notifications-d1.js +215 -10
  228. package/dist/signals/notifications-d1.js.map +1 -1
  229. package/dist/signals/router.d.ts +6 -4
  230. package/dist/signals/router.d.ts.map +1 -1
  231. package/dist/signals/router.js +49 -84
  232. package/dist/signals/router.js.map +1 -1
  233. package/dist/signals/thread-do-routes.d.ts +2 -0
  234. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  235. package/dist/signals/thread-do-routes.js +250 -81
  236. package/dist/signals/thread-do-routes.js.map +1 -1
  237. package/package.json +9 -7
  238. package/scripts/seed-deployment-identity.mjs +27 -6
@@ -6,46 +6,72 @@
6
6
  // to `new Mastra({ storage })` — no migration step needed for the runner.
7
7
  import { D1Store } from '@mastra/cloudflare-d1';
8
8
  import { MastraCompositeStore, } from '@mastra/core/storage';
9
+ import { missingTableReadsEmpty } from './cause-chain.js';
10
+ import { normalizeD1RunExecutionIdentity, normalizeStartExecutionIdentity, } from './execution-admission.js';
11
+ import { FencedWorkflowsStorageD1 } from './fenced-workflows-d1.js';
12
+ import { notificationTimestampMillis, notificationTimestampSql, } from './notification-predicate.js';
9
13
  import { isPathSafeId } from './path-safe-id.js';
14
+ import { decodeRunStartIdentity, runExecutionIdentityFor, } from './run-provenance.js';
15
+ import { RESOURCE_OWNER_TABLE } from './run-storage-tables.js';
10
16
  import { START_IDEMPOTENCY_TABLE } from './start-idempotency.js';
17
+ import { admissionReservationFromRow, reservationFromRow, reservationSchemaStage, START_IDEMPOTENCY_COLUMNS, } from './start-reservation-contract.js';
11
18
  import { validateTablePrefix } from './table-prefix.js';
19
+ import { decodeRawWorkflowSnapshotResult, prepareRawWorkflowSnapshotRead, snapshotResultRows, } from './workflow-snapshot-row.js';
20
+ export { RESOURCE_OWNER_TABLE } from './run-storage-tables.js';
12
21
  export function createD1Storage(options) {
13
- const tablePrefix = validateTablePrefix(options.tablePrefix);
22
+ const { binding, id: suppliedId, tablePrefix: suppliedPrefix, domains: suppliedDomains, } = options;
23
+ const domainSource = suppliedDomains ?? {};
24
+ const capturedDomains = {
25
+ workflows: domainSource.workflows,
26
+ workflowDefinitions: domainSource.workflowDefinitions,
27
+ scores: domainSource.scores,
28
+ memory: domainSource.memory,
29
+ channels: domainSource.channels,
30
+ notifications: domainSource.notifications,
31
+ observability: domainSource.observability,
32
+ agents: domainSource.agents,
33
+ datasets: domainSource.datasets,
34
+ experiments: domainSource.experiments,
35
+ promptBlocks: domainSource.promptBlocks,
36
+ scorerDefinitions: domainSource.scorerDefinitions,
37
+ mcpClients: domainSource.mcpClients,
38
+ mcpServers: domainSource.mcpServers,
39
+ workspaces: domainSource.workspaces,
40
+ skills: domainSource.skills,
41
+ favorites: domainSource.favorites,
42
+ blobs: domainSource.blobs,
43
+ backgroundTasks: domainSource.backgroundTasks,
44
+ schedules: domainSource.schedules,
45
+ harness: domainSource.harness,
46
+ toolProviderConnections: domainSource.toolProviderConnections,
47
+ threadState: domainSource.threadState,
48
+ knowledge: domainSource.knowledge,
49
+ };
50
+ const { workflows: suppliedWorkflows, ...otherDomains } = capturedDomains;
51
+ const id = suppliedId ?? 'flowsafe';
52
+ const tablePrefix = validateTablePrefix(suppliedPrefix);
53
+ const domainConfig = {
54
+ binding: binding,
55
+ ...(tablePrefix === undefined ? {} : { tablePrefix }),
56
+ };
14
57
  const d1 = new D1Store({
15
- id: options.id ?? 'flowsafe',
58
+ id,
16
59
  // @mastra/cloudflare-d1's own D1Store signature wants the real
17
60
  // D1Database; D1DatabaseBinding is the structural subset this package
18
61
  // exposes instead, so consumers of its shipped types don't need
19
62
  // @cloudflare/workers-types installed.
20
- binding: options.binding,
21
- ...(tablePrefix !== undefined ? { tablePrefix } : {}),
63
+ ...domainConfig,
22
64
  });
23
- // No extra domains ⇒ return the D1Store itself (it IS a MastraCompositeStore),
24
- // preserving byte-identical behavior for every host that does not opt into
25
- // signals. With domains, compose them OVER d1 as the default: its own init()
26
- // (all adapter tables, DDL ordering, coalesced callers) runs first via the
27
- // parentDefault path, THEN each override domain's init() — the composite never
28
- // double-inits a parent's domain (validated: chunk #runInit).
29
- if (!options.domains)
30
- return d1;
65
+ const workflows = suppliedWorkflows === undefined
66
+ ? new FencedWorkflowsStorageD1(domainConfig)
67
+ : suppliedWorkflows;
31
68
  return new MastraCompositeStore({
32
- id: options.id ?? 'flowsafe',
69
+ id,
33
70
  default: d1,
34
- domains: options.domains,
71
+ domains: { ...otherDomains, workflows },
35
72
  });
36
73
  }
37
- /**
38
- * Mastra workflow terminals plus FlowSafe's lifecycle-owned terminals.
39
- * Deleting a live run (running/suspended/waiting/pending/paused) would kill a
40
- * pending approval, so only these are ever purged.
41
- *
42
- * Exported because retention and the drain inventory must agree on the word
43
- * "terminal" to the letter. The purge deletes what this set matches; the
44
- * inventory counts what it does NOT, and a run that is terminal to one and live
45
- * to the other is either a row the purge reaps while the inventory still calls
46
- * it work, or — worse — a run the inventory declares finished while it is still
47
- * executing, which is exactly the reading a migration would act on.
48
- */
74
+ /** Shared with the drain inventory so cleanup and liveness use the same vocabulary. */
49
75
  export const RUN_TERMINAL_STATUSES = [
50
76
  'success',
51
77
  'failed',
@@ -56,27 +82,23 @@ export const RUN_TERMINAL_STATUSES = [
56
82
  'cancelled',
57
83
  'timed_out',
58
84
  ];
59
- /**
60
- * The SQL that decides one snapshot row is TERMINAL, with `?` for each entry of
61
- * RUN_TERMINAL_STATUSES in order.
62
- *
63
- * A shared FRAGMENT rather than a shared list because the rule is not "the
64
- * status is in the set": a run that reached 'cancelled' or 'timed_out' is
65
- * terminal only once its lifecycle cleanup stamped `cleanupCompletedAt`, and
66
- * before that it is still executing compensation. Two hand-written copies of
67
- * that carve-out are two chances for one of them to answer "finished" for a run
68
- * that is mid-cleanup — the retention purge would delete a live run's snapshot,
69
- * and the drain inventory would report a deployment empty while it still runs
70
- * work. The caller supplies the `json_valid` guard, because it decides which
71
- * way an unclassifiable row should fail.
72
- */
73
- export const RUN_TERMINAL_SNAPSHOT_SQL = `json_extract(snapshot, '$.status') IN (${RUN_TERMINAL_STATUSES.map(() => '?').join(', ')})
85
+ /** Duplicate keys can disagree between SQLite and JSON.parse on terminal eligibility. */
86
+ export const RUN_TERMINAL_SNAPSHOT_SQL = `json_type(snapshot, '$') = 'object'
87
+ AND (SELECT count(*) FROM json_each(snapshot) WHERE key COLLATE BINARY = 'status') = 1
88
+ AND (SELECT count(*) FROM json_each(snapshot) WHERE key COLLATE BINARY = 'requestContext') <= 1
89
+ AND (SELECT count(*) FROM json_each(snapshot, '$.requestContext') WHERE key COLLATE BINARY = 'flowsafe.runLifecycle') <= 1
90
+ AND (SELECT count(*) FROM json_each(snapshot, '$.requestContext."flowsafe.runLifecycle"') WHERE key COLLATE BINARY = 'terminal') <= 1
91
+ AND (SELECT count(*) FROM json_each(snapshot, '$.requestContext."flowsafe.runLifecycle".terminal') WHERE key COLLATE BINARY = 'cleanupCompletedAt') <= 1
92
+ AND json_extract(snapshot, '$.status') IN (${RUN_TERMINAL_STATUSES.map(() => '?').join(', ')})
74
93
  AND (
75
94
  json_extract(snapshot, '$.status') NOT IN ('cancelled', 'timed_out')
76
- OR json_extract(
77
- snapshot,
78
- '$.requestContext."flowsafe.runLifecycle".terminal.cleanupCompletedAt'
79
- ) IS NOT NULL
95
+ OR (
96
+ json_type(snapshot, '$.requestContext."flowsafe.runLifecycle".terminal.cleanupCompletedAt') IN ('integer', 'real')
97
+ AND json_extract(snapshot, '$.requestContext."flowsafe.runLifecycle".terminal.cleanupCompletedAt') BETWEEN 0 AND 9007199254740991
98
+ AND json_extract(snapshot, '$.requestContext."flowsafe.runLifecycle".terminal.cleanupCompletedAt') = CAST(
99
+ json_extract(snapshot, '$.requestContext."flowsafe.runLifecycle".terminal.cleanupCompletedAt') AS INTEGER
100
+ )
101
+ )
80
102
  )`;
81
103
  const DEADLINE_LIVE_STATUSES = [
82
104
  'running',
@@ -218,394 +240,901 @@ export async function sweepExpiredRunDeadlines(db, options) {
218
240
  }
219
241
  return processed;
220
242
  }
221
- /**
222
- * The MASTRA-OWNED tables `purgeExpiredWorkflowRuns` deletes from under the run
223
- * TTL — the production anchor the schema guard cross-checks every `run-ttl`
224
- * retention declaration against. The guard reads THIS, not a literal copied
225
- * into the test, so a purge that changes what it targets and a guard that still
226
- * blesses the old set cannot drift apart silently.
227
- *
228
- * Mastra-owned specifically: the purge ALSO deletes from flowsafe's own
229
- * registries when a caller wires them, and those live in
230
- * RUN_TTL_FLOWSAFE_PURGE_TABLES below rather than here — see its note for why
231
- * the two sets are not one.
232
- */
233
243
  export const RUN_TTL_PURGE_TABLES = [
234
244
  'mastra_workflow_snapshot',
235
245
  ];
236
- /**
237
- * The resource-ownership registry's table, named here rather than imported from
238
- * the store that creates it (approval-api/resource-ownership.ts).
239
- *
240
- * The layering forbids the import: do-runner may reach approval-api only
241
- * through its declared leaves, and the ownership store is not one — it is built
242
- * ON do-runner. So this file has always carried the name as a literal inside
243
- * RUN_TTL_FLOWSAFE_PURGE_TABLES; giving it a name adds no second home, it names
244
- * the one that was already here, and lets the drain inventory read the registry
245
- * without a third copy. The census test crosses it against
246
- * RESOURCE_OWNERSHIP_TABLE, which is the only place the two can be compared.
247
- */
248
- export const RESOURCE_OWNER_TABLE = 'flowsafe_resource_owners';
249
- /**
250
- * The FLOWSAFE-owned tables this purge also deletes from when the caller wires
251
- * them, and the reason they are not in the list above.
252
- *
253
- * `RUN_TTL_PURGE_TABLES` is cross-checked against the `mastra_%` inventory in
254
- * mastra-schema-guard.test.ts — its job is to catch a @mastra/core bump that
255
- * changes what run retention targets. These two are ours, they are optional
256
- * (a lower-level caller without the registries omits both), and they are
257
- * deleted on a DIFFERENT predicate: `flowsafe_resource_owners` when its run's
258
- * last snapshot is gone, `flowsafe_start_idempotency` when its reservation is
259
- * settled AND past the key-validity horizon. Folding them into the Mastra
260
- * anchor would make that guard assert an equality it cannot mean.
261
- */
262
246
  export const RUN_TTL_FLOWSAFE_PURGE_TABLES = [
263
247
  RESOURCE_OWNER_TABLE,
264
248
  START_IDEMPOTENCY_TABLE,
265
249
  ];
266
- /**
267
- * Data-retention purge: deletes TERMINAL runs (success/failed/tripwire/
268
- * canceled/bailed/skipped and cleanup-complete cancelled/timed_out) whose
269
- * updatedAt is older than the TTL from
270
- * mastra_workflow_snapshot — and, when `artifactStore` is wired, each purged
271
- * run's R2 artifacts with its row, plus (when their tables are wired) the run's
272
- * ownership row and its spent start reservation, each in the SAME transaction
273
- * as the snapshot delete. Live runs (running/suspended/waiting/
274
- * pending/paused) are never touched — expiring a suspended run would kill a
275
- * pending approval. A missing snapshot table reads as zero purgeable runs
276
- * (Mastra creates it lazily with the first persisted run). TTL enforcement
277
- * is a storage-layer property, so it lives here; alarm scheduling stays with
278
- * the caller. Returns the number of deleted rows.
279
- */
280
- export async function purgeExpiredWorkflowRuns(db, options) {
281
- const prefix = validateTablePrefix(options.tablePrefix) ?? '';
282
- const now = options.now ?? Date.now;
283
- // @mastra/cloudflare-d1 stores updatedAt as ISO-8601 TEXT
284
- // (persistWorkflowSnapshot serializes via toISOString), so lexicographic
285
- // < against an ISO cutoff is a correct timestamp comparison.
286
- const cutoff = new Date(now() - options.ttlMs).toISOString();
287
- // json_extract throws on malformed JSON and would abort the WHOLE delete —
288
- // one corrupt row must not stop every valid terminal row from being
289
- // reclaimed. The CASE guard (not `AND json_valid(...)`) is load-bearing:
290
- // SQLite does not guarantee AND short-circuit order in a WHERE, so a bare
291
- // conjunct could still evaluate the extract on the bad row. Unclassifiable
292
- // rows yield NULL and survive (fail safe: never delete what can't be
293
- // proven terminal).
294
- const eligible = `updatedAt < ?
295
- AND CASE WHEN json_valid(snapshot) THEN
296
- (
297
- ${RUN_TERMINAL_SNAPSHOT_SQL}
298
- )
299
- ELSE 0 END`;
300
- const resourceOwnerTable = options.resourceOwnerTable;
301
- if (resourceOwnerTable !== undefined &&
302
- !/^[A-Za-z_][A-Za-z0-9_]*$/.test(resourceOwnerTable)) {
303
- throw new Error('resourceOwnerTable must be a safe SQL identifier');
304
- }
305
- const startIdempotencyTable = options.startIdempotencyTable;
306
- if (startIdempotencyTable !== undefined &&
307
- !/^[A-Za-z_][A-Za-z0-9_]*$/.test(startIdempotencyTable)) {
308
- throw new Error('startIdempotencyTable must be a safe SQL identifier');
309
- }
310
- // Floored at the run TTL, never below it — see startIdempotencyTtlMs. A
311
- // reservation deleted while its run is still readable would let the next
312
- // retry of that key start a SECOND run beside the live one.
313
- const reservationCutoff = now() -
314
- Math.max(options.startIdempotencyTtlMs ?? options.ttlMs, options.ttlMs);
315
- const batch = resourceOwnerTable || startIdempotencyTable
316
- ? db.batch?.bind(db)
317
- : undefined;
318
- if ((resourceOwnerTable || startIdempotencyTable) && !batch) {
319
- throw new Error('purgeExpiredWorkflowRuns requires database.batch() for atomic owner cleanup');
320
- }
321
- /**
322
- * The two reservation statements that ride a snapshot delete, in order.
323
- *
324
- * They run INSIDE the same `batch()` as the snapshot's own DELETE and AFTER
325
- * it, which is what makes the pairing atomic: by the time these execute, the
326
- * runs named here have no snapshot in this transaction, so neither statement
327
- * can act on a reservation whose run is still readable.
328
- *
329
- * 1. DELETE the reservations already past the horizon. This is the pairing
330
- * the design asks for: a spent key and the run it named leave together.
331
- * 2. MARK the rest terminal. A reservation still inside its horizon must
332
- * survive — that is what makes a late retry ALREADY_SETTLED rather than a
333
- * fresh start — but its run is gone, so it is settled by definition. This
334
- * also HEALS the reconcile a crash between a run's terminal persist and
335
- * `settleRun` would have lost, and re-stamps `updated_at` so the horizon
336
- * is measured from a point at which the reservation is definitely spent.
337
- *
338
- * `state <> 'terminal'` also settles `reserved` rows, not just `started`
339
- * ones. The ordinary lifecycle should not produce one here — a run only
340
- * persists a snapshot after its claim, so a row this statement can see is
341
- * normally `started` — and the point is that this statement does not
342
- * depend on that. It is selected by RUN, and every run it names has just
343
- * lost its snapshot in this same transaction, so whatever left the row
344
- * un-claimed (a released claim, a hand-edited row, a caller yet to be
345
- * written), the run it names is gone and the key cannot be worth starting
346
- * again. Settling too eagerly costs a retry a refusal it can resolve with
347
- * a fresh key; leaving a row readable as `reserved` after its run is
348
- * unreadable costs a second run of work that already completed.
349
- */
350
- /**
351
- * Whether the reservation table has been seen to exist this pass.
352
- *
353
- * It is created lazily by the first `reserve()`, so a deployment on which no
354
- * idempotency key has ever been used has none — and a batch naming a missing
355
- * table fails as ONE TRANSACTION, taking the snapshot delete down with it.
356
- * That would turn "this host wired reservations and nobody has used one yet"
357
- * into "run retention is silently unenforced", so the first such failure
358
- * retries the batch WITHOUT the reservation statements and the pass carries
359
- * on with the pairing disabled. Nothing is lost: a table that does not exist
360
- * holds no reservation to reap.
361
- */
362
- let reservationsUnavailable = false;
363
- const reservationStatements = (runIds) => {
364
- if (!startIdempotencyTable ||
365
- reservationsUnavailable ||
366
- runIds.length === 0) {
367
- return [];
250
+ const RETENTION_SQL_BYTES = 90_000;
251
+ const RETENTION_SELECTOR_BYTES = 1_000_000;
252
+ const RETENTION_FRAGMENT_BYTES = 4096;
253
+ const RETENTION_NAMESPACES = 64;
254
+ const RETENTION_PAGE = 90;
255
+ const RETENTION_SUFFIX = 'mastra_workflow_snapshot';
256
+ const RETENTION_PATH = '$.requestContext."flowsafe.runProvenance"';
257
+ const RETENTION_OWNED_KEYS = [
258
+ 'version',
259
+ 'startToken',
260
+ 'startIdentity',
261
+ 'agentStart',
262
+ ];
263
+ const retentionEncoder = new TextEncoder();
264
+ function retentionRegistry(value) {
265
+ if (value === undefined)
266
+ return undefined;
267
+ if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))
268
+ throw new Error('retention registry must be a safe SQL identifier');
269
+ if (value.length >= RETENTION_SQL_BYTES)
270
+ throw new Error('retention registry exceeds SQL byte budget');
271
+ return value.toLowerCase();
272
+ }
273
+ function retentionRecord(value, keys) {
274
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
275
+ throw new Error('run retention cursor is malformed');
276
+ const captured = {};
277
+ for (const key of Reflect.ownKeys(value)) {
278
+ if (typeof key !== 'string' || !keys.includes(key))
279
+ throw new Error('run retention cursor is malformed');
280
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
281
+ if (!descriptor || !('value' in descriptor))
282
+ throw new Error('run retention cursor is malformed');
283
+ captured[key] = descriptor.value;
284
+ }
285
+ return captured;
286
+ }
287
+ /** @internal */
288
+ export function parseRunRetentionCursor(value) {
289
+ if (value === undefined)
290
+ return undefined;
291
+ const { version, tablePrefix, startIdempotencyTable, snapshots, reservations, } = retentionRecord(value, [
292
+ 'version',
293
+ 'tablePrefix',
294
+ 'startIdempotencyTable',
295
+ 'snapshots',
296
+ 'reservations',
297
+ ]);
298
+ if (version !== 1 || typeof tablePrefix !== 'string')
299
+ throw new Error('run retention cursor is malformed');
300
+ const prefix = validateTablePrefix(tablePrefix)?.toLowerCase() ?? '';
301
+ const table = retentionRegistry(startIdempotencyTable);
302
+ const capturePosition = (position) => {
303
+ if (position === undefined)
304
+ return undefined;
305
+ const { afterRowId, highWaterRowId } = retentionRecord(position, [
306
+ 'afterRowId',
307
+ 'highWaterRowId',
308
+ ]);
309
+ if (typeof afterRowId !== 'number' ||
310
+ !Number.isSafeInteger(afterRowId) ||
311
+ typeof highWaterRowId !== 'number' ||
312
+ !Number.isSafeInteger(highWaterRowId) ||
313
+ afterRowId > highWaterRowId)
314
+ throw new Error('run retention position is malformed');
315
+ return Object.freeze({ afterRowId, highWaterRowId });
316
+ };
317
+ const snapshotPosition = capturePosition(snapshots);
318
+ const reservationPosition = capturePosition(reservations);
319
+ if (reservationPosition && table === undefined)
320
+ throw new Error('reservation cursor requires a registry');
321
+ return Object.freeze({
322
+ version: 1,
323
+ tablePrefix: prefix,
324
+ ...(table === undefined ? {} : { startIdempotencyTable: table }),
325
+ ...(snapshotPosition === undefined ? {} : { snapshots: snapshotPosition }),
326
+ ...(reservationPosition === undefined
327
+ ? {}
328
+ : { reservations: reservationPosition }),
329
+ });
330
+ }
331
+ function retentionStatement(sql, values) {
332
+ if (retentionEncoder.encode(sql).length > RETENTION_SQL_BYTES ||
333
+ values.length > 100)
334
+ throw new Error('run retention statement exceeds SQL or binding budget');
335
+ return { sql, values };
336
+ }
337
+ function retentionSelectorJson(values) {
338
+ const json = JSON.stringify(values);
339
+ if (retentionEncoder.encode(json).length > RETENTION_SELECTOR_BYTES)
340
+ throw new Error('run retention selector exceeds byte budget');
341
+ return json;
342
+ }
343
+ function prepareRetentionStatement(db, statement) {
344
+ return db.prepare(statement.sql).bind(...statement.values);
345
+ }
346
+ async function observeRunRetentionSchema(db, table) {
347
+ const names = snapshotResultRows(await db
348
+ .prepare(`SELECT name, type FROM sqlite_schema
349
+ WHERE type IN ('table', 'view') AND lower(name) GLOB '*${RETENTION_SUFFIX}'
350
+ ORDER BY lower(name) LIMIT ${RETENTION_NAMESPACES + 1}`)
351
+ .all());
352
+ if (names.length > RETENTION_NAMESPACES)
353
+ throw new Error('run retention namespace overflow');
354
+ const canonical = [];
355
+ for (const row of names) {
356
+ if (row.type !== 'table' ||
357
+ typeof row.name !== 'string' ||
358
+ !row.name.toLowerCase().endsWith(RETENTION_SUFFIX))
359
+ throw new Error('run retention namespace is not a supported table');
360
+ validateTablePrefix(row.name.slice(0, -RETENTION_SUFFIX.length));
361
+ const name = row.name.toLowerCase();
362
+ if (canonical.includes(name))
363
+ throw new Error('run retention duplicate namespace');
364
+ canonical.push(name);
365
+ }
366
+ let stage;
367
+ let metadata = null;
368
+ if (table !== undefined) {
369
+ const rows = snapshotResultRows(await prepareRetentionStatement(db, retentionStatement(`SELECT s.type AS schema_type,
370
+ p.cid, p.name, p.type, p."notnull", p.dflt_value, p.pk, p.hidden
371
+ FROM sqlite_schema s LEFT JOIN pragma_table_xinfo(?1) p ON 1
372
+ WHERE lower(s.name)=?1 AND s.type IN ('table','view') ORDER BY p.cid LIMIT 14`, [table])).all());
373
+ if (rows.length > 0) {
374
+ if (rows.some((row, index) => row.schema_type !== 'table' || row.cid !== index))
375
+ throw new Error('run retention reservation schema is unsupported');
376
+ stage = reservationSchemaStage({ results: rows });
377
+ if (stage === undefined)
378
+ throw new Error('run retention reservation schema is empty');
379
+ metadata = rows.map((row) => [
380
+ row.cid,
381
+ row.name,
382
+ row.type,
383
+ row.notnull,
384
+ row.dflt_value,
385
+ row.pk,
386
+ row.hidden,
387
+ ]);
388
+ }
389
+ }
390
+ return {
391
+ names: canonical,
392
+ table,
393
+ stage,
394
+ bindings: [
395
+ JSON.stringify(canonical),
396
+ table ?? null,
397
+ metadata === null ? null : JSON.stringify(metadata),
398
+ ],
399
+ };
400
+ }
401
+ const RETENTION_SCHEMA_SQL = `WITH expected_names(name) AS (SELECT value FROM json_each(?1)),
402
+ current_names(name,type) AS (
403
+ SELECT lower(name),type FROM sqlite_schema WHERE type IN ('table','view')
404
+ AND lower(name) GLOB '*${RETENTION_SUFFIX}' LIMIT ${RETENTION_NAMESPACES + 1}
405
+ ), ecols(cid,name,type,nn,dflt,pk,hidden) AS (
406
+ SELECT json_extract(value,'$[0]'),json_extract(value,'$[1]'),json_extract(value,'$[2]'),
407
+ json_extract(value,'$[3]'),json_extract(value,'$[4]'),json_extract(value,'$[5]'),json_extract(value,'$[6]') FROM json_each(?3)
408
+ ), ccols(cid,name,type,nn,dflt,pk,hidden) AS (
409
+ SELECT cid,name,type,"notnull",dflt_value,pk,hidden FROM pragma_table_xinfo(?2) ORDER BY cid LIMIT 14
410
+ ), schema_ok(ok) AS (SELECT
411
+ (SELECT count(*) FROM current_names)=(SELECT count(*) FROM expected_names)
412
+ AND NOT EXISTS (SELECT name FROM current_names EXCEPT SELECT name FROM expected_names)
413
+ AND NOT EXISTS (SELECT 1 FROM current_names WHERE type COLLATE BINARY <> 'table')
414
+ AND CASE WHEN ?2 IS NULL THEN 1 WHEN ?3 IS NULL THEN NOT EXISTS (
415
+ SELECT 1 FROM sqlite_schema WHERE lower(name)=?2 AND type IN ('table','view'))
416
+ ELSE EXISTS (SELECT 1 FROM sqlite_schema WHERE lower(name)=?2 AND type='table')
417
+ AND (SELECT count(*) FROM ccols)=(SELECT count(*) FROM ecols)
418
+ AND NOT EXISTS (SELECT * FROM ccols EXCEPT SELECT * FROM ecols) END)`;
419
+ function retentionPathGuard() {
420
+ return `json_type(s.snapshot,'$')='object'
421
+ AND (SELECT count(*) FROM json_each(s.snapshot) WHERE key COLLATE BINARY='requestContext') <= 1
422
+ AND (json_type(s.snapshot,'$.requestContext') IS NULL OR json_type(s.snapshot,'$.requestContext')='object')
423
+ AND (SELECT count(*) FROM json_each(s.snapshot,'$.requestContext') WHERE key COLLATE BINARY='flowsafe.runProvenance') <= 1
424
+ AND NOT EXISTS (SELECT key FROM json_each(s.snapshot,'${RETENTION_PATH}')
425
+ WHERE key COLLATE BINARY IN ('version','startToken','startIdentity','agentStart') GROUP BY key COLLATE BINARY HAVING count(*) > 1)`;
426
+ }
427
+ function retentionOwnedExpressions() {
428
+ return RETENTION_OWNED_KEYS.map((key) => `s.snapshot -> '${RETENTION_PATH}.${key}'`);
429
+ }
430
+ function retentionOwnedProjection() {
431
+ const expressions = retentionOwnedExpressions();
432
+ const size = expressions
433
+ .map((expression) => `COALESCE(length(CAST((${expression}) AS BLOB)),0)`)
434
+ .join('+');
435
+ const bounded = `CASE WHEN json_valid(s.snapshot) THEN (${size})<=${RETENTION_FRAGMENT_BYTES} ELSE 0 END`;
436
+ return `CASE WHEN json_valid(s.snapshot) THEN ${retentionPathGuard()} ELSE 0 END AS path_ok,
437
+ CASE WHEN json_valid(s.snapshot) THEN json_type(s.snapshot,'${RETENTION_PATH}') END AS provenance_type,
438
+ ${bounded} AS owned_ok,
439
+ ${expressions.map((expression, index) => `CASE WHEN ${bounded} THEN ${expression} END AS owned_${index}`).join(',')}`;
440
+ }
441
+ function retentionOwnedEquality(path) {
442
+ return `CASE WHEN json_valid(s.snapshot) THEN json_type(s.snapshot,'${RETENTION_PATH}')='object'
443
+ AND ${retentionPathGuard()} AND ${retentionOwnedExpressions()
444
+ .map((expression, index) => `(${expression}) COLLATE BINARY IS json_extract(c.value,'${path}[${index}]')`)
445
+ .join(' AND ')} ELSE 0 END`;
446
+ }
447
+ function decodeRunRetentionCandidate(row, prefix) {
448
+ for (const key of [
449
+ 'workflow_name',
450
+ 'run_id',
451
+ 'path_ok',
452
+ 'owned_ok',
453
+ 'provenance_type',
454
+ ...RETENTION_OWNED_KEYS.map((_, index) => `owned_${index}`),
455
+ ]) {
456
+ if (!Object.hasOwn(row, key))
457
+ throw new Error('run retention capsule projection is incomplete');
458
+ }
459
+ if (![0, 1, null].includes(row.path_ok) ||
460
+ ![0, 1].includes(row.owned_ok) ||
461
+ ![
462
+ null,
463
+ 'object',
464
+ 'array',
465
+ 'text',
466
+ 'integer',
467
+ 'real',
468
+ 'true',
469
+ 'false',
470
+ 'null',
471
+ ].includes(row.provenance_type))
472
+ throw new Error('run retention capsule projection is malformed');
473
+ const owned = RETENTION_OWNED_KEYS.map((_, index) => row[`owned_${index}`]);
474
+ if (owned.some((value) => value !== null && typeof value !== 'string'))
475
+ throw new Error('run retention capsule projection is malformed');
476
+ let fragments;
477
+ try {
478
+ fragments = owned.map((value) => typeof value === 'string' ? JSON.parse(value) : undefined);
479
+ }
480
+ catch {
481
+ throw new Error('run retention capsule projection is malformed');
482
+ }
483
+ if (!isPathSafeId(row.workflow_name) ||
484
+ !isPathSafeId(row.run_id) ||
485
+ row.path_ok !== 1 ||
486
+ row.owned_ok !== 1)
487
+ return undefined;
488
+ try {
489
+ let value;
490
+ if (row.provenance_type !== null) {
491
+ if (row.provenance_type !== 'object')
492
+ return undefined;
493
+ const object = {};
494
+ RETENTION_OWNED_KEYS.forEach((key, index) => {
495
+ if (typeof owned[index] === 'string')
496
+ object[key] = fragments[index];
497
+ });
498
+ value = object;
368
499
  }
369
- const placeholders = runIds.map(() => '?').join(', ');
500
+ const decoded = decodeRunStartIdentity(value);
501
+ if (decoded === undefined)
502
+ return 'legacy';
503
+ const execution = normalizeD1RunExecutionIdentity(runExecutionIdentityFor({
504
+ tablePrefix: prefix,
505
+ workflowId: row.workflow_name,
506
+ runId: row.run_id,
507
+ }, decoded));
508
+ const start = decoded.startIdentity === undefined
509
+ ? undefined
510
+ : normalizeStartExecutionIdentity({
511
+ ...execution,
512
+ ...decoded.startIdentity,
513
+ });
370
514
  return [
371
- db
372
- .prepare(`DELETE FROM ${startIdempotencyTable}
373
- WHERE run_id IN (${placeholders})
374
- AND state = 'terminal' AND updated_at < ?`)
375
- .bind(...runIds, reservationCutoff),
376
- db
377
- .prepare(`UPDATE ${startIdempotencyTable}
378
- SET state = 'terminal', updated_at = ?
379
- WHERE run_id IN (${placeholders}) AND state <> 'terminal'`)
380
- .bind(now(), ...runIds),
515
+ execution.workflowId,
516
+ execution.runId,
517
+ owned,
518
+ start === undefined
519
+ ? null
520
+ : [
521
+ prefix,
522
+ start.startToken,
523
+ start.owner.kind,
524
+ start.owner.id,
525
+ start.target.kind,
526
+ start.target.id,
527
+ start.target.kind === 'agent' ? start.target.threadId : null,
528
+ ],
381
529
  ];
530
+ }
531
+ catch {
532
+ return undefined;
533
+ }
534
+ }
535
+ function retentionTerminalSql(first) {
536
+ let binding = first;
537
+ return RUN_TERMINAL_SNAPSHOT_SQL.replace(/\bsnapshot\b/g, 's.snapshot')
538
+ .replace(/\?/g, () => `?${binding++}`)
539
+ .replace(/json_extract\(s.snapshot, '\$\.status'\)/g, "json_extract(s.snapshot, '$.status') COLLATE BINARY");
540
+ }
541
+ function retentionPageStatement(table, position, limit, projection, extra = []) {
542
+ return retentionStatement(`WITH bounds(h) AS MATERIALIZED (SELECT COALESCE(?1,(SELECT MAX(rowid) FROM "${table}"))),
543
+ page AS (SELECT rowid AS rid FROM "${table}",bounds WHERE rowid <= h ${position ? 'AND rowid > ?2' : ''} ORDER BY rowid LIMIT ?3)
544
+ SELECT b.h,p.rid,${projection} FROM bounds b LEFT JOIN page p ON 1
545
+ LEFT JOIN "${table}" s ON s.rowid=p.rid ORDER BY p.rid`, [
546
+ position?.highWaterRowId ?? null,
547
+ position?.afterRowId ?? null,
548
+ limit,
549
+ ...extra,
550
+ ]);
551
+ }
552
+ function decodeRetentionPage(result, position, limit) {
553
+ const rows = snapshotResultRows(result);
554
+ if (rows.length === 0 || rows.length > limit)
555
+ throw new Error('run retention page is malformed');
556
+ const highWater = rows[0]?.h;
557
+ if (highWater !== null &&
558
+ (typeof highWater !== 'number' || !Number.isSafeInteger(highWater)))
559
+ throw new Error('run retention high water is malformed');
560
+ if (position && highWater !== position.highWaterRowId)
561
+ throw new Error('run retention high water changed');
562
+ let previous = position?.afterRowId;
563
+ for (const row of rows) {
564
+ if (row.h !== highWater)
565
+ throw new Error('run retention high water disagrees');
566
+ if (row.rid === null && rows.length === 1)
567
+ return { rows: [] };
568
+ if (typeof row.rid !== 'number' ||
569
+ !Number.isSafeInteger(row.rid) ||
570
+ typeof highWater !== 'number' ||
571
+ row.rid > highWater ||
572
+ (previous !== undefined && row.rid <= previous))
573
+ throw new Error('run retention row position is malformed');
574
+ previous = row.rid;
575
+ }
576
+ if (previous === undefined || typeof highWater !== 'number')
577
+ throw new Error('run retention page is malformed');
578
+ return {
579
+ rows,
580
+ ...(rows.length < limit || previous === highWater
581
+ ? {}
582
+ : {
583
+ position: Object.freeze({
584
+ afterRowId: previous,
585
+ highWaterRowId: highWater,
586
+ }),
587
+ }),
382
588
  };
383
- /**
384
- * Reap the reservations that OUTLIVED their snapshot.
385
- *
386
- * The paired statements above only ever see runs whose snapshot is expiring
387
- * in THIS pass, and a reservation is meant to survive that moment — the whole
388
- * point of a horizon longer than run retention is that a late retry still
389
- * finds ALREADY_SETTLED after the summary is gone. Which means the pairing
390
- * alone can never delete those rows: by the time they are old enough, their
391
- * snapshot has been gone for passes and nothing re-visits them. This sweep is
392
- * what keeps the table finite, and without it the reservation table would be
393
- * the one piece of this deployment's state that only ever grows.
394
- *
395
- * `NOT EXISTS (snapshot)` is not an optimization — it is the safety predicate
396
- * that makes this sweep structurally unable to delete a reservation whose run
397
- * is still readable, whatever a caller configured the horizon to be. The
398
- * LIMIT rides a rowid subselect for the same reason every other purge here
399
- * does: plain `DELETE ... LIMIT` needs a SQLite compile-time option D1 does
400
- * not guarantee.
401
- */
402
- /**
403
- * Run a snapshot-delete batch, retrying once without the reservation
404
- * statements if the reservation table turns out not to exist yet.
405
- *
406
- * `build(withReservations)` rather than a prepared array, because D1
407
- * statements are single-use once run: a retry has to re-prepare.
408
- */
409
- const runPurgeBatch = async (build) => {
410
- if (!batch)
411
- throw new Error('purgeExpiredWorkflowRuns: batch unavailable');
412
- try {
413
- return await batch(build(true));
589
+ }
590
+ function retentionMembership(names, selector) {
591
+ if (names.length === 0)
592
+ return 'SELECT NULL AS run_id WHERE 0';
593
+ const compoundLimit = 5;
594
+ const grouped = names.length > compoundLimit;
595
+ const definitions = grouped
596
+ ? [`retention_ids(run_id) AS MATERIALIZED (${selector})`]
597
+ : [];
598
+ let selects = names.map((name) => `SELECT DISTINCT run_id COLLATE BINARY AS run_id FROM "${name}" WHERE run_id COLLATE BINARY IN (${grouped ? 'SELECT run_id FROM retention_ids' : selector})`);
599
+ // Materialized groups prevent flattening beyond workerd's compound limit.
600
+ while (selects.length > compoundLimit) {
601
+ const next = [];
602
+ for (let index = 0; index < selects.length; index += compoundLimit) {
603
+ const name = `retention_members_${definitions.length}`;
604
+ definitions.push(`${name}(run_id) AS MATERIALIZED (${selects.slice(index, index + compoundLimit).join(' UNION ALL ')})`);
605
+ next.push(`SELECT run_id FROM ${name}`);
414
606
  }
415
- catch (error) {
416
- if (startIdempotencyTable === undefined ||
417
- reservationsUnavailable ||
418
- !isMissingTable(error, startIdempotencyTable)) {
419
- throw error;
607
+ selects = next;
608
+ }
609
+ return `${definitions.length > 0 ? `WITH ${definitions.join(', ')} ` : ''}${selects.join(' UNION ALL ')}`;
610
+ }
611
+ function retentionSnapshotGroup(schema, table, owner, selectors, raw, cutoff, keyCutoff, now) {
612
+ const result = [
613
+ retentionStatement(`${RETENTION_SCHEMA_SQL} SELECT ok AS schema_ok FROM schema_ok`, [...schema.bindings]),
614
+ ];
615
+ const json = retentionSelectorJson(selectors);
616
+ if (schema.names.includes(table)) {
617
+ result.push(raw
618
+ ? retentionStatement(`${RETENTION_SCHEMA_SQL} DELETE FROM "${table}" AS s WHERE (SELECT ok FROM schema_ok)=1
619
+ AND s.workflow_name COLLATE BINARY=?4 AND s.run_id COLLATE BINARY=?5 AND s.snapshot COLLATE BINARY=?6
620
+ AND s.createdAt COLLATE BINARY IS ?7 AND s.updatedAt COLLATE BINARY IS ?8 AND s.resourceId COLLATE BINARY IS ?9
621
+ AND s.updatedAt COLLATE BINARY < ?10 AND CASE WHEN json_valid(s.snapshot) THEN (${retentionTerminalSql(11)}) AND ${retentionPathGuard()} ELSE 0 END`, [
622
+ ...schema.bindings,
623
+ raw.workflowId,
624
+ raw.runId,
625
+ raw.snapshot,
626
+ raw.createdAt,
627
+ raw.updatedAt,
628
+ raw.resourceId,
629
+ cutoff,
630
+ ...RUN_TERMINAL_STATUSES,
631
+ ])
632
+ : retentionStatement(`${RETENTION_SCHEMA_SQL} DELETE FROM "${table}" AS s WHERE (SELECT ok FROM schema_ok)=1
633
+ AND s.updatedAt COLLATE BINARY < ?5 AND CASE WHEN json_valid(s.snapshot) THEN (${retentionTerminalSql(6)}) ELSE 0 END
634
+ AND EXISTS (SELECT 1 FROM json_each(?4) c WHERE s.workflow_name COLLATE BINARY=json_extract(c.value,'$[0]')
635
+ AND s.run_id COLLATE BINARY=json_extract(c.value,'$[1]') AND ${retentionOwnedEquality('$[2]')})`, [...schema.bindings, json, cutoff, ...RUN_TERMINAL_STATUSES]));
636
+ }
637
+ if (owner !== undefined) {
638
+ const candidates = "SELECT json_extract(value,'$[1]') FROM json_each(?4)";
639
+ result.push(retentionStatement(`${RETENTION_SCHEMA_SQL}, present(run_id) AS (${retentionMembership(schema.names, candidates)})
640
+ DELETE FROM "${owner}" WHERE (SELECT ok FROM schema_ok)=1 AND resource_kind COLLATE BINARY='run' AND reservation_token IS NULL
641
+ AND resource_id COLLATE BINARY IN (${candidates}) AND NOT EXISTS (SELECT 1 FROM present WHERE present.run_id COLLATE BINARY=resource_id COLLATE BINARY)`, [...schema.bindings, json]));
642
+ }
643
+ if (!raw && schema.stage === 3 && schema.table !== undefined) {
644
+ const absence = schema.names.includes(table)
645
+ ? `NOT EXISTS (SELECT 1 FROM "${table}" s WHERE s.workflow_name COLLATE BINARY=json_extract(c.value,'$[0]') AND s.run_id COLLATE BINARY=json_extract(c.value,'$[1]'))`
646
+ : '1';
647
+ const fields = [
648
+ 'start_table_prefix',
649
+ 'start_token',
650
+ 'owner_kind',
651
+ 'owner_id',
652
+ 'target_kind',
653
+ 'target_id',
654
+ 'thread_id',
655
+ ];
656
+ const pair = `EXISTS (SELECT 1 FROM json_each(?4) c WHERE json_type(c.value,'$[3]')='array' AND
657
+ ${fields.map((field, index) => `r.${field} COLLATE BINARY IS json_extract(c.value,'$[3][${index}]')`).join(' AND ')}
658
+ AND r.start_workflow_id COLLATE BINARY=json_extract(c.value,'$[0]') AND r.run_id COLLATE BINARY=json_extract(c.value,'$[1]') AND ${absence})`;
659
+ result.push(retentionStatement(`${RETENTION_SCHEMA_SQL} DELETE FROM "${schema.table}" AS r WHERE (SELECT ok FROM schema_ok)=1
660
+ AND r.state COLLATE BINARY='terminal' AND ${retentionFiniteExpiry('r.updated_at', '?5')} AND ${pair}`, [...schema.bindings, json, keyCutoff]));
661
+ result.push(retentionStatement(`${RETENTION_SCHEMA_SQL} UPDATE "${schema.table}" AS r SET state='terminal', updated_at=?5
662
+ WHERE (SELECT ok FROM schema_ok)=1 AND r.state COLLATE BINARY IN ('reserved','started') AND ${pair}`, [...schema.bindings, json, now]));
663
+ }
664
+ return result;
665
+ }
666
+ function retentionFiniteExpiry(column, cutoff) {
667
+ return `typeof(${column}) IN ('integer','real') AND ${column} BETWEEN -1.7976931348623157e308 AND 1.7976931348623157e308 AND ${column} < ${cutoff}`;
668
+ }
669
+ function retentionBatchResult(value, count) {
670
+ if (!Array.isArray(value) || value.length !== count)
671
+ throw new Error('run retention batch result is malformed');
672
+ let deleted = 0;
673
+ let schemaOk = false;
674
+ for (let index = 0; index < count; index += 1) {
675
+ if (!Object.hasOwn(value, index))
676
+ throw new Error('run retention batch result is sparse');
677
+ const result = value[index];
678
+ if (result === null ||
679
+ typeof result !== 'object' ||
680
+ Array.isArray(result) ||
681
+ ('success' in result && result.success !== true))
682
+ throw new Error('run retention batch result failed');
683
+ if (index === 0) {
684
+ const rows = snapshotResultRows(result);
685
+ if (rows.length !== 1 ||
686
+ (rows[0]?.schema_ok !== 0 && rows[0]?.schema_ok !== 1))
687
+ throw new Error('run retention schema result is malformed');
688
+ schemaOk = rows[0]?.schema_ok === 1;
689
+ }
690
+ else {
691
+ const changes = result.meta?.changes;
692
+ if (typeof changes !== 'number' ||
693
+ !Number.isSafeInteger(changes) ||
694
+ changes < 0 ||
695
+ (!schemaOk && changes !== 0))
696
+ throw new Error('run retention mutation result is uncertain');
697
+ if (index === 1)
698
+ deleted = changes;
699
+ }
700
+ }
701
+ return { schemaOk, deleted };
702
+ }
703
+ function retentionReservationProjection(stage) {
704
+ const columns = START_IDEMPOTENCY_COLUMNS.slice(0, 10 + stage).map(([name]) => name);
705
+ const scalars = columns
706
+ .map((name) => `typeof(s."${name}") IN ('null','text','integer','real')`)
707
+ .join(' AND ');
708
+ const size = columns
709
+ .map((name) => `COALESCE(length(CAST(s."${name}" AS BLOB)),0)`)
710
+ .join('+');
711
+ const json = `json_object(${columns.map((name) => `'${name}',s."${name}"`).join(',')})`;
712
+ return `CASE WHEN ${scalars} AND (${size}) <= ${RETENTION_FRAGMENT_BYTES} THEN CASE WHEN length(CAST(${json} AS BLOB)) <= ${RETENTION_FRAGMENT_BYTES} THEN ${json} END END AS raw`;
713
+ }
714
+ function decodeRetentionReservationProjection(row, stage) {
715
+ if (row.raw === null)
716
+ return undefined;
717
+ if (typeof row.raw !== 'string')
718
+ throw new Error('run retention reservation projection is malformed');
719
+ let raw;
720
+ try {
721
+ raw = JSON.parse(row.raw);
722
+ }
723
+ catch {
724
+ throw new Error('run retention reservation projection is malformed');
725
+ }
726
+ const columns = START_IDEMPOTENCY_COLUMNS.slice(0, 10 + stage).map(([name]) => name);
727
+ if (raw === null ||
728
+ typeof raw !== 'object' ||
729
+ Array.isArray(raw) ||
730
+ Object.keys(raw).length !== columns.length ||
731
+ columns.some((name) => !Object.hasOwn(raw, name)) ||
732
+ Object.values(raw).some((value) => value !== null &&
733
+ typeof value !== 'string' &&
734
+ typeof value !== 'number'))
735
+ throw new Error('run retention reservation projection is malformed');
736
+ return raw;
737
+ }
738
+ function retentionOrphanGroup(schema, orphans, keyCutoff) {
739
+ const first = orphans[0];
740
+ if (!first || schema.stage === undefined)
741
+ throw new Error('run retention orphan group is empty');
742
+ const json = retentionSelectorJson(orphans.map((orphan) => [
743
+ orphan.raw,
744
+ Array.isArray(orphan.observation) ? orphan.observation : null,
745
+ ]));
746
+ const columns = START_IDEMPOTENCY_COLUMNS.slice(0, 10 + schema.stage).map(([name]) => name);
747
+ const exact = columns
748
+ .map((name) => `r."${name}" COLLATE BINARY IS json_extract(c.value,'$[0].${name}')`)
749
+ .join(' AND ');
750
+ let guard;
751
+ let membership = '';
752
+ if (first.observation === 'legacy') {
753
+ membership = `, present(run_id) AS (${retentionMembership(schema.names, "SELECT json_extract(value,'$[0].run_id') FROM json_each(?4)")})`;
754
+ guard =
755
+ 'NOT EXISTS (SELECT 1 FROM present WHERE run_id COLLATE BINARY=r.run_id COLLATE BINARY)';
756
+ }
757
+ else if (first.observation === 'missing')
758
+ guard = '1';
759
+ else {
760
+ const address = `s.workflow_name COLLATE BINARY=json_extract(c.value,'$[0].start_workflow_id') AND s.run_id COLLATE BINARY=json_extract(c.value,'$[0].run_id')`;
761
+ guard =
762
+ first.observation === 'absent'
763
+ ? `NOT EXISTS (SELECT 1 FROM "${first.namespace}" s WHERE ${address})`
764
+ : `EXISTS (SELECT 1 FROM "${first.namespace}" s WHERE ${address} AND ${retentionOwnedEquality('$[1]')})`;
765
+ }
766
+ return [
767
+ retentionStatement(`${RETENTION_SCHEMA_SQL} SELECT ok AS schema_ok FROM schema_ok`, [...schema.bindings]),
768
+ retentionStatement(`${RETENTION_SCHEMA_SQL}${membership} DELETE FROM "${schema.table}" AS r WHERE (SELECT ok FROM schema_ok)=1
769
+ AND r.state COLLATE BINARY='terminal' AND ${retentionFiniteExpiry('r.updated_at', '?5')}
770
+ AND EXISTS (SELECT 1 FROM json_each(?4) c WHERE ${exact} AND ${guard})`, [...schema.bindings, json, keyCutoff]),
771
+ ];
772
+ }
773
+ function retentionOrphanPackets(candidates) {
774
+ const groups = new Map();
775
+ for (const candidate of candidates) {
776
+ const key = `${candidate.namespace ?? ''}/${typeof candidate.observation === 'string' ? candidate.observation : 'different'}`;
777
+ const group = groups.get(key) ?? [];
778
+ group.push(candidate);
779
+ groups.set(key, group);
780
+ }
781
+ const packets = [];
782
+ for (const group of groups.values()) {
783
+ let packet = [];
784
+ let bytes = 2;
785
+ for (const candidate of group) {
786
+ const rowBytes = retentionEncoder.encode(JSON.stringify([
787
+ candidate.raw,
788
+ Array.isArray(candidate.observation) ? candidate.observation : null,
789
+ ])).length;
790
+ if (rowBytes + 2 > RETENTION_SELECTOR_BYTES)
791
+ throw new Error('run retention orphan selector exceeds byte budget');
792
+ if (bytes + rowBytes + (packet.length ? 1 : 0) >
793
+ RETENTION_SELECTOR_BYTES) {
794
+ packets.push(packet);
795
+ packet = [];
796
+ bytes = 2;
420
797
  }
421
- reservationsUnavailable = true;
422
- return batch(build(false));
798
+ bytes += rowBytes + (packet.length ? 1 : 0);
799
+ packet.push(candidate);
423
800
  }
801
+ if (packet.length)
802
+ packets.push(packet);
803
+ }
804
+ return packets;
805
+ }
806
+ /** Delete expired snapshots with durable, independent physical scan positions. */
807
+ export async function purgeExpiredWorkflowRuns(db, options) {
808
+ const { ttlMs, tablePrefix, artifactStore, resourceOwnerTable, startIdempotencyTable, startIdempotencyTtlMs, limit: suppliedLimit, now: suppliedNow, cursor: suppliedCursor, advanceCursor, } = options;
809
+ const prepare = db.prepare;
810
+ const batch = db.batch;
811
+ const deleteRun = artifactStore?.deleteRun;
812
+ if (typeof prepare !== 'function' ||
813
+ typeof batch !== 'function' ||
814
+ typeof advanceCursor !== 'function' ||
815
+ (artifactStore !== undefined && typeof deleteRun !== 'function'))
816
+ throw new Error('purgeExpiredWorkflowRuns requires database.batch(), advanceCursor and a valid artifact callback');
817
+ const captured = {
818
+ prepare: prepare.bind(db),
819
+ batch: batch.bind(db),
424
820
  };
425
- const sweepOrphanedStartReservations = async () => {
426
- if (!startIdempotencyTable || reservationsUnavailable)
821
+ const deleteArtifacts = deleteRun?.bind(artifactStore);
822
+ const prefix = validateTablePrefix(tablePrefix)?.toLowerCase() ?? '';
823
+ const owner = retentionRegistry(resourceOwnerTable);
824
+ const registry = retentionRegistry(startIdempotencyTable);
825
+ let cursor = parseRunRetentionCursor(suppliedCursor);
826
+ if (cursor &&
827
+ (cursor.tablePrefix !== prefix || cursor.startIdempotencyTable !== registry))
828
+ throw new Error('run retention cursor scope mismatch');
829
+ if (!Number.isFinite(ttlMs) ||
830
+ ttlMs < 0 ||
831
+ (startIdempotencyTtlMs !== undefined &&
832
+ (!Number.isFinite(startIdempotencyTtlMs) || startIdempotencyTtlMs < 0)))
833
+ throw new Error('run retention TTL must be finite and nonnegative');
834
+ if (suppliedLimit !== undefined &&
835
+ (!Number.isSafeInteger(suppliedLimit) || suppliedLimit <= 0))
836
+ throw new Error('run retention limit must be a positive safe integer');
837
+ const limit = Math.min(suppliedLimit ?? RETENTION_PAGE, RETENTION_PAGE);
838
+ const nowFunction = suppliedNow === undefined ? Date.now : suppliedNow;
839
+ if (typeof nowFunction !== 'function')
840
+ throw new Error('run retention clock is invalid');
841
+ const now = nowFunction();
842
+ const keyCutoff = now - Math.max(ttlMs, startIdempotencyTtlMs ?? ttlMs);
843
+ const snapshotCutoff = now - ttlMs;
844
+ if (!Number.isFinite(now) ||
845
+ !Number.isFinite(keyCutoff) ||
846
+ !Number.isFinite(snapshotCutoff))
847
+ throw new Error('run retention cutoff is invalid');
848
+ const cutoff = new Date(snapshotCutoff).toISOString();
849
+ if (!/^\d{4}-/.test(cutoff))
850
+ throw new Error('run retention cutoff must have a four-digit ISO year');
851
+ const table = `${prefix}${RETENTION_SUFFIX}`;
852
+ let schema = await observeRunRetentionSchema(captured, registry);
853
+ let schemaRetryUsed = false;
854
+ let deleted = 0;
855
+ const failures = [];
856
+ const reportedSkips = new Set();
857
+ const reportUnsupported = (kind) => {
858
+ if (reportedSkips.has(kind))
427
859
  return;
860
+ reportedSkips.add(kind);
861
+ console.warn(JSON.stringify({ type: 'run-retention-skip', kind, tablePrefix: prefix }));
862
+ };
863
+ const knownSkip = (error) => {
864
+ if (failures.length >= 8)
865
+ return;
866
+ let message = 'unreadable error';
428
867
  try {
429
- await db
430
- .prepare(`DELETE FROM ${startIdempotencyTable}
431
- WHERE rowid IN (
432
- SELECT r.rowid FROM ${startIdempotencyTable} AS r
433
- WHERE r.state = 'terminal' AND r.updated_at < ?
434
- AND NOT EXISTS (
435
- SELECT 1 FROM ${prefix}mastra_workflow_snapshot AS s
436
- WHERE s.run_id = r.run_id
437
- )
438
- LIMIT ?
439
- )`)
440
- .bind(reservationCutoff, options.limit ?? 1000)
441
- .run();
868
+ message = errorMessageOf(error).slice(0, 256);
442
869
  }
443
- catch (error) {
444
- // Either table may legitimately not exist yet: the reservation table is
445
- // created by the first reserve() and the snapshot table by the first run.
446
- // Neither absence is a fault, and neither leaves anything to reap.
447
- if (isMissingTable(error, startIdempotencyTable) ||
448
- isMissingTable(error, `${prefix}mastra_workflow_snapshot`)) {
449
- return;
870
+ catch { }
871
+ failures.push(message);
872
+ };
873
+ const refresh = async () => {
874
+ if (schemaRetryUsed)
875
+ throw new Error('run retention schema changed repeatedly');
876
+ schemaRetryUsed = true;
877
+ schema = await observeRunRetentionSchema(captured, registry);
878
+ };
879
+ const execute = async (build, onRetry) => {
880
+ for (;;) {
881
+ const statements = build();
882
+ let result;
883
+ try {
884
+ const prepared = statements.map((statement) => prepareRetentionStatement(captured, statement));
885
+ result = await captured.batch(prepared);
450
886
  }
451
- throw error;
887
+ catch (error) {
888
+ let missing = false;
889
+ try {
890
+ missing = [...schema.names, ...(registry ? [registry] : [])].some((name) => missingTableReadsEmpty(error, name));
891
+ }
892
+ catch { }
893
+ if (!missing)
894
+ throw error;
895
+ const previous = JSON.stringify(schema.bindings);
896
+ await refresh();
897
+ if (JSON.stringify(schema.bindings) === previous)
898
+ throw error;
899
+ if (onRetry)
900
+ await onRetry();
901
+ continue;
902
+ }
903
+ const outcome = retentionBatchResult(result, statements.length);
904
+ if (outcome.schemaOk)
905
+ return outcome.deleted;
906
+ await refresh();
907
+ if (onRetry)
908
+ await onRetry();
452
909
  }
453
910
  };
454
- if (options.artifactStore) {
455
- // Artifact-paired path, run by run: artifacts BEFORE the row, because
456
- // the row is the only record of the run's artifact keys — dying between
457
- // the two leaves the row for the next sweep (deleteRun is idempotent),
458
- // while row-first would strand the artifacts forever. Each deleted row
459
- // is durable progress: a mid-pass crash or the LIMIT batch cap resumes
460
- // at the survivors on the next firing, and per-run failures are
461
- // isolated below so one wedged run cannot stall the rows behind it.
462
- let rows;
911
+ const advance = async (component, position) => {
912
+ const next = {
913
+ version: 1,
914
+ tablePrefix: prefix,
915
+ ...(registry === undefined ? {} : { startIdempotencyTable: registry }),
916
+ ...cursor,
917
+ };
918
+ delete next[component];
919
+ if (position)
920
+ next[component] = position;
921
+ cursor = Object.freeze(next);
922
+ await advanceCursor(cursor);
923
+ };
924
+ const snapshotGroup = (selectors, raw) => retentionSnapshotGroup(schema, table, owner, selectors, raw, cutoff, keyCutoff, now);
925
+ const artifacts = async (workflowId, runId) => {
463
926
  try {
464
- ({ results: rows } = await db
465
- .prepare(`SELECT workflow_name, run_id
466
- FROM ${prefix}mastra_workflow_snapshot
467
- WHERE ${eligible}
468
- LIMIT ?`)
469
- .bind(cutoff, ...RUN_TERMINAL_STATUSES, options.limit ?? 100)
470
- .all());
927
+ await deleteArtifacts?.(workflowId, runId);
928
+ return true;
471
929
  }
472
930
  catch (error) {
473
- if (!isMissingTable(error, `${prefix}mastra_workflow_snapshot`))
474
- throw error;
475
- return 0;
931
+ knownSkip(error);
932
+ return false;
476
933
  }
477
- let deleted = 0;
478
- const failures = [];
479
- for (const row of rows) {
934
+ };
935
+ if (schema.names.includes(table)) {
936
+ const page = decodeRetentionPage(await prepareRetentionStatement(captured, retentionPageStatement(table, cursor?.snapshots, limit, `CASE WHEN length(s.workflow_name)<=200 THEN s.workflow_name END AS workflow_name,
937
+ CASE WHEN length(s.run_id)<=200 THEN s.run_id END AS run_id,
938
+ s.updatedAt COLLATE BINARY < ?4 AND CASE WHEN json_valid(s.snapshot) THEN (${retentionTerminalSql(5)}) ELSE 0 END AS eligible,
939
+ ${retentionOwnedProjection()}`, [cutoff, ...RUN_TERMINAL_STATUSES])).all(), cursor?.snapshots, limit);
940
+ const modern = [];
941
+ for (const row of page.rows) {
942
+ if (!Object.hasOwn(row, 'eligible') ||
943
+ ![0, 1, null].includes(row.eligible))
944
+ throw new Error('run retention eligibility projection is malformed');
945
+ if (row.eligible !== 1)
946
+ continue;
947
+ const candidate = decodeRunRetentionCandidate(row, prefix);
948
+ if (candidate === undefined) {
949
+ reportUnsupported('snapshot');
950
+ continue;
951
+ }
952
+ if (candidate !== 'legacy') {
953
+ modern.push(candidate);
954
+ continue;
955
+ }
956
+ const address = {
957
+ tablePrefix: prefix,
958
+ workflowId: row.workflow_name,
959
+ runId: row.run_id,
960
+ };
961
+ const read = prepareRawWorkflowSnapshotRead(captured, address);
962
+ const result = await read.statement.all();
963
+ const rawRows = snapshotResultRows(result);
964
+ if (rawRows.length > 1 ||
965
+ rawRows.some((rawRow) => [
966
+ 'workflow_name',
967
+ 'run_id',
968
+ 'resourceId',
969
+ 'snapshot',
970
+ 'createdAt',
971
+ 'updatedAt',
972
+ ].some((key) => !Object.hasOwn(rawRow, key))))
973
+ throw new Error('run retention raw snapshot result is malformed');
974
+ let raw;
480
975
  try {
481
- await options.artifactStore.deleteRun(row.workflow_name, row.run_id);
976
+ raw = decodeRawWorkflowSnapshotResult(result, read.address);
977
+ if (!raw || raw.updatedAt >= cutoff)
978
+ continue;
979
+ const snapshot = JSON.parse(raw.snapshot);
980
+ const cleanupCompletedAt = snapshot.requestContext?.['flowsafe.runLifecycle']?.terminal
981
+ ?.cleanupCompletedAt;
982
+ if (decodeRunStartIdentity(snapshot.requestContext?.['flowsafe.runProvenance']) !== undefined ||
983
+ !RUN_TERMINAL_STATUSES.includes(snapshot.status) ||
984
+ ((snapshot.status === 'cancelled' ||
985
+ snapshot.status === 'timed_out') &&
986
+ (!Number.isSafeInteger(cleanupCompletedAt) ||
987
+ cleanupCompletedAt < 0)))
988
+ continue;
482
989
  }
483
- catch (error) {
484
- // Isolate per run: aborting the
485
- // loop would re-hit this run at the same scan position every firing
486
- // and stall every eligible row behind it forever. Its row survives
487
- // as its own retry cursor; the aggregate throw below keeps the
488
- // purge duty's error surface firing. A wedged run does occupy a batch
489
- // slot until fixed, so isolation holds while wedged runs number
490
- // fewer than `limit`.
491
- failures.push({
492
- run: `${row.workflow_name}/${row.run_id}`,
493
- message: errorMessageOf(error),
494
- });
990
+ catch {
991
+ reportUnsupported('legacy-snapshot');
495
992
  continue;
496
993
  }
497
- // Re-checking eligibility keys the delete to the row the SELECT saw;
498
- // terminal is absorbing, so this is belt-and-braces, not a race fix.
499
- //
500
- // A FACTORY, not one prepared statement: D1 statements are single-use
501
- // once run, and `runPurgeBatch` re-prepares its whole batch when the
502
- // reservation table turns out not to exist. Written once so the batch and
503
- // non-batch paths cannot drift onto different delete predicates.
504
- const deleteSnapshot = () => db
505
- .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
506
- WHERE workflow_name = ? AND run_id = ? AND ${eligible}`)
507
- .bind(row.workflow_name, row.run_id, cutoff, ...RUN_TERMINAL_STATUSES);
508
- if (batch) {
509
- const [result] = await runPurgeBatch((withReservations) => [
510
- deleteSnapshot(),
511
- ...(resourceOwnerTable
512
- ? [
513
- db
514
- .prepare(`DELETE FROM ${resourceOwnerTable}
515
- WHERE resource_kind = 'run' AND resource_id = ?
516
- AND NOT EXISTS (
517
- SELECT 1 FROM ${prefix}mastra_workflow_snapshot
518
- WHERE run_id = ?
519
- )`)
520
- .bind(row.run_id, row.run_id),
521
- ]
522
- : []),
523
- ...(withReservations ? reservationStatements([row.run_id]) : []),
524
- ]);
525
- deleted += d1Changes(result);
994
+ const selectors = [
995
+ [address.workflowId, address.runId, [], null],
996
+ ];
997
+ snapshotGroup(selectors, raw);
998
+ if (await artifacts(address.workflowId, address.runId)) {
999
+ const count = await execute(() => snapshotGroup(selectors, raw));
1000
+ if (schema.names.includes(table))
1001
+ deleted += count;
526
1002
  }
527
- else {
528
- deleted += d1Changes(await deleteSnapshot().run());
1003
+ }
1004
+ if (modern.length > 0) {
1005
+ snapshotGroup(modern);
1006
+ const ready = [];
1007
+ for (const candidate of modern)
1008
+ if (await artifacts(candidate[0], candidate[1]))
1009
+ ready.push(candidate);
1010
+ if (ready.length > 0) {
1011
+ const count = await execute(() => snapshotGroup(ready));
1012
+ if (schema.names.includes(table))
1013
+ deleted += count;
529
1014
  }
530
1015
  }
531
- await sweepOrphanedStartReservations();
532
- if (failures.length > 0) {
533
- throw new Error(`purgeExpiredWorkflowRuns: artifact deletion failed for ${failures.length} of ${rows.length} eligible run(s), the rest were purged (${failures
534
- .map((failure) => `${failure.run}: ${failure.message}`)
535
- .join('; ')})`);
1016
+ await advance('snapshots', page.position);
1017
+ }
1018
+ else
1019
+ await advance('snapshots', undefined);
1020
+ const classifyOrphans = async (raws) => {
1021
+ const orphans = [];
1022
+ const grouped = new Map();
1023
+ if (schema.stage === undefined)
1024
+ return orphans;
1025
+ for (const raw of raws) {
1026
+ try {
1027
+ let row = reservationFromRow(raw, schema.stage);
1028
+ if (row.state !== 'terminal' || row.updatedAt >= keyCutoff)
1029
+ continue;
1030
+ if (row.binding.kind === 'legacy') {
1031
+ orphans.push({ raw, observation: 'legacy' });
1032
+ continue;
1033
+ }
1034
+ row = admissionReservationFromRow(raw, schema.stage);
1035
+ if (row.binding.kind !== 'bound' ||
1036
+ row.binding.execution.tablePrefix === null)
1037
+ continue;
1038
+ const namespace = `${row.binding.execution.tablePrefix}${RETENTION_SUFFIX}`;
1039
+ if (!schema.names.includes(namespace)) {
1040
+ orphans.push({ raw, namespace, observation: 'missing' });
1041
+ continue;
1042
+ }
1043
+ const values = grouped.get(namespace) ?? [];
1044
+ values.push(raw);
1045
+ grouped.set(namespace, values);
1046
+ }
1047
+ catch {
1048
+ reportUnsupported('reservation');
1049
+ }
536
1050
  }
537
- return deleted;
538
- }
539
- // Row-only path: LIMIT-batched like the artifact path, but against D1's
540
- // per-QUERY budget rather than the subrequest cap (it stays one statement
541
- // per firing whatever the batch size, hence the larger default). An
542
- // unbounded DELETE over a huge first backlog can exceed the per-query
543
- // limits and then fail the same way on EVERY firing — retention silently
544
- // unenforced, the exact wedge the one-duty-per-alarm split exists to avoid. The
545
- // shrinking eligible set is the cursor: a backlog drains across firings.
546
- let deleted;
547
- try {
548
- if (batch) {
549
- // D1 accepts at most 100 bound parameters per statement. Keep the exact
550
- // rowid + owner-id transaction below under that limit even when a caller
551
- // requests a larger generic purge batch.
552
- const limit = Math.min(options.limit ?? 1000, 90);
553
- const selected = await db
554
- .prepare(`SELECT rowid, run_id
555
- FROM ${prefix}mastra_workflow_snapshot
556
- WHERE ${eligible}
557
- LIMIT ?`)
558
- .bind(cutoff, ...RUN_TERMINAL_STATUSES, limit)
559
- .all();
560
- if (selected.results.length === 0) {
561
- // No eligible run this pass, but reservations left behind by EARLIER
562
- // passes still age out — so the orphan sweep runs before the return.
563
- await sweepOrphanedStartReservations();
564
- return 0;
1051
+ for (const [namespace, values] of grouped) {
1052
+ const selectors = retentionSelectorJson(values.map((raw) => [raw.start_workflow_id, raw.run_id]));
1053
+ const rows = snapshotResultRows(await prepareRetentionStatement(captured, retentionStatement(`SELECT c.key AS candidate, s.rowid AS present,
1054
+ json_extract(c.value,'$[0]') AS workflow_name, json_extract(c.value,'$[1]') AS run_id, ${retentionOwnedProjection()}
1055
+ FROM json_each(?1) c LEFT JOIN "${namespace}" s ON s.workflow_name COLLATE BINARY=json_extract(c.value,'$[0]')
1056
+ AND s.run_id COLLATE BINARY=json_extract(c.value,'$[1]') ORDER BY c.key`, [selectors])).all());
1057
+ if (rows.length !== values.length)
1058
+ throw new Error('run retention orphan observation is malformed');
1059
+ for (const [index, row] of rows.entries()) {
1060
+ if (row.candidate !== index || !Object.hasOwn(row, 'present'))
1061
+ throw new Error('run retention orphan observation is malformed');
1062
+ const raw = values[index];
1063
+ if (!raw)
1064
+ throw new Error('run retention orphan candidate is missing');
1065
+ if (row.workflow_name !== raw.start_workflow_id ||
1066
+ row.run_id !== raw.run_id)
1067
+ throw new Error('run retention orphan address is malformed');
1068
+ if (row.present !== null &&
1069
+ (typeof row.present !== 'number' ||
1070
+ !Number.isSafeInteger(row.present)))
1071
+ throw new Error('run retention orphan rowid is malformed');
1072
+ const decoded = decodeRunRetentionCandidate(row, namespace.slice(0, -RETENTION_SUFFIX.length));
1073
+ if (row.present === null) {
1074
+ orphans.push({ raw, namespace, observation: 'absent' });
1075
+ continue;
1076
+ }
1077
+ if (decoded === undefined)
1078
+ reportUnsupported('orphan-snapshot');
1079
+ if (decoded &&
1080
+ decoded !== 'legacy' &&
1081
+ typeof decoded[2][1] === 'string' &&
1082
+ JSON.parse(decoded[2][1]) !== raw.start_token)
1083
+ orphans.push({ raw, namespace, observation: decoded[2] });
565
1084
  }
566
- const rowIds = selected.results.map((row) => row.rowid);
567
- const runIds = [...new Set(selected.results.map((row) => row.run_id))];
568
- const rowPlaceholders = rowIds.map(() => '?').join(', ');
569
- const runPlaceholders = runIds.map(() => '?').join(', ');
570
- const [result] = await runPurgeBatch((withReservations) => [
571
- db
572
- .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
573
- WHERE rowid IN (${rowPlaceholders}) AND ${eligible}`)
574
- .bind(...rowIds, cutoff, ...RUN_TERMINAL_STATUSES),
575
- ...(resourceOwnerTable
576
- ? [
577
- db
578
- .prepare(`DELETE FROM ${resourceOwnerTable}
579
- WHERE resource_kind = 'run'
580
- AND resource_id IN (${runPlaceholders})
581
- AND resource_id NOT IN (
582
- SELECT run_id FROM ${prefix}mastra_workflow_snapshot
583
- )`)
584
- .bind(...runIds),
585
- ]
586
- : []),
587
- ...(withReservations ? reservationStatements(runIds) : []),
588
- ]);
589
- deleted = d1Changes(result);
590
1085
  }
591
- else {
592
- deleted = d1Changes(await db
593
- .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
594
- WHERE rowid IN (
595
- SELECT rowid FROM ${prefix}mastra_workflow_snapshot
596
- WHERE ${eligible}
597
- LIMIT ?
598
- )`)
599
- .bind(cutoff, ...RUN_TERMINAL_STATUSES, options.limit ?? 1000)
600
- .run());
1086
+ return orphans;
1087
+ };
1088
+ if (schema.stage !== undefined && registry !== undefined) {
1089
+ const page = decodeRetentionPage(await prepareRetentionStatement(captured, retentionPageStatement(registry, cursor?.reservations, limit, retentionReservationProjection(schema.stage))).all(), cursor?.reservations, limit);
1090
+ const raws = [];
1091
+ for (const row of page.rows) {
1092
+ const raw = decodeRetentionReservationProjection(row, schema.stage);
1093
+ if (raw === undefined) {
1094
+ reportUnsupported('reservation');
1095
+ continue;
1096
+ }
1097
+ raws.push(raw);
601
1098
  }
1099
+ const candidates = await classifyOrphans(raws);
1100
+ for (const initial of retentionOrphanPackets(candidates)) {
1101
+ let pending = initial;
1102
+ const retry = async () => {
1103
+ if (schema.stage === undefined) {
1104
+ pending = [];
1105
+ return;
1106
+ }
1107
+ const keys = retentionSelectorJson(initial.map((candidate) => candidate.raw.key));
1108
+ const rows = snapshotResultRows(await prepareRetentionStatement(captured, retentionStatement(`SELECT ${retentionReservationProjection(schema.stage)}
1109
+ FROM "${registry}" s WHERE s.key COLLATE BINARY IN (SELECT value FROM json_each(?1)) LIMIT ?2`, [keys, limit + 1])).all());
1110
+ if (rows.length > initial.length)
1111
+ throw new Error('run retention orphan retry is ambiguous');
1112
+ const unchanged = [];
1113
+ for (const row of rows) {
1114
+ const raw = decodeRetentionReservationProjection(row, schema.stage);
1115
+ if (raw === undefined) {
1116
+ reportUnsupported('reservation');
1117
+ continue;
1118
+ }
1119
+ const prior = initial.find((candidate) => candidate.raw.key === raw.key)?.raw;
1120
+ if (prior &&
1121
+ Object.entries(prior).every(([key, value]) => Object.hasOwn(raw, key) && raw[key] === value) &&
1122
+ Object.entries(raw).every(([key, value]) => Object.hasOwn(prior, key) || value === null))
1123
+ unchanged.push(raw);
1124
+ }
1125
+ pending = await classifyOrphans(unchanged);
1126
+ };
1127
+ await execute(() => [
1128
+ retentionStatement(`${RETENTION_SCHEMA_SQL} SELECT ok AS schema_ok FROM schema_ok`, [...schema.bindings]),
1129
+ ...retentionOrphanPackets(pending).flatMap((packet) => retentionOrphanGroup(schema, packet, keyCutoff).slice(1)),
1130
+ ], retry);
1131
+ }
1132
+ await advance('reservations', page.position);
602
1133
  }
603
- catch (error) {
604
- if (!isMissingTable(error, `${prefix}mastra_workflow_snapshot`))
605
- throw error;
606
- return 0;
607
- }
608
- await sweepOrphanedStartReservations();
1134
+ else
1135
+ await advance('reservations', undefined);
1136
+ if (failures.length > 0)
1137
+ throw new Error(`purgeExpiredWorkflowRuns: artifact deletion failed (${failures.join('; ')})`);
609
1138
  return deleted;
610
1139
  }
611
1140
  // D1 binds at most 100 parameters per query. Each id chunk below shares its
@@ -895,19 +1424,18 @@ const NOTIFICATION_TERMINAL_STATUSES = [
895
1424
  * rows from `mastra_notifications` once their `updatedAt` is older than the TTL,
896
1425
  * at the storage layer so alarm maintenance reaps them without a live agent —
897
1426
  * the same posture as the other purges (raw D1 binding, failure-isolated duty).
898
- * `updatedAt` is ISO-8601 TEXT, so lexicographic `<` is a correct timestamp
899
- * comparison. A missing table reads as zero (notifications may never have been
900
- * sent). Scheduling stays with the caller.
1427
+ * A missing table reads as zero (notifications may never have been sent).
1428
+ * Scheduling stays with the caller.
901
1429
  */
902
1430
  export async function purgeExpiredNotifications(db, options) {
903
1431
  const prefix = validateTablePrefix(options.tablePrefix) ?? '';
904
1432
  const now = options.now ?? Date.now;
905
- const cutoff = new Date(now() - options.ttlMs).toISOString();
1433
+ const cutoff = notificationTimestampMillis(new Date(now() - options.ttlMs));
906
1434
  const placeholders = NOTIFICATION_TERMINAL_STATUSES.map(() => '?').join(', ');
907
1435
  try {
908
1436
  return d1Changes(await db
909
1437
  .prepare(`DELETE FROM ${prefix}mastra_notifications
910
- WHERE status IN (${placeholders}) AND updatedAt < ?`)
1438
+ WHERE status IN (${placeholders}) AND ${notificationTimestampSql('updatedAt')} < ?`)
911
1439
  .bind(...NOTIFICATION_TERMINAL_STATUSES, cutoff)
912
1440
  .run());
913
1441
  }
@@ -1002,7 +1530,12 @@ export function d1Changes(result) {
1002
1530
  return typeof changes === 'number' ? changes : 0;
1003
1531
  }
1004
1532
  function errorMessageOf(error) {
1005
- return error instanceof Error ? error.message : String(error);
1533
+ try {
1534
+ return String(error instanceof Error ? error.message : error);
1535
+ }
1536
+ catch {
1537
+ return 'unreadable error';
1538
+ }
1006
1539
  }
1007
1540
  /**
1008
1541
  * SQLite/D1's "no such table". For the purges, a table that was never