@proofoftech/flowsafe 0.20.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.
- package/CHANGELOG.md +81 -0
- package/README.md +55 -8
- package/deployment-identity-protocol.d.mts +28 -3
- package/deployment-identity-protocol.mjs +275 -21
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +11 -2
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +3 -1
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +837 -332
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +8 -0
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +239 -62
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +90 -6
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +371 -29
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/agent-runner/index.d.ts +1 -1
- package/dist/agent-runner/index.d.ts.map +1 -1
- package/dist/agent-runner/index.js.map +1 -1
- package/dist/approval-api/actor-context.d.ts +4 -0
- package/dist/approval-api/actor-context.d.ts.map +1 -1
- package/dist/approval-api/actor-context.js +53 -5
- package/dist/approval-api/actor-context.js.map +1 -1
- package/dist/approval-api/principal.d.ts +1 -1
- package/dist/approval-api/principal.js +1 -1
- package/dist/approval-api/retention.d.ts +1 -2
- package/dist/approval-api/retention.d.ts.map +1 -1
- package/dist/approval-api/retention.js.map +1 -1
- package/dist/approval-api/service.d.ts +10 -14
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +49 -22
- package/dist/approval-api/service.js.map +1 -1
- package/dist/audit-export/index.d.ts +2 -2
- package/dist/audit-export/index.js +2 -2
- package/dist/background-tasks/d1-storage.d.ts +4 -3
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +7 -13
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/do-runner/constants.d.ts +3 -0
- package/dist/do-runner/constants.d.ts.map +1 -0
- package/dist/do-runner/constants.js +3 -0
- package/dist/do-runner/constants.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +31 -157
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +933 -402
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +462 -175
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-admission.d.ts +114 -0
- package/dist/do-runner/execution-admission.d.ts.map +1 -0
- package/dist/do-runner/execution-admission.js +206 -0
- package/dist/do-runner/execution-admission.js.map +1 -0
- package/dist/do-runner/execution-context.d.ts.map +1 -1
- package/dist/do-runner/execution-context.js +1 -0
- package/dist/do-runner/execution-context.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +74 -30
- package/dist/do-runner/execution-fence.d.ts.map +1 -1
- package/dist/do-runner/execution-fence.js +684 -120
- package/dist/do-runner/execution-fence.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflow-capability.js +3 -0
- package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.js +894 -0
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
- package/dist/do-runner/index.d.ts +13 -8
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +6 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
- package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
- package/dist/do-runner/initial-admission-refusal.js +41 -0
- package/dist/do-runner/initial-admission-refusal.js.map +1 -0
- package/dist/do-runner/inventory.d.ts +2 -1
- package/dist/do-runner/inventory.d.ts.map +1 -1
- package/dist/do-runner/inventory.js +28 -39
- package/dist/do-runner/inventory.js.map +1 -1
- package/dist/do-runner/notification-predicate.d.ts +7 -7
- package/dist/do-runner/notification-predicate.d.ts.map +1 -1
- package/dist/do-runner/notification-predicate.js +134 -7
- package/dist/do-runner/notification-predicate.js.map +1 -1
- package/dist/do-runner/run-lifecycle.d.ts +20 -1
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +67 -13
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-provenance.d.ts +38 -0
- package/dist/do-runner/run-provenance.d.ts.map +1 -0
- package/dist/do-runner/run-provenance.js +152 -0
- package/dist/do-runner/run-provenance.js.map +1 -0
- package/dist/do-runner/run-storage-tables.d.ts +2 -0
- package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
- package/dist/do-runner/run-storage-tables.js +4 -0
- package/dist/do-runner/run-storage-tables.js.map +1 -0
- package/dist/do-runner/run-terminal-state.d.ts +29 -0
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
- package/dist/do-runner/run-terminal-state.js +105 -0
- package/dist/do-runner/run-terminal-state.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +108 -46
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +927 -438
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +35 -258
- package/dist/do-runner/start-idempotency.d.ts.map +1 -1
- package/dist/do-runner/start-idempotency.js +602 -494
- package/dist/do-runner/start-idempotency.js.map +1 -1
- package/dist/do-runner/start-reservation-contract.d.ts +103 -0
- package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
- package/dist/do-runner/start-reservation-contract.js +338 -0
- package/dist/do-runner/start-reservation-contract.js.map +1 -0
- package/dist/do-runner/suspension-deadline.d.ts +4 -11
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +8 -12
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/table-prefix.d.ts.map +1 -1
- package/dist/do-runner/table-prefix.js +2 -1
- package/dist/do-runner/table-prefix.js.map +1 -1
- package/dist/do-runner/testing.d.ts +3 -0
- package/dist/do-runner/testing.d.ts.map +1 -0
- package/dist/do-runner/testing.js +3 -0
- package/dist/do-runner/testing.js.map +1 -0
- package/dist/do-runner/thread-do.d.ts +2 -1
- package/dist/do-runner/thread-do.d.ts.map +1 -1
- package/dist/do-runner/thread-do.js +14 -10
- package/dist/do-runner/thread-do.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
- package/dist/do-runner/workflow-snapshot-row.js +97 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +1 -5
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +32 -53
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +10 -7
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts +16 -0
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +181 -0
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +2 -14
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +31 -24
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +5 -6
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +38 -6
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +110 -93
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +4 -14
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +23 -40
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +7 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +4 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +3 -17
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +4 -24
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +6 -2
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +93 -80
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/thread-topology.d.ts +1 -1
- package/dist/host-kit/thread-topology.d.ts.map +1 -1
- package/dist/host-kit/thread-topology.js +7 -3
- package/dist/host-kit/thread-topology.js.map +1 -1
- package/dist/internal-error-response.d.ts.map +1 -1
- package/dist/internal-error-response.js +16 -6
- package/dist/internal-error-response.js.map +1 -1
- package/dist/schedules/index.d.ts +1 -0
- package/dist/schedules/index.d.ts.map +1 -1
- package/dist/schedules/index.js +1 -7
- package/dist/schedules/index.js.map +1 -1
- package/dist/schedules/mutation-contract.d.ts +38 -0
- package/dist/schedules/mutation-contract.d.ts.map +1 -0
- package/dist/schedules/mutation-contract.js +21 -0
- package/dist/schedules/mutation-contract.js.map +1 -0
- package/dist/schedules/router.d.ts +11 -19
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +130 -49
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/schedules-d1.d.ts +11 -5
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +570 -143
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/storage.d.ts +0 -7
- package/dist/schedules/storage.d.ts.map +1 -1
- package/dist/schedules/storage.js +0 -27
- package/dist/schedules/storage.js.map +1 -1
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +7 -1
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +1 -1
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +99 -109
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/d1-shared.d.ts +11 -8
- package/dist/signals/d1-shared.d.ts.map +1 -1
- package/dist/signals/d1-shared.js +1 -6
- package/dist/signals/d1-shared.js.map +1 -1
- package/dist/signals/index.d.ts +1 -1
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +1 -1
- package/dist/signals/index.js.map +1 -1
- package/dist/signals/notification-dispatch.d.ts +96 -5
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +418 -53
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +6 -1
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +215 -10
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/router.d.ts +6 -4
- package/dist/signals/router.d.ts.map +1 -1
- package/dist/signals/router.js +49 -84
- package/dist/signals/router.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +2 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +252 -73
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +6 -3
- package/patches/@mastra__core@1.53.0.patch +54 -0
- package/scripts/seed-deployment-identity.mjs +12 -5
|
@@ -6,46 +6,70 @@
|
|
|
6
6
|
// to `new Mastra({ storage })` — no migration step needed for the runner.
|
|
7
7
|
import { D1Store } from '@mastra/cloudflare-d1';
|
|
8
8
|
import { MastraCompositeStore, } from '@mastra/core/storage';
|
|
9
|
+
import { missingTableReadsEmpty } from './cause-chain.js';
|
|
10
|
+
import { normalizeD1RunExecutionIdentity, normalizeStartExecutionIdentity, } from './execution-admission.js';
|
|
11
|
+
import { FencedWorkflowsStorageD1 } from './fenced-workflows-d1.js';
|
|
12
|
+
import { notificationTimestampMillis, notificationTimestampSql, } from './notification-predicate.js';
|
|
9
13
|
import { isPathSafeId } from './path-safe-id.js';
|
|
14
|
+
import { decodeRunStartIdentity, runExecutionIdentityFor, } from './run-provenance.js';
|
|
15
|
+
import { RESOURCE_OWNER_TABLE } from './run-storage-tables.js';
|
|
10
16
|
import { START_IDEMPOTENCY_TABLE } from './start-idempotency.js';
|
|
17
|
+
import { admissionReservationFromRow, reservationFromRow, reservationSchemaStage, START_IDEMPOTENCY_COLUMNS, } from './start-reservation-contract.js';
|
|
11
18
|
import { validateTablePrefix } from './table-prefix.js';
|
|
19
|
+
import { decodeRawWorkflowSnapshotResult, prepareRawWorkflowSnapshotRead, snapshotResultRows, } from './workflow-snapshot-row.js';
|
|
20
|
+
export { RESOURCE_OWNER_TABLE } from './run-storage-tables.js';
|
|
12
21
|
export function createD1Storage(options) {
|
|
13
|
-
const tablePrefix =
|
|
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
|
+
};
|
|
14
55
|
const d1 = new D1Store({
|
|
15
|
-
id
|
|
56
|
+
id,
|
|
16
57
|
// @mastra/cloudflare-d1's own D1Store signature wants the real
|
|
17
58
|
// D1Database; D1DatabaseBinding is the structural subset this package
|
|
18
59
|
// exposes instead, so consumers of its shipped types don't need
|
|
19
60
|
// @cloudflare/workers-types installed.
|
|
20
|
-
|
|
21
|
-
...(tablePrefix !== undefined ? { tablePrefix } : {}),
|
|
61
|
+
...domainConfig,
|
|
22
62
|
});
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
// (all adapter tables, DDL ordering, coalesced callers) runs first via the
|
|
27
|
-
// parentDefault path, THEN each override domain's init() — the composite never
|
|
28
|
-
// double-inits a parent's domain (validated: chunk #runInit).
|
|
29
|
-
if (!options.domains)
|
|
30
|
-
return d1;
|
|
63
|
+
const workflows = suppliedWorkflows === undefined
|
|
64
|
+
? new FencedWorkflowsStorageD1(domainConfig)
|
|
65
|
+
: suppliedWorkflows;
|
|
31
66
|
return new MastraCompositeStore({
|
|
32
|
-
id
|
|
67
|
+
id,
|
|
33
68
|
default: d1,
|
|
34
|
-
domains:
|
|
69
|
+
domains: { ...otherDomains, workflows },
|
|
35
70
|
});
|
|
36
71
|
}
|
|
37
|
-
/**
|
|
38
|
-
* Mastra workflow terminals plus FlowSafe's lifecycle-owned terminals.
|
|
39
|
-
* Deleting a live run (running/suspended/waiting/pending/paused) would kill a
|
|
40
|
-
* pending approval, so only these are ever purged.
|
|
41
|
-
*
|
|
42
|
-
* Exported because retention and the drain inventory must agree on the word
|
|
43
|
-
* "terminal" to the letter. The purge deletes what this set matches; the
|
|
44
|
-
* inventory counts what it does NOT, and a run that is terminal to one and live
|
|
45
|
-
* to the other is either a row the purge reaps while the inventory still calls
|
|
46
|
-
* it work, or — worse — a run the inventory declares finished while it is still
|
|
47
|
-
* executing, which is exactly the reading a migration would act on.
|
|
48
|
-
*/
|
|
72
|
+
/** Shared with the drain inventory so cleanup and liveness use the same vocabulary. */
|
|
49
73
|
export const RUN_TERMINAL_STATUSES = [
|
|
50
74
|
'success',
|
|
51
75
|
'failed',
|
|
@@ -56,27 +80,23 @@ export const RUN_TERMINAL_STATUSES = [
|
|
|
56
80
|
'cancelled',
|
|
57
81
|
'timed_out',
|
|
58
82
|
];
|
|
59
|
-
/**
|
|
60
|
-
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* terminal
|
|
66
|
-
|
|
67
|
-
* that carve-out are two chances for one of them to answer "finished" for a run
|
|
68
|
-
* that is mid-cleanup — the retention purge would delete a live run's snapshot,
|
|
69
|
-
* and the drain inventory would report a deployment empty while it still runs
|
|
70
|
-
* work. The caller supplies the `json_valid` guard, because it decides which
|
|
71
|
-
* way an unclassifiable row should fail.
|
|
72
|
-
*/
|
|
73
|
-
export const RUN_TERMINAL_SNAPSHOT_SQL = `json_extract(snapshot, '$.status') IN (${RUN_TERMINAL_STATUSES.map(() => '?').join(', ')})
|
|
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(', ')})
|
|
74
91
|
AND (
|
|
75
92
|
json_extract(snapshot, '$.status') NOT IN ('cancelled', 'timed_out')
|
|
76
|
-
OR
|
|
77
|
-
snapshot,
|
|
78
|
-
'$.requestContext."flowsafe.runLifecycle".terminal.cleanupCompletedAt'
|
|
79
|
-
|
|
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
|
+
)
|
|
80
100
|
)`;
|
|
81
101
|
const DEADLINE_LIVE_STATUSES = [
|
|
82
102
|
'running',
|
|
@@ -218,394 +238,901 @@ export async function sweepExpiredRunDeadlines(db, options) {
|
|
|
218
238
|
}
|
|
219
239
|
return processed;
|
|
220
240
|
}
|
|
221
|
-
/**
|
|
222
|
-
* The MASTRA-OWNED tables `purgeExpiredWorkflowRuns` deletes from under the run
|
|
223
|
-
* TTL — the production anchor the schema guard cross-checks every `run-ttl`
|
|
224
|
-
* retention declaration against. The guard reads THIS, not a literal copied
|
|
225
|
-
* into the test, so a purge that changes what it targets and a guard that still
|
|
226
|
-
* blesses the old set cannot drift apart silently.
|
|
227
|
-
*
|
|
228
|
-
* Mastra-owned specifically: the purge ALSO deletes from flowsafe's own
|
|
229
|
-
* registries when a caller wires them, and those live in
|
|
230
|
-
* RUN_TTL_FLOWSAFE_PURGE_TABLES below rather than here — see its note for why
|
|
231
|
-
* the two sets are not one.
|
|
232
|
-
*/
|
|
233
241
|
export const RUN_TTL_PURGE_TABLES = [
|
|
234
242
|
'mastra_workflow_snapshot',
|
|
235
243
|
];
|
|
236
|
-
/**
|
|
237
|
-
* The resource-ownership registry's table, named here rather than imported from
|
|
238
|
-
* the store that creates it (approval-api/resource-ownership.ts).
|
|
239
|
-
*
|
|
240
|
-
* The layering forbids the import: do-runner may reach approval-api only
|
|
241
|
-
* through its declared leaves, and the ownership store is not one — it is built
|
|
242
|
-
* ON do-runner. So this file has always carried the name as a literal inside
|
|
243
|
-
* RUN_TTL_FLOWSAFE_PURGE_TABLES; giving it a name adds no second home, it names
|
|
244
|
-
* the one that was already here, and lets the drain inventory read the registry
|
|
245
|
-
* without a third copy. The census test crosses it against
|
|
246
|
-
* RESOURCE_OWNERSHIP_TABLE, which is the only place the two can be compared.
|
|
247
|
-
*/
|
|
248
|
-
export const RESOURCE_OWNER_TABLE = 'flowsafe_resource_owners';
|
|
249
|
-
/**
|
|
250
|
-
* The FLOWSAFE-owned tables this purge also deletes from when the caller wires
|
|
251
|
-
* them, and the reason they are not in the list above.
|
|
252
|
-
*
|
|
253
|
-
* `RUN_TTL_PURGE_TABLES` is cross-checked against the `mastra_%` inventory in
|
|
254
|
-
* mastra-schema-guard.test.ts — its job is to catch a @mastra/core bump that
|
|
255
|
-
* changes what run retention targets. These two are ours, they are optional
|
|
256
|
-
* (a lower-level caller without the registries omits both), and they are
|
|
257
|
-
* deleted on a DIFFERENT predicate: `flowsafe_resource_owners` when its run's
|
|
258
|
-
* last snapshot is gone, `flowsafe_start_idempotency` when its reservation is
|
|
259
|
-
* settled AND past the key-validity horizon. Folding them into the Mastra
|
|
260
|
-
* anchor would make that guard assert an equality it cannot mean.
|
|
261
|
-
*/
|
|
262
244
|
export const RUN_TTL_FLOWSAFE_PURGE_TABLES = [
|
|
263
245
|
RESOURCE_OWNER_TABLE,
|
|
264
246
|
START_IDEMPOTENCY_TABLE,
|
|
265
247
|
];
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
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;
|
|
368
497
|
}
|
|
369
|
-
const
|
|
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
|
+
});
|
|
370
512
|
return [
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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
|
+
],
|
|
381
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
|
+
}),
|
|
382
586
|
};
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
* not guarantee.
|
|
401
|
-
*/
|
|
402
|
-
/**
|
|
403
|
-
* Run a snapshot-delete batch, retrying once without the reservation
|
|
404
|
-
* statements if the reservation table turns out not to exist yet.
|
|
405
|
-
*
|
|
406
|
-
* `build(withReservations)` rather than a prepared array, because D1
|
|
407
|
-
* statements are single-use once run: a retry has to re-prepare.
|
|
408
|
-
*/
|
|
409
|
-
const runPurgeBatch = async (build) => {
|
|
410
|
-
if (!batch)
|
|
411
|
-
throw new Error('purgeExpiredWorkflowRuns: batch unavailable');
|
|
412
|
-
try {
|
|
413
|
-
return await batch(build(true));
|
|
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}`);
|
|
414
604
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
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;
|
|
420
795
|
}
|
|
421
|
-
|
|
422
|
-
|
|
796
|
+
bytes += rowBytes + (packet.length ? 1 : 0);
|
|
797
|
+
packet.push(candidate);
|
|
423
798
|
}
|
|
799
|
+
if (packet.length)
|
|
800
|
+
packets.push(packet);
|
|
801
|
+
}
|
|
802
|
+
return packets;
|
|
803
|
+
}
|
|
804
|
+
/** Delete expired snapshots with durable, independent physical scan positions. */
|
|
805
|
+
export async function purgeExpiredWorkflowRuns(db, options) {
|
|
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),
|
|
424
818
|
};
|
|
425
|
-
const
|
|
426
|
-
|
|
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))
|
|
427
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';
|
|
428
865
|
try {
|
|
429
|
-
|
|
430
|
-
.prepare(`DELETE FROM ${startIdempotencyTable}
|
|
431
|
-
WHERE rowid IN (
|
|
432
|
-
SELECT r.rowid FROM ${startIdempotencyTable} AS r
|
|
433
|
-
WHERE r.state = 'terminal' AND r.updated_at < ?
|
|
434
|
-
AND NOT EXISTS (
|
|
435
|
-
SELECT 1 FROM ${prefix}mastra_workflow_snapshot AS s
|
|
436
|
-
WHERE s.run_id = r.run_id
|
|
437
|
-
)
|
|
438
|
-
LIMIT ?
|
|
439
|
-
)`)
|
|
440
|
-
.bind(reservationCutoff, options.limit ?? 1000)
|
|
441
|
-
.run();
|
|
866
|
+
message = errorMessageOf(error).slice(0, 256);
|
|
442
867
|
}
|
|
443
|
-
catch
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
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);
|
|
450
884
|
}
|
|
451
|
-
|
|
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();
|
|
452
907
|
}
|
|
453
908
|
};
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
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) => {
|
|
463
924
|
try {
|
|
464
|
-
(
|
|
465
|
-
|
|
466
|
-
FROM ${prefix}mastra_workflow_snapshot
|
|
467
|
-
WHERE ${eligible}
|
|
468
|
-
LIMIT ?`)
|
|
469
|
-
.bind(cutoff, ...RUN_TERMINAL_STATUSES, options.limit ?? 100)
|
|
470
|
-
.all());
|
|
925
|
+
await deleteArtifacts?.(workflowId, runId);
|
|
926
|
+
return true;
|
|
471
927
|
}
|
|
472
928
|
catch (error) {
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
return 0;
|
|
929
|
+
knownSkip(error);
|
|
930
|
+
return false;
|
|
476
931
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
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;
|
|
480
973
|
try {
|
|
481
|
-
|
|
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;
|
|
482
987
|
}
|
|
483
|
-
catch
|
|
484
|
-
|
|
485
|
-
// loop would re-hit this run at the same scan position every firing
|
|
486
|
-
// and stall every eligible row behind it forever. Its row survives
|
|
487
|
-
// as its own retry cursor; the aggregate throw below keeps the
|
|
488
|
-
// purge duty's error surface firing. A wedged run does occupy a batch
|
|
489
|
-
// slot until fixed, so isolation holds while wedged runs number
|
|
490
|
-
// fewer than `limit`.
|
|
491
|
-
failures.push({
|
|
492
|
-
run: `${row.workflow_name}/${row.run_id}`,
|
|
493
|
-
message: errorMessageOf(error),
|
|
494
|
-
});
|
|
988
|
+
catch {
|
|
989
|
+
reportUnsupported('legacy-snapshot');
|
|
495
990
|
continue;
|
|
496
991
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
.prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
|
|
506
|
-
WHERE workflow_name = ? AND run_id = ? AND ${eligible}`)
|
|
507
|
-
.bind(row.workflow_name, row.run_id, cutoff, ...RUN_TERMINAL_STATUSES);
|
|
508
|
-
if (batch) {
|
|
509
|
-
const [result] = await runPurgeBatch((withReservations) => [
|
|
510
|
-
deleteSnapshot(),
|
|
511
|
-
...(resourceOwnerTable
|
|
512
|
-
? [
|
|
513
|
-
db
|
|
514
|
-
.prepare(`DELETE FROM ${resourceOwnerTable}
|
|
515
|
-
WHERE resource_kind = 'run' AND resource_id = ?
|
|
516
|
-
AND NOT EXISTS (
|
|
517
|
-
SELECT 1 FROM ${prefix}mastra_workflow_snapshot
|
|
518
|
-
WHERE run_id = ?
|
|
519
|
-
)`)
|
|
520
|
-
.bind(row.run_id, row.run_id),
|
|
521
|
-
]
|
|
522
|
-
: []),
|
|
523
|
-
...(withReservations ? reservationStatements([row.run_id]) : []),
|
|
524
|
-
]);
|
|
525
|
-
deleted += d1Changes(result);
|
|
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;
|
|
526
1000
|
}
|
|
527
|
-
|
|
528
|
-
|
|
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;
|
|
529
1012
|
}
|
|
530
1013
|
}
|
|
531
|
-
await
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
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
|
+
}
|
|
536
1048
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
.
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
.
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
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] });
|
|
565
1082
|
}
|
|
566
|
-
const rowIds = selected.results.map((row) => row.rowid);
|
|
567
|
-
const runIds = [...new Set(selected.results.map((row) => row.run_id))];
|
|
568
|
-
const rowPlaceholders = rowIds.map(() => '?').join(', ');
|
|
569
|
-
const runPlaceholders = runIds.map(() => '?').join(', ');
|
|
570
|
-
const [result] = await runPurgeBatch((withReservations) => [
|
|
571
|
-
db
|
|
572
|
-
.prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
|
|
573
|
-
WHERE rowid IN (${rowPlaceholders}) AND ${eligible}`)
|
|
574
|
-
.bind(...rowIds, cutoff, ...RUN_TERMINAL_STATUSES),
|
|
575
|
-
...(resourceOwnerTable
|
|
576
|
-
? [
|
|
577
|
-
db
|
|
578
|
-
.prepare(`DELETE FROM ${resourceOwnerTable}
|
|
579
|
-
WHERE resource_kind = 'run'
|
|
580
|
-
AND resource_id IN (${runPlaceholders})
|
|
581
|
-
AND resource_id NOT IN (
|
|
582
|
-
SELECT run_id FROM ${prefix}mastra_workflow_snapshot
|
|
583
|
-
)`)
|
|
584
|
-
.bind(...runIds),
|
|
585
|
-
]
|
|
586
|
-
: []),
|
|
587
|
-
...(withReservations ? reservationStatements(runIds) : []),
|
|
588
|
-
]);
|
|
589
|
-
deleted = d1Changes(result);
|
|
590
1083
|
}
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
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);
|
|
601
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);
|
|
602
1131
|
}
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
}
|
|
608
|
-
await sweepOrphanedStartReservations();
|
|
1132
|
+
else
|
|
1133
|
+
await advance('reservations', undefined);
|
|
1134
|
+
if (failures.length > 0)
|
|
1135
|
+
throw new Error(`purgeExpiredWorkflowRuns: artifact deletion failed (${failures.join('; ')})`);
|
|
609
1136
|
return deleted;
|
|
610
1137
|
}
|
|
611
1138
|
// D1 binds at most 100 parameters per query. Each id chunk below shares its
|
|
@@ -895,19 +1422,18 @@ const NOTIFICATION_TERMINAL_STATUSES = [
|
|
|
895
1422
|
* rows from `mastra_notifications` once their `updatedAt` is older than the TTL,
|
|
896
1423
|
* at the storage layer so alarm maintenance reaps them without a live agent —
|
|
897
1424
|
* the same posture as the other purges (raw D1 binding, failure-isolated duty).
|
|
898
|
-
*
|
|
899
|
-
*
|
|
900
|
-
* 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.
|
|
901
1427
|
*/
|
|
902
1428
|
export async function purgeExpiredNotifications(db, options) {
|
|
903
1429
|
const prefix = validateTablePrefix(options.tablePrefix) ?? '';
|
|
904
1430
|
const now = options.now ?? Date.now;
|
|
905
|
-
const cutoff = new Date(now() - options.ttlMs)
|
|
1431
|
+
const cutoff = notificationTimestampMillis(new Date(now() - options.ttlMs));
|
|
906
1432
|
const placeholders = NOTIFICATION_TERMINAL_STATUSES.map(() => '?').join(', ');
|
|
907
1433
|
try {
|
|
908
1434
|
return d1Changes(await db
|
|
909
1435
|
.prepare(`DELETE FROM ${prefix}mastra_notifications
|
|
910
|
-
WHERE status IN (${placeholders}) AND updatedAt < ?`)
|
|
1436
|
+
WHERE status IN (${placeholders}) AND ${notificationTimestampSql('updatedAt')} < ?`)
|
|
911
1437
|
.bind(...NOTIFICATION_TERMINAL_STATUSES, cutoff)
|
|
912
1438
|
.run());
|
|
913
1439
|
}
|
|
@@ -1002,7 +1528,12 @@ export function d1Changes(result) {
|
|
|
1002
1528
|
return typeof changes === 'number' ? changes : 0;
|
|
1003
1529
|
}
|
|
1004
1530
|
function errorMessageOf(error) {
|
|
1005
|
-
|
|
1531
|
+
try {
|
|
1532
|
+
return String(error instanceof Error ? error.message : error);
|
|
1533
|
+
}
|
|
1534
|
+
catch {
|
|
1535
|
+
return 'unreadable error';
|
|
1536
|
+
}
|
|
1006
1537
|
}
|
|
1007
1538
|
/**
|
|
1008
1539
|
* SQLite/D1's "no such table". For the purges, a table that was never
|