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