@proofoftech/flowsafe 0.17.0 → 0.18.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.
@@ -0,0 +1,183 @@
1
+ import type { RunSummary } from './runtime.js';
2
+ /** Reserved key a step sets in its `suspend()` payload to arm a deadline. */
3
+ export declare const SUSPENSION_DEADLINE_PAYLOAD_KEY = "flowsafe.deadlineMs";
4
+ /** Reserved key wrapping the resume data an expired deadline resumes with. */
5
+ export declare const SUSPENSION_TIMEOUT_RESUME_KEY = "flowsafe.suspensionTimeout";
6
+ /** Durable Object storage key holding one run's armed deadlines. */
7
+ export declare const SUSPENSION_DEADLINE_STORAGE_KEY = "flowsafe:suspension-deadline:v1";
8
+ /**
9
+ * Requester recorded on a timeout resume. A self-initiated resume must be
10
+ * distinguishable in run provenance from the human or automation that advanced
11
+ * the run to the suspension, so it files under a reserved system id of its own
12
+ * rather than borrowing the recorded requester's identity.
13
+ */
14
+ export declare const SUSPENSION_DEADLINE_PRINCIPAL_ID = "flowsafe-suspension-deadline";
15
+ /** Shortest armable deadline; anything smaller is a tight arm-then-wake loop. */
16
+ export declare const MIN_SUSPENSION_DEADLINE_MS = 1000;
17
+ /** Longest armable deadline (365 days), so week-scale waits still fit. */
18
+ export declare const MAX_SUSPENSION_DEADLINE_MS = 31536000000;
19
+ /** Per-run entry cap; a run cannot grow its object's storage without bound. */
20
+ export declare const MAX_SUSPENSION_DEADLINES_PER_RUN = 32;
21
+ /** Failed timeout resumes tolerated before an entry is abandoned. */
22
+ export declare const MAX_SUSPENSION_DEADLINE_ATTEMPTS = 5;
23
+ /**
24
+ * Mastra's marker for a suspension that happened inside a NESTED workflow: the
25
+ * persisted payload carries the inner step path under `__workflow_meta.path`.
26
+ * Verified in Mastra 1.50.0; `runtime.test.ts` pins it, because a rename would
27
+ * otherwise silently re-open the arming of unfenceable nested suspensions.
28
+ */
29
+ export declare const MASTRA_WORKFLOW_META_KEY = "__workflow_meta";
30
+ export interface SuspensionDeadlineEntry {
31
+ /**
32
+ * The suspended step's DOT-JOINED path, which is how both RunSummary
33
+ * projections key `suspendPayload`, `suspendedAt` and `resumeCount`. Nested
34
+ * paths are never armed, so this is a top-level step id — one that may
35
+ * itself contain a dot.
36
+ */
37
+ step: string;
38
+ /** Epoch milliseconds: the suspension's own time plus its deadline. */
39
+ deadlineAt: number;
40
+ /** Fence: the step's suspension time in the summary that armed this entry. */
41
+ suspendedAt: number;
42
+ /** Fence: the step's resume ordinal, normalized to 0 on a first suspension. */
43
+ resumeCount: number;
44
+ /**
45
+ * Failed timeout resumes so far; absent until the first failure. At the full
46
+ * budget the entry is a TOMBSTONE: abandoned for the suspension it was armed
47
+ * against, never selected and never armed again, and kept in the record only
48
+ * so that suspension cannot re-derive itself a fresh budget.
49
+ */
50
+ attempts?: number;
51
+ /**
52
+ * Epoch milliseconds; paired with `attempts` as its backoff floor. A
53
+ * tombstone carries none, because it is never retried.
54
+ */
55
+ nextAttemptAt?: number;
56
+ /**
57
+ * Epoch milliseconds of the FIRST wake whose authoritative read did not
58
+ * succeed, absent while reads are working. Such a wake charges nothing — an
59
+ * unread run is no evidence about the entry — so this is the only thing
60
+ * bounding an entry whose run became permanently unreadable; the wake that
61
+ * owns it abandons the entry once it has stood for a day. Any successful
62
+ * read clears it.
63
+ */
64
+ unreadableSince?: number;
65
+ }
66
+ export interface SuspensionDeadlineRecord {
67
+ version: 1;
68
+ workflowId: string;
69
+ runId: string;
70
+ entries: SuspensionDeadlineEntry[];
71
+ }
72
+ export interface SuspensionTimeoutEnvelope {
73
+ /** Id of the step whose deadline expired. */
74
+ step: string;
75
+ /** Epoch milliseconds the deadline was armed for. */
76
+ deadlineAt: number;
77
+ /** Epoch milliseconds the wake acted on it. */
78
+ expiredAt: number;
79
+ }
80
+ /** Resume data a timeout resume carries, distinguishable from a real signal. */
81
+ export type SuspensionTimeoutResumeData = {
82
+ [SUSPENSION_TIMEOUT_RESUME_KEY]: SuspensionTimeoutEnvelope;
83
+ };
84
+ /** A derived deadline that will NOT be armed, with the reason to log. */
85
+ export interface RejectedSuspensionDeadline {
86
+ step: string;
87
+ reason: string;
88
+ }
89
+ /**
90
+ * Read every armable deadline out of an authoritative suspended summary.
91
+ *
92
+ * NEVER throws on author data. By the time this runs Mastra has already
93
+ * persisted the suspension, so a malformed `flowsafe.deadlineMs` cannot be
94
+ * rejected by failing the caller: that would leave the run suspended AND the
95
+ * caller erroring. The entry is reported in `rejected` for the caller to log,
96
+ * and the suspension stays an ordinary one.
97
+ *
98
+ * Works on either projection of the same suspension — the live result and the
99
+ * snapshot-rehydrated `status()` — and must agree with itself across the two,
100
+ * because the boundary that arms an entry and the wake that fences it do not
101
+ * read the same one.
102
+ *
103
+ * The arming invariant: an entry may be armed only for a suspension that
104
+ * EXCLUSIVELY OWNS the dot-joined key its fence fields are read from. A
105
+ * nested suspension fails "owns" — the key's fence belongs to the enclosing
106
+ * step — and a key collision fails "exclusively" — two suspensions answer to
107
+ * one key, which Mastra's own snapshot namespace also collides. Refusing is
108
+ * all flowsafe can do there: arming would let a wake deliver one suspension's
109
+ * timeout envelope to an unrelated step. Each refusal below is a detector for
110
+ * one projection's way of breaking that invariant.
111
+ */
112
+ export declare function suspensionDeadlinesOf(summary: RunSummary): {
113
+ entries: SuspensionDeadlineEntry[];
114
+ rejected: RejectedSuspensionDeadline[];
115
+ };
116
+ /**
117
+ * Whether a summary is self-consistent enough to reconcile from: a suspended
118
+ * run always has at least one suspended path, so a 'suspended' status with
119
+ * none describes no suspension anyone could act on. Reconciling from it would
120
+ * derive nothing and wipe the stored record of a run that is still suspended.
121
+ *
122
+ * The SECOND line of defence, not the primary one. It rejects that projection
123
+ * whatever produced it, but it does not cover Mastra's in-memory fallback in
124
+ * general: the fallback reports the Run object's own status, which is
125
+ * 'pending' for a run that has never been resumed — the dominant case, and one
126
+ * this predicate calls readable. The primary guard is the `isFromInMemory`
127
+ * marker check inside `RunnerRuntime.authoritativeStatus`, which is keyed on
128
+ * the read having reached storage rather than on the shape it returned. The
129
+ * two signals are independent, so both are kept.
130
+ */
131
+ export declare function isReadableRunSummary(summary: RunSummary): boolean;
132
+ /** Strict hydration of the stored record; `undefined` in, `undefined` out. */
133
+ export declare function parseSuspensionDeadlineRecord(value: unknown): SuspensionDeadlineRecord | undefined;
134
+ /**
135
+ * A spent entry, kept for the suspension it was armed against: the ledger at
136
+ * the budget, and every field that only means something while it is still
137
+ * being retried — the backoff floor, the unreadable-state clock — dropped,
138
+ * because a tombstone is never selected, never armed and never read again.
139
+ * Lives beside its two recognizers, `abandoned()` and `storedEntry`'s ledger
140
+ * rule, so the shape they accept and the shape written here cannot drift.
141
+ * Exported from this module for the run object that writes it; deliberately
142
+ * NOT from the package barrel, which exposes no part of the stored record.
143
+ */
144
+ export declare function tombstoned(entry: SuspensionDeadlineEntry): SuspensionDeadlineEntry;
145
+ /** Earliest wake the record needs, honouring a retry floor over a due entry. */
146
+ export declare function nextSuspensionDeadlineAt(stored: SuspensionDeadlineRecord | undefined): number | undefined;
147
+ /**
148
+ * Whether a wake at `now` owes this entry work: it has reached its deadline
149
+ * (or the retry floor past it) and its budget is not spent. One wake resumes
150
+ * ONE such entry, but a failed authoritative read is one fact about all of
151
+ * them, so the unreadable-state clock is stamped across the whole due batch.
152
+ */
153
+ export declare function isSuspensionDeadlineDue(entry: SuspensionDeadlineEntry, now: number): boolean;
154
+ /** The one entry a wake at `now` should act on, earliest deadline first. */
155
+ export declare function dueSuspensionDeadline(stored: SuspensionDeadlineRecord | undefined, now: number): SuspensionDeadlineEntry | undefined;
156
+ /** The resume data a timeout resume delivers to the expired step. */
157
+ export declare function suspensionTimeoutResumeData(entry: SuspensionDeadlineEntry, expiredAt: number): SuspensionTimeoutResumeData;
158
+ /**
159
+ * Structural guard a step uses to tell a timeout resume from a real signal,
160
+ * so consumer code branches on this contract instead of a string literal.
161
+ */
162
+ export declare function isSuspensionTimeoutResumeData(value: unknown): value is SuspensionTimeoutResumeData;
163
+ /**
164
+ * Carry the retry ledger of a stored entry onto the freshly derived one for
165
+ * the SAME suspension. An entry whose fence or deadline moved is a different
166
+ * suspension, so it starts with a clean ledger; a stored entry with no derived
167
+ * counterpart is gone and is dropped. This carry is also the tombstone's whole
168
+ * lifecycle: a spent ledger rides every reconcile of the unchanged suspension
169
+ * — which is what keeps the suspension from re-deriving a fresh budget — and
170
+ * is dropped the moment the suspension moves on, so a later suspension of the
171
+ * same step starts over.
172
+ *
173
+ * `unreadableSince` is deliberately NOT carried, and that is what clears it: a
174
+ * reconcile only ever follows evidence that the run is real and current — an
175
+ * authoritative read that succeeded, or a live summary handed back by a
176
+ * lifecycle boundary — and either ends the unreadable stretch the clock was
177
+ * counting. A host that drives boundaries oftener than daily therefore keeps
178
+ * the clock from maturing even while the row read keeps failing; in the case
179
+ * the bound exists for — a registration a deploy dropped for good — the
180
+ * boundaries throw too, so nothing clears it and the bound holds.
181
+ */
182
+ export declare function mergeSuspensionDeadlines(previous: SuspensionDeadlineRecord | undefined, derived: readonly SuspensionDeadlineEntry[]): SuspensionDeadlineEntry[];
183
+ //# sourceMappingURL=suspension-deadline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suspension-deadline.d.ts","sourceRoot":"","sources":["../../src/do-runner/suspension-deadline.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,6EAA6E;AAC7E,eAAO,MAAM,+BAA+B,wBAAwB,CAAC;AAErE,8EAA8E;AAC9E,eAAO,MAAM,6BAA6B,+BAA+B,CAAC;AAE1E,oEAAoE;AACpE,eAAO,MAAM,+BAA+B,oCACT,CAAC;AAEpC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,iCAAiC,CAAC;AAE/E,iFAAiF;AACjF,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAEhD,0EAA0E;AAC1E,eAAO,MAAM,0BAA0B,cAAiB,CAAC;AAEzD,+EAA+E;AAC/E,eAAO,MAAM,gCAAgC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;;;GAcG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAIjE;AAED,8EAA8E;AAC9E,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,OAAO,GACb,wBAAwB,GAAG,SAAS,CAkBtC;AAED;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,uBAAuB,GAC7B,uBAAuB,CAQzB;AAeD,gFAAgF;AAChF,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,wBAAwB,GAAG,SAAS,GAC3C,MAAM,GAAG,SAAS,CAQpB;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,uBAAuB,EAC9B,GAAG,EAAE,MAAM,GACV,OAAO,CAET;AAED,4EAA4E;AAC5E,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,wBAAwB,GAAG,SAAS,EAC5C,GAAG,EAAE,MAAM,GACV,uBAAuB,GAAG,SAAS,CAOrC;AAED,qEAAqE;AACrE,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,uBAAuB,EAC9B,SAAS,EAAE,MAAM,GAChB,2BAA2B,CAQ7B;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,2BAA2B,CAQtC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,wBAAwB,GAAG,SAAS,EAC9C,OAAO,EAAE,SAAS,uBAAuB,EAAE,GAC1C,uBAAuB,EAAE,CAqB3B"}
@@ -0,0 +1,451 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Per-suspension deadlines — the durable wake schedule that lets a run resume
3
+ // itself when the signal a suspended step waits for never arrives.
4
+ //
5
+ // `suspend()` is Mastra's, not flowsafe's, and a suspension is the one
6
+ // lifecycle transition the runtime persists nothing of its own for: the
7
+ // snapshot it writes is Mastra's workflow state. So the arming value cannot be
8
+ // a flowsafe option — it travels inside the payload the step hands `suspend()`,
9
+ // under a reserved dotted key (the `flowsafe.` convention the request-context
10
+ // keys already use), and this module reads it back out of the authoritative
11
+ // RunSummary that start, resume, and status already project.
12
+ //
13
+ // The derived record lives in Durable Object storage, NOT in the snapshot's
14
+ // requestContext beside RunLifecycleState (run-lifecycle.ts). A suspension
15
+ // deadline is one object's wake schedule: it has no meaning once that object's
16
+ // run leaves 'suspended', and the alarm that consumes it must read it before it
17
+ // has loaded any snapshot. Storage is also why the parse below is strict —
18
+ // stored state is untrusted input, so every field is validated and a malformed
19
+ // record throws instead of being coerced, exactly as parseRunLifecycle does.
20
+ //
21
+ // Everything here is pure; arming, wake scheduling, and the timeout resume live
22
+ // in durable-object.ts, so a non-DO host (tests, local runners) is unaffected.
23
+ import { isPathSafeId } from './path-safe-id.js';
24
+ /** Reserved key a step sets in its `suspend()` payload to arm a deadline. */
25
+ export const SUSPENSION_DEADLINE_PAYLOAD_KEY = 'flowsafe.deadlineMs';
26
+ /** Reserved key wrapping the resume data an expired deadline resumes with. */
27
+ export const SUSPENSION_TIMEOUT_RESUME_KEY = 'flowsafe.suspensionTimeout';
28
+ /** Durable Object storage key holding one run's armed deadlines. */
29
+ export const SUSPENSION_DEADLINE_STORAGE_KEY = 'flowsafe:suspension-deadline:v1';
30
+ /**
31
+ * Requester recorded on a timeout resume. A self-initiated resume must be
32
+ * distinguishable in run provenance from the human or automation that advanced
33
+ * the run to the suspension, so it files under a reserved system id of its own
34
+ * rather than borrowing the recorded requester's identity.
35
+ */
36
+ export const SUSPENSION_DEADLINE_PRINCIPAL_ID = 'flowsafe-suspension-deadline';
37
+ /** Shortest armable deadline; anything smaller is a tight arm-then-wake loop. */
38
+ export const MIN_SUSPENSION_DEADLINE_MS = 1_000;
39
+ /** Longest armable deadline (365 days), so week-scale waits still fit. */
40
+ export const MAX_SUSPENSION_DEADLINE_MS = 31_536_000_000;
41
+ /** Per-run entry cap; a run cannot grow its object's storage without bound. */
42
+ export const MAX_SUSPENSION_DEADLINES_PER_RUN = 32;
43
+ /** Failed timeout resumes tolerated before an entry is abandoned. */
44
+ export const MAX_SUSPENSION_DEADLINE_ATTEMPTS = 5;
45
+ /**
46
+ * Mastra's marker for a suspension that happened inside a NESTED workflow: the
47
+ * persisted payload carries the inner step path under `__workflow_meta.path`.
48
+ * Verified in Mastra 1.50.0; `runtime.test.ts` pins it, because a rename would
49
+ * otherwise silently re-open the arming of unfenceable nested suspensions.
50
+ */
51
+ export const MASTRA_WORKFLOW_META_KEY = '__workflow_meta';
52
+ // Step ids are bounded for the same reason every other stored free-text field
53
+ // is: a stored record must stay small enough to read back on every alarm wake.
54
+ const MAX_SUSPENSION_DEADLINE_STEP_LENGTH = 500;
55
+ const MALFORMED = 'stored suspension deadline is malformed';
56
+ function record(value) {
57
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
58
+ ? value
59
+ : undefined;
60
+ }
61
+ // Every number this module persists — an epoch millisecond and the resume
62
+ // ordinal alike — has to clear the same bar, so the predicate is named for the
63
+ // bar rather than for one of its callers. run-lifecycle.ts names the identical
64
+ // check `validTime` because there it only ever guards timestamps.
65
+ function nonNegativeInteger(value) {
66
+ return Number.isSafeInteger(value) && value >= 0;
67
+ }
68
+ function validStep(value) {
69
+ return (typeof value === 'string' &&
70
+ value.length > 0 &&
71
+ value.length <= MAX_SUSPENSION_DEADLINE_STEP_LENGTH);
72
+ }
73
+ // Read Mastra's nesting marker defensively: the payload is author data carrying
74
+ // one framework-owned field, so a renamed, missing or reshaped marker must
75
+ // degrade to "not nested" here rather than throw on a suspension flowsafe has
76
+ // already been handed. The tripwire test is what makes such a rename loud.
77
+ function nestedPath(payload) {
78
+ const path = record(payload[MASTRA_WORKFLOW_META_KEY])?.path;
79
+ return Array.isArray(path) && path.length > 0 ? path : undefined;
80
+ }
81
+ /**
82
+ * Detector for the "exclusively" half of the arming invariant (see
83
+ * suspensionDeadlinesOf): every joined key that more than one suspension of
84
+ * this run answers to. Each projection shows a collision differently, so both
85
+ * rules are needed: two suspended paths joining to one key can only appear on
86
+ * the live projection (the rehydrated one splits unique stored keys), and a
87
+ * key implied by another suspended key's nesting marker only on the rehydrated
88
+ * one (live nested payloads carry no marker).
89
+ *
90
+ * Both rules read only each suspended key's OWN payload, never the
91
+ * nested-payload fallback below, which deliberately reads a different step's
92
+ * payload.
93
+ */
94
+ function ambiguousSuspendedKeys(suspended, payloads) {
95
+ const seen = new Set();
96
+ const ambiguous = new Set();
97
+ for (const path of suspended) {
98
+ const key = path.join('.');
99
+ if (seen.has(key))
100
+ ambiguous.add(key);
101
+ seen.add(key);
102
+ const payload = record(payloads?.[key]);
103
+ const nested = payload && nestedPath(payload);
104
+ if (nested)
105
+ ambiguous.add([key, ...nested].join('.'));
106
+ }
107
+ return ambiguous;
108
+ }
109
+ function storedEntry(value) {
110
+ const stored = record(value);
111
+ if (!stored)
112
+ throw new Error(MALFORMED);
113
+ const { attempts, nextAttemptAt, unreadableSince } = stored;
114
+ // A ledger below the budget is still retrying and needs its floor; one AT the
115
+ // budget is a tombstone, which is never selected again and so must carry no
116
+ // floor. The two fields are otherwise one fact — a count with no floor would
117
+ // retry immediately, a floor with no count would retry forever.
118
+ const retrying = attempts !== undefined && attempts !== MAX_SUSPENSION_DEADLINE_ATTEMPTS;
119
+ if (!validStep(stored.step) ||
120
+ !nonNegativeInteger(stored.deadlineAt) ||
121
+ !nonNegativeInteger(stored.suspendedAt) ||
122
+ !nonNegativeInteger(stored.resumeCount) ||
123
+ // The budget itself reads back, because a spent one stays as a tombstone.
124
+ // More than the budget cannot have been written here, and accepting it
125
+ // would let a foreign writer make this module's own log say "after 6".
126
+ (attempts !== undefined &&
127
+ (!Number.isSafeInteger(attempts) ||
128
+ attempts < 1 ||
129
+ attempts > MAX_SUSPENSION_DEADLINE_ATTEMPTS)) ||
130
+ (nextAttemptAt !== undefined) !== retrying ||
131
+ (nextAttemptAt !== undefined && !nonNegativeInteger(nextAttemptAt)) ||
132
+ // Unpaired with the ledger, unlike the floor above: it records how long
133
+ // reads have been failing, which is independent of how many resumes have.
134
+ (unreadableSince !== undefined && !nonNegativeInteger(unreadableSince))) {
135
+ throw new Error(MALFORMED);
136
+ }
137
+ return {
138
+ step: stored.step,
139
+ deadlineAt: stored.deadlineAt,
140
+ suspendedAt: stored.suspendedAt,
141
+ resumeCount: stored.resumeCount,
142
+ ...(attempts === undefined ? {} : { attempts: attempts }),
143
+ ...(nextAttemptAt === undefined
144
+ ? {}
145
+ : { nextAttemptAt: nextAttemptAt }),
146
+ ...(unreadableSince === undefined
147
+ ? {}
148
+ : { unreadableSince: unreadableSince }),
149
+ };
150
+ }
151
+ // Total order on (deadlineAt, step) so the entry a wake acts on is
152
+ // deterministic even for equal deadlines. It does not order the stored record:
153
+ // a retry charge appends the entry it re-armed.
154
+ function byDueThenStep(left, right) {
155
+ if (left.deadlineAt !== right.deadlineAt) {
156
+ return left.deadlineAt - right.deadlineAt;
157
+ }
158
+ return left.step < right.step ? -1 : left.step > right.step ? 1 : 0;
159
+ }
160
+ /**
161
+ * Read every armable deadline out of an authoritative suspended summary.
162
+ *
163
+ * NEVER throws on author data. By the time this runs Mastra has already
164
+ * persisted the suspension, so a malformed `flowsafe.deadlineMs` cannot be
165
+ * rejected by failing the caller: that would leave the run suspended AND the
166
+ * caller erroring. The entry is reported in `rejected` for the caller to log,
167
+ * and the suspension stays an ordinary one.
168
+ *
169
+ * Works on either projection of the same suspension — the live result and the
170
+ * snapshot-rehydrated `status()` — and must agree with itself across the two,
171
+ * because the boundary that arms an entry and the wake that fences it do not
172
+ * read the same one.
173
+ *
174
+ * The arming invariant: an entry may be armed only for a suspension that
175
+ * EXCLUSIVELY OWNS the dot-joined key its fence fields are read from. A
176
+ * nested suspension fails "owns" — the key's fence belongs to the enclosing
177
+ * step — and a key collision fails "exclusively" — two suspensions answer to
178
+ * one key, which Mastra's own snapshot namespace also collides. Refusing is
179
+ * all flowsafe can do there: arming would let a wake deliver one suspension's
180
+ * timeout envelope to an unrelated step. Each refusal below is a detector for
181
+ * one projection's way of breaking that invariant.
182
+ */
183
+ export function suspensionDeadlinesOf(summary) {
184
+ const entries = [];
185
+ const rejected = [];
186
+ if (summary.status !== 'suspended')
187
+ return { entries, rejected };
188
+ const payloads = record(summary.suspendPayload);
189
+ const suspended = summary.suspended ?? [];
190
+ const ambiguous = ambiguousSuspendedKeys(suspended, payloads);
191
+ for (const path of suspended) {
192
+ // The DOT-JOINED path is the entry key, because it is what indexes
193
+ // `suspendPayload`, `suspendedAt` and `resumeCount` in BOTH projections
194
+ // (['a.b'] live, ['a','b'] rehydrated), so the wake's fence recognizes
195
+ // what a boundary armed.
196
+ const step = path.join('.');
197
+ const payload = record(payloads?.[step]);
198
+ // A LIVE nested suspension is the one shape whose payload is NOT under its
199
+ // own path: Mastra reports the nested path but keys the payload by the
200
+ // TOP-LEVEL step. Reading it there is what turns a nested arming request
201
+ // into a loud rejection instead of silence.
202
+ const nestedPayload = payload === undefined && path.length > 1
203
+ ? record(payloads?.[path[0]])
204
+ : undefined;
205
+ const armed = payload ?? nestedPayload;
206
+ // No payload, or no reserved key in it: an ordinary suspension, silently.
207
+ if (!armed)
208
+ continue;
209
+ const deadlineMs = armed[SUSPENSION_DEADLINE_PAYLOAD_KEY];
210
+ if (deadlineMs === undefined)
211
+ continue;
212
+ // "Exclusively" is checked before "owns" so the log names the sharper
213
+ // reason, and after the silent exits above so a run that asked for nothing
214
+ // still says nothing.
215
+ if (ambiguous.has(step)) {
216
+ rejected.push({ step, reason: 'ambiguous suspended step path' });
217
+ continue;
218
+ }
219
+ // Detector for the "owns" half of the invariant, and a LOUD one — silence
220
+ // here would look to the author exactly like a deadline that was accepted.
221
+ // Each projection presents a nested suspension its own way: the live one
222
+ // as a multi-segment path whose payload sits under its first segment
223
+ // (`nestedPayload` above), the rehydrated one as the top-level step alone,
224
+ // recognizable only by Mastra's nesting marker inside the payload.
225
+ if (nestedPayload !== undefined || nestedPath(armed) !== undefined) {
226
+ rejected.push({
227
+ step,
228
+ reason: 'nested suspension paths are not supported',
229
+ });
230
+ continue;
231
+ }
232
+ if (!validStep(step)) {
233
+ rejected.push({ step, reason: 'suspended step id is unusable' });
234
+ continue;
235
+ }
236
+ if (!Number.isSafeInteger(deadlineMs)) {
237
+ rejected.push({
238
+ step,
239
+ reason: `${SUSPENSION_DEADLINE_PAYLOAD_KEY} must be a safe integer`,
240
+ });
241
+ continue;
242
+ }
243
+ if (deadlineMs < MIN_SUSPENSION_DEADLINE_MS ||
244
+ deadlineMs > MAX_SUSPENSION_DEADLINE_MS) {
245
+ rejected.push({
246
+ step,
247
+ reason: `${SUSPENSION_DEADLINE_PAYLOAD_KEY} must be between ${MIN_SUSPENSION_DEADLINE_MS} and ${MAX_SUSPENSION_DEADLINE_MS} ms`,
248
+ });
249
+ continue;
250
+ }
251
+ const suspendedAt = summary.suspendedAt?.[step];
252
+ // A deadline that cannot be fenced must not be armed: without suspendedAt
253
+ // the alarm could not tell this suspension from a later one at the same
254
+ // step, and would resume a run a real signal had already moved on.
255
+ if (!nonNegativeInteger(suspendedAt)) {
256
+ rejected.push({ step, reason: 'no suspendedAt fence' });
257
+ continue;
258
+ }
259
+ // Absent resumeCount is normal on a step's FIRST suspension; the runtime
260
+ // only stamps the ordinal once the step has been resumed.
261
+ const resumeCount = summary.resumeCount?.[step];
262
+ if (resumeCount !== undefined && !nonNegativeInteger(resumeCount)) {
263
+ rejected.push({ step, reason: 'resumeCount fence is malformed' });
264
+ continue;
265
+ }
266
+ // suspendedAt + deadlineMs, never now + deadlineMs: re-deriving from an
267
+ // unchanged suspension must yield a byte-identical entry, or repeated
268
+ // reconciliation would walk the deadline forward and it would never fire.
269
+ const deadlineAt = suspendedAt + deadlineMs;
270
+ if (!Number.isSafeInteger(deadlineAt)) {
271
+ rejected.push({
272
+ step,
273
+ reason: `${SUSPENSION_DEADLINE_PAYLOAD_KEY} exceeds the supported range`,
274
+ });
275
+ continue;
276
+ }
277
+ entries.push({
278
+ step,
279
+ deadlineAt,
280
+ suspendedAt,
281
+ resumeCount: resumeCount ?? 0,
282
+ });
283
+ }
284
+ entries.sort(byDueThenStep);
285
+ for (const overflow of entries.splice(MAX_SUSPENSION_DEADLINES_PER_RUN)) {
286
+ rejected.push({
287
+ step: overflow.step,
288
+ reason: `run already arms ${MAX_SUSPENSION_DEADLINES_PER_RUN} suspension deadlines`,
289
+ });
290
+ }
291
+ return { entries, rejected };
292
+ }
293
+ /**
294
+ * Whether a summary is self-consistent enough to reconcile from: a suspended
295
+ * run always has at least one suspended path, so a 'suspended' status with
296
+ * none describes no suspension anyone could act on. Reconciling from it would
297
+ * derive nothing and wipe the stored record of a run that is still suspended.
298
+ *
299
+ * The SECOND line of defence, not the primary one. It rejects that projection
300
+ * whatever produced it, but it does not cover Mastra's in-memory fallback in
301
+ * general: the fallback reports the Run object's own status, which is
302
+ * 'pending' for a run that has never been resumed — the dominant case, and one
303
+ * this predicate calls readable. The primary guard is the `isFromInMemory`
304
+ * marker check inside `RunnerRuntime.authoritativeStatus`, which is keyed on
305
+ * the read having reached storage rather than on the shape it returned. The
306
+ * two signals are independent, so both are kept.
307
+ */
308
+ export function isReadableRunSummary(summary) {
309
+ return !(summary.status === 'suspended' && (summary.suspended ?? []).length === 0);
310
+ }
311
+ /** Strict hydration of the stored record; `undefined` in, `undefined` out. */
312
+ export function parseSuspensionDeadlineRecord(value) {
313
+ if (value === undefined)
314
+ return undefined;
315
+ const stored = record(value);
316
+ if (stored?.version !== 1 ||
317
+ !isPathSafeId(stored.workflowId) ||
318
+ !isPathSafeId(stored.runId) ||
319
+ !Array.isArray(stored.entries) ||
320
+ stored.entries.length > MAX_SUSPENSION_DEADLINES_PER_RUN) {
321
+ throw new Error(MALFORMED);
322
+ }
323
+ return {
324
+ version: 1,
325
+ workflowId: stored.workflowId,
326
+ runId: stored.runId,
327
+ entries: stored.entries.map(storedEntry),
328
+ };
329
+ }
330
+ /**
331
+ * A spent entry, kept for the suspension it was armed against: the ledger at
332
+ * the budget, and every field that only means something while it is still
333
+ * being retried — the backoff floor, the unreadable-state clock — dropped,
334
+ * because a tombstone is never selected, never armed and never read again.
335
+ * Lives beside its two recognizers, `abandoned()` and `storedEntry`'s ledger
336
+ * rule, so the shape they accept and the shape written here cannot drift.
337
+ * Exported from this module for the run object that writes it; deliberately
338
+ * NOT from the package barrel, which exposes no part of the stored record.
339
+ */
340
+ export function tombstoned(entry) {
341
+ return {
342
+ step: entry.step,
343
+ deadlineAt: entry.deadlineAt,
344
+ suspendedAt: entry.suspendedAt,
345
+ resumeCount: entry.resumeCount,
346
+ attempts: MAX_SUSPENSION_DEADLINE_ATTEMPTS,
347
+ };
348
+ }
349
+ // A spent ledger is a tombstone: the entry stays stored so its suspension
350
+ // cannot re-derive itself a fresh budget, but both selectors below must skip
351
+ // it — selecting it would retry past the budget, and arming for it would wake
352
+ // the object at its long-past deadline forever.
353
+ function abandoned(entry) {
354
+ return (entry.attempts ?? 0) >= MAX_SUSPENSION_DEADLINE_ATTEMPTS;
355
+ }
356
+ /** When an entry needs its wake: the deadline, or the retry floor past it. */
357
+ function dueAt(entry) {
358
+ return Math.max(entry.deadlineAt, entry.nextAttemptAt ?? 0);
359
+ }
360
+ /** Earliest wake the record needs, honouring a retry floor over a due entry. */
361
+ export function nextSuspensionDeadlineAt(stored) {
362
+ let next;
363
+ for (const entry of stored?.entries ?? []) {
364
+ if (abandoned(entry))
365
+ continue;
366
+ const due = dueAt(entry);
367
+ if (next === undefined || due < next)
368
+ next = due;
369
+ }
370
+ return next;
371
+ }
372
+ /**
373
+ * Whether a wake at `now` owes this entry work: it has reached its deadline
374
+ * (or the retry floor past it) and its budget is not spent. One wake resumes
375
+ * ONE such entry, but a failed authoritative read is one fact about all of
376
+ * them, so the unreadable-state clock is stamped across the whole due batch.
377
+ */
378
+ export function isSuspensionDeadlineDue(entry, now) {
379
+ return !abandoned(entry) && dueAt(entry) <= now;
380
+ }
381
+ /** The one entry a wake at `now` should act on, earliest deadline first. */
382
+ export function dueSuspensionDeadline(stored, now) {
383
+ let due;
384
+ for (const entry of stored?.entries ?? []) {
385
+ if (!isSuspensionDeadlineDue(entry, now))
386
+ continue;
387
+ if (!due || byDueThenStep(entry, due) < 0)
388
+ due = entry;
389
+ }
390
+ return due;
391
+ }
392
+ /** The resume data a timeout resume delivers to the expired step. */
393
+ export function suspensionTimeoutResumeData(entry, expiredAt) {
394
+ return {
395
+ [SUSPENSION_TIMEOUT_RESUME_KEY]: {
396
+ step: entry.step,
397
+ deadlineAt: entry.deadlineAt,
398
+ expiredAt,
399
+ },
400
+ };
401
+ }
402
+ /**
403
+ * Structural guard a step uses to tell a timeout resume from a real signal,
404
+ * so consumer code branches on this contract instead of a string literal.
405
+ */
406
+ export function isSuspensionTimeoutResumeData(value) {
407
+ const envelope = record(record(value)?.[SUSPENSION_TIMEOUT_RESUME_KEY]);
408
+ return (envelope !== undefined &&
409
+ validStep(envelope.step) &&
410
+ nonNegativeInteger(envelope.deadlineAt) &&
411
+ nonNegativeInteger(envelope.expiredAt));
412
+ }
413
+ /**
414
+ * Carry the retry ledger of a stored entry onto the freshly derived one for
415
+ * the SAME suspension. An entry whose fence or deadline moved is a different
416
+ * suspension, so it starts with a clean ledger; a stored entry with no derived
417
+ * counterpart is gone and is dropped. This carry is also the tombstone's whole
418
+ * lifecycle: a spent ledger rides every reconcile of the unchanged suspension
419
+ * — which is what keeps the suspension from re-deriving a fresh budget — and
420
+ * is dropped the moment the suspension moves on, so a later suspension of the
421
+ * same step starts over.
422
+ *
423
+ * `unreadableSince` is deliberately NOT carried, and that is what clears it: a
424
+ * reconcile only ever follows evidence that the run is real and current — an
425
+ * authoritative read that succeeded, or a live summary handed back by a
426
+ * lifecycle boundary — and either ends the unreadable stretch the clock was
427
+ * counting. A host that drives boundaries oftener than daily therefore keeps
428
+ * the clock from maturing even while the row read keeps failing; in the case
429
+ * the bound exists for — a registration a deploy dropped for good — the
430
+ * boundaries throw too, so nothing clears it and the bound holds.
431
+ */
432
+ export function mergeSuspensionDeadlines(previous, derived) {
433
+ return derived.map((entry) => {
434
+ const carried = previous?.entries.find((stored) => stored.step === entry.step &&
435
+ stored.suspendedAt === entry.suspendedAt &&
436
+ stored.resumeCount === entry.resumeCount &&
437
+ stored.deadlineAt === entry.deadlineAt);
438
+ return carried?.attempts === undefined
439
+ ? entry
440
+ : {
441
+ ...entry,
442
+ attempts: carried.attempts,
443
+ // A tombstone carries no floor; spreading `undefined` back in would
444
+ // store a property the strict parser then has to treat as absent.
445
+ ...(carried.nextAttemptAt === undefined
446
+ ? {}
447
+ : { nextAttemptAt: carried.nextAttemptAt }),
448
+ };
449
+ });
450
+ }
451
+ //# sourceMappingURL=suspension-deadline.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suspension-deadline.js","sourceRoot":"","sources":["../../src/do-runner/suspension-deadline.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,8EAA8E;AAC9E,mEAAmE;AACnE,EAAE;AACF,uEAAuE;AACvE,wEAAwE;AACxE,+EAA+E;AAC/E,gFAAgF;AAChF,8EAA8E;AAC9E,4EAA4E;AAC5E,6DAA6D;AAC7D,EAAE;AACF,4EAA4E;AAC5E,2EAA2E;AAC3E,+EAA+E;AAC/E,gFAAgF;AAChF,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAE/E,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD,6EAA6E;AAC7E,MAAM,CAAC,MAAM,+BAA+B,GAAG,qBAAqB,CAAC;AAErE,8EAA8E;AAC9E,MAAM,CAAC,MAAM,6BAA6B,GAAG,4BAA4B,CAAC;AAE1E,oEAAoE;AACpE,MAAM,CAAC,MAAM,+BAA+B,GAC1C,iCAAiC,CAAC;AAEpC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,8BAA8B,CAAC;AAE/E,iFAAiF;AACjF,MAAM,CAAC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEhD,0EAA0E;A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