@proofoftech/flowsafe 0.4.0 → 0.6.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.
- package/CHANGELOG.md +307 -0
- package/dist/agent-runner/approval-shapes.d.ts +36 -0
- package/dist/agent-runner/approval-shapes.d.ts.map +1 -0
- package/dist/agent-runner/approval-shapes.js +101 -0
- package/dist/agent-runner/approval-shapes.js.map +1 -0
- package/dist/agent-runner/durable-agent-runner.d.ts +154 -0
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -0
- package/dist/agent-runner/durable-agent-runner.js +291 -0
- package/dist/agent-runner/durable-agent-runner.js.map +1 -0
- package/dist/agent-runner/index.d.ts +3 -0
- package/dist/agent-runner/index.d.ts.map +1 -0
- package/dist/agent-runner/index.js +10 -0
- package/dist/agent-runner/index.js.map +1 -0
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +85 -17
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/index.d.ts +1 -1
- package/dist/approval-api/index.d.ts.map +1 -1
- package/dist/approval-api/index.js.map +1 -1
- package/dist/approval-api/router.d.ts +1 -1
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +1 -0
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +2 -2
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +15 -1
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/store.d.ts +10 -6
- package/dist/approval-api/store.d.ts.map +1 -1
- package/dist/approval-api/store.js +15 -0
- package/dist/approval-api/store.js.map +1 -1
- package/dist/approval-api/tenant-context.d.ts.map +1 -1
- package/dist/approval-api/tenant-context.js +15 -0
- package/dist/approval-api/tenant-context.js.map +1 -1
- package/dist/approval-api/types.d.ts +8 -0
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js.map +1 -1
- package/dist/background-tasks/d1-storage.d.ts +66 -0
- package/dist/background-tasks/d1-storage.d.ts.map +1 -0
- package/dist/background-tasks/d1-storage.js +196 -0
- package/dist/background-tasks/d1-storage.js.map +1 -0
- package/dist/background-tasks/host.d.ts +82 -0
- package/dist/background-tasks/host.d.ts.map +1 -0
- package/dist/background-tasks/host.js +275 -0
- package/dist/background-tasks/host.js.map +1 -0
- package/dist/background-tasks/index.d.ts +7 -0
- package/dist/background-tasks/index.d.ts.map +1 -0
- package/dist/background-tasks/index.js +10 -0
- package/dist/background-tasks/index.js.map +1 -0
- package/dist/background-tasks/routes.d.ts +15 -0
- package/dist/background-tasks/routes.d.ts.map +1 -0
- package/dist/background-tasks/routes.js +144 -0
- package/dist/background-tasks/routes.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +343 -2
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +565 -12
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +29 -0
- package/dist/do-runner/do-error-response.d.ts.map +1 -0
- package/dist/do-runner/do-error-response.js +73 -0
- package/dist/do-runner/do-error-response.js.map +1 -0
- package/dist/do-runner/durable-object.d.ts +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +2 -16
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/index.d.ts +9 -3
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +8 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +20 -0
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +12 -1
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/pubsub.d.ts +18 -0
- package/dist/do-runner/pubsub.d.ts.map +1 -0
- package/dist/do-runner/pubsub.js +42 -0
- package/dist/do-runner/pubsub.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +24 -0
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +29 -2
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/thread-do.d.ts +74 -0
- package/dist/do-runner/thread-do.d.ts.map +1 -0
- package/dist/do-runner/thread-do.js +156 -0
- package/dist/do-runner/thread-do.js.map +1 -0
- package/dist/do-runner/thread-header.d.ts +16 -0
- package/dist/do-runner/thread-header.d.ts.map +1 -0
- package/dist/do-runner/thread-header.js +24 -0
- package/dist/do-runner/thread-header.js.map +1 -0
- package/dist/goals/index.d.ts +2 -0
- package/dist/goals/index.d.ts.map +1 -0
- package/dist/goals/index.js +7 -0
- package/dist/goals/index.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +87 -0
- package/dist/goals/objective-routes.d.ts.map +1 -0
- package/dist/goals/objective-routes.js +375 -0
- package/dist/goals/objective-routes.js.map +1 -0
- package/dist/host-kit/approval-bridge.d.ts +24 -4
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +32 -10
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/env-vars.d.ts +20 -0
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +30 -0
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +111 -4
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +253 -63
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/index.d.ts +3 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +7 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/memory-boundary.d.ts +64 -0
- package/dist/host-kit/memory-boundary.d.ts.map +1 -0
- package/dist/host-kit/memory-boundary.js +109 -0
- package/dist/host-kit/memory-boundary.js.map +1 -0
- package/dist/host-kit/route-path.d.ts +17 -0
- package/dist/host-kit/route-path.d.ts.map +1 -0
- package/dist/host-kit/route-path.js +35 -0
- package/dist/host-kit/route-path.js.map +1 -0
- package/dist/host-kit/thread-topology.d.ts +44 -0
- package/dist/host-kit/thread-topology.d.ts.map +1 -0
- package/dist/host-kit/thread-topology.js +76 -0
- package/dist/host-kit/thread-topology.js.map +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal-error-response.d.ts +3 -0
- package/dist/internal-error-response.d.ts.map +1 -0
- package/dist/internal-error-response.js +20 -0
- package/dist/internal-error-response.js.map +1 -0
- package/dist/numeric-config.d.ts +4 -0
- package/dist/numeric-config.d.ts.map +1 -0
- package/dist/numeric-config.js +23 -0
- package/dist/numeric-config.js.map +1 -0
- package/dist/schedules/index.d.ts +5 -0
- package/dist/schedules/index.d.ts.map +1 -0
- package/dist/schedules/index.js +13 -0
- package/dist/schedules/index.js.map +1 -0
- package/dist/schedules/router.d.ts +66 -0
- package/dist/schedules/router.d.ts.map +1 -0
- package/dist/schedules/router.js +827 -0
- package/dist/schedules/router.js.map +1 -0
- package/dist/schedules/schedules-d1.d.ts +30 -0
- package/dist/schedules/schedules-d1.d.ts.map +1 -0
- package/dist/schedules/schedules-d1.js +374 -0
- package/dist/schedules/schedules-d1.js.map +1 -0
- package/dist/schedules/storage.d.ts +11 -0
- package/dist/schedules/storage.d.ts.map +1 -0
- package/dist/schedules/storage.js +34 -0
- package/dist/schedules/storage.js.map +1 -0
- package/dist/schedules/tick.d.ts +131 -0
- package/dist/schedules/tick.d.ts.map +1 -0
- package/dist/schedules/tick.js +598 -0
- package/dist/schedules/tick.js.map +1 -0
- package/dist/signal-providers/delivery.d.ts +24 -0
- package/dist/signal-providers/delivery.d.ts.map +1 -0
- package/dist/signal-providers/delivery.js +62 -0
- package/dist/signal-providers/delivery.js.map +1 -0
- package/dist/signal-providers/github-provider.d.ts +33 -0
- package/dist/signal-providers/github-provider.d.ts.map +1 -0
- package/dist/signal-providers/github-provider.js +116 -0
- package/dist/signal-providers/github-provider.js.map +1 -0
- package/dist/signal-providers/host-do.d.ts +79 -0
- package/dist/signal-providers/host-do.d.ts.map +1 -0
- package/dist/signal-providers/host-do.js +216 -0
- package/dist/signal-providers/host-do.js.map +1 -0
- package/dist/signal-providers/index.d.ts +7 -0
- package/dist/signal-providers/index.d.ts.map +1 -0
- package/dist/signal-providers/index.js +19 -0
- package/dist/signal-providers/index.js.map +1 -0
- package/dist/signal-providers/provider.d.ts +92 -0
- package/dist/signal-providers/provider.d.ts.map +1 -0
- package/dist/signal-providers/provider.js +87 -0
- package/dist/signal-providers/provider.js.map +1 -0
- package/dist/signal-providers/subscription-d1.d.ts +88 -0
- package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
- package/dist/signal-providers/subscription-d1.js +259 -0
- package/dist/signal-providers/subscription-d1.js.map +1 -0
- package/dist/signal-providers/webhook-route.d.ts +88 -0
- package/dist/signal-providers/webhook-route.d.ts.map +1 -0
- package/dist/signal-providers/webhook-route.js +391 -0
- package/dist/signal-providers/webhook-route.js.map +1 -0
- package/dist/signals/client.d.ts +72 -0
- package/dist/signals/client.d.ts.map +1 -0
- package/dist/signals/client.js +87 -0
- package/dist/signals/client.js.map +1 -0
- package/dist/signals/d1-shared.d.ts +43 -0
- package/dist/signals/d1-shared.d.ts.map +1 -0
- package/dist/signals/d1-shared.js +46 -0
- package/dist/signals/d1-shared.js.map +1 -0
- package/dist/signals/index.d.ts +9 -0
- package/dist/signals/index.d.ts.map +1 -0
- package/dist/signals/index.js +15 -0
- package/dist/signals/index.js.map +1 -0
- package/dist/signals/notification-dispatch.d.ts +52 -0
- package/dist/signals/notification-dispatch.d.ts.map +1 -0
- package/dist/signals/notification-dispatch.js +198 -0
- package/dist/signals/notification-dispatch.js.map +1 -0
- package/dist/signals/notifications-d1.d.ts +28 -0
- package/dist/signals/notifications-d1.d.ts.map +1 -0
- package/dist/signals/notifications-d1.js +704 -0
- package/dist/signals/notifications-d1.js.map +1 -0
- package/dist/signals/router.d.ts +73 -0
- package/dist/signals/router.d.ts.map +1 -0
- package/dist/signals/router.js +240 -0
- package/dist/signals/router.js.map +1 -0
- package/dist/signals/storage.d.ts +11 -0
- package/dist/signals/storage.d.ts.map +1 -0
- package/dist/signals/storage.js +27 -0
- package/dist/signals/storage.js.map +1 -0
- package/dist/signals/thread-do-routes.d.ts +82 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -0
- package/dist/signals/thread-do-routes.js +660 -0
- package/dist/signals/thread-do-routes.js.map +1 -0
- package/dist/signals/thread-state-d1.d.ts +22 -0
- package/dist/signals/thread-state-d1.d.ts.map +1 -0
- package/dist/signals/thread-state-d1.js +83 -0
- package/dist/signals/thread-state-d1.js.map +1 -0
- package/package.json +11 -2
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
// happens lazily via Mastra's storage-init proxy once the store is handed
|
|
6
6
|
// to `new Mastra({ storage })` — no migration step needed for the runner.
|
|
7
7
|
import { D1Store } from '@mastra/cloudflare-d1';
|
|
8
|
+
import { MastraCompositeStore, } from '@mastra/core/storage';
|
|
8
9
|
import { TENANT_ID_PATTERN } from './path-safe-id.js';
|
|
9
10
|
export function createD1Storage(options) {
|
|
10
|
-
|
|
11
|
+
const d1 = new D1Store({
|
|
11
12
|
id: options.id ?? 'flowsafe',
|
|
12
13
|
// @mastra/cloudflare-d1's own D1Store signature wants the real
|
|
13
14
|
// D1Database; D1DatabaseBinding is the structural subset this package
|
|
@@ -18,6 +19,19 @@ export function createD1Storage(options) {
|
|
|
18
19
|
? { tablePrefix: options.tablePrefix }
|
|
19
20
|
: {}),
|
|
20
21
|
});
|
|
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;
|
|
30
|
+
return new MastraCompositeStore({
|
|
31
|
+
id: options.id ?? 'flowsafe',
|
|
32
|
+
default: d1,
|
|
33
|
+
domains: options.domains,
|
|
34
|
+
});
|
|
21
35
|
}
|
|
22
36
|
// Terminal statuses per WorkflowRunStatus (@mastra/core workflows/types).
|
|
23
37
|
// Deleting a live run (running/suspended/waiting/pending/paused) would kill
|
|
@@ -30,6 +44,19 @@ const TERMINAL_STATUSES = [
|
|
|
30
44
|
'bailed',
|
|
31
45
|
'skipped',
|
|
32
46
|
];
|
|
47
|
+
/**
|
|
48
|
+
* The tables `purgeExpiredWorkflowRuns` deletes from under the run TTL — the
|
|
49
|
+
* production anchor the schema guard cross-checks every `run-ttl` retention
|
|
50
|
+
* declaration against (DL-003), the retention-leg analog of
|
|
51
|
+
* TENANT_RANGE_PURGE_TABLES for the offboarding leg. One table, because the run
|
|
52
|
+
* TTL rides a `run_id` range paired with artifact deletion and an app-owned
|
|
53
|
+
* index (its own block below), not the tenant-range map. The guard reads THIS,
|
|
54
|
+
* not a literal copied into the test, so a purge that changes what it targets
|
|
55
|
+
* and a guard that still blesses the old set cannot drift apart silently.
|
|
56
|
+
*/
|
|
57
|
+
export const RUN_TTL_PURGE_TABLES = [
|
|
58
|
+
'mastra_workflow_snapshot',
|
|
59
|
+
];
|
|
33
60
|
/**
|
|
34
61
|
* Data-retention purge: deletes TERMINAL runs (success/failed/tripwire/
|
|
35
62
|
* canceled/bailed/skipped) whose updatedAt is older than the TTL from
|
|
@@ -143,6 +170,376 @@ export async function purgeExpiredWorkflowRuns(db, options) {
|
|
|
143
170
|
return 0;
|
|
144
171
|
}
|
|
145
172
|
}
|
|
173
|
+
// D1 binds at most 100 parameters per query. Each id chunk below shares its
|
|
174
|
+
// statement with the cutoff bind of the eligibility re-check, so the chunk
|
|
175
|
+
// ceiling must leave room for it — 90 keeps comfortable headroom without
|
|
176
|
+
// making the batch loop meaningfully longer.
|
|
177
|
+
const D1_BIND_CHUNK = 90;
|
|
178
|
+
function chunked(values, size) {
|
|
179
|
+
const chunks = [];
|
|
180
|
+
for (let index = 0; index < values.length; index += size) {
|
|
181
|
+
chunks.push(values.slice(index, index + size));
|
|
182
|
+
}
|
|
183
|
+
return chunks;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The tables `purgeExpiredThreads` deletes from under the thread TTL — the
|
|
187
|
+
* production anchor the schema guard cross-checks the `thread-ttl` retention
|
|
188
|
+
* declaration against, AND the target set a `cascade` child must appear in to be
|
|
189
|
+
* believed (DL-003). BOTH tables are here because the purge reaps a thread and
|
|
190
|
+
* its messages together: `mastra_threads` by its own `updatedAt`,
|
|
191
|
+
* `mastra_messages` by cascade (a message has no idleness signal of its own — see
|
|
192
|
+
* the purge doc). So the inventory's `mastra_messages: { retention: cascade with
|
|
193
|
+
* mastra_threads }` is only legal because `mastra_messages` is genuinely a delete
|
|
194
|
+
* target here; a cascade naming a parent whose purge never touches the child is
|
|
195
|
+
* the lie the guard now catches.
|
|
196
|
+
*/
|
|
197
|
+
export const THREAD_TTL_PURGE_TABLES = [
|
|
198
|
+
'mastra_threads',
|
|
199
|
+
'mastra_messages',
|
|
200
|
+
];
|
|
201
|
+
/**
|
|
202
|
+
* Thread-level retention (docs/agent-memory-tenancy.md item 7): deletes agent
|
|
203
|
+
* memory threads whose `updatedAt` is older than the TTL, each with its
|
|
204
|
+
* messages. The terminal-status shape `purgeExpiredWorkflowRuns` uses does not
|
|
205
|
+
* transfer — threads are not per-run and have no status, so there is nothing to
|
|
206
|
+
* prove "finished" about one. Time since last write IS the only signal a thread
|
|
207
|
+
* is done, which is why the TTL keys on `updatedAt` (the D1 memory domain stamps
|
|
208
|
+
* it on every saveThread, so an active conversation never ages out).
|
|
209
|
+
*
|
|
210
|
+
* MESSAGES BEFORE THREADS: a message carries a `createdAt` but no `updatedAt`,
|
|
211
|
+
* so there is no per-message IDLENESS signal — a message's lifetime is its
|
|
212
|
+
* thread's, and its rows are reachable only through it. Deleting a thread first
|
|
213
|
+
* would strand its messages beyond every later firing of this purge (only
|
|
214
|
+
* purgeTenant, at offboarding, still ranges over their salted `thread_id`).
|
|
215
|
+
*
|
|
216
|
+
* EVERY statement re-checks the CURRENT row rather than trusting the SELECT's id
|
|
217
|
+
* list, and that is load-bearing here in a way it is not for
|
|
218
|
+
* purgeExpiredWorkflowRuns (where terminal status is absorbing, so its re-check
|
|
219
|
+
* is belt-and-braces). "Idle" is precisely NOT absorbing — a thread can come
|
|
220
|
+
* back to life mid-purge — and the writer is not atomic either: the memory
|
|
221
|
+
* domain's saveMessages issues its message insert and its `UPDATE mastra_threads
|
|
222
|
+
* SET updatedAt` as two INDEPENDENT calls under one Promise.all, so a send's
|
|
223
|
+
* message can be visible while its thread still reads idle. That TORN state is
|
|
224
|
+
* what each guard answers:
|
|
225
|
+
*
|
|
226
|
+
* - The message DELETE re-reads the thread's current `updatedAt` (subquery) AND
|
|
227
|
+
* bounds itself to `createdAt < cutoff`. The subquery alone would sweep a
|
|
228
|
+
* just-arrived message into the same statement as the genuinely old ones —
|
|
229
|
+
* it keys on the THREAD's staleness, and the bump has not landed — silently
|
|
230
|
+
* destroying the message the user just sent. `createdAt` is the message's own
|
|
231
|
+
* evidence of recency, and the only guard that survives a torn write.
|
|
232
|
+
* - The thread DELETE re-checks `updatedAt < cutoff` AND fires only when `NOT
|
|
233
|
+
* EXISTS` any message for it. Sequence alone cannot carry "messages before
|
|
234
|
+
* threads": a message landing after the message DELETE leaves an idle-looking
|
|
235
|
+
* thread whose row would go out from under it. The NOT EXISTS makes the
|
|
236
|
+
* invariant — never delete a thread a message points at — a property of the
|
|
237
|
+
* statement rather than of timing.
|
|
238
|
+
*
|
|
239
|
+
* Together: a torn or concurrent send at ANY point in the sequence keeps both
|
|
240
|
+
* its message and its thread; the thread's next firing (by then bumped, or by
|
|
241
|
+
* then genuinely idle again) decides its fate on fresh evidence.
|
|
242
|
+
*
|
|
243
|
+
* Residuals, both accepted, neither reachable by a read path: (1) a send landing
|
|
244
|
+
* between the two DELETEs loses the already-expiring history while the thread
|
|
245
|
+
* and the new message survive — strictly better than the deletion that was
|
|
246
|
+
* milliseconds away. (2) A message inserted AFTER its thread's row is already
|
|
247
|
+
* gone is orphaned by the writer, not by this purge; D1 offers no cross-statement
|
|
248
|
+
* transaction through this seam to close it. An orphan is unreachable by recall
|
|
249
|
+
* (nothing lists a thread that does not exist), stays tenant-salted on its
|
|
250
|
+
* `thread_id`, and is reaped by purgeTenant at offboarding — a hygiene cost, not
|
|
251
|
+
* a leak.
|
|
252
|
+
*
|
|
253
|
+
* `mastra_resources` (working memory) is deliberately untouched: a resource is
|
|
254
|
+
* the OWNER's, shared across every thread they have, so one thread aging out
|
|
255
|
+
* says nothing about it. It is reaped at offboarding (purgeTenant).
|
|
256
|
+
*
|
|
257
|
+
* Missing tables read as zero (a deployment with no agent memory never created
|
|
258
|
+
* them). Scheduling stays with the caller — see createFlowsafeWorker's
|
|
259
|
+
* THREAD_RETENTION_DAYS duty.
|
|
260
|
+
*/
|
|
261
|
+
export async function purgeExpiredThreads(db, options) {
|
|
262
|
+
const now = options.now ?? Date.now;
|
|
263
|
+
const prefix = options.tablePrefix ?? '';
|
|
264
|
+
// @mastra/cloudflare-d1 stores the memory tables' TIMESTAMP columns as
|
|
265
|
+
// ISO-8601 TEXT (the same serialization the snapshot rows use), so a
|
|
266
|
+
// lexicographic < against an ISO cutoff is a correct timestamp comparison.
|
|
267
|
+
const cutoff = new Date(now() - options.ttlMs).toISOString();
|
|
268
|
+
let expired;
|
|
269
|
+
try {
|
|
270
|
+
({ results: expired } = await db
|
|
271
|
+
.prepare(`SELECT id FROM ${prefix}mastra_threads
|
|
272
|
+
WHERE updatedAt < ?
|
|
273
|
+
ORDER BY updatedAt
|
|
274
|
+
LIMIT ?`)
|
|
275
|
+
.bind(cutoff, options.limit ?? 100)
|
|
276
|
+
.all());
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
if (!isMissingTable(error))
|
|
280
|
+
throw error;
|
|
281
|
+
return { threads: 0, messages: 0 };
|
|
282
|
+
}
|
|
283
|
+
const ids = expired.map((row) => row.id);
|
|
284
|
+
if (ids.length === 0)
|
|
285
|
+
return { threads: 0, messages: 0 };
|
|
286
|
+
const batches = chunked(ids, D1_BIND_CHUNK);
|
|
287
|
+
const placeholders = (chunk) => chunk.map(() => '?').join(', ');
|
|
288
|
+
// The eligibility re-check, as a subquery so the message delete rides the
|
|
289
|
+
// thread's CURRENT updatedAt rather than the SELECT's stale membership.
|
|
290
|
+
const stillExpired = (chunk) => `SELECT id FROM ${prefix}mastra_threads
|
|
291
|
+
WHERE id IN (${placeholders(chunk)}) AND updatedAt < ?`;
|
|
292
|
+
let messages = 0;
|
|
293
|
+
let hasMessagesTable = true;
|
|
294
|
+
for (const chunk of batches) {
|
|
295
|
+
try {
|
|
296
|
+
messages += d1Changes(await db
|
|
297
|
+
.prepare(`DELETE FROM ${prefix}mastra_messages
|
|
298
|
+
WHERE thread_id IN (${stillExpired(chunk)})
|
|
299
|
+
AND createdAt < ?`)
|
|
300
|
+
.bind(...chunk, cutoff, cutoff)
|
|
301
|
+
.run());
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
// A host whose memory domain never initialized has threads but no
|
|
305
|
+
// messages table; anything else is a real failure and must reach the
|
|
306
|
+
// cron's error surface rather than silently orphan a thread's history.
|
|
307
|
+
if (!isMissingTable(error))
|
|
308
|
+
throw error;
|
|
309
|
+
hasMessagesTable = false;
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
// The structural invariant: never delete a thread a message still points at
|
|
314
|
+
// (see the header — the writer's insert and its updatedAt bump are not atomic,
|
|
315
|
+
// so updatedAt alone cannot carry this). Dropped only when the table does not
|
|
316
|
+
// exist, where "no message points at it" is vacuously true and the subquery
|
|
317
|
+
// would throw instead.
|
|
318
|
+
const noMessagesLeft = hasMessagesTable
|
|
319
|
+
? ` AND NOT EXISTS (SELECT 1 FROM ${prefix}mastra_messages
|
|
320
|
+
WHERE thread_id = ${prefix}mastra_threads.id)`
|
|
321
|
+
: '';
|
|
322
|
+
let threads = 0;
|
|
323
|
+
for (const chunk of batches) {
|
|
324
|
+
threads += d1Changes(await db
|
|
325
|
+
.prepare(`DELETE FROM ${prefix}mastra_threads
|
|
326
|
+
WHERE id IN (${placeholders(chunk)}) AND updatedAt < ?${noMessagesLeft}`)
|
|
327
|
+
.bind(...chunk, cutoff)
|
|
328
|
+
.run());
|
|
329
|
+
}
|
|
330
|
+
return { threads, messages };
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* The table `purgeExpiredBackgroundTasks` deletes from under the background-task
|
|
334
|
+
* TTL — the production anchor the schema guard cross-checks the
|
|
335
|
+
* `background-task-ttl` retention declaration against (DL-003), the Track B
|
|
336
|
+
* analog of RUN_TTL_PURGE_TABLES. One table: the TTL rides `completedAt` on
|
|
337
|
+
* `mastra_background_tasks` alone, no cascade.
|
|
338
|
+
*/
|
|
339
|
+
export const BACKGROUND_TASK_TTL_PURGE_TABLES = [
|
|
340
|
+
'mastra_background_tasks',
|
|
341
|
+
];
|
|
342
|
+
/** Terminal statuses the failed-class TTL reaps together (core cleanup mirrors this set). */
|
|
343
|
+
const BACKGROUND_TASK_FAILED_STATUSES = [
|
|
344
|
+
'failed',
|
|
345
|
+
'cancelled',
|
|
346
|
+
'timed_out',
|
|
347
|
+
];
|
|
348
|
+
/**
|
|
349
|
+
* Background-task TTL cleanup (DL-003 retention leg): deletes terminal task
|
|
350
|
+
* rows from `mastra_background_tasks` once their `completedAt` is older than the
|
|
351
|
+
* TTL, mirroring core `BackgroundTaskManager.cleanup()` at the storage layer so
|
|
352
|
+
* a purge cron can reap them WITHOUT a live manager — the same posture as
|
|
353
|
+
* purgeExpiredWorkflowRuns/purgeExpiredThreads (raw D1 binding, failure-isolated
|
|
354
|
+
* as a cron duty). Two windows, exactly as core: completed rows expire fast
|
|
355
|
+
* (default 1h), failed/cancelled/timed_out slowly (default 24h) so a failure
|
|
356
|
+
* stays inspectable.
|
|
357
|
+
*
|
|
358
|
+
* `completedAt` is stored as ISO-8601 TEXT (`toISOString()`), so lexicographic
|
|
359
|
+
* `<` against an ISO cutoff is a correct timestamp comparison — the same bet the
|
|
360
|
+
* other purges take. `completedAt IS NOT NULL` is load-bearing: a row without a
|
|
361
|
+
* completion stamp cannot be proven old, so it survives (fail safe). Live rows
|
|
362
|
+
* (pending / running / suspended) are never matched — deleting a suspended task
|
|
363
|
+
* mid-flight would strand its resume. A missing table reads as zero (background
|
|
364
|
+
* tasks may never have run). Scheduling stays with the caller.
|
|
365
|
+
*/
|
|
366
|
+
export async function purgeExpiredBackgroundTasks(db, options = {}) {
|
|
367
|
+
const now = options.now ?? Date.now;
|
|
368
|
+
const prefix = options.tablePrefix ?? '';
|
|
369
|
+
const table = `${prefix}mastra_background_tasks`;
|
|
370
|
+
const completedCutoff = new Date(now() - (options.completedTtlMs ?? 3_600_000)).toISOString();
|
|
371
|
+
const failedCutoff = new Date(now() - (options.failedTtlMs ?? 86_400_000)).toISOString();
|
|
372
|
+
const failedPlaceholders = BACKGROUND_TASK_FAILED_STATUSES.map(() => '?').join(', ');
|
|
373
|
+
try {
|
|
374
|
+
// Internal evented-engine snapshots use the UNSALTED task id. Consume that
|
|
375
|
+
// association before deleting the task rows that make tenant/retention
|
|
376
|
+
// ownership discoverable.
|
|
377
|
+
try {
|
|
378
|
+
await db
|
|
379
|
+
.prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
|
|
380
|
+
WHERE workflow_name = '__background-task'
|
|
381
|
+
AND run_id IN (
|
|
382
|
+
SELECT id FROM ${table}
|
|
383
|
+
WHERE status = 'completed'
|
|
384
|
+
AND completedAt IS NOT NULL AND completedAt < ?
|
|
385
|
+
)`)
|
|
386
|
+
.bind(completedCutoff)
|
|
387
|
+
.run();
|
|
388
|
+
await db
|
|
389
|
+
.prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
|
|
390
|
+
WHERE workflow_name = '__background-task'
|
|
391
|
+
AND run_id IN (
|
|
392
|
+
SELECT id FROM ${table}
|
|
393
|
+
WHERE status IN (${failedPlaceholders})
|
|
394
|
+
AND completedAt IS NOT NULL AND completedAt < ?
|
|
395
|
+
)`)
|
|
396
|
+
.bind(...BACKGROUND_TASK_FAILED_STATUSES, failedCutoff)
|
|
397
|
+
.run();
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
// A deployment may have task rows before its workflow table is created;
|
|
401
|
+
// no associated snapshots can exist in that case.
|
|
402
|
+
if (!isMissingTable(error))
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
405
|
+
const completed = d1Changes(await db
|
|
406
|
+
.prepare(`DELETE FROM ${table}
|
|
407
|
+
WHERE status = 'completed'
|
|
408
|
+
AND completedAt IS NOT NULL AND completedAt < ?`)
|
|
409
|
+
.bind(completedCutoff)
|
|
410
|
+
.run());
|
|
411
|
+
const failed = d1Changes(await db
|
|
412
|
+
.prepare(`DELETE FROM ${table}
|
|
413
|
+
WHERE status IN (${failedPlaceholders})
|
|
414
|
+
AND completedAt IS NOT NULL AND completedAt < ?`)
|
|
415
|
+
.bind(...BACKGROUND_TASK_FAILED_STATUSES, failedCutoff)
|
|
416
|
+
.run());
|
|
417
|
+
return { completed, failed };
|
|
418
|
+
}
|
|
419
|
+
catch (error) {
|
|
420
|
+
if (!isMissingTable(error))
|
|
421
|
+
throw error;
|
|
422
|
+
return { completed: 0, failed: 0 };
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* The table `purgeExpiredNotifications` deletes from under the notification TTL
|
|
427
|
+
* — the anchor the schema guard cross-checks the `notification-ttl` retention
|
|
428
|
+
* declaration against (DL-003), the Track C analog of
|
|
429
|
+
* BACKGROUND_TASK_TTL_PURGE_TABLES.
|
|
430
|
+
*/
|
|
431
|
+
export const NOTIFICATION_TTL_PURGE_TABLES = [
|
|
432
|
+
'mastra_notifications',
|
|
433
|
+
];
|
|
434
|
+
/** Terminal notification statuses the TTL reaps (a delivered/seen/… inbox item is done). */
|
|
435
|
+
const NOTIFICATION_TERMINAL_STATUSES = [
|
|
436
|
+
'delivered',
|
|
437
|
+
'seen',
|
|
438
|
+
'dismissed',
|
|
439
|
+
'archived',
|
|
440
|
+
'discarded',
|
|
441
|
+
];
|
|
442
|
+
/**
|
|
443
|
+
* Notification TTL cleanup (DL-003 retention leg): deletes TERMINAL agent-inbox
|
|
444
|
+
* rows from `mastra_notifications` once their `updatedAt` is older than the TTL,
|
|
445
|
+
* at the storage layer so a cron reaps them without a live agent — the same
|
|
446
|
+
* posture as the other purges (raw D1 binding, failure-isolated as a cron duty).
|
|
447
|
+
* `updatedAt` is ISO-8601 TEXT, so lexicographic `<` is a correct timestamp
|
|
448
|
+
* comparison. A missing table reads as zero (notifications may never have been
|
|
449
|
+
* sent). Scheduling stays with the caller.
|
|
450
|
+
*/
|
|
451
|
+
export async function purgeExpiredNotifications(db, options) {
|
|
452
|
+
const now = options.now ?? Date.now;
|
|
453
|
+
const prefix = options.tablePrefix ?? '';
|
|
454
|
+
const cutoff = new Date(now() - options.ttlMs).toISOString();
|
|
455
|
+
const placeholders = NOTIFICATION_TERMINAL_STATUSES.map(() => '?').join(', ');
|
|
456
|
+
try {
|
|
457
|
+
return d1Changes(await db
|
|
458
|
+
.prepare(`DELETE FROM ${prefix}mastra_notifications
|
|
459
|
+
WHERE status IN (${placeholders}) AND updatedAt < ?`)
|
|
460
|
+
.bind(...NOTIFICATION_TERMINAL_STATUSES, cutoff)
|
|
461
|
+
.run());
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
if (!isMissingTable(error))
|
|
465
|
+
throw error;
|
|
466
|
+
return 0;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* The table `purgeExpiredThreadState` deletes from under the thread-state TTL —
|
|
471
|
+
* the anchor the schema guard cross-checks the `thread-state-ttl` retention
|
|
472
|
+
* declaration against (DL-003).
|
|
473
|
+
*/
|
|
474
|
+
export const THREAD_STATE_TTL_PURGE_TABLES = [
|
|
475
|
+
'mastra_thread_state',
|
|
476
|
+
];
|
|
477
|
+
/**
|
|
478
|
+
* Thread-state TTL cleanup (DL-003 retention leg): deletes thread-state rows
|
|
479
|
+
* from `mastra_thread_state` once their `updatedAt` is older than the TTL. Keys
|
|
480
|
+
* on `updatedAt` for the same reason `purgeExpiredThreads` does — thread state
|
|
481
|
+
* has no terminal status, so time-since-last-write is the only "done" signal.
|
|
482
|
+
* ISO-8601 TEXT encoding; missing table reads as zero; scheduling stays with the
|
|
483
|
+
* caller. Independent of the thread TTL (an orphan row is reaped here or at
|
|
484
|
+
* offboarding by purgeTenant), so it self-bounds without touching the delicate
|
|
485
|
+
* messages-before-threads ordering of purgeExpiredThreads.
|
|
486
|
+
*/
|
|
487
|
+
export async function purgeExpiredThreadState(db, options) {
|
|
488
|
+
const now = options.now ?? Date.now;
|
|
489
|
+
const prefix = options.tablePrefix ?? '';
|
|
490
|
+
const cutoff = new Date(now() - options.ttlMs).toISOString();
|
|
491
|
+
try {
|
|
492
|
+
return d1Changes(await db
|
|
493
|
+
.prepare(`DELETE FROM ${prefix}mastra_thread_state WHERE updatedAt < ?`)
|
|
494
|
+
.bind(cutoff)
|
|
495
|
+
.run());
|
|
496
|
+
}
|
|
497
|
+
catch (error) {
|
|
498
|
+
if (!isMissingTable(error))
|
|
499
|
+
throw error;
|
|
500
|
+
return 0;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* The table `purgeExpiredScheduleTriggers` deletes from under the trigger-row TTL
|
|
505
|
+
* — the anchor the schema guard cross-checks the `schedule-trigger-ttl` retention
|
|
506
|
+
* declaration against (DL-003), the Track D analog of THREAD_STATE_TTL_PURGE_TABLES.
|
|
507
|
+
* Only the trigger HISTORY expires; the schedule rows themselves are standing
|
|
508
|
+
* config (retention 'none', reaped at offboarding by purgeTenant).
|
|
509
|
+
*/
|
|
510
|
+
export const SCHEDULE_TRIGGER_TTL_PURGE_TABLES = [
|
|
511
|
+
'mastra_schedule_triggers',
|
|
512
|
+
];
|
|
513
|
+
/**
|
|
514
|
+
* Schedule-trigger TTL cleanup (DL-003 retention leg): deletes trigger-history
|
|
515
|
+
* rows from `mastra_schedule_triggers` once their `actualFireAt` is older than the
|
|
516
|
+
* TTL, at the storage layer so a cron reaps them without a live tick — the same
|
|
517
|
+
* posture as the other purges (raw D1 binding, failure-isolated as a cron duty).
|
|
518
|
+
*
|
|
519
|
+
* `actualFireAt` is stored as INTEGER ms-epoch (core types
|
|
520
|
+
* `ScheduleTrigger.actualFireAt` as `number`, unlike the ISO-TEXT timestamp
|
|
521
|
+
* columns the other domains use), so the comparison is a NUMERIC `<` against a
|
|
522
|
+
* numeric cutoff — a correct timestamp comparison over integers. A missing table
|
|
523
|
+
* reads as zero (schedules may never have fired). Scheduling stays with the
|
|
524
|
+
* caller. Deleting trigger history never touches a live schedule (its own row is
|
|
525
|
+
* in `mastra_schedules`), so there is no ordering constraint.
|
|
526
|
+
*/
|
|
527
|
+
export async function purgeExpiredScheduleTriggers(db, options) {
|
|
528
|
+
const now = options.now ?? Date.now;
|
|
529
|
+
const prefix = options.tablePrefix ?? '';
|
|
530
|
+
const cutoff = now() - options.ttlMs;
|
|
531
|
+
try {
|
|
532
|
+
return d1Changes(await db
|
|
533
|
+
.prepare(`DELETE FROM ${prefix}mastra_schedule_triggers WHERE actualFireAt < ?`)
|
|
534
|
+
.bind(cutoff)
|
|
535
|
+
.run());
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
if (!isMissingTable(error))
|
|
539
|
+
throw error;
|
|
540
|
+
return 0;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
146
543
|
// One CREATE INDEX per (database, prefix) per isolate: purgeTenant runs this,
|
|
147
544
|
// and the demo reaper invokes purgeTenant in a LIMIT-batched loop — without
|
|
148
545
|
// the memo that is one DDL round-trip to the D1 primary per tenant per cron
|
|
@@ -178,6 +575,58 @@ export async function ensureSnapshotRunIdIndex(db, tablePrefix = '') {
|
|
|
178
575
|
}
|
|
179
576
|
await ready;
|
|
180
577
|
}
|
|
578
|
+
/**
|
|
579
|
+
* The tenant-range purge inventory — EXTENSIBLE by construction (DL-003): each
|
|
580
|
+
* later track appends its adopted table here instead of editing purgeTenant's
|
|
581
|
+
* body, so adoption is one additive row plus the counter/result pair the types
|
|
582
|
+
* force alongside it. Ordering is not load-bearing (the deletes run
|
|
583
|
+
* concurrently; see purgeTenant).
|
|
584
|
+
*
|
|
585
|
+
* `mastra_workflow_snapshot` is deliberately absent: it rides the same range but
|
|
586
|
+
* over `run_id`, paired with artifact deletion and an app-owned index, so it
|
|
587
|
+
* keeps its own block. `mastra_background_tasks` (Track B) rides the range over
|
|
588
|
+
* its own `run_id` — the originating run's INV-1 salted id, always present on a
|
|
589
|
+
* task row — without artifacts or an app index, so it lives here. Tables no
|
|
590
|
+
* feature writes yet (`mastra_scorers`) are absent because nothing salts their
|
|
591
|
+
* ids yet — the schema-guard's inventory pin is what forces that decision when a
|
|
592
|
+
* track adopts one.
|
|
593
|
+
*/
|
|
594
|
+
export const TENANT_RANGE_PURGE_TABLES = [
|
|
595
|
+
{ counter: 'messages', table: 'mastra_messages', column: 'thread_id' },
|
|
596
|
+
{ counter: 'threads', table: 'mastra_threads', column: 'id' },
|
|
597
|
+
{ counter: 'resources', table: 'mastra_resources', column: 'id' },
|
|
598
|
+
{
|
|
599
|
+
counter: 'backgroundTasks',
|
|
600
|
+
table: 'mastra_background_tasks',
|
|
601
|
+
column: 'run_id',
|
|
602
|
+
},
|
|
603
|
+
// Track C — both thread-keyed: their `thread_id` holds the salted memory
|
|
604
|
+
// threadId (`${tenantId}_${uuid}`), so the same exact range applies.
|
|
605
|
+
{
|
|
606
|
+
counter: 'notifications',
|
|
607
|
+
table: 'mastra_notifications',
|
|
608
|
+
column: 'thread_id',
|
|
609
|
+
},
|
|
610
|
+
{
|
|
611
|
+
counter: 'threadState',
|
|
612
|
+
table: 'mastra_thread_state',
|
|
613
|
+
column: 'thread_id',
|
|
614
|
+
},
|
|
615
|
+
];
|
|
616
|
+
/**
|
|
617
|
+
* The metadata-filtered purge inventory (DL-003) — the offboarding coverage for
|
|
618
|
+
* tables whose tenant is a JSON `metadata.tenantId` (stamped by the schedules
|
|
619
|
+
* facade at create + the tick on every trigger), not a salted id column. Both
|
|
620
|
+
* Track D tables are here: schedule rows and their trigger history. The DELETE is
|
|
621
|
+
* `WHERE json_extract(metadata, '$.tenantId') = ?` (the same SQLite json_extract
|
|
622
|
+
* the run-snapshot purge already uses on `snapshot`), so a NULL/absent metadata
|
|
623
|
+
* never matches — every row our facade/tick writes carries it, so this reaps them
|
|
624
|
+
* all. Ordering is not load-bearing (deletes run concurrently; see purgeTenant).
|
|
625
|
+
*/
|
|
626
|
+
export const TENANT_METADATA_PURGE_TABLES = [
|
|
627
|
+
{ counter: 'schedules', table: 'mastra_schedules' },
|
|
628
|
+
{ counter: 'scheduleTriggers', table: 'mastra_schedule_triggers' },
|
|
629
|
+
];
|
|
181
630
|
/**
|
|
182
631
|
* Complete tenant offboarding: reaps EVERY tenant-keyed store — snapshot
|
|
183
632
|
* rows of ANY status (a tenant's suspended-and-abandoned runs are never
|
|
@@ -216,6 +665,19 @@ export async function purgeTenant(db, options) {
|
|
|
216
665
|
const prefix = options.tablePrefix ?? '';
|
|
217
666
|
const lower = `${tenantId}_`;
|
|
218
667
|
const upper = `${tenantId}\x60`;
|
|
668
|
+
let backgroundTaskIds = [];
|
|
669
|
+
try {
|
|
670
|
+
const { results } = await db
|
|
671
|
+
.prepare(`SELECT id FROM ${prefix}mastra_background_tasks
|
|
672
|
+
WHERE run_id >= ? AND run_id < ?`)
|
|
673
|
+
.bind(lower, upper)
|
|
674
|
+
.all();
|
|
675
|
+
backgroundTaskIds = results.map((row) => row.id);
|
|
676
|
+
}
|
|
677
|
+
catch (error) {
|
|
678
|
+
if (!isMissingTable(error))
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
219
681
|
// The snapshot table exists only once Mastra lazily creates it for the
|
|
220
682
|
// first persisted run. A tenant that never started one — routine for an
|
|
221
683
|
// expired demo sandbox — has zero snapshots and artifacts, and its
|
|
@@ -242,7 +704,25 @@ export async function purgeTenant(db, options) {
|
|
|
242
704
|
WHERE run_id >= ? AND run_id < ?`)
|
|
243
705
|
.bind(lower, upper)
|
|
244
706
|
.all();
|
|
245
|
-
|
|
707
|
+
const artifactRows = [...results];
|
|
708
|
+
for (const ids of chunked(backgroundTaskIds, D1_BIND_CHUNK)) {
|
|
709
|
+
if (ids.length === 0)
|
|
710
|
+
continue;
|
|
711
|
+
const associated = await db
|
|
712
|
+
.prepare(`SELECT workflow_name, run_id
|
|
713
|
+
FROM ${prefix}mastra_workflow_snapshot
|
|
714
|
+
WHERE workflow_name = '__background-task'
|
|
715
|
+
AND run_id IN (${ids.map(() => '?').join(', ')})`)
|
|
716
|
+
.bind(...ids)
|
|
717
|
+
.all();
|
|
718
|
+
artifactRows.push(...associated.results);
|
|
719
|
+
}
|
|
720
|
+
const seen = new Set();
|
|
721
|
+
for (const row of artifactRows) {
|
|
722
|
+
const key = `${row.workflow_name}\0${row.run_id}`;
|
|
723
|
+
if (seen.has(key))
|
|
724
|
+
continue;
|
|
725
|
+
seen.add(key);
|
|
246
726
|
artifacts += await options.artifactStore.deleteRun(row.workflow_name, row.run_id);
|
|
247
727
|
}
|
|
248
728
|
}
|
|
@@ -252,11 +732,22 @@ export async function purgeTenant(db, options) {
|
|
|
252
732
|
WHERE run_id >= ? AND run_id < ?`)
|
|
253
733
|
.bind(lower, upper)
|
|
254
734
|
.run());
|
|
735
|
+
for (const ids of chunked(backgroundTaskIds, D1_BIND_CHUNK)) {
|
|
736
|
+
if (ids.length === 0)
|
|
737
|
+
continue;
|
|
738
|
+
snapshots += d1Changes(await db
|
|
739
|
+
.prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
|
|
740
|
+
WHERE workflow_name = '__background-task'
|
|
741
|
+
AND run_id IN (${ids.map(() => '?').join(', ')})`)
|
|
742
|
+
.bind(...ids)
|
|
743
|
+
.run());
|
|
744
|
+
}
|
|
255
745
|
}
|
|
256
|
-
// 3.
|
|
746
|
+
// 3. Every tenant-range table (TENANT_RANGE_PURGE_TABLES — today the
|
|
747
|
+
// agent-memory rows) — the SAME exact range, over the salted ids the
|
|
257
748
|
// memory-id chokepoint mints (threads/resources by id, messages by their
|
|
258
749
|
// NOT-NULL thread_id; message ids themselves are unsalted by design). The
|
|
259
|
-
//
|
|
750
|
+
// DELETEs run concurrently via Promise.all — child-before-parent order is
|
|
260
751
|
// non-load-bearing (messages range on their own thread_id column, Mastra
|
|
261
752
|
// declares no FK, every table independently re-sweepable after a mid-purge
|
|
262
753
|
// failure in any order), the memory[counter] writes hit distinct keys so
|
|
@@ -265,13 +756,15 @@ export async function purgeTenant(db, options) {
|
|
|
265
756
|
// table reads as empty — the tables exist wherever createD1Storage ran
|
|
266
757
|
// (eager creation), but crafted test databases and non-D1Store hosts may
|
|
267
758
|
// not have them.
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
759
|
+
const memory = {
|
|
760
|
+
threads: 0,
|
|
761
|
+
messages: 0,
|
|
762
|
+
resources: 0,
|
|
763
|
+
backgroundTasks: 0,
|
|
764
|
+
notifications: 0,
|
|
765
|
+
threadState: 0,
|
|
766
|
+
};
|
|
767
|
+
await Promise.all(TENANT_RANGE_PURGE_TABLES.filter(({ counter }) => counter !== 'backgroundTasks').map(async ({ counter, table, column }) => {
|
|
275
768
|
try {
|
|
276
769
|
memory[counter] = d1Changes(await db
|
|
277
770
|
.prepare(`DELETE FROM ${prefix}${table} WHERE ${column} >= ? AND ${column} < ?`)
|
|
@@ -283,6 +776,41 @@ export async function purgeTenant(db, options) {
|
|
|
283
776
|
throw error;
|
|
284
777
|
}
|
|
285
778
|
}));
|
|
779
|
+
// The task row is the only durable association between its salted parent run
|
|
780
|
+
// and the unsalted __background-task snapshot. Delete it only after the
|
|
781
|
+
// associated snapshots/artifacts above have been consumed.
|
|
782
|
+
try {
|
|
783
|
+
memory.backgroundTasks = d1Changes(await db
|
|
784
|
+
.prepare(`DELETE FROM ${prefix}mastra_background_tasks
|
|
785
|
+
WHERE run_id >= ? AND run_id < ?`)
|
|
786
|
+
.bind(lower, upper)
|
|
787
|
+
.run());
|
|
788
|
+
}
|
|
789
|
+
catch (error) {
|
|
790
|
+
if (!isMissingTable(error))
|
|
791
|
+
throw error;
|
|
792
|
+
}
|
|
793
|
+
// 3b. Metadata-filtered tables (Track D schedules + triggers): their tenant is
|
|
794
|
+
// a JSON metadata.tenantId, not a salted id, so they cannot ride the range
|
|
795
|
+
// above. Same posture — concurrent deletes, per-table missing-table tolerance,
|
|
796
|
+
// a first real error still rejects. json_extract on a NULL metadata yields NULL
|
|
797
|
+
// and matches nothing (a row our facade/tick never wrote).
|
|
798
|
+
const metadataCounts = {
|
|
799
|
+
schedules: 0,
|
|
800
|
+
scheduleTriggers: 0,
|
|
801
|
+
};
|
|
802
|
+
await Promise.all(TENANT_METADATA_PURGE_TABLES.map(async ({ counter, table }) => {
|
|
803
|
+
try {
|
|
804
|
+
metadataCounts[counter] = d1Changes(await db
|
|
805
|
+
.prepare(`DELETE FROM ${prefix}${table} WHERE json_extract(metadata, '$.tenantId') = ?`)
|
|
806
|
+
.bind(tenantId)
|
|
807
|
+
.run());
|
|
808
|
+
}
|
|
809
|
+
catch (error) {
|
|
810
|
+
if (!isMissingTable(error))
|
|
811
|
+
throw error;
|
|
812
|
+
}
|
|
813
|
+
}));
|
|
286
814
|
// 4. Approvals — by the tenant_id column. Hosts without the approval queue
|
|
287
815
|
// have no such table; a missing table is the only tolerated failure.
|
|
288
816
|
let approvals = 0;
|
|
@@ -296,7 +824,32 @@ export async function purgeTenant(db, options) {
|
|
|
296
824
|
if (!isMissingTable(error))
|
|
297
825
|
throw error;
|
|
298
826
|
}
|
|
299
|
-
|
|
827
|
+
// 5. Signal subscriptions (Track E) — the same flowsafe-owned tenant_id-column
|
|
828
|
+
// delete as approvals (NOT a mastra_* table, so not in the ranged/metadata
|
|
829
|
+
// inventories above; retention is 'none' — standing config reaped only here).
|
|
830
|
+
// The table name is the literal signal-providers/subscription-d1.ts owns
|
|
831
|
+
// (SIGNAL_SUBSCRIPTIONS_TABLE); a do-runner import of signals/signal-providers
|
|
832
|
+
// would cycle, so it is hardcoded like flowsafe_approvals. Missing table (a
|
|
833
|
+
// host with no signal providers) is the only tolerated failure.
|
|
834
|
+
let subscriptions = 0;
|
|
835
|
+
try {
|
|
836
|
+
subscriptions = d1Changes(await db
|
|
837
|
+
.prepare('DELETE FROM flowsafe_signal_subscriptions WHERE tenant_id = ?')
|
|
838
|
+
.bind(tenantId)
|
|
839
|
+
.run());
|
|
840
|
+
}
|
|
841
|
+
catch (error) {
|
|
842
|
+
if (!isMissingTable(error))
|
|
843
|
+
throw error;
|
|
844
|
+
}
|
|
845
|
+
return {
|
|
846
|
+
snapshots,
|
|
847
|
+
...memory,
|
|
848
|
+
...metadataCounts,
|
|
849
|
+
approvals,
|
|
850
|
+
subscriptions,
|
|
851
|
+
artifacts,
|
|
852
|
+
};
|
|
300
853
|
}
|
|
301
854
|
/** Rows affected by a D1 write, read from its `{ meta: { changes } }` envelope. */
|
|
302
855
|
export function d1Changes(result) {
|