@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.
- package/CHANGELOG.md +14 -0
- package/README.md +40 -0
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +30 -4
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +9 -1
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts +13 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +825 -29
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/index.d.ts +3 -1
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +2 -1
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/runtime.d.ts +43 -0
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +67 -0
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/suspension-deadline.d.ts +183 -0
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -0
- package/dist/do-runner/suspension-deadline.js +451 -0
- package/dist/do-runner/suspension-deadline.js.map +1 -0
- package/dist/do-runner/thread-do.d.ts +5 -1
- package/dist/do-runner/thread-do.d.ts.map +1 -1
- package/dist/do-runner/thread-do.js +24 -1
- package/dist/do-runner/thread-do.js.map +1 -1
- package/package.json +1 -1
|
@@ -8,26 +8,62 @@
|
|
|
8
8
|
// enforced by RunnerRuntime's per-run FIFO locks; routing one DO instance per run
|
|
9
9
|
// (idFromName(`${workflowId}:${runId}`)) makes those locks authoritative,
|
|
10
10
|
// since all traffic for a run lands on one instance. The object's alarm is
|
|
11
|
-
// reserved for recovering run-owner claims that outlive an interrupted start
|
|
11
|
+
// reserved for recovering run-owner claims that outlive an interrupted start
|
|
12
|
+
// and for the per-suspension deadlines of this run (suspension-deadline.ts);
|
|
13
|
+
// both duties share one wake, armed at the earliest of the two due times.
|
|
12
14
|
import { decodeExecutionPrincipal, isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
|
|
13
15
|
import { newWebSocketPair, safeSend } from './cf-types.js';
|
|
14
16
|
import { verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from './deployment-identity.js';
|
|
15
17
|
import { DoStatusError, doErrorResponse } from './do-error-response.js';
|
|
16
18
|
import { EXECUTION_PRINCIPAL_HEADER } from './execution-principal-header.js';
|
|
17
19
|
import { isPathSafeId } from './path-safe-id.js';
|
|
18
|
-
import { InvalidRunRequestError, RunAlreadyExistsError, UnknownRunError, } from './runtime.js';
|
|
20
|
+
import { InvalidRunRequestError, RunAlreadyExistsError, RunStateUnreadableError, UnknownRunError, } from './runtime.js';
|
|
19
21
|
import { resolveScheduleStartOwner, } from './schedule-source.js';
|
|
22
|
+
import { dueSuspensionDeadline, isReadableRunSummary, isSuspensionDeadlineDue, MAX_SUSPENSION_DEADLINE_ATTEMPTS, MAX_SUSPENSION_DEADLINES_PER_RUN, mergeSuspensionDeadlines, nextSuspensionDeadlineAt, parseSuspensionDeadlineRecord, SUSPENSION_DEADLINE_PRINCIPAL_ID, SUSPENSION_DEADLINE_STORAGE_KEY, SUSPENSION_TIMEOUT_RESUME_KEY, suspensionDeadlinesOf, suspensionTimeoutResumeData, tombstoned, } from './suspension-deadline.js';
|
|
20
23
|
const RUN_OWNER_RECOVERY_KEY = 'flowsafe:run-owner-recovery:v1';
|
|
21
24
|
const RUN_OWNER_RECOVERY_DELAY_MS = 60_000;
|
|
25
|
+
const SUSPENSION_DEADLINE_RETRY_MS = 60_000;
|
|
26
|
+
// How long a run's state may stay unreadable before the entries due under it
|
|
27
|
+
// are given up on. A read that never succeeds is never charged, so without this
|
|
28
|
+
// bound one run whose workflow registration a deploy dropped for good would
|
|
29
|
+
// keep a 60 s heartbeat forever. A day is four orders of magnitude past any
|
|
30
|
+
// credible storage incident, so nothing but a permanent fault reaches it.
|
|
31
|
+
//
|
|
32
|
+
// The bound is per DUE BATCH, not per entry: one failed read stamps every entry
|
|
33
|
+
// due at that wake, so a record of any size clears about a day after its last
|
|
34
|
+
// entry falls due. An entry armed far in the future starts its own day only
|
|
35
|
+
// when it comes due — until then it is not this wake's business and is left
|
|
36
|
+
// untouched.
|
|
37
|
+
const SUSPENSION_DEADLINE_UNREADABLE_LIMIT_MS = 86_400_000;
|
|
38
|
+
// Cloudflare runs an alarm scheduled in the past immediately. An entry that is
|
|
39
|
+
// already due therefore cannot be armed at its own deadline: the wake would
|
|
40
|
+
// re-arm at the same past time and spin. Every arm is floored this far out, so
|
|
41
|
+
// a wake that fails to consume its entry costs one wake per second at worst
|
|
42
|
+
// until the retry ledger backs it off or drops it. The ledger is what ends
|
|
43
|
+
// that, so the floor only bounds a wake that CHARGES one. The three classes
|
|
44
|
+
// that never do converge nothing and keep the 60 s recovery cadence instead: a
|
|
45
|
+
// wake whose authoritative read did not succeed (uncharged by design — it is
|
|
46
|
+
// no evidence about the entry), a wake that could not BUILD its runtime (a
|
|
47
|
+
// misconfigured binding is a fault of the host, and says nothing about any
|
|
48
|
+
// entry either), and a wake that could not read its record or write its ledger
|
|
49
|
+
// at all. The first has one exception: a read that has not succeeded for a day
|
|
50
|
+
// abandons the entries due under it, and abandoning IS a convergence — that
|
|
51
|
+
// wake arms from what is left, which for a record holding nothing else is the
|
|
52
|
+
// delete that ends the heartbeat. Otherwise an unrelated entry's wake is
|
|
53
|
+
// deferred to the watchdog — up to a minute late, and only while the fault
|
|
54
|
+
// lasts.
|
|
55
|
+
const SUSPENSION_DEADLINE_ARM_FLOOR_MS = 1_000;
|
|
22
56
|
class DurableObjectRunIdentityError extends DoStatusError {
|
|
23
57
|
status = 403;
|
|
24
58
|
}
|
|
25
59
|
export class DurableObjectRunner {
|
|
26
60
|
env;
|
|
27
|
-
/** Absent in Node tests; present under workerd and
|
|
61
|
+
/** Absent in Node tests; present under workerd for storage and the alarm. */
|
|
28
62
|
state;
|
|
29
63
|
#runtime;
|
|
30
64
|
#operationTail = Promise.resolve();
|
|
65
|
+
/** `step\0reason` of every suspension deadline this object has reported. */
|
|
66
|
+
#reportedSuspensionRejections = new Set();
|
|
31
67
|
constructor(state, env) {
|
|
32
68
|
this.state = state;
|
|
33
69
|
this.env = env;
|
|
@@ -89,6 +125,22 @@ export class DurableObjectRunner {
|
|
|
89
125
|
}
|
|
90
126
|
return value;
|
|
91
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* The reserved timeout envelope is minted by the alarm and by nothing else.
|
|
130
|
+
* A caller allowed to resume could otherwise drive a step's timeout branch
|
|
131
|
+
* while provenance still names them as the requester, which would make the
|
|
132
|
+
* one contract this feature sells — a timeout resume is distinguishable from
|
|
133
|
+
* a real signal — untrue. The KEY is refused, not just a well-formed
|
|
134
|
+
* envelope, so a step that reads the key directly cannot be fooled either.
|
|
135
|
+
*/
|
|
136
|
+
#resumeData(value) {
|
|
137
|
+
if (value !== null &&
|
|
138
|
+
typeof value === 'object' &&
|
|
139
|
+
SUSPENSION_TIMEOUT_RESUME_KEY in value) {
|
|
140
|
+
throw new InvalidRunRequestError(`resume data must not carry the reserved '${SUSPENSION_TIMEOUT_RESUME_KEY}' key`);
|
|
141
|
+
}
|
|
142
|
+
return value;
|
|
143
|
+
}
|
|
92
144
|
#trustedExecutionPrincipal(request) {
|
|
93
145
|
const encoded = request.headers.get(EXECUTION_PRINCIPAL_HEADER);
|
|
94
146
|
const principal = encoded ? decodeExecutionPrincipal(encoded) : undefined;
|
|
@@ -164,36 +216,115 @@ export class DurableObjectRunner {
|
|
|
164
216
|
release();
|
|
165
217
|
}
|
|
166
218
|
}
|
|
167
|
-
|
|
219
|
+
/**
|
|
220
|
+
* The arming path for this object's one alarm, which two independent duties
|
|
221
|
+
* share: run-owner recovery and the run's suspension deadlines. Every arm
|
|
222
|
+
* that reflects CONVERGED state routes through here, or through the
|
|
223
|
+
* #armAlarmFor it delegates to, because an alarm set for one duty from a
|
|
224
|
+
* site that cannot see the other would silently drop the other's wake — a
|
|
225
|
+
* suspended run's deadline is then lost until something else happens to
|
|
226
|
+
* re-arm it, and nothing else has to. The unconditional watchdog arm
|
|
227
|
+
* (#armAlarmWatchdog, and the retry wake a failed reconcile leaves behind)
|
|
228
|
+
* is the deliberate exception: it is set before anything is read, when no
|
|
229
|
+
* duty's state is known yet, and the body's own final arm replaces it.
|
|
230
|
+
*
|
|
231
|
+
* `recoveryDueAt` is the recovery time a caller is arming right now; without
|
|
232
|
+
* it the stored recovery record supplies one. No duty pending at all is the
|
|
233
|
+
* only case that deletes the alarm.
|
|
234
|
+
*/
|
|
235
|
+
async #armNextAlarm(recoveryDueAt) {
|
|
236
|
+
await this.#armAlarmFor(await this.#readSuspensionDeadlines(), recoveryDueAt);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* #armNextAlarm for a caller that already holds the record — the one it just
|
|
240
|
+
* read to derive entries, or the one it just wrote. Re-reading it here would
|
|
241
|
+
* charge every lifecycle boundary a second storage read for state the caller
|
|
242
|
+
* is holding.
|
|
243
|
+
*/
|
|
244
|
+
async #armAlarmFor(stored, recoveryDueAt) {
|
|
168
245
|
const storage = this.state?.storage;
|
|
169
246
|
if (!storage)
|
|
170
247
|
return;
|
|
171
248
|
if (!storage.setAlarm) {
|
|
172
|
-
throw new Error('run owner recovery
|
|
249
|
+
throw new Error('run owner recovery and suspension deadlines require Durable Object alarms');
|
|
250
|
+
}
|
|
251
|
+
const suspensionDueAt = nextSuspensionDeadlineAt(stored);
|
|
252
|
+
const recoveryDue = recoveryDueAt ??
|
|
253
|
+
((await storage.get(RUN_OWNER_RECOVERY_KEY)) !== undefined
|
|
254
|
+
? Date.now() + RUN_OWNER_RECOVERY_DELAY_MS
|
|
255
|
+
: undefined);
|
|
256
|
+
// `now` is sampled AFTER the awaited recovery-key read above. Hoisting it
|
|
257
|
+
// before the read would shrink the floor by the read's latency, and the
|
|
258
|
+
// floor is the anti-spin guarantee for an entry that is already due.
|
|
259
|
+
const due = nextDutyAlarmAt(suspensionDueAt, recoveryDue, Date.now());
|
|
260
|
+
if (due === undefined) {
|
|
261
|
+
await storage.deleteAlarm?.();
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
await storage.setAlarm(due);
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* The unconditional watchdog wake every alarm() body opens with: set BEFORE
|
|
268
|
+
* any read, so a body that dies mid-flight still leaves this object woken,
|
|
269
|
+
* and never a delete, because no branch has converged yet. One recovery delay
|
|
270
|
+
* out because that is the cadence of the duty that can only be retried, and
|
|
271
|
+
* because it is the wake the object keeps if the body cannot get far enough
|
|
272
|
+
* to compute a better one; the body's own final #armNextAlarm() replaces it
|
|
273
|
+
* with the true next due time.
|
|
274
|
+
*
|
|
275
|
+
* A reconcile whose write failed leaves the same wake for the same reason:
|
|
276
|
+
* it too knows only that something must wake this object, and nothing about
|
|
277
|
+
* what is stored — which is precisely what it could not write.
|
|
278
|
+
*/
|
|
279
|
+
async #armAlarmWatchdog() {
|
|
280
|
+
const storage = this.state?.storage;
|
|
281
|
+
if (!storage?.setAlarm) {
|
|
282
|
+
throw new Error('run owner recovery and suspension deadlines require Durable Object alarms');
|
|
173
283
|
}
|
|
174
284
|
await storage.setAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
|
|
285
|
+
}
|
|
286
|
+
async #armRunOwnerRecovery(recovery) {
|
|
287
|
+
const storage = this.state?.storage;
|
|
288
|
+
if (!storage)
|
|
289
|
+
return;
|
|
290
|
+
// Arm BEFORE journaling, never after: an isolate that dies between the two
|
|
291
|
+
// leaves a journal with no wake, and nothing else would recover the claim.
|
|
292
|
+
// An alarm with no journal yet is harmless — that wake finds nothing to do.
|
|
293
|
+
// One arm is enough, because a second one after the write would compute the
|
|
294
|
+
// same time from the same two inputs.
|
|
295
|
+
await this.#armNextAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
|
|
175
296
|
await storage.put(RUN_OWNER_RECOVERY_KEY, recovery);
|
|
176
|
-
await storage.setAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
|
|
177
297
|
}
|
|
178
|
-
|
|
298
|
+
/**
|
|
299
|
+
* `keepWake` is set by a caller whose reconciliation failed with something
|
|
300
|
+
* to arm: the retry wake it left is the only thing that will re-derive that
|
|
301
|
+
* deadline, and re-arming from storage here would find no record and no
|
|
302
|
+
* journal and DELETE it. Keeping the recovery cadence instead costs one
|
|
303
|
+
* spurious wake and cannot lose a deadline.
|
|
304
|
+
*/
|
|
305
|
+
async #clearRunOwnerRecovery(keepWake) {
|
|
179
306
|
const storage = this.state?.storage;
|
|
180
307
|
if (!storage)
|
|
181
308
|
return;
|
|
182
309
|
await storage.delete(RUN_OWNER_RECOVERY_KEY);
|
|
183
|
-
|
|
310
|
+
if (keepWake) {
|
|
311
|
+
await this.#armAlarmWatchdog();
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
await this.#armNextAlarm();
|
|
184
315
|
}
|
|
185
|
-
async #clearRunOwnerRecoveryBestEffort() {
|
|
316
|
+
async #clearRunOwnerRecoveryBestEffort(keepWake) {
|
|
186
317
|
try {
|
|
187
|
-
await this.#clearRunOwnerRecovery();
|
|
318
|
+
await this.#clearRunOwnerRecovery(keepWake);
|
|
188
319
|
}
|
|
189
320
|
catch (error) {
|
|
190
321
|
console.error('run owner recovery cleanup failed', error);
|
|
191
322
|
}
|
|
192
323
|
}
|
|
193
|
-
async #settleRunOwnerBestEffort(recovery, release) {
|
|
324
|
+
async #settleRunOwnerBestEffort(recovery, release, keepWake = false) {
|
|
194
325
|
try {
|
|
195
326
|
await this.runOwnership(this.env).settleReservation(recovery.token, release ? [{ kind: 'run', resourceId: recovery.runId }] : []);
|
|
196
|
-
await this.#clearRunOwnerRecoveryBestEffort();
|
|
327
|
+
await this.#clearRunOwnerRecoveryBestEffort(keepWake);
|
|
197
328
|
}
|
|
198
329
|
catch (error) {
|
|
199
330
|
console.error('run owner recovery settlement failed', error);
|
|
@@ -208,14 +339,582 @@ export class DurableObjectRunner {
|
|
|
208
339
|
async #rearmRunOwnerRecovery() {
|
|
209
340
|
const storage = this.state?.storage;
|
|
210
341
|
if (!storage?.setAlarm) {
|
|
211
|
-
throw new Error('run owner recovery
|
|
342
|
+
throw new Error('run owner recovery and suspension deadlines require Durable Object alarms');
|
|
343
|
+
}
|
|
344
|
+
await this.#armNextAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Hydrate this run's armed deadlines. A record this instance cannot parse is
|
|
348
|
+
* logged and deleted rather than thrown: the alarm has to converge, and a
|
|
349
|
+
* record that throws on every wake would strand the run's remaining
|
|
350
|
+
* deadlines forever.
|
|
351
|
+
*/
|
|
352
|
+
async #readSuspensionDeadlines() {
|
|
353
|
+
const storage = this.state?.storage;
|
|
354
|
+
if (!storage)
|
|
355
|
+
return undefined;
|
|
356
|
+
const stored = await storage.get(SUSPENSION_DEADLINE_STORAGE_KEY);
|
|
357
|
+
try {
|
|
358
|
+
return parseSuspensionDeadlineRecord(stored);
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
console.error('stored suspension deadline discarded', error);
|
|
362
|
+
await storage.delete(SUSPENSION_DEADLINE_STORAGE_KEY);
|
|
363
|
+
return undefined;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Persist the run's armed deadlines and re-arm from what was just written.
|
|
368
|
+
* `stored` is the record the caller read to compute `entries`: a boundary
|
|
369
|
+
* with nothing stored that derives nothing writes nothing at all, because
|
|
370
|
+
* every consumer that never arms a deadline would otherwise pay a delete and
|
|
371
|
+
* an alarm write at each start, resume and termination. Nothing changed
|
|
372
|
+
* there, so the alarm the recovery duty owns is left exactly as it was.
|
|
373
|
+
*/
|
|
374
|
+
async #writeSuspensionDeadlines(workflowId, runId, stored, entries) {
|
|
375
|
+
const storage = this.state?.storage;
|
|
376
|
+
if (!storage)
|
|
377
|
+
return;
|
|
378
|
+
if (stored === undefined && entries.length === 0)
|
|
379
|
+
return;
|
|
380
|
+
let written;
|
|
381
|
+
if (entries.length === 0) {
|
|
382
|
+
await storage.delete(SUSPENSION_DEADLINE_STORAGE_KEY);
|
|
383
|
+
}
|
|
384
|
+
else {
|
|
385
|
+
written = { version: 1, workflowId, runId, entries: [...entries] };
|
|
386
|
+
await storage.put(SUSPENSION_DEADLINE_STORAGE_KEY, written);
|
|
387
|
+
}
|
|
388
|
+
await this.#armAlarmFor(written);
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Re-derive this run's deadlines from an authoritative summary and re-arm.
|
|
392
|
+
* Called at every lifecycle boundary that produces one, and at every wake
|
|
393
|
+
* that ends without a resume: derivation is idempotent (an entry is keyed by
|
|
394
|
+
* the suspension that created it), so a boundary that changed nothing
|
|
395
|
+
* rewrites the same record, a run that is no longer suspended derives
|
|
396
|
+
* nothing and clears it, and a suspension nothing has armed yet is armed
|
|
397
|
+
* here. That last case is why this is the wake's own no-resume exit: a run
|
|
398
|
+
* whose only remaining event is its own alarm has no other boundary coming.
|
|
399
|
+
*/
|
|
400
|
+
async #reconcileSuspensionDeadlines(workflowId, runId, summary, stored) {
|
|
401
|
+
if (!this.state?.storage)
|
|
402
|
+
return;
|
|
403
|
+
const { entries: derived, rejected } = suspensionDeadlinesOf(summary);
|
|
404
|
+
for (const rejection of rejected) {
|
|
405
|
+
this.#logSuspensionDeadlineRejection(runId, rejection);
|
|
406
|
+
}
|
|
407
|
+
// `stored` is the record a wake already read this alarm; re-reading it
|
|
408
|
+
// here would be the second storage read #armAlarmFor's JSDoc refuses to
|
|
409
|
+
// pay. `null` is a wake that read and found NOTHING stored, which `??`
|
|
410
|
+
// could not tell from a lifecycle boundary holding no record at all
|
|
411
|
+
// (undefined) — the one that must read.
|
|
412
|
+
const previous = stored === undefined
|
|
413
|
+
? await this.#readSuspensionDeadlines()
|
|
414
|
+
: (stored ?? undefined);
|
|
415
|
+
// The ledger belongs to a suspension of THIS run: a record stamped for
|
|
416
|
+
// another run carries nothing this run may inherit. The merge matches on
|
|
417
|
+
// the suspension's own keys and not on the record's ids, so without this a
|
|
418
|
+
// foreign entry whose step, fence and deadline happened to coincide would
|
|
419
|
+
// hand its spent budget to this run's live deadline, which would then be
|
|
420
|
+
// born abandoned. `previous` still reaches the write below, whose
|
|
421
|
+
// write-or-skip decision is about the key that is stored, not about whose
|
|
422
|
+
// run it names.
|
|
423
|
+
const inherited = previous?.workflowId === workflowId && previous.runId === runId
|
|
424
|
+
? previous
|
|
425
|
+
: undefined;
|
|
426
|
+
await this.#writeSuspensionDeadlines(workflowId, runId, previous, mergeSuspensionDeadlines(inherited, derived));
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Report a deadline the run asked for and did not get, once. Derivation runs
|
|
430
|
+
* at every boundary, so an unchanged suspension re-derives the identical
|
|
431
|
+
* rejection: logging each one every time would bury the rest of the log
|
|
432
|
+
* under a single author mistake. Bounded by the per-run entry cap so a
|
|
433
|
+
* long-lived object with a churning set of steps cannot grow this set.
|
|
434
|
+
*/
|
|
435
|
+
#logSuspensionDeadlineRejection(runId, rejection) {
|
|
436
|
+
const seen = `${rejection.step}\u0000${rejection.reason}`;
|
|
437
|
+
if (this.#reportedSuspensionRejections.has(seen))
|
|
438
|
+
return;
|
|
439
|
+
if (this.#reportedSuspensionRejections.size >=
|
|
440
|
+
MAX_SUSPENSION_DEADLINES_PER_RUN) {
|
|
441
|
+
this.#reportedSuspensionRejections.clear();
|
|
442
|
+
}
|
|
443
|
+
this.#reportedSuspensionRejections.add(seen);
|
|
444
|
+
console.error(`suspension deadline not armed for step '${rejection.step}' of run '${runId}': ${rejection.reason}`);
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Reconciliation is bookkeeping ABOUT a transition that has already been
|
|
448
|
+
* persisted by the runtime. Failing the caller's start, resume, or
|
|
449
|
+
* termination over it would report a lifecycle failure that did not happen,
|
|
450
|
+
* so the failure is logged instead — and, when there was something to arm,
|
|
451
|
+
* answered with a retry wake, because a suspended run is guaranteed no other
|
|
452
|
+
* boundary. That wake re-derives from `authoritativeStatus()` whether or not
|
|
453
|
+
* a record exists (#reconcileFromAuthoritativeStatus); the record it holds is
|
|
454
|
+
* only the identity fallback, with its ledger carried by the merge. Returns
|
|
455
|
+
* whether the deadlines converged, so a caller that would otherwise re-arm
|
|
456
|
+
* from storage can leave the retry wake alone (#clearRunOwnerRecovery's
|
|
457
|
+
* `keepWake`).
|
|
458
|
+
*
|
|
459
|
+
* A failure to arm the retry wake itself loses the deadline. That is the
|
|
460
|
+
* lost-alarm failure mode the design already owns, now narrowed to it.
|
|
461
|
+
*/
|
|
462
|
+
async #reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary) {
|
|
463
|
+
try {
|
|
464
|
+
await this.#reconcileSuspensionDeadlines(workflowId, runId, summary);
|
|
465
|
+
return true;
|
|
466
|
+
}
|
|
467
|
+
catch (error) {
|
|
468
|
+
console.error('suspension deadline reconciliation failed', error);
|
|
469
|
+
// Derivation is pure and never throws, so asking it what was at stake
|
|
470
|
+
// costs nothing. Nothing derivable means nothing was lost: a stale
|
|
471
|
+
// record that could not be deleted is healed by its own alarm.
|
|
472
|
+
if (suspensionDeadlinesOf(summary).entries.length === 0)
|
|
473
|
+
return true;
|
|
474
|
+
try {
|
|
475
|
+
await this.#armAlarmWatchdog();
|
|
476
|
+
}
|
|
477
|
+
catch (alarmError) {
|
|
478
|
+
console.error('suspension deadline retry wake failed', alarmError);
|
|
479
|
+
}
|
|
480
|
+
return false;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
// An entry is keyed by the DOT-JOINED suspended path, exactly as the summary
|
|
484
|
+
// keys the two fence fields read below, so the path is joined here too. The
|
|
485
|
+
// wake reads the rehydrated projection, which splits a stored key on every
|
|
486
|
+
// dot: comparing a single segment instead would fail to recognize a top-level
|
|
487
|
+
// step id containing a dot ([['a','b']] against 'a.b') and silently discard
|
|
488
|
+
// its deadline. Nested paths never reach this point (suspension-deadline.ts
|
|
489
|
+
// refuses them, having no fence of their own), so a joined match cannot be a
|
|
490
|
+
// nested suspension wearing a top-level entry's key.
|
|
491
|
+
#suspensionFenceMatches(summary, entry) {
|
|
492
|
+
return (summary.status === 'suspended' &&
|
|
493
|
+
(summary.suspended ?? []).some((path) => path.join('.') === entry.step) &&
|
|
494
|
+
summary.suspendedAt?.[entry.step] === entry.suspendedAt &&
|
|
495
|
+
(summary.resumeCount?.[entry.step] ?? 0) === entry.resumeCount);
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Charge one failed wake to the retry ledger of the entry that wake was
|
|
499
|
+
* working on, and abandon that entry once the budget is spent. Every failure
|
|
500
|
+
* INSIDE the deadline duty that leaves its entry unconsumed comes through
|
|
501
|
+
* here, because an entry that stays due would otherwise re-arm the alarm at
|
|
502
|
+
* an already-past time, which Cloudflare fires immediately: the ledger is
|
|
503
|
+
* what turns a persistent failure into a backoff rather than a wake loop.
|
|
504
|
+
* A wake that fails before the duty runs at all cannot converge a ledger and
|
|
505
|
+
* does not try to — it keeps the watchdog's recovery cadence instead.
|
|
506
|
+
*
|
|
507
|
+
* Abandonment keeps the entry as a TOMBSTONE (`attempts` at the budget, no
|
|
508
|
+
* retry floor) rather than removing it: every reconcile re-derives the
|
|
509
|
+
* still-armed suspend payload, so a removed entry would come back with a
|
|
510
|
+
* clean ledger on the next boundary or wake — past due, armed at the floor —
|
|
511
|
+
* and the budget would bound one burst instead of the suspension. The merge
|
|
512
|
+
* carries the tombstone while the fence is unchanged and drops it when the
|
|
513
|
+
* suspension moves on, so a later suspension of the same step starts fresh.
|
|
514
|
+
*/
|
|
515
|
+
async #chargeSuspensionDeadlineAttempt(stored, entry, now, error) {
|
|
516
|
+
const { workflowId, runId } = stored;
|
|
517
|
+
const remaining = entriesWithoutStep(stored.entries, entry.step);
|
|
518
|
+
const attempts = (entry.attempts ?? 0) + 1;
|
|
519
|
+
if (attempts >= MAX_SUSPENSION_DEADLINE_ATTEMPTS) {
|
|
520
|
+
console.error(`suspension deadline for step '${entry.step}' of run '${runId}' dropped after ${attempts} failed wakes`, error);
|
|
521
|
+
await this.#writeSuspensionDeadlines(workflowId, runId, stored, [
|
|
522
|
+
...remaining,
|
|
523
|
+
tombstoned(entry),
|
|
524
|
+
]);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
console.error(`suspension deadline wake for step '${entry.step}' of run '${runId}' failed (attempt ${attempts})`, error);
|
|
528
|
+
// Rebuilt field by field rather than spread from `entry`: the REBUILD is
|
|
529
|
+
// what drops the unreadable-state stamp. Two wakes reach a charge: one
|
|
530
|
+
// whose authoritative read SUCCEEDED — and a successful read is exactly
|
|
531
|
+
// what clears that stamp — and the identity assert, the one charged
|
|
532
|
+
// failure that read nothing.
|
|
533
|
+
// Clearing the stamp there costs nothing: an entry a foreign record put in
|
|
534
|
+
// front of this object's own name is charged every wake and tombstoned by
|
|
535
|
+
// the fifth, which is how that record goes quiet.
|
|
536
|
+
await this.#writeSuspensionDeadlines(workflowId, runId, stored, [
|
|
537
|
+
...remaining,
|
|
538
|
+
{
|
|
539
|
+
step: entry.step,
|
|
540
|
+
deadlineAt: entry.deadlineAt,
|
|
541
|
+
suspendedAt: entry.suspendedAt,
|
|
542
|
+
resumeCount: entry.resumeCount,
|
|
543
|
+
attempts,
|
|
544
|
+
// attempts caps at 4 here, so the backoff tops out at 480s and needs
|
|
545
|
+
// no ceiling of its own.
|
|
546
|
+
nextAttemptAt: now + SUSPENSION_DEADLINE_RETRY_MS * 2 ** (attempts - 1),
|
|
547
|
+
},
|
|
548
|
+
]);
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Record that this wake could not read the run's authoritative state, and
|
|
552
|
+
* abandon an entry once that has been true of it for a day.
|
|
553
|
+
*
|
|
554
|
+
* Stamps EVERY entry due at this wake, not just the one the wake selected: a
|
|
555
|
+
* read that did not succeed is one fact about the whole run, and one clock
|
|
556
|
+
* per due batch is what keeps an N-entry record's bound at a day rather than
|
|
557
|
+
* N days (a serial clock would only start the second entry's day once the
|
|
558
|
+
* first was abandoned). Entries not yet due are left byte-identical — their
|
|
559
|
+
* day begins when they fall due, not when a sibling's did.
|
|
560
|
+
*
|
|
561
|
+
* Never a charge: a read that did not succeed is no evidence about any entry,
|
|
562
|
+
* and the abandonment budget exists for failed resumes — spending it on a
|
|
563
|
+
* fifteen-minute storage incident would permanently abandon every deadline
|
|
564
|
+
* falling due inside one. The stamp is what still bounds the other side: a
|
|
565
|
+
* run whose state became permanently unreadable (a deploy that dropped the
|
|
566
|
+
* workflow registration for good) would otherwise keep a 60 s heartbeat
|
|
567
|
+
* forever. Any successful read clears it — the merge rebuilds the entry from
|
|
568
|
+
* the derived one, and a charge rebuilds it field by field. The bound is
|
|
569
|
+
* therefore conditional on this write LANDING: it is best effort, and a
|
|
570
|
+
* storage layer that cannot write this key converges nothing anyway, so the
|
|
571
|
+
* failure is logged and the wake keeps its cadence.
|
|
572
|
+
*
|
|
573
|
+
* Writes the record and NOTHING else, deliberately not through
|
|
574
|
+
* #writeSuspensionDeadlines: while the clock is merely running this wake has
|
|
575
|
+
* converged nothing, so the watchdog armed at the top of alarm() is the
|
|
576
|
+
* cadence it must keep. Arming from a still-due entry that no ledger backed
|
|
577
|
+
* off would land on the one-second floor and spin this object for the length
|
|
578
|
+
* of the incident.
|
|
579
|
+
*
|
|
580
|
+
* Answers whether anything was ABANDONED, which is a convergence: giving up
|
|
581
|
+
* on an entry and then waking every minute for it forever is incoherent, so
|
|
582
|
+
* the caller reports it as converged and the body's final arm re-reads what
|
|
583
|
+
* is left — for a record holding nothing else, the delete that finally ends
|
|
584
|
+
* the heartbeat this bound exists to end.
|
|
585
|
+
*/
|
|
586
|
+
async #markSuspensionDeadlineUnreadable(stored, now) {
|
|
587
|
+
const storage = this.state?.storage;
|
|
588
|
+
if (!storage)
|
|
589
|
+
return false;
|
|
590
|
+
try {
|
|
591
|
+
let abandoned = false;
|
|
592
|
+
let changed = false;
|
|
593
|
+
const entries = stored.entries.map((entry) => {
|
|
594
|
+
if (!isSuspensionDeadlineDue(entry, now))
|
|
595
|
+
return entry;
|
|
596
|
+
// Clamped to this wake: a stamp in the FUTURE — a clock that stepped
|
|
597
|
+
// backwards between two wakes, or a hand-written record — would put
|
|
598
|
+
// `now - since` permanently below the limit and pin an uncharged
|
|
599
|
+
// heartbeat forever. Clamping alone would not end it either (the next
|
|
600
|
+
// wake would clamp the same untouched stamp again), so the corrected
|
|
601
|
+
// value is what gets written below: the day starts at this wake.
|
|
602
|
+
const since = Math.min(entry.unreadableSince ?? now, now);
|
|
603
|
+
if (now - since > SUSPENSION_DEADLINE_UNREADABLE_LIMIT_MS) {
|
|
604
|
+
console.error(`suspension deadline for step '${entry.step}' of run '${stored.runId}' abandoned after 24 h of unreadable run state`);
|
|
605
|
+
abandoned = true;
|
|
606
|
+
changed = true;
|
|
607
|
+
return tombstoned(entry);
|
|
608
|
+
}
|
|
609
|
+
// Stamped once: the first unsuccessful read is what starts the clock,
|
|
610
|
+
// and rewriting it every wake would push the bound out forever. A
|
|
611
|
+
// stamp already at its clamped value is that first one; anything else
|
|
612
|
+
// is the future stamp being corrected.
|
|
613
|
+
if (entry.unreadableSince === since)
|
|
614
|
+
return entry;
|
|
615
|
+
changed = true;
|
|
616
|
+
return { ...entry, unreadableSince: since };
|
|
617
|
+
});
|
|
618
|
+
if (!changed)
|
|
619
|
+
return false;
|
|
620
|
+
// The SECOND writer of a tombstone, and the one that deliberately does
|
|
621
|
+
// not arm: the charge writer goes through #writeSuspensionDeadlines and
|
|
622
|
+
// re-arms from what it wrote, while this one has converged nothing worth
|
|
623
|
+
// arming for and leaves the alarm to alarm()'s own final arm on the
|
|
624
|
+
// wakes that did converge.
|
|
625
|
+
await storage.put(SUSPENSION_DEADLINE_STORAGE_KEY, { ...stored, entries });
|
|
626
|
+
return abandoned;
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
console.error('suspension deadline unreadable-state marker failed', error);
|
|
630
|
+
return false;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* The authoritative read every alarm path makes, carrying the one conclusion
|
|
635
|
+
* an alarm may draw from its failure: every way this read can fail —
|
|
636
|
+
* Mastra's in-memory fallback, an unregistered workflow, a storage fault —
|
|
637
|
+
* is a read that did not succeed, and nothing downstream of it may conclude
|
|
638
|
+
* anything else. One helper rather than the same try/catch at each site so
|
|
639
|
+
* that rule is structural: an alarm-path authoritative read that is NOT
|
|
640
|
+
* classified is one that did not come through here.
|
|
641
|
+
*/
|
|
642
|
+
async #authoritativeStatusOrUnreadable(runtime, workflowId, runId) {
|
|
643
|
+
try {
|
|
644
|
+
return await runtime.authoritativeStatus(workflowId, runId);
|
|
645
|
+
}
|
|
646
|
+
catch (error) {
|
|
647
|
+
throw error instanceof RunStateUnreadableError
|
|
648
|
+
? error
|
|
649
|
+
: new RunStateUnreadableError(workflowId, runId, { cause: error });
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Resume the run for the ONE entry this wake selected. Bounded work per wake
|
|
654
|
+
* keeps a run with many armed steps from executing an unbounded number of
|
|
655
|
+
* workflow bodies in a single alarm; #armNextAlarm() schedules the next.
|
|
656
|
+
*
|
|
657
|
+
* Throws on every failure that leaves the entry unconsumed, so its caller can
|
|
658
|
+
* charge the ledger of the entry it selected and no other. The runtime comes
|
|
659
|
+
* from the caller because BUILDING one is not such a failure: a misconfigured
|
|
660
|
+
* binding throws on every wake and says nothing about this entry, so that
|
|
661
|
+
* throw must land before an entry is in hand to charge.
|
|
662
|
+
*/
|
|
663
|
+
async #resumeDueSuspensionDeadline(runtime, stored, entry, now) {
|
|
664
|
+
const { workflowId, runId } = stored;
|
|
665
|
+
// INV-1 at the one boundary whose ids come from storage rather than from
|
|
666
|
+
// the trusted Worker: this wake is about to execute a workflow body, so it
|
|
667
|
+
// must be this object's own run (and its per-run serialization). Charged
|
|
668
|
+
// like any other duty failure, deliberately: it is the one charged failure
|
|
669
|
+
// that read nothing, and charging is what quiets a foreign record's entry
|
|
670
|
+
// (five wakes to a tombstone). It stays here rather than moving up with the
|
|
671
|
+
// runtime because the nothing-due path below deliberately prefers `id.name`
|
|
672
|
+
// over a foreign record, which asserting early would break.
|
|
673
|
+
this.#assertRunIdentity(workflowId, runId);
|
|
674
|
+
// The fence is re-read from authoritative state inside the operation lock:
|
|
675
|
+
// a real signal may have resumed this suspension since the entry was
|
|
676
|
+
// armed, and resuming again would run the step twice.
|
|
677
|
+
//
|
|
678
|
+
// ONLY A READ THAT SUCCEEDED MAY CONCLUDE ANYTHING, which is why this read
|
|
679
|
+
// goes through the classifier above rather than being taken at face value:
|
|
680
|
+
// the caller can then keep the watchdog instead of spending an abandonment
|
|
681
|
+
// budget on an incident, and nothing AFTER this fence can masquerade as
|
|
682
|
+
// one.
|
|
683
|
+
const summary = await this.#authoritativeStatusOrUnreadable(runtime, workflowId, runId);
|
|
684
|
+
// A read that succeeded and found NOTHING is not evidence that a signal got
|
|
685
|
+
// there first either — a read replica may not yet show a snapshot this
|
|
686
|
+
// object itself wrote — but it is evidence the store answered, and D1
|
|
687
|
+
// staleness windows are sub-second against a 900 s budget. So it is charged
|
|
688
|
+
// as a failed wake and terminates as a tombstone, which is what quietly
|
|
689
|
+
// ends the record of a run whose state is genuinely gone. The predicate is
|
|
690
|
+
// the second line of defence, for a self-inconsistent 'suspended'
|
|
691
|
+
// projection from any cause; it must be applied BEFORE the fence check,
|
|
692
|
+
// which such a summary would fail, sending the moved-on reconcile below on
|
|
693
|
+
// to wipe every entry of a run that is still suspended.
|
|
694
|
+
if (!summary || !isReadableRunSummary(summary)) {
|
|
695
|
+
throw new Error(`run '${runId}' of workflow '${workflowId}' read back absent or self-inconsistent`);
|
|
696
|
+
}
|
|
697
|
+
if (!this.#suspensionFenceMatches(summary, entry)) {
|
|
698
|
+
// A discarded deadline must be visible: this is the branch a real signal
|
|
699
|
+
// reaches, and also the one a projection disagreement would reach.
|
|
700
|
+
console.error(`suspension deadline for step '${entry.step}' of run '${runId}' dropped: the suspension it was armed against has moved on`);
|
|
701
|
+
// Reconcile rather than merely drop the entry. The summary in hand is
|
|
702
|
+
// authoritative, and it may show a NEW suspension — one this run's own
|
|
703
|
+
// failed bookkeeping never armed. Dropping alone would leave a suspended
|
|
704
|
+
// run with a derivable deadline, no record, and no further wake. The
|
|
705
|
+
// record this wake read goes with it: re-reading it would be the second
|
|
706
|
+
// storage read #armAlarmFor's JSDoc refuses to pay.
|
|
707
|
+
await this.#reconcileSuspensionDeadlines(workflowId, runId, summary, stored);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
const next = await runtime.resume(workflowId, runId, {
|
|
711
|
+
step: [entry.step],
|
|
712
|
+
resumeData: suspensionTimeoutResumeData(entry, now),
|
|
713
|
+
requestedBy: SUSPENSION_DEADLINE_PRINCIPAL_ID,
|
|
714
|
+
requestedByKind: 'system',
|
|
715
|
+
});
|
|
716
|
+
// EVERYTHING after this point is best effort, because the resume has
|
|
717
|
+
// already run the step: charging a bookkeeping failure to the retry ledger
|
|
718
|
+
// would record a failed resume that in fact succeeded, and could resume the
|
|
719
|
+
// run a second time. The broadcast is one of those failures — its frame is
|
|
720
|
+
// built by JSON.stringify OUTSIDE safeSend's per-socket tolerance, so a
|
|
721
|
+
// step result JSON cannot encode (a bigint, a cycle, a throwing toJSON)
|
|
722
|
+
// throws here rather than in the send it was meant to survive.
|
|
723
|
+
try {
|
|
724
|
+
this.#broadcastRunSummary(next);
|
|
725
|
+
}
|
|
726
|
+
catch (error) {
|
|
727
|
+
console.error('suspension deadline broadcast failed', error);
|
|
728
|
+
}
|
|
729
|
+
await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, next);
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* The shared end of every wake that will not resume AND holds no
|
|
733
|
+
* authoritative summary of its own (the fence-moved branch above re-derives
|
|
734
|
+
* directly from the one it read): re-derive this run's deadlines from
|
|
735
|
+
* authoritative state. The set of wakes that land here with nothing due is
|
|
736
|
+
* ordinary, not anomalous — the watchdog survivor whose duty already ran,
|
|
737
|
+
* H1's retry wake after a failed reconcile, a recovery-armed wake whose
|
|
738
|
+
* start body outlived the 60 s recovery delay (a healthy slow workflow), a
|
|
739
|
+
* workerd alarm redelivery or at-least-once retry after a rethrown recovery
|
|
740
|
+
* error (up to 6 retries), and an entry still inside the 1 s arm floor. The
|
|
741
|
+
* `authoritativeStatus()` read lands off the lifecycle hot path on exactly
|
|
742
|
+
* those wakes — and it is the authoritative read, not `status()`, because
|
|
743
|
+
* this path DELETES a record it derives nothing from, so Mastra's in-memory
|
|
744
|
+
* fallback reaching it would silently wipe the wake state of a run that is
|
|
745
|
+
* still suspended. It cannot be skipped when a record exists: the boundary
|
|
746
|
+
* that should have armed this run's CURRENT suspension may have failed to
|
|
747
|
+
* write, and the record in hand is then stale — its own fence check only
|
|
748
|
+
* runs when its entry falls due, so re-arming to it would let a short
|
|
749
|
+
* re-suspension deadline hide behind a far-future stale one. Accepted cost:
|
|
750
|
+
* an interrupted-start recovery wake that DID arm pays a second
|
|
751
|
+
* `authoritativeStatus()` and record write here after #recoverRunOwner's own
|
|
752
|
+
* reconcile — a rare path.
|
|
753
|
+
*
|
|
754
|
+
* Identity, three ways: a valid `id.name` is the single source under
|
|
755
|
+
* workerd — the trusted Worker addressed this instance as
|
|
756
|
+
* idFromName(`${workflowId}:${runId}`), PATH_SAFE_ID_PATTERN excludes ':'
|
|
757
|
+
* from both ids, and stored ids are never asserted against it (a foreign
|
|
758
|
+
* record's entries are simply dropped by the merge). A name that is present
|
|
759
|
+
* but does not split into two path-safe ids skips the step entirely — a
|
|
760
|
+
* record written from an unvalidated name would discard itself on read-back,
|
|
761
|
+
* and a foreign record must not steer a status read either. Without a name
|
|
762
|
+
* (Node stubs) the stored record supplies the ids; without either, the wake
|
|
763
|
+
* converges to no alarm and a deadline whose record was never written is
|
|
764
|
+
* lost. Production is safe from that last case because the exported topology
|
|
765
|
+
* (host-kit/do-run-topology.ts) always addresses this object by idFromName.
|
|
766
|
+
*/
|
|
767
|
+
async #reconcileFromAuthoritativeStatus(stored) {
|
|
768
|
+
const name = this.state?.id?.name;
|
|
769
|
+
let workflowId;
|
|
770
|
+
let runId;
|
|
771
|
+
if (name !== undefined) {
|
|
772
|
+
const parts = name.split(':');
|
|
773
|
+
if (parts.length !== 2)
|
|
774
|
+
return;
|
|
775
|
+
const [namedWorkflowId, namedRunId] = parts;
|
|
776
|
+
// isPathSafeId rejects the empty string and narrows both halves, so a
|
|
777
|
+
// separate truthiness check would only restate it.
|
|
778
|
+
if (!isPathSafeId(namedWorkflowId) || !isPathSafeId(namedRunId))
|
|
779
|
+
return;
|
|
780
|
+
workflowId = namedWorkflowId;
|
|
781
|
+
runId = namedRunId;
|
|
782
|
+
}
|
|
783
|
+
else if (stored) {
|
|
784
|
+
workflowId = stored.workflowId;
|
|
785
|
+
runId = stored.runId;
|
|
786
|
+
}
|
|
787
|
+
else {
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
// Built outside the wrap below on purpose: a runtime that cannot be BUILT
|
|
791
|
+
// is a binding fault, not an unreadable run, and its throw belongs to the
|
|
792
|
+
// caller's generic branch (which has no entry in hand here, so it keeps the
|
|
793
|
+
// watchdog either way).
|
|
794
|
+
const runtime = this.#ensureRuntime();
|
|
795
|
+
// Through the same classifier the resume path uses, so a read that did not
|
|
796
|
+
// succeed reaches the caller as one fact with one log line instead of the
|
|
797
|
+
// charged-failure wording for a wake that charges nothing.
|
|
798
|
+
const summary = await this.#authoritativeStatusOrUnreadable(runtime, workflowId, runId);
|
|
799
|
+
if (!summary)
|
|
800
|
+
return;
|
|
801
|
+
// The second line of defence, for a self-inconsistent 'suspended'
|
|
802
|
+
// projection the marker does not cover: it converges exactly like an
|
|
803
|
+
// absent read — without reconciling, so the record in hand stays and the
|
|
804
|
+
// caller's re-arm keeps its wake — but it is logged, because unlike a
|
|
805
|
+
// truly unknown run it means a suspended run's state could not be read.
|
|
806
|
+
if (!isReadableRunSummary(summary)) {
|
|
807
|
+
// Worded apart from the resume path's identical-looking refusal on
|
|
808
|
+
// purpose: that one is CHARGED to the entry's budget and this one never
|
|
809
|
+
// is, so an operator grepping the log can tell which consequence a line
|
|
810
|
+
// carried.
|
|
811
|
+
console.error(`run '${runId}' of workflow '${workflowId}' state read back self-inconsistent; keeping the record`);
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
await this.#reconcileSuspensionDeadlines(workflowId, runId, summary, stored);
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Never rethrows. workerd retries a thrown alarm(), which would re-run this
|
|
818
|
+
* whole wake — including a resume that may have executed workflow steps — so
|
|
819
|
+
* this branch owns its own retry ledger and reports failures instead.
|
|
820
|
+
*
|
|
821
|
+
* Answers whether the deadline duty CONVERGED, which is what tells the
|
|
822
|
+
* caller its final arm is safe. It did not converge when nothing could be
|
|
823
|
+
* charged or settled for a failure — the record unreadable, the runtime
|
|
824
|
+
* unbuildable, the ledger write itself failing, or an authoritative read
|
|
825
|
+
* that did not succeed (which is never charged at all) — because an arm
|
|
826
|
+
* computed from a still-due entry that no ledger backed off lands on the
|
|
827
|
+
* floor and wakes again a second later, forever. The one exception is the
|
|
828
|
+
* 24 h abandonment of a continuously unreadable entry: that settles the
|
|
829
|
+
* entry, so it converges.
|
|
830
|
+
*/
|
|
831
|
+
async #runDueSuspensionDeadline(now) {
|
|
832
|
+
let stored;
|
|
833
|
+
let entry;
|
|
834
|
+
try {
|
|
835
|
+
stored = await this.#readSuspensionDeadlines();
|
|
836
|
+
if (!stored) {
|
|
837
|
+
// `null`, not nothing: this wake HAS read the record key and found it
|
|
838
|
+
// empty, so the reconcile below must not read it a second time.
|
|
839
|
+
await this.#reconcileFromAuthoritativeStatus(null);
|
|
840
|
+
return true;
|
|
841
|
+
}
|
|
842
|
+
// Built BEFORE an entry is selected, and passed down rather than built
|
|
843
|
+
// where it is used. `build(env)` is the host's, and a misconfigured
|
|
844
|
+
// binding throws from it on every wake — a fault that says nothing about
|
|
845
|
+
// any entry, so charging it would tombstone a live deadline in five
|
|
846
|
+
// wakes. Landing the throw with no entry in hand keeps it uncharged, on
|
|
847
|
+
// the watchdog cadence, exactly like the identity failure one layer up.
|
|
848
|
+
const runtime = this.#ensureRuntime();
|
|
849
|
+
entry = dueSuspensionDeadline(stored, now);
|
|
850
|
+
if (!entry) {
|
|
851
|
+
// Same end as the no-record wake: a wake that will not resume
|
|
852
|
+
// re-derives from authoritative state, because the boundary that
|
|
853
|
+
// should have armed this run's current suspension may have failed to
|
|
854
|
+
// write, and the record in hand is then stale (its own fence check
|
|
855
|
+
// only runs when it falls due).
|
|
856
|
+
await this.#reconcileFromAuthoritativeStatus(stored);
|
|
857
|
+
return true;
|
|
858
|
+
}
|
|
859
|
+
await this.#resumeDueSuspensionDeadline(runtime, stored, entry, now);
|
|
860
|
+
return true;
|
|
861
|
+
}
|
|
862
|
+
catch (error) {
|
|
863
|
+
// Classified FIRST, or every degraded wake would also log the generic
|
|
864
|
+
// failure below. A read that did not succeed converges nothing and
|
|
865
|
+
// charges nothing: it keeps the watchdog cadence until it heals, and the
|
|
866
|
+
// entry it was working on carries the clock that bounds that.
|
|
867
|
+
if (error instanceof RunStateUnreadableError) {
|
|
868
|
+
console.error('suspension deadline wake could not read authoritative state', error);
|
|
869
|
+
// Converged only where the marker ABANDONS an entry: that is the one
|
|
870
|
+
// outcome here that settles anything, and leaving the alarm armed for
|
|
871
|
+
// an entry just given up on would keep the heartbeat forever.
|
|
872
|
+
//
|
|
873
|
+
// `entry` is the gate, not the target: it is what proves this wake had
|
|
874
|
+
// duty work due at all (a wake whose nothing-due re-derivation could
|
|
875
|
+
// not read has no clock to run), and the marker then covers every entry
|
|
876
|
+
// due at the same moment, because one failed read is one fact about
|
|
877
|
+
// them all.
|
|
878
|
+
return stored && entry
|
|
879
|
+
? await this.#markSuspensionDeadlineUnreadable(stored, now)
|
|
880
|
+
: false;
|
|
881
|
+
}
|
|
882
|
+
console.error('suspension deadline wake failed', error);
|
|
883
|
+
// The charge names the entry this wake had in hand, never one re-selected
|
|
884
|
+
// afterwards: with two entries due, re-selecting would push the second
|
|
885
|
+
// one out and spend a fifth of a budget it never used. A failure with no
|
|
886
|
+
// entry in hand — the record itself unreadable, or the re-derivation
|
|
887
|
+
// above — has nothing to charge, so it keeps the watchdog cadence.
|
|
888
|
+
if (!stored || !entry)
|
|
889
|
+
return false;
|
|
890
|
+
try {
|
|
891
|
+
await this.#chargeSuspensionDeadlineAttempt(stored, entry, now, error);
|
|
892
|
+
return true;
|
|
893
|
+
}
|
|
894
|
+
catch (ledgerError) {
|
|
895
|
+
console.error('suspension deadline ledger update failed', ledgerError);
|
|
896
|
+
return false;
|
|
897
|
+
}
|
|
212
898
|
}
|
|
213
|
-
await storage.setAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
|
|
214
899
|
}
|
|
215
900
|
async #recoverRunOwner(recovery) {
|
|
216
901
|
const summary = await this.#ensureRuntime().recoverStartAttempt(recovery.workflowId, recovery.runId, recovery.token);
|
|
217
902
|
await this.runOwnership(this.env).settleReservation(recovery.token, summary ? [] : [{ kind: 'run', resourceId: recovery.runId }]);
|
|
218
|
-
|
|
903
|
+
// A start interrupted AFTER Mastra persisted a suspension is the one case
|
|
904
|
+
// where no other boundary is coming: the route that would have reconciled
|
|
905
|
+
// died with its isolate, and clearing the journal below re-arms the alarm
|
|
906
|
+
// from a record nothing ever wrote. This summary is the authoritative one
|
|
907
|
+
// recoverStartAttempt read back, so derive from it here or the run stays
|
|
908
|
+
// suspended with no wake at all. It needs no readability guard of its own:
|
|
909
|
+
// recoverStartAttempt now throws RunStateUnreadableError on Mastra's
|
|
910
|
+
// in-memory fallback BEFORE it concludes anything from it, so a degraded
|
|
911
|
+
// read never reaches this line. That throw leaves the journal and the
|
|
912
|
+
// reservation intact and propagates to alarm(), which classifies it and
|
|
913
|
+
// keeps the 60 s recovery cadence until the read heals.
|
|
914
|
+
const reconciled = summary
|
|
915
|
+
? await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, summary)
|
|
916
|
+
: true;
|
|
917
|
+
await this.#clearRunOwnerRecovery(!reconciled);
|
|
219
918
|
}
|
|
220
919
|
#runOwnerRecovery(value) {
|
|
221
920
|
if (value === null || typeof value !== 'object') {
|
|
@@ -243,20 +942,50 @@ export class DurableObjectRunner {
|
|
|
243
942
|
}
|
|
244
943
|
async alarm() {
|
|
245
944
|
await this.#withOperationLock(async () => {
|
|
246
|
-
await this.#
|
|
945
|
+
await this.#armAlarmWatchdog();
|
|
946
|
+
// The watchdog arm above is deliberately the ONLY arm on the path where
|
|
947
|
+
// this throws. A misbound namespace fails verification on every wake, so
|
|
948
|
+
// the deadline duty below never runs and its retry ledger can never
|
|
949
|
+
// converge; arming at an already-due deadline here (floored one second
|
|
950
|
+
// out) would then wake every suspended run's object every second for as
|
|
951
|
+
// long as the misbinding lasts. Failing with the watchdog in place keeps
|
|
952
|
+
// the recovery cadence this object woke at before it served deadlines.
|
|
953
|
+
await verifyDurableObjectDeploymentIdentity(this.state, this.env);
|
|
954
|
+
// The two duties are failure-isolated: a run-owner recovery that throws
|
|
955
|
+
// must not skip a due suspension deadline (and its re-arm), and neither
|
|
956
|
+
// must be able to leave the object with no wake at all.
|
|
957
|
+
let recoveryError;
|
|
247
958
|
try {
|
|
248
|
-
await
|
|
249
|
-
const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
|
|
250
|
-
if (!stored) {
|
|
251
|
-
await this.state?.storage?.deleteAlarm?.();
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
await this.#recoverRunOwner(this.#runOwnerRecovery(stored));
|
|
959
|
+
await this.#recoverPendingRunOwner();
|
|
255
960
|
}
|
|
256
961
|
catch (error) {
|
|
257
|
-
|
|
258
|
-
|
|
962
|
+
recoveryError = error;
|
|
963
|
+
}
|
|
964
|
+
const converged = await this.#runDueSuspensionDeadline(Date.now());
|
|
965
|
+
// A duty that converged nothing has no arm to compute: the watchdog set
|
|
966
|
+
// at the top of this body IS the cadence it falls back to, and re-arming
|
|
967
|
+
// here would min it against an entry no ledger could back off — the same
|
|
968
|
+
// treatment, for the same reason, as the identity failure above.
|
|
969
|
+
if (recoveryError !== undefined) {
|
|
970
|
+
if (recoveryError instanceof RunStateUnreadableError) {
|
|
971
|
+
// Never rethrown: workerd retries a thrown alarm() up to six times,
|
|
972
|
+
// which would be a retry storm during the exact storage incident
|
|
973
|
+
// that caused it. Nothing was settled, so the journal survives and
|
|
974
|
+
// #armNextAlarm below reads it and arms the 60 s recovery cadence —
|
|
975
|
+
// the published rule for a wake that cannot read what it needs. The
|
|
976
|
+
// held reservation degrades owner() reads until the read heals or
|
|
977
|
+
// the isolate is evicted, which clears the in-memory run the marker
|
|
978
|
+
// comes from.
|
|
979
|
+
console.error('run owner recovery could not read authoritative state', recoveryError);
|
|
980
|
+
}
|
|
981
|
+
else {
|
|
982
|
+
if (converged)
|
|
983
|
+
await this.#rearmRunOwnerRecovery();
|
|
984
|
+
throw recoveryError;
|
|
985
|
+
}
|
|
259
986
|
}
|
|
987
|
+
if (converged)
|
|
988
|
+
await this.#armNextAlarm();
|
|
260
989
|
});
|
|
261
990
|
}
|
|
262
991
|
async #route(request) {
|
|
@@ -286,6 +1015,11 @@ export class DurableObjectRunner {
|
|
|
286
1015
|
const source = await this.#startSource(principal, workflowId, runId, body.scheduleId, body.dispatchId);
|
|
287
1016
|
const runtime = this.#ensureRuntime();
|
|
288
1017
|
await this.#recoverPendingRunOwner();
|
|
1018
|
+
// Stays on status(), and NOT because failing open would be safer: the
|
|
1019
|
+
// dangerous shape here is a row miss with no in-memory Run, which
|
|
1020
|
+
// carries no marker at all, so authoritativeStatus could not tell it
|
|
1021
|
+
// from an absent run either. The recovery above is what covers the
|
|
1022
|
+
// interrupted-start case, and it fails closed on an unreadable read.
|
|
289
1023
|
const existing = await runtime.status(workflowId, runId);
|
|
290
1024
|
if (existing) {
|
|
291
1025
|
const registered = await this.runOwnership(this.env).owner('run', runId);
|
|
@@ -331,18 +1065,31 @@ export class DurableObjectRunner {
|
|
|
331
1065
|
try {
|
|
332
1066
|
persisted = await runtime.recoverStartAttempt(workflowId, runId, recovery.token);
|
|
333
1067
|
}
|
|
334
|
-
catch {
|
|
1068
|
+
catch (recoverError) {
|
|
1069
|
+
// Logged, never swallowed silently: this read is the only thing
|
|
1070
|
+
// that could tell an interrupted start apart from a failed one,
|
|
1071
|
+
// and its own failure is the reason the journal is being left
|
|
1072
|
+
// armed for the alarm to retry.
|
|
1073
|
+
console.error('interrupted start could not read authoritative state', recoverError);
|
|
335
1074
|
await this.#rearmRunOwnerRecovery();
|
|
336
1075
|
throw error;
|
|
337
1076
|
}
|
|
338
1077
|
if (persisted) {
|
|
339
|
-
await this.#
|
|
1078
|
+
const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, persisted);
|
|
1079
|
+
await this.#settleRunOwnerBestEffort(recovery, false, !reconciled);
|
|
340
1080
|
return json(persisted);
|
|
341
1081
|
}
|
|
342
1082
|
await this.#settleRunOwnerBestEffort(recovery, true);
|
|
343
1083
|
throw error;
|
|
344
1084
|
}
|
|
345
|
-
|
|
1085
|
+
// Reconcile BEFORE settling, never after: settling clears the
|
|
1086
|
+
// recovery journal, and clearing it re-arms from storage — which, on
|
|
1087
|
+
// a run whose FIRST deadline write has not happened yet, finds no
|
|
1088
|
+
// record and no journal and deletes the alarm. With the journal
|
|
1089
|
+
// still stored the write's own arm takes the min of the two due
|
|
1090
|
+
// times, so no interleaving leaves this object without a wake.
|
|
1091
|
+
const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
|
|
1092
|
+
await this.#settleRunOwnerBestEffort(recovery, false, !reconciled);
|
|
346
1093
|
// DL-018: the authoritative RunSummary is the run-progress frame; push it
|
|
347
1094
|
// to any subscribed run-channel socket at this lifecycle boundary.
|
|
348
1095
|
this.#broadcastRunSummary(summary);
|
|
@@ -427,17 +1174,19 @@ export class DurableObjectRunner {
|
|
|
427
1174
|
const body = (await readJson(request)) ?? {};
|
|
428
1175
|
const requestedBy = this.#requestedBy(body.requestedBy);
|
|
429
1176
|
const requestedByKind = this.#requestedByKind(body.requestedByKind);
|
|
1177
|
+
const resumeData = this.#resumeData(body.resumeData);
|
|
430
1178
|
return this.#withOperationLock(async () => {
|
|
431
1179
|
const runtime = this.#ensureRuntime();
|
|
432
1180
|
const summary = await runtime.resume(workflowId, runId, {
|
|
433
1181
|
step: body.step,
|
|
434
|
-
resumeData
|
|
1182
|
+
resumeData,
|
|
435
1183
|
requestedBy,
|
|
436
1184
|
requestedByKind,
|
|
437
1185
|
...(body.deadlineMs === undefined
|
|
438
1186
|
? {}
|
|
439
1187
|
: { deadlineMs: body.deadlineMs }),
|
|
440
1188
|
});
|
|
1189
|
+
await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
|
|
441
1190
|
// DL-018: broadcast the post-resume authoritative summary.
|
|
442
1191
|
this.#broadcastRunSummary(summary);
|
|
443
1192
|
return json(summary);
|
|
@@ -461,6 +1210,10 @@ export class DurableObjectRunner {
|
|
|
461
1210
|
return this.#withOperationLock(async () => {
|
|
462
1211
|
const owner = await this.runOwnership(this.env).owner('run', runId);
|
|
463
1212
|
if (action === 'terminate-replay') {
|
|
1213
|
+
// Degrades CLOSED: the in-memory fallback reports 'pending', which
|
|
1214
|
+
// is neither terminal status, so a replay during a degraded read is
|
|
1215
|
+
// refused with UnknownRunError rather than replayed against a run
|
|
1216
|
+
// whose terminal state could not be read.
|
|
464
1217
|
const summary = await runtime.status(workflowId, runId);
|
|
465
1218
|
if (summary?.status !== 'cancelled' &&
|
|
466
1219
|
summary?.status !== 'timed_out') {
|
|
@@ -469,6 +1222,7 @@ export class DurableObjectRunner {
|
|
|
469
1222
|
}
|
|
470
1223
|
const result = await runtime.terminateAsPrincipal(workflowId, runId, principal, owner ?? principal);
|
|
471
1224
|
const summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner ?? principal, result);
|
|
1225
|
+
await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
|
|
472
1226
|
this.#broadcastRunSummary(summary);
|
|
473
1227
|
return json(summary);
|
|
474
1228
|
});
|
|
@@ -493,6 +1247,12 @@ export class DurableObjectRunner {
|
|
|
493
1247
|
return this.#withOperationLock(async () => {
|
|
494
1248
|
const owner = await this.runOwnership(this.env).owner('run', runId);
|
|
495
1249
|
if (!owner) {
|
|
1250
|
+
// Degrades CLOSED, same as the replay guard: 'pending' is not
|
|
1251
|
+
// 'timed_out', so the throw stands. It costs more here — this route
|
|
1252
|
+
// is driven by the maintenance sweep, and the throw fails the whole
|
|
1253
|
+
// sweep pass for that interval — but the next pass retries it, so a
|
|
1254
|
+
// degraded read delays the sweep rather than timing out a run whose
|
|
1255
|
+
// state nothing could read.
|
|
496
1256
|
const summary = await runtime.status(workflowId, runId);
|
|
497
1257
|
if (summary?.status !== 'timed_out') {
|
|
498
1258
|
throw new UnknownRunError(workflowId, runId);
|
|
@@ -500,9 +1260,18 @@ export class DurableObjectRunner {
|
|
|
500
1260
|
}
|
|
501
1261
|
const result = await runtime.timeOutAsPrincipal(workflowId, runId, cas, principal, owner ?? principal);
|
|
502
1262
|
if (!result.casMatched || result.cleanup.cleanupCompleted) {
|
|
1263
|
+
// The only terminal path that returns without finalizing, so it is
|
|
1264
|
+
// also the only one that would leave a record armed for a run that
|
|
1265
|
+
// can never suspend again. It reconciles from `result.summary` — a
|
|
1266
|
+
// post-transition read of a run this call has just settled or found
|
|
1267
|
+
// already settled or CAS-stale, taken after #loadSnapshot succeeded
|
|
1268
|
+
// on the same store — so it is an ordinary re-derivation, not a
|
|
1269
|
+
// conclusion drawn from a read that might not have reached storage.
|
|
1270
|
+
await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, result.summary);
|
|
503
1271
|
return json(result.summary);
|
|
504
1272
|
}
|
|
505
1273
|
const summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner ?? principal, result);
|
|
1274
|
+
await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
|
|
506
1275
|
this.#broadcastRunSummary(summary);
|
|
507
1276
|
return json(summary);
|
|
508
1277
|
});
|
|
@@ -545,6 +1314,33 @@ export class DurableObjectRunner {
|
|
|
545
1314
|
// Nothing to reconcile on a broadcast-only channel.
|
|
546
1315
|
}
|
|
547
1316
|
}
|
|
1317
|
+
/**
|
|
1318
|
+
* The one decision behind every converged-state arm: the earlier of the two
|
|
1319
|
+
* duties' due times, floored SUSPENSION_DEADLINE_ARM_FLOOR_MS out so an
|
|
1320
|
+
* already-due entry cannot re-arm at its own past time (which Cloudflare
|
|
1321
|
+
* fires immediately). `undefined` means no duty is pending and the caller
|
|
1322
|
+
* deletes the alarm. Pure so it can be pinned in isolation; exported from
|
|
1323
|
+
* this module only, never from the package barrel. Callers must sample `now`
|
|
1324
|
+
* AFTER their last await — under workerd's I/O-frozen clock an earlier sample
|
|
1325
|
+
* would shrink the floor by that await's latency and weaken the anti-spin
|
|
1326
|
+
* guarantee.
|
|
1327
|
+
*/
|
|
1328
|
+
export function nextDutyAlarmAt(suspensionDueAt, recoveryDueAt, now) {
|
|
1329
|
+
const due = suspensionDueAt === undefined
|
|
1330
|
+
? recoveryDueAt
|
|
1331
|
+
: recoveryDueAt === undefined
|
|
1332
|
+
? suspensionDueAt
|
|
1333
|
+
: Math.min(suspensionDueAt, recoveryDueAt);
|
|
1334
|
+
if (due === undefined)
|
|
1335
|
+
return undefined;
|
|
1336
|
+
return Math.max(due, now + SUSPENSION_DEADLINE_ARM_FLOOR_MS);
|
|
1337
|
+
}
|
|
1338
|
+
// One entry per suspended step is the stored record's key, so settling an entry
|
|
1339
|
+
// is "drop this step". Matching on the step id rather than on object identity
|
|
1340
|
+
// lets a caller settle an entry it read back separately from the record.
|
|
1341
|
+
function entriesWithoutStep(entries, step) {
|
|
1342
|
+
return entries.filter((entry) => entry.step !== step);
|
|
1343
|
+
}
|
|
548
1344
|
/** The run-channel wire frame containing the authoritative RunSummary. */
|
|
549
1345
|
function runFrame(summary) {
|
|
550
1346
|
return JSON.stringify({ type: 'run', summary });
|